imap.c 26 KB

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