imap.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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->fd, 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->fd, 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. #endif
  203. if (ret)
  204. perror (func);
  205. else
  206. fprintf (stderr, "%s: unexpected EOF\n", func);
  207. }
  208. /* simple line buffering */
  209. static int
  210. buffer_gets (buffer_t * b, char **s)
  211. {
  212. int n;
  213. int start = b->offset;
  214. *s = b->buf + start;
  215. for (;;)
  216. {
  217. /* make sure we have enough data to read the \r\n sequence */
  218. if (b->offset + 1 >= b->bytes)
  219. {
  220. if (start != 0)
  221. {
  222. /* shift down used bytes */
  223. *s = b->buf;
  224. assert (start <= b->bytes);
  225. n = b->bytes - start;
  226. if (n)
  227. memmove (b->buf, b->buf + start, n);
  228. b->offset -= start;
  229. b->bytes = n;
  230. start = 0;
  231. }
  232. n =
  233. socket_read (b->sock, b->buf + b->bytes,
  234. sizeof (b->buf) - b->bytes);
  235. if (n <= 0)
  236. {
  237. socket_perror ("read", b->sock, n);
  238. return -1;
  239. }
  240. b->bytes += n;
  241. }
  242. if (b->buf[b->offset] == '\r')
  243. {
  244. assert (b->offset + 1 < b->bytes);
  245. if (b->buf[b->offset + 1] == '\n')
  246. {
  247. b->buf[b->offset] = 0; /* terminate the string */
  248. b->offset += 2; /* next line */
  249. return 0;
  250. }
  251. }
  252. b->offset++;
  253. }
  254. /* not reached */
  255. }
  256. static int
  257. parse_fetch (imap_t * imap, list_t * list)
  258. {
  259. list_t *tmp;
  260. unsigned int uid = 0;
  261. unsigned int mask = 0;
  262. unsigned int size = 0;
  263. message_t *cur;
  264. if (!is_list (list))
  265. return -1;
  266. for (tmp = list->child; tmp; tmp = tmp->next)
  267. {
  268. if (is_atom (tmp))
  269. {
  270. if (!strcmp ("UID", tmp->val))
  271. {
  272. tmp = tmp->next;
  273. if (is_atom (tmp))
  274. {
  275. uid = atoi (tmp->val);
  276. if (uid < imap->minuid)
  277. {
  278. /* already saw this message */
  279. return 0;
  280. }
  281. else if (uid > imap->maxuid)
  282. imap->maxuid = uid;
  283. }
  284. else
  285. puts ("Error, unable to parse UID");
  286. }
  287. else if (!strcmp ("FLAGS", tmp->val))
  288. {
  289. tmp = tmp->next;
  290. if (is_list (tmp))
  291. {
  292. list_t *flags = tmp->child;
  293. for (; flags; flags = flags->next)
  294. {
  295. if (is_atom (flags))
  296. {
  297. if (!strcmp ("\\Seen", flags->val))
  298. mask |= D_SEEN;
  299. else if (!strcmp ("\\Flagged", flags->val))
  300. mask |= D_FLAGGED;
  301. else if (!strcmp ("\\Deleted", flags->val))
  302. mask |= D_DELETED;
  303. else if (!strcmp ("\\Answered", flags->val))
  304. mask |= D_ANSWERED;
  305. else if (!strcmp ("\\Draft", flags->val))
  306. mask |= D_DRAFT;
  307. else if (!strcmp ("\\Recent", flags->val))
  308. mask |= D_RECENT;
  309. else
  310. printf ("Warning, unknown flag %s\n",
  311. flags->val);
  312. }
  313. else
  314. puts ("Error, unable to parse FLAGS list");
  315. }
  316. }
  317. else
  318. puts ("Error, unable to parse FLAGS");
  319. }
  320. else if (!strcmp ("RFC822.SIZE", tmp->val))
  321. {
  322. tmp = tmp->next;
  323. if (is_atom (tmp))
  324. size = atol (tmp->val);
  325. }
  326. }
  327. }
  328. cur = calloc (1, sizeof (message_t));
  329. cur->next = imap->msgs;
  330. imap->msgs = cur;
  331. if (mask & D_DELETED)
  332. imap->deleted++;
  333. cur->uid = uid;
  334. cur->flags = mask;
  335. cur->size = size;
  336. return 0;
  337. }
  338. static void
  339. parse_response_code (imap_t * imap, char *s)
  340. {
  341. char *arg;
  342. if (*s != '[')
  343. return; /* no response code */
  344. s++;
  345. arg = next_arg (&s);
  346. if (!strcmp ("UIDVALIDITY", arg))
  347. {
  348. arg = next_arg (&s);
  349. imap->uidvalidity = atol (arg);
  350. }
  351. else if (!strcmp ("ALERT", arg))
  352. {
  353. /* RFC2060 says that these messages MUST be displayed
  354. * to the user
  355. */
  356. fputs ("***ALERT*** ", stdout);
  357. puts (s);
  358. }
  359. }
  360. static int
  361. imap_exec (imap_t * imap, const char *fmt, ...)
  362. {
  363. va_list ap;
  364. char tmp[256];
  365. char buf[256];
  366. char *cmd;
  367. char *arg;
  368. char *arg1;
  369. int n;
  370. va_start (ap, fmt);
  371. vsnprintf (tmp, sizeof (tmp), fmt, ap);
  372. va_end (ap);
  373. snprintf (buf, sizeof (buf), "%d %s\r\n", ++Tag, tmp);
  374. if (Verbose)
  375. {
  376. fputs (">>> ", stdout);
  377. fputs (buf, stdout);
  378. }
  379. n = socket_write (imap->sock, buf, strlen (buf));
  380. if (n <= 0)
  381. {
  382. socket_perror ("write", imap->sock, n);
  383. return -1;
  384. }
  385. for (;;)
  386. {
  387. if (buffer_gets (imap->buf, &cmd))
  388. return -1;
  389. if (Verbose)
  390. puts (cmd);
  391. arg = next_arg (&cmd);
  392. if (*arg == '*')
  393. {
  394. arg = next_arg (&cmd);
  395. if (!arg)
  396. {
  397. puts ("Error, unable to parse untagged command");
  398. return -1;
  399. }
  400. if (!strcmp ("NAMESPACE", arg))
  401. {
  402. imap->ns_personal = parse_list (cmd, &cmd);
  403. imap->ns_other = parse_list (cmd, &cmd);
  404. imap->ns_shared = parse_list (cmd, 0);
  405. }
  406. else if (!strcmp ("OK", arg) || !strcmp ("BAD", arg) ||
  407. !strcmp ("NO", arg) || !strcmp ("BYE", arg) ||
  408. !strcmp ("PREAUTH", arg))
  409. {
  410. parse_response_code (imap, cmd);
  411. }
  412. else if (!strcmp ("CAPABILITY", arg))
  413. {
  414. #if HAVE_LIBSSL
  415. while ((arg = next_arg (&cmd)))
  416. {
  417. if (!strcmp ("STARTTLS", arg))
  418. imap->have_starttls = 1;
  419. else if (!strcmp ("AUTH=CRAM-MD5", arg))
  420. imap->have_cram = 1;
  421. else if (!strcmp ("NAMESPACE", arg))
  422. imap->have_namespace = 1;
  423. }
  424. #endif
  425. }
  426. else if ((arg1 = next_arg (&cmd)))
  427. {
  428. if (!strcmp ("EXISTS", arg1))
  429. imap->count = atoi (arg);
  430. else if (!strcmp ("RECENT", arg1))
  431. imap->recent = atoi (arg);
  432. else if (!strcmp ("FETCH", arg1))
  433. {
  434. list_t *list;
  435. list = parse_list (cmd, 0);
  436. if (parse_fetch (imap, list))
  437. {
  438. free_list (list);
  439. return -1;
  440. }
  441. free_list (list);
  442. }
  443. }
  444. else
  445. {
  446. puts ("Error, unable to parse untagged command");
  447. return -1;
  448. }
  449. }
  450. #if HAVE_LIBSSL
  451. else if (*arg == '+')
  452. {
  453. char *resp;
  454. if (!imap->cram)
  455. {
  456. puts ("Error, not doing CRAM-MD5 authentication");
  457. return -1;
  458. }
  459. resp = cram (cmd, imap->box->user, imap->box->pass);
  460. n = socket_write (imap->sock, resp, strlen (resp));
  461. if (n <= 0)
  462. {
  463. socket_perror ("write", imap->sock, n);
  464. return -1;
  465. }
  466. if (Verbose)
  467. puts (resp);
  468. n = socket_write (imap->sock, "\r\n", 2);
  469. if (n <= 0)
  470. {
  471. socket_perror ("write", imap->sock, n);
  472. return -1;
  473. }
  474. free (resp);
  475. imap->cram = 0;
  476. }
  477. #endif
  478. else if ((size_t) atol (arg) != Tag)
  479. {
  480. puts ("wrong tag");
  481. return -1;
  482. }
  483. else
  484. {
  485. arg = next_arg (&cmd);
  486. parse_response_code (imap, cmd);
  487. if (!strcmp ("OK", arg))
  488. return 0;
  489. return -1;
  490. }
  491. }
  492. /* not reached */
  493. }
  494. /* `box' is the config info for the maildrop to sync. `minuid' is the
  495. * minimum UID to consider. in normal mode this will be 1, but in --fast
  496. * mode we only fetch messages newer than the last one seen in the local
  497. * mailbox.
  498. */
  499. imap_t *
  500. imap_open (config_t * box, unsigned int minuid, imap_t * imap, int flags)
  501. {
  502. int ret;
  503. int s;
  504. struct sockaddr_in addr;
  505. struct hostent *he;
  506. char *arg, *rsp;
  507. int reuse = 0;
  508. int preauth = 0;
  509. #if HAVE_LIBSSL
  510. int use_ssl = 0;
  511. #endif
  512. (void) flags;
  513. if (imap)
  514. {
  515. /* determine whether or not we can reuse the existing session */
  516. if (strcmp (box->host, imap->box->host) ||
  517. strcmp (box->user, imap->box->user) ||
  518. box->port != imap->box->port
  519. #if HAVE_LIBSSL
  520. /* ensure that security requirements are met */
  521. || (box->require_ssl ^ imap->box->require_ssl)
  522. || (box->require_cram ^ imap->box->require_cram)
  523. #endif
  524. )
  525. {
  526. /* can't reuse */
  527. imap_close (imap);
  528. imap = 0;
  529. }
  530. else
  531. {
  532. reuse = 1;
  533. /* reset mailbox-specific state info */
  534. imap->recent = 0;
  535. imap->deleted = 0;
  536. imap->count = 0;
  537. imap->maxuid = 0;
  538. free_message (imap->msgs);
  539. imap->msgs = 0;
  540. }
  541. }
  542. if (!imap)
  543. {
  544. imap = calloc (1, sizeof (imap_t));
  545. imap->sock = calloc (1, sizeof (Socket_t));
  546. imap->buf = calloc (1, sizeof (buffer_t));
  547. imap->buf->sock = imap->sock;
  548. imap->sock->fd = -1;
  549. }
  550. imap->box = box;
  551. imap->minuid = minuid;
  552. imap->prefix = "";
  553. if (!reuse)
  554. {
  555. int a[2];
  556. /* open connection to IMAP server */
  557. if (box->tunnel)
  558. {
  559. printf ("Starting tunnel '%s'...", box->tunnel);
  560. fflush (stdout);
  561. if (socketpair (PF_UNIX, SOCK_STREAM, 0, a))
  562. {
  563. perror ("socketpair");
  564. exit (1);
  565. }
  566. if (fork () == 0)
  567. {
  568. if (dup2 (a[0],0) || dup2 (a[0], 1))
  569. {
  570. _exit(127);
  571. }
  572. close (a[1]);
  573. execl ("/bin/sh", "sh", "-c", box->tunnel);
  574. _exit (127);
  575. }
  576. close (a[0]);
  577. imap->sock->fd = a[1];
  578. puts ("ok");
  579. }
  580. else
  581. {
  582. memset (&addr, 0, sizeof (addr));
  583. addr.sin_port = htons (box->port);
  584. addr.sin_family = AF_INET;
  585. printf ("Resolving %s... ", box->host);
  586. fflush (stdout);
  587. he = gethostbyname (box->host);
  588. if (!he)
  589. {
  590. perror ("gethostbyname");
  591. return 0;
  592. }
  593. puts ("ok");
  594. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  595. s = socket (PF_INET, SOCK_STREAM, 0);
  596. printf ("Connecting to %s:%hu... ", inet_ntoa (addr.sin_addr),
  597. ntohs (addr.sin_port));
  598. fflush (stdout);
  599. if (connect (s, (struct sockaddr *) &addr, sizeof (addr)))
  600. {
  601. perror ("connect");
  602. exit (1);
  603. }
  604. puts ("ok");
  605. imap->sock->fd = s;
  606. }
  607. }
  608. do
  609. {
  610. /* read the greeting string */
  611. if (buffer_gets (imap->buf, &rsp))
  612. {
  613. puts ("Error, no greeting response");
  614. ret = -1;
  615. break;
  616. }
  617. if (Verbose)
  618. puts (rsp);
  619. arg = next_arg (&rsp);
  620. if (!arg || *arg != '*' || (arg = next_arg (&rsp)) == NULL)
  621. {
  622. puts ("Error, invalid greeting response");
  623. ret = -1;
  624. break;
  625. }
  626. if (!strcmp ("PREAUTH", arg))
  627. preauth = 1;
  628. else if (strcmp ("OK", arg) != 0)
  629. {
  630. puts ("Error, unknown greeting response");
  631. ret = -1;
  632. break;
  633. }
  634. /* if we are reusing the existing connection, we can skip the
  635. * authentication steps.
  636. */
  637. if (!reuse)
  638. {
  639. #if HAVE_LIBSSL
  640. if (box->use_imaps)
  641. use_ssl = 1;
  642. else
  643. {
  644. /* let's see what this puppy can do... */
  645. if ((ret = imap_exec (imap, "CAPABILITY")))
  646. break;
  647. if (box->use_sslv2 || box->use_sslv3 || box->use_tlsv1)
  648. {
  649. /* always try to select SSL support if available */
  650. if (imap->have_starttls)
  651. {
  652. if ((ret = imap_exec (imap, "STARTTLS")))
  653. break;
  654. use_ssl = 1;
  655. }
  656. }
  657. }
  658. if (!use_ssl)
  659. {
  660. if (box->require_ssl)
  661. {
  662. puts ("Error, SSL support not available");
  663. ret = -1;
  664. break;
  665. }
  666. else if (box->use_sslv2 || box->use_sslv3 || box->use_tlsv1)
  667. puts ("Warning, SSL support not available");
  668. }
  669. else
  670. {
  671. /* initialize SSL */
  672. if (init_ssl (box))
  673. {
  674. ret = -1;
  675. break;
  676. }
  677. imap->sock->ssl = SSL_new (SSLContext);
  678. SSL_set_fd (imap->sock->ssl, imap->sock->fd);
  679. ret = SSL_connect (imap->sock->ssl);
  680. if (ret <= 0)
  681. {
  682. socket_perror ("connect", imap->sock, ret);
  683. break;
  684. }
  685. /* verify the server certificate */
  686. if ((ret = verify_cert (imap->sock->ssl)))
  687. break;
  688. /* to conform to RFC2595 we need to forget all information
  689. * retrieved from CAPABILITY invocations before STARTTLS.
  690. */
  691. imap->have_namespace = 0;
  692. imap->have_cram = 0;
  693. imap->have_starttls = 0;
  694. imap->sock->use_ssl = 1;
  695. puts ("SSL support enabled");
  696. if ((ret = imap_exec (imap, "CAPABILITY")))
  697. break;
  698. }
  699. #else
  700. if ((ret = imap_exec (imap, "CAPABILITY")))
  701. break;
  702. #endif
  703. if (!preauth)
  704. {
  705. puts ("Logging in...");
  706. if (!box->pass)
  707. {
  708. /*
  709. * if we don't have a global password set, prompt the user for
  710. * it now.
  711. */
  712. if (!global.pass)
  713. {
  714. global.pass = getpass ("Password:");
  715. if (!global.pass)
  716. {
  717. fprintf (stderr, "Skipping %s, no password", box->path);
  718. break;
  719. }
  720. }
  721. box->pass = strdup (global.pass);
  722. }
  723. #if HAVE_LIBSSL
  724. if (imap->have_cram)
  725. {
  726. puts ("Authenticating with CRAM-MD5");
  727. imap->cram = 1;
  728. if ((ret = imap_exec (imap, "AUTHENTICATE CRAM-MD5")))
  729. break;
  730. }
  731. else if (imap->box->require_cram)
  732. {
  733. puts
  734. ("Error, CRAM-MD5 authentication is not supported by server");
  735. ret = -1;
  736. break;
  737. }
  738. else
  739. #endif
  740. {
  741. #if HAVE_LIBSSL
  742. if (!use_ssl)
  743. #endif
  744. puts
  745. ("*** Warning *** Password is being sent in the clear");
  746. if (
  747. (ret =
  748. imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user,
  749. box->pass)))
  750. {
  751. puts ("Error, LOGIN failed");
  752. break;
  753. }
  754. }
  755. }
  756. /* get NAMESPACE info */
  757. if (box->use_namespace && imap->have_namespace)
  758. {
  759. if ((ret = imap_exec (imap, "NAMESPACE")))
  760. break;
  761. }
  762. } /* !reuse */
  763. /* XXX for now assume personal namespace */
  764. if (imap->box->use_namespace && is_list (imap->ns_personal) &&
  765. is_list (imap->ns_personal->child) &&
  766. is_atom (imap->ns_personal->child->child))
  767. {
  768. imap->prefix = imap->ns_personal->child->child->val;
  769. }
  770. fputs ("Selecting mailbox... ", stdout);
  771. fflush (stdout);
  772. if ((ret = imap_exec (imap, "SELECT \"%s%s\"", imap->prefix, box->box)))
  773. break;
  774. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  775. puts ("Reading IMAP mailbox index");
  776. if (imap->count > 0)
  777. {
  778. if ((ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  779. imap->minuid)))
  780. break;
  781. }
  782. }
  783. while (0);
  784. if (ret)
  785. {
  786. imap_close (imap);
  787. imap = 0;
  788. }
  789. return imap;
  790. }
  791. void
  792. imap_close (imap_t * imap)
  793. {
  794. if (imap)
  795. {
  796. imap_exec (imap, "LOGOUT");
  797. close (imap->sock->fd);
  798. free (imap->sock);
  799. free (imap->buf);
  800. free_message (imap->msgs);
  801. memset (imap, 0xff, sizeof (imap_t));
  802. free (imap);
  803. }
  804. }
  805. /* write a buffer stripping all \r bytes */
  806. static int
  807. write_strip (int fd, char *buf, size_t len)
  808. {
  809. size_t start = 0;
  810. size_t end = 0;
  811. ssize_t n;
  812. while (start < len)
  813. {
  814. while (end < len && buf[end] != '\r')
  815. end++;
  816. n = write (fd, buf + start, end - start);
  817. if (n == -1)
  818. {
  819. perror ("write");
  820. return -1;
  821. }
  822. else if ((size_t) n != end - start)
  823. {
  824. /* short write, try again */
  825. start += n;
  826. }
  827. else
  828. {
  829. /* write complete */
  830. end++;
  831. start = end;
  832. }
  833. }
  834. return 0;
  835. }
  836. static int
  837. send_server (Socket_t * sock, const char *fmt, ...)
  838. {
  839. char buf[128];
  840. char cmd[128];
  841. va_list ap;
  842. int n;
  843. va_start (ap, fmt);
  844. vsnprintf (buf, sizeof (buf), fmt, ap);
  845. va_end (ap);
  846. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  847. n = socket_write (sock, cmd, strlen (cmd));
  848. if (n <= 0)
  849. {
  850. socket_perror ("write", sock, n);
  851. return -1;
  852. }
  853. if (Verbose)
  854. fputs (cmd, stdout);
  855. return 0;
  856. }
  857. int
  858. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  859. {
  860. char *cmd;
  861. char *arg;
  862. size_t bytes;
  863. size_t n;
  864. char buf[1024];
  865. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  866. for (;;)
  867. {
  868. if (buffer_gets (imap->buf, &cmd))
  869. return -1;
  870. if (Verbose)
  871. puts (cmd);
  872. if (*cmd == '*')
  873. {
  874. /* need to figure out how long the message is
  875. * * <msgno> FETCH (RFC822 {<size>}
  876. */
  877. next_arg (&cmd); /* * */
  878. next_arg (&cmd); /* <msgno> */
  879. arg = next_arg (&cmd); /* FETCH */
  880. if (strcasecmp ("FETCH", arg) != 0)
  881. {
  882. /* this is likely an untagged response, such as when new
  883. * mail arrives in the middle of the session. just skip
  884. * it for now.
  885. *
  886. * eg.,
  887. * "* 4000 EXISTS"
  888. * "* 2 RECENT"
  889. *
  890. */
  891. printf ("skipping untagged response: %s\n", arg);
  892. continue;
  893. }
  894. while ((arg = next_arg (&cmd)) && *arg != '{')
  895. ;
  896. if (!arg)
  897. {
  898. puts ("parse error getting size");
  899. return -1;
  900. }
  901. bytes = strtol (arg + 1, 0, 10);
  902. /* dump whats left over in the input buffer */
  903. n = imap->buf->bytes - imap->buf->offset;
  904. if (n > bytes)
  905. {
  906. /* the entire message fit in the buffer */
  907. n = bytes;
  908. }
  909. /* ick. we have to strip out the \r\n line endings, so
  910. * i can't just dump the raw bytes to disk.
  911. */
  912. if (write_strip (fd, imap->buf->buf + imap->buf->offset, n))
  913. {
  914. /* write failed, message is not delivered */
  915. return -1;
  916. }
  917. bytes -= n;
  918. /* mark that we used part of the buffer */
  919. imap->buf->offset += n;
  920. /* now read the rest of the message */
  921. while (bytes > 0)
  922. {
  923. n = bytes;
  924. if (n > sizeof (buf))
  925. n = sizeof (buf);
  926. n = socket_read (imap->sock, buf, n);
  927. if (n > 0)
  928. {
  929. if (write_strip (fd, buf, n))
  930. {
  931. /* write failed */
  932. return -1;
  933. }
  934. bytes -= n;
  935. }
  936. else
  937. {
  938. socket_perror ("read", imap->sock, n);
  939. return -1;
  940. }
  941. }
  942. buffer_gets (imap->buf, &cmd);
  943. if (Verbose)
  944. puts (cmd); /* last part of line */
  945. }
  946. else
  947. {
  948. arg = next_arg (&cmd);
  949. if (!arg || (size_t) atoi (arg) != Tag)
  950. {
  951. puts ("wrong tag");
  952. return -1;
  953. }
  954. arg = next_arg (&cmd);
  955. if (!strcmp ("OK", arg))
  956. return 0;
  957. return -1;
  958. }
  959. }
  960. /* not reached */
  961. }
  962. /* add flags to existing flags */
  963. int
  964. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  965. {
  966. char buf[256];
  967. int i;
  968. buf[0] = 0;
  969. for (i = 0; i < D_MAX; i++)
  970. {
  971. if (flags & (1 << i))
  972. snprintf (buf + strlen (buf),
  973. sizeof (buf) - strlen (buf), "%s%s",
  974. (buf[0] != 0) ? " " : "", Flags[i]);
  975. }
  976. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  977. }
  978. int
  979. imap_expunge (imap_t * imap)
  980. {
  981. return imap_exec (imap, "EXPUNGE");
  982. }
  983. int
  984. imap_copy_message (imap_t * imap, unsigned int uid, const char *mailbox)
  985. {
  986. return imap_exec (imap, "UID COPY %u \"%s%s\"", uid, imap->prefix,
  987. mailbox);
  988. }
  989. int
  990. imap_append_message (imap_t * imap, int fd, message_t * msg)
  991. {
  992. char buf[1024];
  993. size_t len;
  994. size_t sofar = 0;
  995. int lines = 0;
  996. char flagstr[128];
  997. char *s;
  998. size_t i;
  999. size_t start, end;
  1000. char *arg;
  1001. /* ugh, we need to count the number of newlines */
  1002. while (sofar < msg->size)
  1003. {
  1004. len = msg->size - sofar;
  1005. if (len > sizeof (buf))
  1006. len = sizeof (buf);
  1007. len = read (fd, buf, len);
  1008. if (len == (size_t) - 1)
  1009. {
  1010. perror ("read");
  1011. return -1;
  1012. }
  1013. for (i = 0; i < len; i++)
  1014. if (buf[i] == '\n')
  1015. lines++;
  1016. sofar += len;
  1017. }
  1018. flagstr[0] = 0;
  1019. if (msg->flags)
  1020. {
  1021. strcpy (flagstr, "(");
  1022. if (msg->flags & D_DELETED)
  1023. snprintf (flagstr + strlen (flagstr),
  1024. sizeof (flagstr) - strlen (flagstr), "%s\\Deleted",
  1025. flagstr[1] ? " " : "");
  1026. if (msg->flags & D_ANSWERED)
  1027. snprintf (flagstr + strlen (flagstr),
  1028. sizeof (flagstr) - strlen (flagstr), "%s\\Answered",
  1029. flagstr[1] ? " " : "");
  1030. if (msg->flags & D_SEEN)
  1031. snprintf (flagstr + strlen (flagstr),
  1032. sizeof (flagstr) - strlen (flagstr), "%s\\Seen",
  1033. flagstr[1] ? " " : "");
  1034. if (msg->flags & D_FLAGGED)
  1035. snprintf (flagstr + strlen (flagstr),
  1036. sizeof (flagstr) - strlen (flagstr), "%s\\Flagged",
  1037. flagstr[1] ? " " : "");
  1038. if (msg->flags & D_DRAFT)
  1039. snprintf (flagstr + strlen (flagstr),
  1040. sizeof (flagstr) - strlen (flagstr), "%s\\Draft",
  1041. flagstr[1] ? " " : "");
  1042. snprintf (flagstr + strlen (flagstr),
  1043. sizeof (flagstr) - strlen (flagstr), ") ");
  1044. }
  1045. send_server (imap->sock, "APPEND %s%s %s{%d}",
  1046. imap->prefix, imap->box->box, flagstr, msg->size + lines);
  1047. if (buffer_gets (imap->buf, &s))
  1048. return -1;
  1049. if (Verbose)
  1050. puts (s);
  1051. if (*s != '+')
  1052. {
  1053. puts ("Error, expected `+' from server (aborting)");
  1054. return -1;
  1055. }
  1056. /* rewind */
  1057. lseek (fd, 0, 0);
  1058. sofar = 0;
  1059. while (sofar < msg->size)
  1060. {
  1061. len = msg->size - sofar;
  1062. if (len > sizeof (buf))
  1063. len = sizeof (buf);
  1064. len = read (fd, buf, len);
  1065. if (len == (size_t) - 1)
  1066. return -1;
  1067. start = 0;
  1068. while (start < len)
  1069. {
  1070. end = start;
  1071. while (end < len && buf[end] != '\n')
  1072. end++;
  1073. if (start != end)
  1074. socket_write (imap->sock, buf + start, end - start);
  1075. /* only send a crlf if we actually hit the end of a line. we
  1076. * might be in the middle of a line in which case we don't
  1077. * send one.
  1078. */
  1079. if (end != len)
  1080. socket_write (imap->sock, "\r\n", 2);
  1081. start = end + 1;
  1082. }
  1083. sofar += len;
  1084. }
  1085. socket_write (imap->sock, "\r\n", 2);
  1086. for (;;)
  1087. {
  1088. if (buffer_gets (imap->buf, &s))
  1089. return -1;
  1090. if (Verbose)
  1091. puts (s);
  1092. arg = next_arg (&s);
  1093. if (*arg == '*')
  1094. {
  1095. /* XXX just ignore it for now */
  1096. }
  1097. else if (atoi (arg) != (int) Tag)
  1098. {
  1099. puts ("wrong tag");
  1100. return -1;
  1101. }
  1102. else
  1103. {
  1104. int uid;
  1105. arg = next_arg (&s);
  1106. if (strcmp (arg, "OK"))
  1107. return -1;
  1108. arg = next_arg (&s);
  1109. if (*arg != '[')
  1110. break;
  1111. arg++;
  1112. if (strcasecmp ("APPENDUID", arg))
  1113. {
  1114. puts ("Error, expected APPENDUID");
  1115. break;
  1116. }
  1117. arg = next_arg (&s);
  1118. if (!arg)
  1119. break;
  1120. if (atoi (arg) != (int) imap->uidvalidity)
  1121. {
  1122. puts ("Error, UIDVALIDITY doesn't match APPENDUID");
  1123. return -1;
  1124. }
  1125. arg = next_arg (&s);
  1126. if (!arg)
  1127. break;
  1128. uid = strtol (arg, &s, 10);
  1129. if (*s != ']')
  1130. {
  1131. /* parse error */
  1132. break;
  1133. }
  1134. return uid;
  1135. }
  1136. }
  1137. return 0;
  1138. }