imap.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. /* we check the result of the verification after SSL_connect() */
  123. SSL_CTX_set_verify (SSLContext, SSL_VERIFY_NONE, 0);
  124. return 0;
  125. }
  126. #endif /* HAVE_LIBSSL */
  127. static int
  128. socket_read (Socket_t * sock, char *buf, size_t len)
  129. {
  130. #if HAVE_LIBSSL
  131. if (sock->use_ssl)
  132. return SSL_read (sock->ssl, buf, len);
  133. #endif
  134. return read (sock->fd, buf, len);
  135. }
  136. static int
  137. socket_write (Socket_t * sock, char *buf, size_t len)
  138. {
  139. #if HAVE_LIBSSL
  140. if (sock->use_ssl)
  141. return SSL_write (sock->ssl, buf, len);
  142. #endif
  143. return write (sock->fd, buf, len);
  144. }
  145. /* simple line buffering */
  146. static int
  147. buffer_gets (buffer_t * b, char **s)
  148. {
  149. int n;
  150. int start = b->offset;
  151. *s = b->buf + start;
  152. for (;;)
  153. {
  154. if (b->offset + 2 > b->bytes)
  155. {
  156. /* shift down used bytes */
  157. *s = b->buf;
  158. assert (start <= b->bytes);
  159. n = b->bytes - start;
  160. if (n)
  161. memmove (b->buf, b->buf + start, n);
  162. b->offset = n;
  163. start = 0;
  164. n =
  165. socket_read (b->sock, b->buf + b->offset,
  166. sizeof (b->buf) - b->offset);
  167. if (n <= 0)
  168. {
  169. if (n == -1)
  170. perror ("read");
  171. else
  172. puts ("EOF");
  173. return -1;
  174. }
  175. b->bytes = b->offset + n;
  176. // printf ("buffer_gets:read %d bytes\n", n);
  177. }
  178. if (b->buf[b->offset] == '\r')
  179. {
  180. if (b->buf[b->offset + 1] == '\n')
  181. {
  182. b->buf[b->offset] = 0; /* terminate the string */
  183. b->offset += 2; /* next line */
  184. return 0;
  185. }
  186. }
  187. b->offset++;
  188. }
  189. /* not reached */
  190. }
  191. static int
  192. parse_fetch (imap_t * imap, list_t * list)
  193. {
  194. list_t *tmp;
  195. unsigned int uid = 0;
  196. unsigned int mask = 0;
  197. unsigned int size = 0;
  198. message_t *cur;
  199. if (!is_list (list))
  200. return -1;
  201. for (tmp = list->child; tmp; tmp = tmp->next)
  202. {
  203. if (is_atom (tmp))
  204. {
  205. if (!strcmp ("UID", tmp->val))
  206. {
  207. tmp = tmp->next;
  208. if (is_atom (tmp))
  209. {
  210. uid = atoi (tmp->val);
  211. if (uid < imap->minuid)
  212. {
  213. /* already saw this message */
  214. return 0;
  215. }
  216. }
  217. else
  218. puts ("Error, unable to parse UID");
  219. }
  220. else if (!strcmp ("FLAGS", tmp->val))
  221. {
  222. tmp = tmp->next;
  223. if (is_list (tmp))
  224. {
  225. list_t *flags = tmp->child;
  226. for (; flags; flags = flags->next)
  227. {
  228. if (is_atom (flags))
  229. {
  230. if (!strcmp ("\\Seen", flags->val))
  231. mask |= D_SEEN;
  232. else if (!strcmp ("\\Flagged", flags->val))
  233. mask |= D_FLAGGED;
  234. else if (!strcmp ("\\Deleted", flags->val))
  235. mask |= D_DELETED;
  236. else if (!strcmp ("\\Answered", flags->val))
  237. mask |= D_ANSWERED;
  238. else if (!strcmp ("\\Draft", flags->val))
  239. mask |= D_DRAFT;
  240. else if (!strcmp ("\\Recent", flags->val))
  241. mask |= D_RECENT;
  242. else
  243. printf ("Warning, unknown flag %s\n",
  244. flags->val);
  245. }
  246. else
  247. puts ("Error, unable to parse FLAGS list");
  248. }
  249. }
  250. else
  251. puts ("Error, unable to parse FLAGS");
  252. }
  253. else if (!strcmp ("RFC822.SIZE", tmp->val))
  254. {
  255. tmp = tmp->next;
  256. if (is_atom (tmp))
  257. size = atol (tmp->val);
  258. }
  259. }
  260. }
  261. cur = calloc (1, sizeof (message_t));
  262. cur->next = imap->msgs;
  263. imap->msgs = cur;
  264. if (mask & D_DELETED)
  265. imap->deleted++;
  266. cur->uid = uid;
  267. cur->flags = mask;
  268. cur->size = size;
  269. return 0;
  270. }
  271. static void
  272. parse_response_code (imap_t * imap, char *s)
  273. {
  274. char *arg;
  275. if (*s != '[')
  276. return; /* no response code */
  277. s++;
  278. arg = next_arg (&s);
  279. if (!strcmp ("UIDVALIDITY", arg))
  280. {
  281. arg = next_arg (&s);
  282. imap->uidvalidity = atol (arg);
  283. }
  284. else if (!strcmp ("ALERT", arg))
  285. {
  286. /* RFC2060 says that these messages MUST be displayed
  287. * to the user
  288. */
  289. fputs ("***ALERT*** ", stdout);
  290. puts (s);
  291. }
  292. }
  293. static int
  294. imap_exec (imap_t * imap, const char *fmt, ...)
  295. {
  296. va_list ap;
  297. char tmp[256];
  298. char buf[256];
  299. char *cmd;
  300. char *arg;
  301. char *arg1;
  302. va_start (ap, fmt);
  303. vsnprintf (tmp, sizeof (tmp), fmt, ap);
  304. va_end (ap);
  305. snprintf (buf, sizeof (buf), "%d %s\r\n", ++Tag, tmp);
  306. if (Verbose)
  307. fputs (buf, stdout);
  308. socket_write (imap->sock, buf, strlen (buf));
  309. for (;;)
  310. {
  311. if (buffer_gets (imap->buf, &cmd))
  312. return -1;
  313. if (Verbose)
  314. puts (cmd);
  315. arg = next_arg (&cmd);
  316. if (*arg == '*')
  317. {
  318. arg = next_arg (&cmd);
  319. if (!arg)
  320. {
  321. puts ("Error, unable to parse untagged command");
  322. return -1;
  323. }
  324. if (!strcmp ("NAMESPACE", arg))
  325. {
  326. imap->ns_personal = parse_list (cmd, &cmd);
  327. imap->ns_other = parse_list (cmd, &cmd);
  328. imap->ns_shared = parse_list (cmd, 0);
  329. }
  330. else if (!strcmp ("OK", arg) || !strcmp ("BAD", arg) ||
  331. !strcmp ("NO", arg) || !strcmp ("PREAUTH", arg) ||
  332. !strcmp ("BYE", arg))
  333. {
  334. parse_response_code (imap, cmd);
  335. }
  336. else if ((arg1 = next_arg (&cmd)))
  337. {
  338. if (!strcmp ("EXISTS", arg1))
  339. imap->count = atoi (arg);
  340. else if (!strcmp ("RECENT", arg1))
  341. imap->recent = atoi (arg);
  342. else if (!strcmp ("FETCH", arg1))
  343. {
  344. list_t *list;
  345. list = parse_list (cmd, 0);
  346. if (parse_fetch (imap, list))
  347. {
  348. free_list (list);
  349. return -1;
  350. }
  351. free_list (list);
  352. }
  353. }
  354. else
  355. {
  356. puts ("Error, unable to parse untagged command");
  357. return -1;
  358. }
  359. }
  360. else if ((size_t) atol (arg) != Tag)
  361. {
  362. puts ("wrong tag");
  363. return -1;
  364. }
  365. else
  366. {
  367. arg = next_arg (&cmd);
  368. parse_response_code (imap, cmd);
  369. if (!strcmp ("OK", arg))
  370. return 0;
  371. return -1;
  372. }
  373. }
  374. /* not reached */
  375. }
  376. /* `box' is the config info for the maildrop to sync. `minuid' is the
  377. * minimum UID to consider. in normal mode this will be 1, but in --fast
  378. * mode we only fetch messages newer than the last one seen in the local
  379. * mailbox.
  380. */
  381. imap_t *
  382. imap_open (config_t * box, unsigned int minuid)
  383. {
  384. int ret;
  385. imap_t *imap;
  386. int s;
  387. struct sockaddr_in sin;
  388. struct hostent *he;
  389. char *ns_prefix = "";
  390. #if HAVE_LIBSSL
  391. int use_ssl = 0;
  392. #endif
  393. #if HAVE_LIBSSL
  394. /* initialize SSL */
  395. if (init_ssl (box))
  396. return 0;
  397. #endif
  398. /* open connection to IMAP server */
  399. memset (&sin, 0, sizeof (sin));
  400. sin.sin_port = htons (box->port);
  401. sin.sin_family = AF_INET;
  402. printf ("Resolving %s... ", box->host);
  403. fflush (stdout);
  404. he = gethostbyname (box->host);
  405. if (!he)
  406. {
  407. perror ("gethostbyname");
  408. return 0;
  409. }
  410. puts ("ok");
  411. sin.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  412. s = socket (PF_INET, SOCK_STREAM, 0);
  413. printf ("Connecting to %s:%hu... ", inet_ntoa (sin.sin_addr),
  414. ntohs (sin.sin_port));
  415. fflush (stdout);
  416. if (connect (s, (struct sockaddr *) &sin, sizeof (sin)))
  417. {
  418. perror ("connect");
  419. exit (1);
  420. }
  421. puts ("ok");
  422. imap = calloc (1, sizeof (imap_t));
  423. imap->sock = calloc (1, sizeof (Socket_t));
  424. imap->sock->fd = s;
  425. imap->buf = calloc (1, sizeof (buffer_t));
  426. imap->buf->sock = imap->sock;
  427. imap->box = box;
  428. imap->minuid = minuid;
  429. #if HAVE_LIBSSL
  430. if (!box->use_imaps)
  431. {
  432. /* always try to select SSL support if available */
  433. ret = imap_exec (imap, "STARTTLS");
  434. if (!ret)
  435. use_ssl = 1;
  436. else if (box->require_ssl)
  437. {
  438. puts ("Error, SSL support not available");
  439. return 0;
  440. }
  441. else
  442. puts ("Warning, SSL support not available");
  443. }
  444. else
  445. use_ssl = 1;
  446. if (use_ssl)
  447. {
  448. imap->sock->ssl = SSL_new (SSLContext);
  449. SSL_set_fd (imap->sock->ssl, imap->sock->fd);
  450. ret = SSL_connect (imap->sock->ssl);
  451. if (ret <= 0)
  452. {
  453. ret = SSL_get_error (imap->sock->ssl, ret);
  454. printf ("Error, SSL_connect: %s\n", ERR_error_string (ret, 0));
  455. return 0;
  456. }
  457. /* verify the server certificate */
  458. if (verify_cert (imap->sock->ssl))
  459. return 0;
  460. imap->sock->use_ssl = 1;
  461. puts ("SSL support enabled");
  462. }
  463. #endif
  464. puts ("Logging in...");
  465. ret = imap_exec (imap, "LOGIN %s %s", box->user, box->pass);
  466. if (!ret)
  467. {
  468. /* get NAMESPACE info */
  469. if (!imap_exec (imap, "NAMESPACE"))
  470. {
  471. /* XXX for now assume personal namespace */
  472. if (is_list (imap->ns_personal) &&
  473. is_list (imap->ns_personal->child) &&
  474. is_atom (imap->ns_personal->child->child))
  475. {
  476. ns_prefix = imap->ns_personal->child->child->val;
  477. }
  478. }
  479. }
  480. if (!ret)
  481. {
  482. fputs ("Selecting mailbox... ", stdout);
  483. fflush (stdout);
  484. ret = imap_exec (imap, "SELECT %s%s", ns_prefix, box->box);
  485. if (!ret)
  486. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  487. }
  488. if (!ret)
  489. {
  490. puts ("Reading IMAP mailbox index");
  491. if (imap->count > 0)
  492. {
  493. ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  494. imap->minuid);
  495. }
  496. }
  497. if (ret)
  498. {
  499. imap_exec (imap, "LOGOUT");
  500. close (s);
  501. free (imap->buf);
  502. free (imap);
  503. imap = 0;
  504. }
  505. return imap;
  506. }
  507. void
  508. imap_close (imap_t * imap)
  509. {
  510. puts ("Closing IMAP connection");
  511. imap_exec (imap, "LOGOUT");
  512. }
  513. /* write a buffer stripping all \r bytes */
  514. static int
  515. write_strip (int fd, char *buf, size_t len)
  516. {
  517. size_t start = 0;
  518. size_t end = 0;
  519. while (start < len)
  520. {
  521. while (end < len && buf[end] != '\r')
  522. end++;
  523. write (fd, buf + start, end - start);
  524. end++;
  525. start = end;
  526. }
  527. return 0;
  528. }
  529. static void
  530. send_server (Socket_t * sock, const char *fmt, ...)
  531. {
  532. char buf[128];
  533. char cmd[128];
  534. va_list ap;
  535. va_start (ap, fmt);
  536. vsnprintf (buf, sizeof (buf), fmt, ap);
  537. va_end (ap);
  538. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  539. socket_write (sock, cmd, strlen (cmd));
  540. if (Verbose)
  541. fputs (cmd, stdout);
  542. }
  543. int
  544. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  545. {
  546. char *cmd;
  547. char *arg;
  548. size_t bytes;
  549. size_t n;
  550. char buf[1024];
  551. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  552. for (;;)
  553. {
  554. if (buffer_gets (imap->buf, &cmd))
  555. return -1;
  556. if (Verbose)
  557. puts (cmd);
  558. if (*cmd == '*')
  559. {
  560. /* need to figure out how long the message is
  561. * * <msgno> FETCH (RFC822 {<size>}
  562. */
  563. next_arg (&cmd); /* * */
  564. next_arg (&cmd); /* <msgno> */
  565. next_arg (&cmd); /* FETCH */
  566. while ((arg = next_arg (&cmd)) && *arg != '{')
  567. ;
  568. if (!arg)
  569. {
  570. puts ("parse error getting size");
  571. return -1;
  572. }
  573. bytes = strtol (arg + 1, 0, 10);
  574. // printf ("receiving %d byte message\n", bytes);
  575. /* dump whats left over in the input buffer */
  576. n = imap->buf->bytes - imap->buf->offset;
  577. if (n > bytes)
  578. {
  579. /* the entire message fit in the buffer */
  580. n = bytes;
  581. }
  582. /* ick. we have to strip out the \r\n line endings, so
  583. * i can't just dump the raw bytes to disk.
  584. */
  585. write_strip (fd, imap->buf->buf + imap->buf->offset, n);
  586. bytes -= n;
  587. // printf ("wrote %d buffered bytes\n", n);
  588. /* mark that we used part of the buffer */
  589. imap->buf->offset += n;
  590. /* now read the rest of the message */
  591. while (bytes > 0)
  592. {
  593. n = bytes;
  594. if (n > sizeof (buf))
  595. n = sizeof (buf);
  596. n = socket_read (imap->sock, buf, n);
  597. if (n > 0)
  598. {
  599. // printf("imap_fetch_message:%d:read %d bytes\n", __LINE__, n);
  600. write_strip (fd, buf, n);
  601. bytes -= n;
  602. }
  603. else
  604. {
  605. if (n == (size_t) - 1)
  606. perror ("read");
  607. else
  608. puts ("EOF");
  609. return -1;
  610. }
  611. }
  612. // puts ("finished fetching msg");
  613. buffer_gets (imap->buf, &cmd);
  614. if (Verbose)
  615. puts (cmd); /* last part of line */
  616. }
  617. else
  618. {
  619. arg = next_arg (&cmd);
  620. if (!arg || (size_t) atoi (arg) != Tag)
  621. {
  622. puts ("wrong tag");
  623. return -1;
  624. }
  625. arg = next_arg (&cmd);
  626. if (!strcmp ("OK", arg))
  627. return 0;
  628. return -1;
  629. }
  630. }
  631. /* not reached */
  632. }
  633. /* add flags to existing flags */
  634. int
  635. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  636. {
  637. char buf[256];
  638. int i;
  639. buf[0] = 0;
  640. for (i = 0; i < D_MAX; i++)
  641. {
  642. if (flags & (1 << i))
  643. snprintf (buf + strlen (buf),
  644. sizeof (buf) - strlen (buf), "%s%s",
  645. (buf[0] != 0) ? " " : "", Flags[i]);
  646. }
  647. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  648. }
  649. int
  650. imap_expunge (imap_t * imap)
  651. {
  652. return imap_exec (imap, "EXPUNGE");
  653. }