imap.c 29 KB

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