imap.c 28 KB

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