imap.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /* $Id$
  2. *
  3. * isync - IMAP4 to maildir mailbox synchronizer
  4. * Copyright (C) 2000-2 Michael R. Elkins <me@mutt.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. #include <assert.h>
  21. #include <unistd.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <ctype.h>
  27. #include <sys/socket.h>
  28. #include <netinet/in.h>
  29. #include <arpa/inet.h>
  30. #include <netdb.h>
  31. #if HAVE_LIBSSL
  32. #include <openssl/err.h>
  33. #endif
  34. #include "isync.h"
  35. const char *Flags[] = {
  36. "\\Seen",
  37. "\\Answered",
  38. "\\Deleted",
  39. "\\Flagged",
  40. "\\Recent",
  41. "\\Draft"
  42. };
  43. void
  44. free_message (message_t * msg)
  45. {
  46. message_t *tmp;
  47. while (msg)
  48. {
  49. tmp = msg;
  50. msg = msg->next;
  51. if (tmp->file)
  52. free (tmp->file);
  53. free (tmp);
  54. }
  55. }
  56. #if HAVE_LIBSSL
  57. #define MAX_DEPTH 1
  58. SSL_CTX *SSLContext = 0;
  59. /* this gets called when a certificate is to be verified */
  60. static int
  61. verify_cert (SSL * ssl)
  62. {
  63. X509 *cert;
  64. int err;
  65. char buf[256];
  66. int ret = -1;
  67. BIO *bio;
  68. cert = SSL_get_peer_certificate (ssl);
  69. if (!cert)
  70. {
  71. puts ("Error, no server certificate");
  72. return -1;
  73. }
  74. err = SSL_get_verify_result (ssl);
  75. if (err == X509_V_OK)
  76. return 0;
  77. printf ("Error, can't verify certificate: %s (%d)\n",
  78. X509_verify_cert_error_string (err), err);
  79. X509_NAME_oneline (X509_get_subject_name (cert), buf, sizeof (buf));
  80. printf ("\nSubject: %s\n", buf);
  81. X509_NAME_oneline (X509_get_issuer_name (cert), buf, sizeof (buf));
  82. printf ("Issuer: %s\n", buf);
  83. bio = BIO_new (BIO_s_mem ());
  84. ASN1_TIME_print (bio, X509_get_notBefore (cert));
  85. memset (buf, 0, sizeof (buf));
  86. BIO_read (bio, buf, sizeof (buf) - 1);
  87. printf ("Valid from: %s\n", buf);
  88. ASN1_TIME_print (bio, X509_get_notAfter (cert));
  89. memset (buf, 0, sizeof (buf));
  90. BIO_read (bio, buf, sizeof (buf) - 1);
  91. BIO_free (bio);
  92. printf (" to: %s\n", buf);
  93. printf
  94. ("\n*** WARNING *** There is no way to verify this certificate. It is\n"
  95. " possible that a hostile attacker has replaced the\n"
  96. " server certificate. Continue at your own risk!\n");
  97. printf ("\nAccept this certificate anyway? [no]: ");
  98. fflush (stdout);
  99. if (fgets (buf, sizeof (buf), stdin) && (buf[0] == 'y' || buf[0] == 'Y'))
  100. {
  101. ret = 0;
  102. puts ("\n*** Fine, but don't say I didn't warn you!\n");
  103. }
  104. return ret;
  105. }
  106. static int
  107. init_ssl (config_t * conf)
  108. {
  109. SSL_METHOD *method;
  110. int options = 0;
  111. if (!conf->cert_file)
  112. {
  113. puts ("Error, CertificateFile not defined");
  114. return -1;
  115. }
  116. SSL_library_init ();
  117. SSL_load_error_strings ();
  118. if (conf->use_tlsv1 && !conf->use_sslv2 && !conf->use_sslv3)
  119. method = TLSv1_client_method ();
  120. else
  121. method = SSLv23_client_method ();
  122. SSLContext = SSL_CTX_new (method);
  123. if (access (conf->cert_file, F_OK))
  124. {
  125. if (errno != ENOENT)
  126. {
  127. perror ("access");
  128. return -1;
  129. }
  130. puts
  131. ("*** Warning, CertificateFile doesn't exist, can't verify server certificates");
  132. }
  133. else
  134. if (!SSL_CTX_load_verify_locations
  135. (SSLContext, conf->cert_file, NULL))
  136. {
  137. printf ("Error, SSL_CTX_load_verify_locations: %s\n",
  138. ERR_error_string (ERR_get_error (), 0));
  139. return -1;
  140. }
  141. if (!conf->use_sslv2)
  142. options |= SSL_OP_NO_SSLv2;
  143. if (!conf->use_sslv3)
  144. options |= SSL_OP_NO_SSLv3;
  145. if (!conf->use_tlsv1)
  146. options |= SSL_OP_NO_TLSv1;
  147. SSL_CTX_set_options (SSLContext, options);
  148. /* we check the result of the verification after SSL_connect() */
  149. SSL_CTX_set_verify (SSLContext, SSL_VERIFY_NONE, 0);
  150. return 0;
  151. }
  152. #endif /* HAVE_LIBSSL */
  153. static int
  154. socket_read (Socket_t * sock, char *buf, size_t len)
  155. {
  156. #if HAVE_LIBSSL
  157. if (sock->use_ssl)
  158. return SSL_read (sock->ssl, buf, len);
  159. #endif
  160. return read (sock->rdfd, buf, len);
  161. }
  162. static int
  163. socket_write (Socket_t * sock, char *buf, size_t len)
  164. {
  165. #if HAVE_LIBSSL
  166. if (sock->use_ssl)
  167. return SSL_write (sock->ssl, buf, len);
  168. #endif
  169. return write (sock->wrfd, buf, len);
  170. }
  171. static void
  172. socket_perror (const char *func, Socket_t *sock, int ret)
  173. {
  174. #if HAVE_LIBSSL
  175. int err;
  176. if (sock->use_ssl)
  177. {
  178. switch ((err = SSL_get_error (sock->ssl, ret)))
  179. {
  180. case SSL_ERROR_SYSCALL:
  181. case SSL_ERROR_SSL:
  182. if ((err = ERR_get_error ()) == 0)
  183. {
  184. if (ret == 0)
  185. fprintf (stderr, "SSL_%s:got EOF\n", func);
  186. else
  187. fprintf (stderr, "SSL_%s:%d:%s\n", func,
  188. errno, strerror (errno));
  189. }
  190. else
  191. fprintf (stderr, "SSL_%s:%d:%s\n", func, err,
  192. ERR_error_string (err, 0));
  193. return;
  194. default:
  195. fprintf (stderr, "SSL_%s:%d:unhandled SSL error\n", func, err);
  196. break;
  197. }
  198. return;
  199. }
  200. #else
  201. (void) sock;
  202. (void) ret;
  203. #endif
  204. perror (func);
  205. }
  206. /* simple line buffering */
  207. static int
  208. buffer_gets (buffer_t * b, char **s)
  209. {
  210. int n;
  211. int start = b->offset;
  212. *s = b->buf + start;
  213. for (;;)
  214. {
  215. /* make sure we have enough data to read the \r\n sequence */
  216. if (b->offset + 1 >= b->bytes)
  217. {
  218. if (start != 0)
  219. {
  220. /* shift down used bytes */
  221. *s = b->buf;
  222. assert (start <= b->bytes);
  223. n = b->bytes - start;
  224. if (n)
  225. memmove (b->buf, b->buf + start, n);
  226. b->offset -= start;
  227. b->bytes = n;
  228. start = 0;
  229. }
  230. n =
  231. socket_read (b->sock, b->buf + b->bytes,
  232. sizeof (b->buf) - b->bytes);
  233. if (n <= 0)
  234. {
  235. socket_perror ("read", b->sock, n);
  236. return -1;
  237. }
  238. b->bytes += n;
  239. }
  240. if (b->buf[b->offset] == '\r')
  241. {
  242. assert (b->offset + 1 < b->bytes);
  243. if (b->buf[b->offset + 1] == '\n')
  244. {
  245. b->buf[b->offset] = 0; /* terminate the string */
  246. b->offset += 2; /* next line */
  247. return 0;
  248. }
  249. }
  250. b->offset++;
  251. }
  252. /* not reached */
  253. }
  254. static int
  255. parse_fetch (imap_t * imap, list_t * list)
  256. {
  257. list_t *tmp;
  258. unsigned int uid = 0;
  259. unsigned int mask = 0;
  260. unsigned int size = 0;
  261. message_t *cur;
  262. if (!is_list (list))
  263. return -1;
  264. for (tmp = list->child; tmp; tmp = tmp->next)
  265. {
  266. if (is_atom (tmp))
  267. {
  268. if (!strcmp ("UID", tmp->val))
  269. {
  270. tmp = tmp->next;
  271. if (is_atom (tmp))
  272. {
  273. uid = atoi (tmp->val);
  274. if (uid < imap->minuid)
  275. {
  276. /* already saw this message */
  277. return 0;
  278. }
  279. else if (uid > imap->maxuid)
  280. imap->maxuid = uid;
  281. }
  282. else
  283. puts ("Error, unable to parse UID");
  284. }
  285. else if (!strcmp ("FLAGS", tmp->val))
  286. {
  287. tmp = tmp->next;
  288. if (is_list (tmp))
  289. {
  290. list_t *flags = tmp->child;
  291. for (; flags; flags = flags->next)
  292. {
  293. if (is_atom (flags))
  294. {
  295. if (!strcmp ("\\Seen", flags->val))
  296. mask |= D_SEEN;
  297. else if (!strcmp ("\\Flagged", flags->val))
  298. mask |= D_FLAGGED;
  299. else if (!strcmp ("\\Deleted", flags->val))
  300. mask |= D_DELETED;
  301. else if (!strcmp ("\\Answered", flags->val))
  302. mask |= D_ANSWERED;
  303. else if (!strcmp ("\\Draft", flags->val))
  304. mask |= D_DRAFT;
  305. else if (!strcmp ("\\Recent", flags->val))
  306. mask |= D_RECENT;
  307. else
  308. printf ("Warning, unknown flag %s\n",
  309. flags->val);
  310. }
  311. else
  312. puts ("Error, unable to parse FLAGS list");
  313. }
  314. }
  315. else
  316. puts ("Error, unable to parse FLAGS");
  317. }
  318. else if (!strcmp ("RFC822.SIZE", tmp->val))
  319. {
  320. tmp = tmp->next;
  321. if (is_atom (tmp))
  322. size = atol (tmp->val);
  323. }
  324. }
  325. }
  326. cur = calloc (1, sizeof (message_t));
  327. cur->next = imap->msgs;
  328. imap->msgs = cur;
  329. if (mask & D_DELETED)
  330. imap->deleted++;
  331. cur->uid = uid;
  332. cur->flags = mask;
  333. cur->size = size;
  334. return 0;
  335. }
  336. static void
  337. parse_response_code (imap_t * imap, char *s)
  338. {
  339. char *arg;
  340. if (*s != '[')
  341. return; /* no response code */
  342. s++;
  343. arg = next_arg (&s);
  344. if (!strcmp ("UIDVALIDITY", arg))
  345. {
  346. arg = next_arg (&s);
  347. imap->uidvalidity = atol (arg);
  348. }
  349. else if (!strcmp ("ALERT", arg))
  350. {
  351. /* RFC2060 says that these messages MUST be displayed
  352. * to the user
  353. */
  354. fputs ("***ALERT*** ", stdout);
  355. puts (s);
  356. }
  357. }
  358. static int
  359. imap_exec (imap_t * imap, const char *fmt, ...)
  360. {
  361. va_list ap;
  362. char tmp[256];
  363. char buf[256];
  364. char *cmd;
  365. char *arg;
  366. char *arg1;
  367. int n;
  368. va_start (ap, fmt);
  369. vsnprintf (tmp, sizeof (tmp), fmt, ap);
  370. va_end (ap);
  371. snprintf (buf, sizeof (buf), "%d %s\r\n", ++Tag, tmp);
  372. if (Verbose)
  373. {
  374. fputs (">>> ", stdout);
  375. fputs (buf, stdout);
  376. }
  377. n = socket_write (imap->sock, buf, strlen (buf));
  378. if (n <= 0)
  379. {
  380. socket_perror ("write", imap->sock, n);
  381. return -1;
  382. }
  383. for (;;)
  384. {
  385. if (buffer_gets (imap->buf, &cmd))
  386. return -1;
  387. if (Verbose)
  388. puts (cmd);
  389. arg = next_arg (&cmd);
  390. if (*arg == '*')
  391. {
  392. arg = next_arg (&cmd);
  393. if (!arg)
  394. {
  395. puts ("Error, unable to parse untagged command");
  396. return -1;
  397. }
  398. if (!strcmp ("NAMESPACE", arg))
  399. {
  400. imap->ns_personal = parse_list (cmd, &cmd);
  401. imap->ns_other = parse_list (cmd, &cmd);
  402. imap->ns_shared = parse_list (cmd, 0);
  403. }
  404. else if (!strcmp ("OK", arg) || !strcmp ("BAD", arg) ||
  405. !strcmp ("NO", arg) || !strcmp ("BYE", arg) ||
  406. !strcmp ("PREAUTH", arg))
  407. {
  408. parse_response_code (imap, cmd);
  409. }
  410. else if (!strcmp ("CAPABILITY", arg))
  411. {
  412. #if HAVE_LIBSSL
  413. while ((arg = next_arg (&cmd)))
  414. {
  415. if (!strcmp ("STARTTLS", arg))
  416. imap->have_starttls = 1;
  417. else if (!strcmp ("AUTH=CRAM-MD5", arg))
  418. imap->have_cram = 1;
  419. else if (!strcmp ("NAMESPACE", arg))
  420. imap->have_namespace = 1;
  421. }
  422. #endif
  423. }
  424. else if ((arg1 = next_arg (&cmd)))
  425. {
  426. if (!strcmp ("EXISTS", arg1))
  427. imap->count = atoi (arg);
  428. else if (!strcmp ("RECENT", arg1))
  429. imap->recent = atoi (arg);
  430. else if (!strcmp ("FETCH", arg1))
  431. {
  432. list_t *list;
  433. list = parse_list (cmd, 0);
  434. if (parse_fetch (imap, list))
  435. {
  436. free_list (list);
  437. return -1;
  438. }
  439. free_list (list);
  440. }
  441. }
  442. else
  443. {
  444. puts ("Error, unable to parse untagged command");
  445. return -1;
  446. }
  447. }
  448. #if HAVE_LIBSSL
  449. else if (*arg == '+')
  450. {
  451. char *resp;
  452. if (!imap->cram)
  453. {
  454. puts ("Error, not doing CRAM-MD5 authentication");
  455. return -1;
  456. }
  457. resp = cram (cmd, imap->box->user, imap->box->pass);
  458. n = socket_write (imap->sock, resp, strlen (resp));
  459. if (n <= 0)
  460. {
  461. socket_perror ("write", imap->sock, n);
  462. return -1;
  463. }
  464. if (Verbose)
  465. puts (resp);
  466. n = socket_write (imap->sock, "\r\n", 2);
  467. if (n <= 0)
  468. {
  469. socket_perror ("write", imap->sock, n);
  470. return -1;
  471. }
  472. free (resp);
  473. imap->cram = 0;
  474. }
  475. #endif
  476. else if ((size_t) atol (arg) != Tag)
  477. {
  478. puts ("wrong tag");
  479. return -1;
  480. }
  481. else
  482. {
  483. arg = next_arg (&cmd);
  484. parse_response_code (imap, cmd);
  485. if (!strcmp ("OK", arg))
  486. return 0;
  487. return -1;
  488. }
  489. }
  490. /* not reached */
  491. }
  492. /* `box' is the config info for the maildrop to sync. `minuid' is the
  493. * minimum UID to consider. in normal mode this will be 1, but in --fast
  494. * mode we only fetch messages newer than the last one seen in the local
  495. * mailbox.
  496. */
  497. imap_t *
  498. imap_open (config_t * box, unsigned int minuid, imap_t * imap, int flags)
  499. {
  500. int ret;
  501. int s;
  502. struct sockaddr_in addr;
  503. struct hostent *he;
  504. char *arg, *rsp;
  505. int reuse = 0;
  506. int preauth = 0;
  507. #if HAVE_LIBSSL
  508. int use_ssl = 0;
  509. #endif
  510. (void) flags;
  511. if (imap)
  512. {
  513. /* determine whether or not we can reuse the existing session */
  514. if (strcmp (box->host, imap->box->host) ||
  515. strcmp (box->user, imap->box->user) ||
  516. box->port != imap->box->port
  517. #if HAVE_LIBSSL
  518. /* ensure that security requirements are met */
  519. || (box->require_ssl ^ imap->box->require_ssl)
  520. || (box->require_cram ^ imap->box->require_cram)
  521. #endif
  522. )
  523. {
  524. /* can't reuse */
  525. imap_close (imap);
  526. imap = 0;
  527. }
  528. else
  529. {
  530. reuse = 1;
  531. /* reset mailbox-specific state info */
  532. imap->recent = 0;
  533. imap->deleted = 0;
  534. imap->count = 0;
  535. imap->maxuid = 0;
  536. free_message (imap->msgs);
  537. imap->msgs = 0;
  538. }
  539. }
  540. if (!imap)
  541. {
  542. imap = calloc (1, sizeof (imap_t));
  543. imap->sock = calloc (1, sizeof (Socket_t));
  544. imap->buf = calloc (1, sizeof (buffer_t));
  545. imap->buf->sock = imap->sock;
  546. }
  547. imap->box = box;
  548. imap->minuid = minuid;
  549. imap->prefix = "";
  550. if (!reuse)
  551. {
  552. /* open connection to IMAP server */
  553. if (box->tunnel)
  554. {
  555. int a[2];
  556. int b[2];
  557. printf ("Executing: %s...", box->tunnel);
  558. fflush (stdout);
  559. if (pipe (a))
  560. {
  561. }
  562. if (pipe (b))
  563. {
  564. }
  565. if (fork () == 0)
  566. {
  567. if (dup2 (a[0],0))
  568. {
  569. _exit(127);
  570. }
  571. close (a[1]);
  572. if (dup2 (b[1],1))
  573. {
  574. _exit (127);
  575. }
  576. close (b[0]);
  577. execl ("/bin/sh","sh","-c", box->tunnel);
  578. _exit (127);
  579. }
  580. close (a[0]);
  581. close (b[1]);
  582. imap->sock->rdfd = b[0];
  583. imap->sock->wrfd = a[1];
  584. puts ("ok");
  585. }
  586. else
  587. {
  588. memset (&addr, 0, sizeof (addr));
  589. addr.sin_port = htons (box->port);
  590. addr.sin_family = AF_INET;
  591. printf ("Resolving %s... ", box->host);
  592. fflush (stdout);
  593. he = gethostbyname (box->host);
  594. if (!he)
  595. {
  596. perror ("gethostbyname");
  597. return 0;
  598. }
  599. puts ("ok");
  600. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  601. s = socket (PF_INET, SOCK_STREAM, 0);
  602. printf ("Connecting to %s:%hu... ", inet_ntoa (addr.sin_addr),
  603. ntohs (addr.sin_port));
  604. fflush (stdout);
  605. if (connect (s, (struct sockaddr *) &addr, sizeof (addr)))
  606. {
  607. perror ("connect");
  608. exit (1);
  609. }
  610. puts ("ok");
  611. imap->sock->rdfd = s;
  612. imap->sock->wrfd = s;
  613. }
  614. }
  615. do
  616. {
  617. /* read the greeting string */
  618. if (buffer_gets (imap->buf, &rsp))
  619. {
  620. puts ("Error, no greeting response");
  621. ret = -1;
  622. break;
  623. }
  624. if (Verbose)
  625. puts (rsp);
  626. arg = next_arg (&rsp);
  627. if (!arg || *arg != '*' || (arg = next_arg (&rsp)) == NULL)
  628. {
  629. puts ("Error, invalid greeting response");
  630. ret = -1;
  631. break;
  632. }
  633. if (!strcmp ("PREAUTH", arg))
  634. preauth = 1;
  635. else if (strcmp ("OK", arg) != 0)
  636. {
  637. puts ("Error, unknown greeting response");
  638. ret = -1;
  639. break;
  640. }
  641. /* if we are reusing the existing connection, we can skip the
  642. * authentication steps.
  643. */
  644. if (!reuse)
  645. {
  646. #if HAVE_LIBSSL
  647. if (box->use_imaps)
  648. use_ssl = 1;
  649. else
  650. {
  651. /* let's see what this puppy can do... */
  652. if ((ret = imap_exec (imap, "CAPABILITY")))
  653. break;
  654. if (box->use_sslv2 || box->use_sslv3 || box->use_tlsv1)
  655. {
  656. /* always try to select SSL support if available */
  657. if (imap->have_starttls)
  658. {
  659. if ((ret = imap_exec (imap, "STARTTLS")))
  660. break;
  661. use_ssl = 1;
  662. }
  663. }
  664. }
  665. if (!use_ssl)
  666. {
  667. if (box->require_ssl)
  668. {
  669. puts ("Error, SSL support not available");
  670. ret = -1;
  671. break;
  672. }
  673. else
  674. puts ("Warning, SSL support not available");
  675. }
  676. else
  677. {
  678. /* initialize SSL */
  679. if (init_ssl (box))
  680. {
  681. ret = -1;
  682. break;
  683. }
  684. imap->sock->ssl = SSL_new (SSLContext);
  685. SSL_set_fd (imap->sock->ssl, imap->sock->rdfd);
  686. ret = SSL_connect (imap->sock->ssl);
  687. if (ret <= 0)
  688. {
  689. socket_perror ("connect", imap->sock, ret);
  690. break;
  691. }
  692. /* verify the server certificate */
  693. if ((ret = verify_cert (imap->sock->ssl)))
  694. break;
  695. /* to conform to RFC2595 we need to forget all information
  696. * retrieved from CAPABILITY invocations before STARTTLS.
  697. */
  698. imap->have_namespace = 0;
  699. imap->have_cram = 0;
  700. imap->have_starttls = 0;
  701. imap->sock->use_ssl = 1;
  702. puts ("SSL support enabled");
  703. if ((ret = imap_exec (imap, "CAPABILITY")))
  704. break;
  705. }
  706. #else
  707. if ((ret = imap_exec (imap, "CAPABILITY")))
  708. break;
  709. #endif
  710. if (!preauth)
  711. {
  712. puts ("Logging in...");
  713. #if HAVE_LIBSSL
  714. if (imap->have_cram)
  715. {
  716. puts ("Authenticating with CRAM-MD5");
  717. imap->cram = 1;
  718. if ((ret = imap_exec (imap, "AUTHENTICATE CRAM-MD5")))
  719. break;
  720. }
  721. else if (imap->box->require_cram)
  722. {
  723. puts
  724. ("Error, CRAM-MD5 authentication is not supported by server");
  725. ret = -1;
  726. break;
  727. }
  728. else
  729. #endif
  730. {
  731. #if HAVE_LIBSSL
  732. if (!use_ssl)
  733. #endif
  734. puts
  735. ("*** Warning *** Password is being sent in the clear");
  736. if (
  737. (ret =
  738. imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user,
  739. box->pass)))
  740. {
  741. puts ("Error, LOGIN failed");
  742. break;
  743. }
  744. }
  745. }
  746. /* get NAMESPACE info */
  747. if (box->use_namespace && imap->have_namespace)
  748. {
  749. if ((ret = imap_exec (imap, "NAMESPACE")))
  750. break;
  751. }
  752. } /* !reuse */
  753. /* XXX for now assume personal namespace */
  754. if (imap->box->use_namespace && is_list (imap->ns_personal) &&
  755. is_list (imap->ns_personal->child) &&
  756. is_atom (imap->ns_personal->child->child))
  757. {
  758. imap->prefix = imap->ns_personal->child->child->val;
  759. }
  760. fputs ("Selecting mailbox... ", stdout);
  761. fflush (stdout);
  762. if ((ret = imap_exec (imap, "SELECT \"%s%s\"", imap->prefix, box->box)))
  763. break;
  764. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  765. puts ("Reading IMAP mailbox index");
  766. if (imap->count > 0)
  767. {
  768. if ((ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  769. imap->minuid)))
  770. break;
  771. }
  772. }
  773. while (0);
  774. if (ret)
  775. {
  776. imap_close (imap);
  777. imap = 0;
  778. }
  779. return imap;
  780. }
  781. void
  782. imap_close (imap_t * imap)
  783. {
  784. if (imap)
  785. {
  786. imap_exec (imap, "LOGOUT");
  787. close (imap->sock->rdfd);
  788. if (imap->sock->rdfd != imap->sock->wrfd)
  789. close (imap->sock->wrfd);
  790. free (imap->sock);
  791. free (imap->buf);
  792. free_message (imap->msgs);
  793. memset (imap, 0xff, sizeof (imap_t));
  794. free (imap);
  795. }
  796. }
  797. /* write a buffer stripping all \r bytes */
  798. static int
  799. write_strip (int fd, char *buf, size_t len)
  800. {
  801. size_t start = 0;
  802. size_t end = 0;
  803. ssize_t n;
  804. while (start < len)
  805. {
  806. while (end < len && buf[end] != '\r')
  807. end++;
  808. n = write (fd, buf + start, end - start);
  809. if (n == -1)
  810. {
  811. perror ("write");
  812. return -1;
  813. }
  814. else if ((size_t) n != end - start)
  815. {
  816. /* short write, try again */
  817. start += n;
  818. }
  819. else
  820. {
  821. /* write complete */
  822. end++;
  823. start = end;
  824. }
  825. }
  826. return 0;
  827. }
  828. static int
  829. send_server (Socket_t * sock, const char *fmt, ...)
  830. {
  831. char buf[128];
  832. char cmd[128];
  833. va_list ap;
  834. int n;
  835. va_start (ap, fmt);
  836. vsnprintf (buf, sizeof (buf), fmt, ap);
  837. va_end (ap);
  838. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  839. n = socket_write (sock, cmd, strlen (cmd));
  840. if (n <= 0)
  841. {
  842. socket_perror ("write", sock, n);
  843. return -1;
  844. }
  845. if (Verbose)
  846. fputs (cmd, stdout);
  847. return 0;
  848. }
  849. int
  850. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  851. {
  852. char *cmd;
  853. char *arg;
  854. size_t bytes;
  855. size_t n;
  856. char buf[1024];
  857. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  858. for (;;)
  859. {
  860. if (buffer_gets (imap->buf, &cmd))
  861. return -1;
  862. if (Verbose)
  863. puts (cmd);
  864. if (*cmd == '*')
  865. {
  866. /* need to figure out how long the message is
  867. * * <msgno> FETCH (RFC822 {<size>}
  868. */
  869. next_arg (&cmd); /* * */
  870. next_arg (&cmd); /* <msgno> */
  871. arg = next_arg (&cmd); /* FETCH */
  872. if (strcasecmp ("FETCH", arg) != 0)
  873. {
  874. /* this is likely an untagged response, such as when new
  875. * mail arrives in the middle of the session. just skip
  876. * it for now.
  877. *
  878. * eg.,
  879. * "* 4000 EXISTS"
  880. * "* 2 RECENT"
  881. *
  882. */
  883. printf ("skipping untagged response: %s\n", arg);
  884. continue;
  885. }
  886. while ((arg = next_arg (&cmd)) && *arg != '{')
  887. ;
  888. if (!arg)
  889. {
  890. puts ("parse error getting size");
  891. return -1;
  892. }
  893. bytes = strtol (arg + 1, 0, 10);
  894. /* dump whats left over in the input buffer */
  895. n = imap->buf->bytes - imap->buf->offset;
  896. if (n > bytes)
  897. {
  898. /* the entire message fit in the buffer */
  899. n = bytes;
  900. }
  901. /* ick. we have to strip out the \r\n line endings, so
  902. * i can't just dump the raw bytes to disk.
  903. */
  904. if (write_strip (fd, imap->buf->buf + imap->buf->offset, n))
  905. {
  906. /* write failed, message is not delivered */
  907. return -1;
  908. }
  909. bytes -= n;
  910. /* mark that we used part of the buffer */
  911. imap->buf->offset += n;
  912. /* now read the rest of the message */
  913. while (bytes > 0)
  914. {
  915. n = bytes;
  916. if (n > sizeof (buf))
  917. n = sizeof (buf);
  918. n = socket_read (imap->sock, buf, n);
  919. if (n > 0)
  920. {
  921. if (write_strip (fd, buf, n))
  922. {
  923. /* write failed */
  924. return -1;
  925. }
  926. bytes -= n;
  927. }
  928. else
  929. {
  930. socket_perror ("read", imap->sock, n);
  931. return -1;
  932. }
  933. }
  934. buffer_gets (imap->buf, &cmd);
  935. if (Verbose)
  936. puts (cmd); /* last part of line */
  937. }
  938. else
  939. {
  940. arg = next_arg (&cmd);
  941. if (!arg || (size_t) atoi (arg) != Tag)
  942. {
  943. puts ("wrong tag");
  944. return -1;
  945. }
  946. arg = next_arg (&cmd);
  947. if (!strcmp ("OK", arg))
  948. return 0;
  949. return -1;
  950. }
  951. }
  952. /* not reached */
  953. }
  954. /* add flags to existing flags */
  955. int
  956. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  957. {
  958. char buf[256];
  959. int i;
  960. buf[0] = 0;
  961. for (i = 0; i < D_MAX; i++)
  962. {
  963. if (flags & (1 << i))
  964. snprintf (buf + strlen (buf),
  965. sizeof (buf) - strlen (buf), "%s%s",
  966. (buf[0] != 0) ? " " : "", Flags[i]);
  967. }
  968. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  969. }
  970. int
  971. imap_expunge (imap_t * imap)
  972. {
  973. return imap_exec (imap, "EXPUNGE");
  974. }
  975. int
  976. imap_copy_message (imap_t * imap, unsigned int uid, const char *mailbox)
  977. {
  978. return imap_exec (imap, "UID COPY %u \"%s%s\"", uid, imap->prefix,
  979. mailbox);
  980. }
  981. int
  982. imap_append_message (imap_t * imap, int fd, message_t * msg)
  983. {
  984. char buf[1024];
  985. size_t len;
  986. size_t sofar = 0;
  987. int lines = 0;
  988. char flagstr[128];
  989. char *s;
  990. size_t i;
  991. size_t start, end;
  992. char *arg;
  993. /* ugh, we need to count the number of newlines */
  994. while (sofar < msg->size)
  995. {
  996. len = msg->size - sofar;
  997. if (len > sizeof (buf))
  998. len = sizeof (buf);
  999. len = read (fd, buf, len);
  1000. if (len == (size_t) - 1)
  1001. {
  1002. perror ("read");
  1003. return -1;
  1004. }
  1005. for (i = 0; i < len; i++)
  1006. if (buf[i] == '\n')
  1007. lines++;
  1008. sofar += len;
  1009. }
  1010. flagstr[0] = 0;
  1011. if (msg->flags)
  1012. {
  1013. strcpy (flagstr, "(");
  1014. if (msg->flags & D_DELETED)
  1015. snprintf (flagstr + strlen (flagstr),
  1016. sizeof (flagstr) - strlen (flagstr), "%s\\Deleted",
  1017. flagstr[1] ? " " : "");
  1018. if (msg->flags & D_ANSWERED)
  1019. snprintf (flagstr + strlen (flagstr),
  1020. sizeof (flagstr) - strlen (flagstr), "%s\\Answered",
  1021. flagstr[1] ? " " : "");
  1022. if (msg->flags & D_SEEN)
  1023. snprintf (flagstr + strlen (flagstr),
  1024. sizeof (flagstr) - strlen (flagstr), "%s\\Seen",
  1025. flagstr[1] ? " " : "");
  1026. if (msg->flags & D_FLAGGED)
  1027. snprintf (flagstr + strlen (flagstr),
  1028. sizeof (flagstr) - strlen (flagstr), "%s\\Flagged",
  1029. flagstr[1] ? " " : "");
  1030. if (msg->flags & D_DRAFT)
  1031. snprintf (flagstr + strlen (flagstr),
  1032. sizeof (flagstr) - strlen (flagstr), "%s\\Draft",
  1033. flagstr[1] ? " " : "");
  1034. snprintf (flagstr + strlen (flagstr),
  1035. sizeof (flagstr) - strlen (flagstr), ") ");
  1036. }
  1037. send_server (imap->sock, "APPEND %s%s %s{%d}",
  1038. imap->prefix, imap->box->box, flagstr, msg->size + lines);
  1039. if (buffer_gets (imap->buf, &s))
  1040. return -1;
  1041. if (Verbose)
  1042. puts (s);
  1043. if (*s != '+')
  1044. {
  1045. puts ("Error, expected `+' from server (aborting)");
  1046. return -1;
  1047. }
  1048. /* rewind */
  1049. lseek (fd, 0, 0);
  1050. sofar = 0;
  1051. while (sofar < msg->size)
  1052. {
  1053. len = msg->size - sofar;
  1054. if (len > sizeof (buf))
  1055. len = sizeof (buf);
  1056. len = read (fd, buf, len);
  1057. if (len == (size_t) - 1)
  1058. return -1;
  1059. start = 0;
  1060. while (start < len)
  1061. {
  1062. end = start;
  1063. while (end < len && buf[end] != '\n')
  1064. end++;
  1065. if (start != end)
  1066. socket_write (imap->sock, buf + start, end - start);
  1067. /* only send a crlf if we actually hit the end of a line. we
  1068. * might be in the middle of a line in which case we don't
  1069. * send one.
  1070. */
  1071. if (end != len)
  1072. socket_write (imap->sock, "\r\n", 2);
  1073. start = end + 1;
  1074. }
  1075. sofar += len;
  1076. }
  1077. socket_write (imap->sock, "\r\n", 2);
  1078. for (;;)
  1079. {
  1080. if (buffer_gets (imap->buf, &s))
  1081. return -1;
  1082. if (Verbose)
  1083. puts (s);
  1084. arg = next_arg (&s);
  1085. if (*arg == '*')
  1086. {
  1087. /* XXX just ignore it for now */
  1088. }
  1089. else if (atoi (arg) != (int) Tag)
  1090. {
  1091. puts ("wrong tag");
  1092. return -1;
  1093. }
  1094. else
  1095. {
  1096. int uid;
  1097. arg = next_arg (&s);
  1098. if (strcmp (arg, "OK"))
  1099. return -1;
  1100. arg = next_arg (&s);
  1101. if (*arg != '[')
  1102. break;
  1103. arg++;
  1104. if (strcasecmp ("APPENDUID", arg))
  1105. {
  1106. puts ("Error, expected APPENDUID");
  1107. break;
  1108. }
  1109. arg = next_arg (&s);
  1110. if (!arg)
  1111. break;
  1112. if (atoi (arg) != (int) imap->uidvalidity)
  1113. {
  1114. puts ("Error, UIDVALIDITY doesn't match APPENDUID");
  1115. return -1;
  1116. }
  1117. arg = next_arg (&s);
  1118. if (!arg)
  1119. break;
  1120. uid = strtol (arg, &s, 10);
  1121. if (*s != ']')
  1122. {
  1123. /* parse error */
  1124. break;
  1125. }
  1126. return uid;
  1127. }
  1128. }
  1129. return 0;
  1130. }