imap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /* $Id$
  2. *
  3. * isync - IMAP4 to maildir mailbox synchronizer
  4. * Copyright (C) 2000 Michael R. Elkins <me@mutt.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. #include <assert.h>
  21. #include <unistd.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <ctype.h>
  27. #include <sys/socket.h>
  28. #include <netinet/in.h>
  29. #include <arpa/inet.h>
  30. #include <netdb.h>
  31. #if HAVE_LIBSSL
  32. #include <openssl/err.h>
  33. #endif
  34. #include "isync.h"
  35. const char *Flags[] = {
  36. "\\Seen",
  37. "\\Answered",
  38. "\\Deleted",
  39. "\\Flagged",
  40. "\\Recent",
  41. "\\Draft"
  42. };
  43. #if HAVE_LIBSSL
  44. #define MAX_DEPTH 1
  45. SSL_CTX *SSLContext = 0;
  46. /* this gets called when a certificate is to be verified */
  47. static int
  48. verify_cert (SSL * ssl)
  49. {
  50. X509 *cert;
  51. int err;
  52. char buf[256];
  53. int ret = -1;
  54. BIO *bio;
  55. cert = SSL_get_peer_certificate (ssl);
  56. if (!cert)
  57. {
  58. puts ("Error, no server certificate");
  59. return -1;
  60. }
  61. err = SSL_get_verify_result (ssl);
  62. if (err == X509_V_OK)
  63. return 0;
  64. printf ("Error, can't verify certificate: %s (%d)\n",
  65. X509_verify_cert_error_string (err), err);
  66. X509_NAME_oneline (X509_get_subject_name (cert), buf, sizeof (buf));
  67. printf ("\nSubject: %s\n", buf);
  68. X509_NAME_oneline (X509_get_issuer_name (cert), buf, sizeof (buf));
  69. printf ("Issuer: %s\n", buf);
  70. bio = BIO_new (BIO_s_mem ());
  71. ASN1_TIME_print (bio, X509_get_notBefore (cert));
  72. memset (buf, 0, sizeof (buf));
  73. BIO_read (bio, buf, sizeof (buf) - 1);
  74. printf ("Valid from: %s\n", buf);
  75. ASN1_TIME_print (bio, X509_get_notAfter (cert));
  76. memset (buf, 0, sizeof (buf));
  77. BIO_read (bio, buf, sizeof (buf) - 1);
  78. BIO_free (bio);
  79. printf (" to: %s\n", buf);
  80. printf
  81. ("\n*** WARNING *** There is no way to verify this certificate. It is\n"
  82. " possible that a hostile attacker has replaced the\n"
  83. " server certificate. Continue at your own risk!\n");
  84. printf ("\nAccept this certificate anyway? [no]: ");
  85. fflush (stdout);
  86. if (fgets (buf, sizeof (buf), stdin) && (buf[0] == 'y' || buf[0] == 'Y'))
  87. {
  88. ret = 0;
  89. puts ("\n*** Fine, but don't say I didn't warn you!\n");
  90. }
  91. return ret;
  92. }
  93. static int
  94. init_ssl (config_t * conf)
  95. {
  96. if (!conf->cert_file)
  97. {
  98. puts ("Error, CertificateFile not defined");
  99. return -1;
  100. }
  101. SSL_library_init ();
  102. SSL_load_error_strings ();
  103. SSLContext = SSL_CTX_new (SSLv23_client_method ());
  104. if (access (conf->cert_file, F_OK))
  105. {
  106. if (errno != ENOENT)
  107. {
  108. perror ("access");
  109. return -1;
  110. }
  111. puts
  112. ("*** Warning, CertificateFile doesn't exist, can't verify server certificates");
  113. }
  114. else
  115. if (!SSL_CTX_load_verify_locations
  116. (SSLContext, conf->cert_file, NULL))
  117. {
  118. printf ("Error, SSL_CTX_load_verify_locations: %s\n",
  119. ERR_error_string (ERR_get_error (), 0));
  120. return -1;
  121. }
  122. if (!conf->use_sslv2)
  123. SSL_CTX_set_options (SSLContext, SSL_OP_NO_SSLv2);
  124. if (!conf->use_sslv3)
  125. SSL_CTX_set_options (SSLContext, SSL_OP_NO_SSLv3);
  126. if (!conf->use_tlsv1)
  127. SSL_CTX_set_options (SSLContext, SSL_OP_NO_TLSv1);
  128. /* we check the result of the verification after SSL_connect() */
  129. SSL_CTX_set_verify (SSLContext, SSL_VERIFY_NONE, 0);
  130. return 0;
  131. }
  132. #endif /* HAVE_LIBSSL */
  133. static int
  134. socket_read (Socket_t * sock, char *buf, size_t len)
  135. {
  136. #if HAVE_LIBSSL
  137. if (sock->use_ssl)
  138. return SSL_read (sock->ssl, buf, len);
  139. #endif
  140. return read (sock->fd, buf, len);
  141. }
  142. static int
  143. socket_write (Socket_t * sock, char *buf, size_t len)
  144. {
  145. #if HAVE_LIBSSL
  146. if (sock->use_ssl)
  147. return SSL_write (sock->ssl, buf, len);
  148. #endif
  149. return write (sock->fd, buf, len);
  150. }
  151. /* simple line buffering */
  152. static int
  153. buffer_gets (buffer_t * b, char **s)
  154. {
  155. int n;
  156. int start = b->offset;
  157. *s = b->buf + start;
  158. for (;;)
  159. {
  160. /* make sure we have enough data to read the \r\n sequence */
  161. if (b->offset + 1 >= b->bytes)
  162. {
  163. if (start != 0)
  164. {
  165. /* shift down used bytes */
  166. *s = b->buf;
  167. assert (start <= b->bytes);
  168. n = b->bytes - start;
  169. if (n)
  170. memmove (b->buf, b->buf + start, n);
  171. b->offset -= start;
  172. b->bytes = n;
  173. start = 0;
  174. }
  175. n =
  176. socket_read (b->sock, b->buf + b->bytes,
  177. sizeof (b->buf) - b->bytes);
  178. if (n <= 0)
  179. {
  180. if (n == -1)
  181. perror ("read");
  182. else
  183. puts ("EOF");
  184. return -1;
  185. }
  186. b->bytes += n;
  187. }
  188. if (b->buf[b->offset] == '\r')
  189. {
  190. assert (b->offset + 1 < b->bytes);
  191. if (b->buf[b->offset + 1] == '\n')
  192. {
  193. b->buf[b->offset] = 0; /* terminate the string */
  194. b->offset += 2; /* next line */
  195. // assert (strchr (*s, '\r') == 0);
  196. return 0;
  197. }
  198. }
  199. b->offset++;
  200. }
  201. /* not reached */
  202. }
  203. static int
  204. parse_fetch (imap_t * imap, list_t * list)
  205. {
  206. list_t *tmp;
  207. unsigned int uid = 0;
  208. unsigned int mask = 0;
  209. unsigned int size = 0;
  210. message_t *cur;
  211. if (!is_list (list))
  212. return -1;
  213. for (tmp = list->child; tmp; tmp = tmp->next)
  214. {
  215. if (is_atom (tmp))
  216. {
  217. if (!strcmp ("UID", tmp->val))
  218. {
  219. tmp = tmp->next;
  220. if (is_atom (tmp))
  221. {
  222. uid = atoi (tmp->val);
  223. if (uid < imap->minuid)
  224. {
  225. /* already saw this message */
  226. return 0;
  227. }
  228. else if (uid > imap->maxuid)
  229. imap->maxuid = uid;
  230. }
  231. else
  232. puts ("Error, unable to parse UID");
  233. }
  234. else if (!strcmp ("FLAGS", tmp->val))
  235. {
  236. tmp = tmp->next;
  237. if (is_list (tmp))
  238. {
  239. list_t *flags = tmp->child;
  240. for (; flags; flags = flags->next)
  241. {
  242. if (is_atom (flags))
  243. {
  244. if (!strcmp ("\\Seen", flags->val))
  245. mask |= D_SEEN;
  246. else if (!strcmp ("\\Flagged", flags->val))
  247. mask |= D_FLAGGED;
  248. else if (!strcmp ("\\Deleted", flags->val))
  249. mask |= D_DELETED;
  250. else if (!strcmp ("\\Answered", flags->val))
  251. mask |= D_ANSWERED;
  252. else if (!strcmp ("\\Draft", flags->val))
  253. mask |= D_DRAFT;
  254. else if (!strcmp ("\\Recent", flags->val))
  255. mask |= D_RECENT;
  256. else
  257. printf ("Warning, unknown flag %s\n",
  258. flags->val);
  259. }
  260. else
  261. puts ("Error, unable to parse FLAGS list");
  262. }
  263. }
  264. else
  265. puts ("Error, unable to parse FLAGS");
  266. }
  267. else if (!strcmp ("RFC822.SIZE", tmp->val))
  268. {
  269. tmp = tmp->next;
  270. if (is_atom (tmp))
  271. size = atol (tmp->val);
  272. }
  273. }
  274. }
  275. #if 0
  276. if (uid == 221)
  277. {
  278. int loop = 1;
  279. while (loop);
  280. }
  281. #endif
  282. cur = calloc (1, sizeof (message_t));
  283. cur->next = imap->msgs;
  284. imap->msgs = cur;
  285. if (mask & D_DELETED)
  286. imap->deleted++;
  287. cur->uid = uid;
  288. cur->flags = mask;
  289. cur->size = size;
  290. return 0;
  291. }
  292. static void
  293. parse_response_code (imap_t * imap, char *s)
  294. {
  295. char *arg;
  296. if (*s != '[')
  297. return; /* no response code */
  298. s++;
  299. arg = next_arg (&s);
  300. if (!strcmp ("UIDVALIDITY", arg))
  301. {
  302. arg = next_arg (&s);
  303. imap->uidvalidity = atol (arg);
  304. }
  305. else if (!strcmp ("ALERT", arg))
  306. {
  307. /* RFC2060 says that these messages MUST be displayed
  308. * to the user
  309. */
  310. fputs ("***ALERT*** ", stdout);
  311. puts (s);
  312. }
  313. }
  314. static int
  315. imap_exec (imap_t * imap, const char *fmt, ...)
  316. {
  317. va_list ap;
  318. char tmp[256];
  319. char buf[256];
  320. char *cmd;
  321. char *arg;
  322. char *arg1;
  323. va_start (ap, fmt);
  324. vsnprintf (tmp, sizeof (tmp), fmt, ap);
  325. va_end (ap);
  326. snprintf (buf, sizeof (buf), "%d %s\r\n", ++Tag, tmp);
  327. if (Verbose)
  328. fputs (buf, stdout);
  329. socket_write (imap->sock, buf, strlen (buf));
  330. for (;;)
  331. {
  332. if (buffer_gets (imap->buf, &cmd))
  333. return -1;
  334. if (Verbose)
  335. puts (cmd);
  336. arg = next_arg (&cmd);
  337. if (*arg == '*')
  338. {
  339. arg = next_arg (&cmd);
  340. if (!arg)
  341. {
  342. puts ("Error, unable to parse untagged command");
  343. return -1;
  344. }
  345. if (!strcmp ("NAMESPACE", arg))
  346. {
  347. imap->ns_personal = parse_list (cmd, &cmd);
  348. imap->ns_other = parse_list (cmd, &cmd);
  349. imap->ns_shared = parse_list (cmd, 0);
  350. }
  351. else if (!strcmp ("OK", arg) || !strcmp ("BAD", arg) ||
  352. !strcmp ("NO", arg) || !strcmp ("PREAUTH", arg) ||
  353. !strcmp ("BYE", arg))
  354. {
  355. parse_response_code (imap, cmd);
  356. }
  357. else if ((arg1 = next_arg (&cmd)))
  358. {
  359. if (!strcmp ("EXISTS", arg1))
  360. imap->count = atoi (arg);
  361. else if (!strcmp ("RECENT", arg1))
  362. imap->recent = atoi (arg);
  363. else if (!strcmp ("FETCH", arg1))
  364. {
  365. list_t *list;
  366. list = parse_list (cmd, 0);
  367. if (parse_fetch (imap, list))
  368. {
  369. free_list (list);
  370. return -1;
  371. }
  372. free_list (list);
  373. }
  374. }
  375. else
  376. {
  377. puts ("Error, unable to parse untagged command");
  378. return -1;
  379. }
  380. }
  381. else if ((size_t) atol (arg) != Tag)
  382. {
  383. puts ("wrong tag");
  384. return -1;
  385. }
  386. else
  387. {
  388. arg = next_arg (&cmd);
  389. parse_response_code (imap, cmd);
  390. if (!strcmp ("OK", arg))
  391. return 0;
  392. return -1;
  393. }
  394. }
  395. /* not reached */
  396. }
  397. /* `box' is the config info for the maildrop to sync. `minuid' is the
  398. * minimum UID to consider. in normal mode this will be 1, but in --fast
  399. * mode we only fetch messages newer than the last one seen in the local
  400. * mailbox.
  401. */
  402. imap_t *
  403. imap_open (config_t * box, unsigned int minuid)
  404. {
  405. int ret;
  406. imap_t *imap;
  407. int s;
  408. struct sockaddr_in sin;
  409. struct hostent *he;
  410. char *ns_prefix = "";
  411. #if HAVE_LIBSSL
  412. int use_ssl = 0;
  413. #endif
  414. #if HAVE_LIBSSL
  415. /* initialize SSL */
  416. if (init_ssl (box))
  417. return 0;
  418. #endif
  419. /* open connection to IMAP server */
  420. memset (&sin, 0, sizeof (sin));
  421. sin.sin_port = htons (box->port);
  422. sin.sin_family = AF_INET;
  423. printf ("Resolving %s... ", box->host);
  424. fflush (stdout);
  425. he = gethostbyname (box->host);
  426. if (!he)
  427. {
  428. perror ("gethostbyname");
  429. return 0;
  430. }
  431. puts ("ok");
  432. sin.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  433. s = socket (PF_INET, SOCK_STREAM, 0);
  434. printf ("Connecting to %s:%hu... ", inet_ntoa (sin.sin_addr),
  435. ntohs (sin.sin_port));
  436. fflush (stdout);
  437. if (connect (s, (struct sockaddr *) &sin, sizeof (sin)))
  438. {
  439. perror ("connect");
  440. exit (1);
  441. }
  442. puts ("ok");
  443. imap = calloc (1, sizeof (imap_t));
  444. imap->sock = calloc (1, sizeof (Socket_t));
  445. imap->sock->fd = s;
  446. imap->buf = calloc (1, sizeof (buffer_t));
  447. imap->buf->sock = imap->sock;
  448. imap->box = box;
  449. imap->minuid = minuid;
  450. #if HAVE_LIBSSL
  451. if (!box->use_imaps)
  452. {
  453. /* always try to select SSL support if available */
  454. ret = imap_exec (imap, "STARTTLS");
  455. if (!ret)
  456. use_ssl = 1;
  457. else if (box->require_ssl)
  458. {
  459. puts ("Error, SSL support not available");
  460. return 0;
  461. }
  462. else
  463. puts ("Warning, SSL support not available");
  464. }
  465. else
  466. use_ssl = 1;
  467. if (use_ssl)
  468. {
  469. imap->sock->ssl = SSL_new (SSLContext);
  470. SSL_set_fd (imap->sock->ssl, imap->sock->fd);
  471. ret = SSL_connect (imap->sock->ssl);
  472. if (ret <= 0)
  473. {
  474. ret = SSL_get_error (imap->sock->ssl, ret);
  475. printf ("Error, SSL_connect: %s\n", ERR_error_string (ret, 0));
  476. return 0;
  477. }
  478. /* verify the server certificate */
  479. if (verify_cert (imap->sock->ssl))
  480. return 0;
  481. imap->sock->use_ssl = 1;
  482. puts ("SSL support enabled");
  483. }
  484. #endif
  485. puts ("Logging in...");
  486. ret = imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user, box->pass);
  487. if (!ret)
  488. {
  489. /* get NAMESPACE info */
  490. if (box->use_namespace && !imap_exec (imap, "NAMESPACE"))
  491. {
  492. /* XXX for now assume personal namespace */
  493. if (is_list (imap->ns_personal) &&
  494. is_list (imap->ns_personal->child) &&
  495. is_atom (imap->ns_personal->child->child))
  496. {
  497. ns_prefix = imap->ns_personal->child->child->val;
  498. }
  499. }
  500. }
  501. if (!ret)
  502. {
  503. fputs ("Selecting mailbox... ", stdout);
  504. fflush (stdout);
  505. ret = imap_exec (imap, "SELECT %s%s", ns_prefix, box->box);
  506. if (!ret)
  507. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  508. }
  509. if (!ret)
  510. {
  511. puts ("Reading IMAP mailbox index");
  512. if (imap->count > 0)
  513. {
  514. ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  515. imap->minuid);
  516. }
  517. }
  518. if (ret)
  519. {
  520. imap_exec (imap, "LOGOUT");
  521. close (s);
  522. free (imap->buf);
  523. free (imap);
  524. imap = 0;
  525. }
  526. return imap;
  527. }
  528. void
  529. imap_close (imap_t * imap)
  530. {
  531. puts ("Closing IMAP connection");
  532. imap_exec (imap, "LOGOUT");
  533. }
  534. /* write a buffer stripping all \r bytes */
  535. static int
  536. write_strip (int fd, char *buf, size_t len)
  537. {
  538. size_t start = 0;
  539. size_t end = 0;
  540. while (start < len)
  541. {
  542. while (end < len && buf[end] != '\r')
  543. end++;
  544. write (fd, buf + start, end - start);
  545. end++;
  546. start = end;
  547. }
  548. return 0;
  549. }
  550. static void
  551. send_server (Socket_t * sock, const char *fmt, ...)
  552. {
  553. char buf[128];
  554. char cmd[128];
  555. va_list ap;
  556. va_start (ap, fmt);
  557. vsnprintf (buf, sizeof (buf), fmt, ap);
  558. va_end (ap);
  559. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  560. socket_write (sock, cmd, strlen (cmd));
  561. if (Verbose)
  562. fputs (cmd, stdout);
  563. }
  564. int
  565. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  566. {
  567. char *cmd;
  568. char *arg;
  569. size_t bytes;
  570. size_t n;
  571. char buf[1024];
  572. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  573. for (;;)
  574. {
  575. if (buffer_gets (imap->buf, &cmd))
  576. return -1;
  577. if (Verbose)
  578. puts (cmd);
  579. if (*cmd == '*')
  580. {
  581. /* need to figure out how long the message is
  582. * * <msgno> FETCH (RFC822 {<size>}
  583. */
  584. next_arg (&cmd); /* * */
  585. next_arg (&cmd); /* <msgno> */
  586. next_arg (&cmd); /* FETCH */
  587. while ((arg = next_arg (&cmd)) && *arg != '{')
  588. ;
  589. if (!arg)
  590. {
  591. puts ("parse error getting size");
  592. return -1;
  593. }
  594. bytes = strtol (arg + 1, 0, 10);
  595. // printf ("receiving %d byte message\n", bytes);
  596. /* dump whats left over in the input buffer */
  597. n = imap->buf->bytes - imap->buf->offset;
  598. if (n > bytes)
  599. {
  600. /* the entire message fit in the buffer */
  601. n = bytes;
  602. }
  603. /* ick. we have to strip out the \r\n line endings, so
  604. * i can't just dump the raw bytes to disk.
  605. */
  606. write_strip (fd, imap->buf->buf + imap->buf->offset, n);
  607. bytes -= n;
  608. // printf ("wrote %d buffered bytes\n", n);
  609. /* mark that we used part of the buffer */
  610. imap->buf->offset += n;
  611. /* now read the rest of the message */
  612. while (bytes > 0)
  613. {
  614. n = bytes;
  615. if (n > sizeof (buf))
  616. n = sizeof (buf);
  617. n = socket_read (imap->sock, buf, n);
  618. if (n > 0)
  619. {
  620. // printf("imap_fetch_message:%d:read %d bytes\n", __LINE__, n);
  621. write_strip (fd, buf, n);
  622. bytes -= n;
  623. }
  624. else
  625. {
  626. if (n == (size_t) - 1)
  627. perror ("read");
  628. else
  629. puts ("EOF");
  630. return -1;
  631. }
  632. }
  633. // puts ("finished fetching msg");
  634. buffer_gets (imap->buf, &cmd);
  635. if (Verbose)
  636. puts (cmd); /* last part of line */
  637. }
  638. else
  639. {
  640. arg = next_arg (&cmd);
  641. if (!arg || (size_t) atoi (arg) != Tag)
  642. {
  643. puts ("wrong tag");
  644. return -1;
  645. }
  646. arg = next_arg (&cmd);
  647. if (!strcmp ("OK", arg))
  648. return 0;
  649. return -1;
  650. }
  651. }
  652. /* not reached */
  653. }
  654. /* add flags to existing flags */
  655. int
  656. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  657. {
  658. char buf[256];
  659. int i;
  660. buf[0] = 0;
  661. for (i = 0; i < D_MAX; i++)
  662. {
  663. if (flags & (1 << i))
  664. snprintf (buf + strlen (buf),
  665. sizeof (buf) - strlen (buf), "%s%s",
  666. (buf[0] != 0) ? " " : "", Flags[i]);
  667. }
  668. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  669. }
  670. int
  671. imap_expunge (imap_t * imap)
  672. {
  673. return imap_exec (imap, "EXPUNGE");
  674. }