imap.c 28 KB

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