imap.c 14 KB

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