imap.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. if (imap)
  511. {
  512. /* determine whether or not we can reuse the existing session */
  513. if (strcmp (box->host, imap->box->host) ||
  514. strcmp (box->user, imap->box->user) ||
  515. box->port != imap->box->port
  516. #if HAVE_LIBSSL
  517. /* ensure that security requirements are met */
  518. || (box->require_ssl ^ imap->box->require_ssl)
  519. || (box->require_cram ^ imap->box->require_cram)
  520. #endif
  521. )
  522. {
  523. /* can't reuse */
  524. imap_close (imap);
  525. imap = 0;
  526. }
  527. else
  528. {
  529. reuse = 1;
  530. /* reset mailbox-specific state info */
  531. imap->recent = 0;
  532. imap->deleted = 0;
  533. imap->count = 0;
  534. imap->maxuid = 0;
  535. free_message (imap->msgs);
  536. imap->msgs = 0;
  537. }
  538. }
  539. if (!imap)
  540. {
  541. imap = calloc (1, sizeof (imap_t));
  542. imap->sock = calloc (1, sizeof (Socket_t));
  543. imap->buf = calloc (1, sizeof (buffer_t));
  544. imap->buf->sock = imap->sock;
  545. }
  546. imap->box = box;
  547. imap->minuid = minuid;
  548. imap->prefix = "";
  549. if (!reuse)
  550. {
  551. /* open connection to IMAP server */
  552. if (box->tunnel)
  553. {
  554. int a[2];
  555. int b[2];
  556. printf ("Executing: %s...", box->tunnel);
  557. fflush (stdout);
  558. if (pipe (a))
  559. {
  560. }
  561. if (pipe (b))
  562. {
  563. }
  564. if (fork () == 0)
  565. {
  566. if (dup2 (a[0],0))
  567. {
  568. _exit(127);
  569. }
  570. close (a[1]);
  571. if (dup2 (b[1],1))
  572. {
  573. _exit (127);
  574. }
  575. close (b[0]);
  576. execl ("/bin/sh","sh","-c", box->tunnel);
  577. _exit (127);
  578. }
  579. close (a[0]);
  580. close (b[1]);
  581. imap->sock->rdfd = b[0];
  582. imap->sock->wrfd = a[1];
  583. puts ("ok");
  584. }
  585. else
  586. {
  587. memset (&addr, 0, sizeof (addr));
  588. addr.sin_port = htons (box->port);
  589. addr.sin_family = AF_INET;
  590. printf ("Resolving %s... ", box->host);
  591. fflush (stdout);
  592. he = gethostbyname (box->host);
  593. if (!he)
  594. {
  595. perror ("gethostbyname");
  596. return 0;
  597. }
  598. puts ("ok");
  599. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  600. s = socket (PF_INET, SOCK_STREAM, 0);
  601. printf ("Connecting to %s:%hu... ", inet_ntoa (addr.sin_addr),
  602. ntohs (addr.sin_port));
  603. fflush (stdout);
  604. if (connect (s, (struct sockaddr *) &addr, sizeof (addr)))
  605. {
  606. perror ("connect");
  607. exit (1);
  608. }
  609. puts ("ok");
  610. imap->sock->rdfd = s;
  611. imap->sock->wrfd = s;
  612. }
  613. }
  614. do
  615. {
  616. /* read the greeting string */
  617. if (buffer_gets (imap->buf, &rsp))
  618. {
  619. puts ("Error, no greeting response");
  620. ret = -1;
  621. break;
  622. }
  623. if (Verbose)
  624. puts (rsp);
  625. arg = next_arg (&rsp);
  626. if (!arg || *arg != '*' || (arg = next_arg (&rsp)) == NULL)
  627. {
  628. puts ("Error, invalid greeting response");
  629. ret = -1;
  630. break;
  631. }
  632. if (!strcmp ("PREAUTH", arg))
  633. preauth = 1;
  634. else if (strcmp ("OK", arg) != 0)
  635. {
  636. puts ("Error, unknown greeting response");
  637. ret = -1;
  638. break;
  639. }
  640. /* if we are reusing the existing connection, we can skip the
  641. * authentication steps.
  642. */
  643. if (!reuse)
  644. {
  645. #if HAVE_LIBSSL
  646. if (box->use_imaps)
  647. use_ssl = 1;
  648. else
  649. {
  650. /* let's see what this puppy can do... */
  651. if ((ret = imap_exec (imap, "CAPABILITY")))
  652. break;
  653. if (box->use_sslv2 || box->use_sslv3 || box->use_tlsv1)
  654. {
  655. /* always try to select SSL support if available */
  656. if (imap->have_starttls)
  657. {
  658. if ((ret = imap_exec (imap, "STARTTLS")))
  659. break;
  660. use_ssl = 1;
  661. }
  662. }
  663. }
  664. if (!use_ssl)
  665. {
  666. if (box->require_ssl)
  667. {
  668. puts ("Error, SSL support not available");
  669. ret = -1;
  670. break;
  671. }
  672. else
  673. puts ("Warning, SSL support not available");
  674. }
  675. else
  676. {
  677. /* initialize SSL */
  678. if (init_ssl (box))
  679. {
  680. ret = -1;
  681. break;
  682. }
  683. imap->sock->ssl = SSL_new (SSLContext);
  684. SSL_set_fd (imap->sock->ssl, imap->sock->rdfd);
  685. ret = SSL_connect (imap->sock->ssl);
  686. if (ret <= 0)
  687. {
  688. socket_perror ("connect", imap->sock, ret);
  689. break;
  690. }
  691. /* verify the server certificate */
  692. if ((ret = verify_cert (imap->sock->ssl)))
  693. break;
  694. /* to conform to RFC2595 we need to forget all information
  695. * retrieved from CAPABILITY invocations before STARTTLS.
  696. */
  697. imap->have_namespace = 0;
  698. imap->have_cram = 0;
  699. imap->have_starttls = 0;
  700. imap->sock->use_ssl = 1;
  701. puts ("SSL support enabled");
  702. if ((ret = imap_exec (imap, "CAPABILITY")))
  703. break;
  704. }
  705. #else
  706. if ((ret = imap_exec (imap, "CAPABILITY")))
  707. break;
  708. #endif
  709. if (!preauth)
  710. {
  711. puts ("Logging in...");
  712. #if HAVE_LIBSSL
  713. if (imap->have_cram)
  714. {
  715. puts ("Authenticating with CRAM-MD5");
  716. imap->cram = 1;
  717. if ((ret = imap_exec (imap, "AUTHENTICATE CRAM-MD5")))
  718. break;
  719. }
  720. else if (imap->box->require_cram)
  721. {
  722. puts
  723. ("Error, CRAM-MD5 authentication is not supported by server");
  724. ret = -1;
  725. break;
  726. }
  727. else
  728. #endif
  729. {
  730. #if HAVE_LIBSSL
  731. if (!use_ssl)
  732. #endif
  733. puts
  734. ("*** Warning *** Password is being sent in the clear");
  735. if (
  736. (ret =
  737. imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user,
  738. box->pass)))
  739. {
  740. puts ("Error, LOGIN failed");
  741. break;
  742. }
  743. }
  744. }
  745. /* get NAMESPACE info */
  746. if (box->use_namespace && imap->have_namespace)
  747. {
  748. if ((ret = imap_exec (imap, "NAMESPACE")))
  749. break;
  750. }
  751. } /* !reuse */
  752. /* XXX for now assume personal namespace */
  753. if (imap->box->use_namespace && is_list (imap->ns_personal) &&
  754. is_list (imap->ns_personal->child) &&
  755. is_atom (imap->ns_personal->child->child))
  756. {
  757. imap->prefix = imap->ns_personal->child->child->val;
  758. }
  759. fputs ("Selecting mailbox... ", stdout);
  760. fflush (stdout);
  761. if ((ret = imap_exec (imap, "SELECT \"%s%s\"", imap->prefix, box->box)))
  762. break;
  763. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  764. puts ("Reading IMAP mailbox index");
  765. if (imap->count > 0)
  766. {
  767. if ((ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  768. imap->minuid)))
  769. break;
  770. }
  771. }
  772. while (0);
  773. if (ret)
  774. {
  775. imap_close (imap);
  776. imap = 0;
  777. }
  778. return imap;
  779. }
  780. void
  781. imap_close (imap_t * imap)
  782. {
  783. if (imap)
  784. {
  785. imap_exec (imap, "LOGOUT");
  786. close (imap->sock->rdfd);
  787. if (imap->sock->rdfd != imap->sock->wrfd)
  788. close (imap->sock->wrfd);
  789. free (imap->sock);
  790. free (imap->buf);
  791. free_message (imap->msgs);
  792. memset (imap, 0xff, sizeof (imap_t));
  793. free (imap);
  794. }
  795. }
  796. /* write a buffer stripping all \r bytes */
  797. static int
  798. write_strip (int fd, char *buf, size_t len)
  799. {
  800. size_t start = 0;
  801. size_t end = 0;
  802. ssize_t n;
  803. while (start < len)
  804. {
  805. while (end < len && buf[end] != '\r')
  806. end++;
  807. n = write (fd, buf + start, end - start);
  808. if (n == -1)
  809. {
  810. perror ("write");
  811. return -1;
  812. }
  813. else if ((size_t) n != end - start)
  814. {
  815. /* short write, try again */
  816. start += n;
  817. }
  818. else
  819. {
  820. /* write complete */
  821. end++;
  822. start = end;
  823. }
  824. }
  825. return 0;
  826. }
  827. static int
  828. send_server (Socket_t * sock, const char *fmt, ...)
  829. {
  830. char buf[128];
  831. char cmd[128];
  832. va_list ap;
  833. int n;
  834. va_start (ap, fmt);
  835. vsnprintf (buf, sizeof (buf), fmt, ap);
  836. va_end (ap);
  837. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  838. n = socket_write (sock, cmd, strlen (cmd));
  839. if (n <= 0)
  840. {
  841. socket_perror ("write", sock, n);
  842. return -1;
  843. }
  844. if (Verbose)
  845. fputs (cmd, stdout);
  846. return 0;
  847. }
  848. int
  849. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  850. {
  851. char *cmd;
  852. char *arg;
  853. size_t bytes;
  854. size_t n;
  855. char buf[1024];
  856. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  857. for (;;)
  858. {
  859. if (buffer_gets (imap->buf, &cmd))
  860. return -1;
  861. if (Verbose)
  862. puts (cmd);
  863. if (*cmd == '*')
  864. {
  865. /* need to figure out how long the message is
  866. * * <msgno> FETCH (RFC822 {<size>}
  867. */
  868. next_arg (&cmd); /* * */
  869. next_arg (&cmd); /* <msgno> */
  870. arg = next_arg (&cmd); /* FETCH */
  871. if (strcasecmp ("FETCH", arg) != 0)
  872. {
  873. /* this is likely an untagged response, such as when new
  874. * mail arrives in the middle of the session. just skip
  875. * it for now.
  876. *
  877. * eg.,
  878. * "* 4000 EXISTS"
  879. * "* 2 RECENT"
  880. *
  881. */
  882. printf ("skipping untagged response: %s\n", arg);
  883. continue;
  884. }
  885. while ((arg = next_arg (&cmd)) && *arg != '{')
  886. ;
  887. if (!arg)
  888. {
  889. puts ("parse error getting size");
  890. return -1;
  891. }
  892. bytes = strtol (arg + 1, 0, 10);
  893. /* dump whats left over in the input buffer */
  894. n = imap->buf->bytes - imap->buf->offset;
  895. if (n > bytes)
  896. {
  897. /* the entire message fit in the buffer */
  898. n = bytes;
  899. }
  900. /* ick. we have to strip out the \r\n line endings, so
  901. * i can't just dump the raw bytes to disk.
  902. */
  903. if (write_strip (fd, imap->buf->buf + imap->buf->offset, n))
  904. {
  905. /* write failed, message is not delivered */
  906. return -1;
  907. }
  908. bytes -= n;
  909. /* mark that we used part of the buffer */
  910. imap->buf->offset += n;
  911. /* now read the rest of the message */
  912. while (bytes > 0)
  913. {
  914. n = bytes;
  915. if (n > sizeof (buf))
  916. n = sizeof (buf);
  917. n = socket_read (imap->sock, buf, n);
  918. if (n > 0)
  919. {
  920. if (write_strip (fd, buf, n))
  921. {
  922. /* write failed */
  923. return -1;
  924. }
  925. bytes -= n;
  926. }
  927. else
  928. {
  929. socket_perror ("read", imap->sock, n);
  930. return -1;
  931. }
  932. }
  933. buffer_gets (imap->buf, &cmd);
  934. if (Verbose)
  935. puts (cmd); /* last part of line */
  936. }
  937. else
  938. {
  939. arg = next_arg (&cmd);
  940. if (!arg || (size_t) atoi (arg) != Tag)
  941. {
  942. puts ("wrong tag");
  943. return -1;
  944. }
  945. arg = next_arg (&cmd);
  946. if (!strcmp ("OK", arg))
  947. return 0;
  948. return -1;
  949. }
  950. }
  951. /* not reached */
  952. }
  953. /* add flags to existing flags */
  954. int
  955. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  956. {
  957. char buf[256];
  958. int i;
  959. buf[0] = 0;
  960. for (i = 0; i < D_MAX; i++)
  961. {
  962. if (flags & (1 << i))
  963. snprintf (buf + strlen (buf),
  964. sizeof (buf) - strlen (buf), "%s%s",
  965. (buf[0] != 0) ? " " : "", Flags[i]);
  966. }
  967. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  968. }
  969. int
  970. imap_expunge (imap_t * imap)
  971. {
  972. return imap_exec (imap, "EXPUNGE");
  973. }
  974. int
  975. imap_copy_message (imap_t * imap, unsigned int uid, const char *mailbox)
  976. {
  977. return imap_exec (imap, "UID COPY %u \"%s%s\"", uid, imap->prefix,
  978. mailbox);
  979. }
  980. int
  981. imap_append_message (imap_t * imap, int fd, message_t * msg)
  982. {
  983. char buf[1024];
  984. size_t len;
  985. size_t sofar = 0;
  986. int lines = 0;
  987. char flagstr[128];
  988. char *s;
  989. size_t i;
  990. size_t start, end;
  991. char *arg;
  992. /* ugh, we need to count the number of newlines */
  993. while (sofar < msg->size)
  994. {
  995. len = msg->size - sofar;
  996. if (len > sizeof (buf))
  997. len = sizeof (buf);
  998. len = read (fd, buf, len);
  999. if (len == (size_t) - 1)
  1000. {
  1001. perror ("read");
  1002. return -1;
  1003. }
  1004. for (i = 0; i < len; i++)
  1005. if (buf[i] == '\n')
  1006. lines++;
  1007. sofar += len;
  1008. }
  1009. flagstr[0] = 0;
  1010. if (msg->flags)
  1011. {
  1012. strcpy (flagstr, "(");
  1013. if (msg->flags & D_DELETED)
  1014. snprintf (flagstr + strlen (flagstr),
  1015. sizeof (flagstr) - strlen (flagstr), "%s\\Deleted",
  1016. flagstr[1] ? " " : "");
  1017. if (msg->flags & D_ANSWERED)
  1018. snprintf (flagstr + strlen (flagstr),
  1019. sizeof (flagstr) - strlen (flagstr), "%s\\Answered",
  1020. flagstr[1] ? " " : "");
  1021. if (msg->flags & D_SEEN)
  1022. snprintf (flagstr + strlen (flagstr),
  1023. sizeof (flagstr) - strlen (flagstr), "%s\\Seen",
  1024. flagstr[1] ? " " : "");
  1025. if (msg->flags & D_FLAGGED)
  1026. snprintf (flagstr + strlen (flagstr),
  1027. sizeof (flagstr) - strlen (flagstr), "%s\\Flagged",
  1028. flagstr[1] ? " " : "");
  1029. if (msg->flags & D_DRAFT)
  1030. snprintf (flagstr + strlen (flagstr),
  1031. sizeof (flagstr) - strlen (flagstr), "%s\\Draft",
  1032. flagstr[1] ? " " : "");
  1033. snprintf (flagstr + strlen (flagstr),
  1034. sizeof (flagstr) - strlen (flagstr), ") ");
  1035. }
  1036. send_server (imap->sock, "APPEND %s%s %s{%d}",
  1037. imap->prefix, imap->box->box, flagstr, msg->size + lines);
  1038. if (buffer_gets (imap->buf, &s))
  1039. return -1;
  1040. if (Verbose)
  1041. puts (s);
  1042. if (*s != '+')
  1043. {
  1044. puts ("Error, expected `+' from server (aborting)");
  1045. return -1;
  1046. }
  1047. /* rewind */
  1048. lseek (fd, 0, 0);
  1049. sofar = 0;
  1050. while (sofar < msg->size)
  1051. {
  1052. len = msg->size - sofar;
  1053. if (len > sizeof (buf))
  1054. len = sizeof (buf);
  1055. len = read (fd, buf, len);
  1056. if (len == (size_t) - 1)
  1057. return -1;
  1058. start = 0;
  1059. while (start < len)
  1060. {
  1061. end = start;
  1062. while (end < len && buf[end] != '\n')
  1063. end++;
  1064. if (start != end)
  1065. socket_write (imap->sock, buf + start, end - start);
  1066. /* only send a crlf if we actually hit the end of a line. we
  1067. * might be in the middle of a line in which case we don't
  1068. * send one.
  1069. */
  1070. if (end != len)
  1071. socket_write (imap->sock, "\r\n", 2);
  1072. start = end + 1;
  1073. }
  1074. sofar += len;
  1075. }
  1076. socket_write (imap->sock, "\r\n", 2);
  1077. for (;;)
  1078. {
  1079. if (buffer_gets (imap->buf, &s))
  1080. return -1;
  1081. if (Verbose)
  1082. puts (s);
  1083. arg = next_arg (&s);
  1084. if (*arg == '*')
  1085. {
  1086. /* XXX just ignore it for now */
  1087. }
  1088. else if (atoi (arg) != (int) Tag)
  1089. {
  1090. puts ("wrong tag");
  1091. return -1;
  1092. }
  1093. else
  1094. {
  1095. int uid;
  1096. arg = next_arg (&s);
  1097. if (strcmp (arg, "OK"))
  1098. return -1;
  1099. arg = next_arg (&s);
  1100. if (*arg != '[')
  1101. break;
  1102. arg++;
  1103. if (strcasecmp ("APPENDUID", arg))
  1104. {
  1105. puts ("Error, expected APPENDUID");
  1106. break;
  1107. }
  1108. arg = next_arg (&s);
  1109. if (!arg)
  1110. break;
  1111. if (atoi (arg) != (int) imap->uidvalidity)
  1112. {
  1113. puts ("Error, UIDVALIDITY doesn't match APPENDUID");
  1114. return -1;
  1115. }
  1116. arg = next_arg (&s);
  1117. if (!arg)
  1118. break;
  1119. uid = strtol (arg, &s, 10);
  1120. if (*s != ']')
  1121. {
  1122. /* parse error */
  1123. break;
  1124. }
  1125. return uid;
  1126. }
  1127. }
  1128. return 0;
  1129. }