imap.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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. void
  44. free_message (message_t * msg)
  45. {
  46. message_t *tmp;
  47. while (msg)
  48. {
  49. tmp = msg;
  50. msg = msg->next;
  51. if (tmp->file)
  52. free (tmp->file);
  53. free (tmp);
  54. }
  55. }
  56. #if HAVE_LIBSSL
  57. #define MAX_DEPTH 1
  58. SSL_CTX *SSLContext = 0;
  59. /* this gets called when a certificate is to be verified */
  60. static int
  61. verify_cert (SSL * ssl)
  62. {
  63. X509 *cert;
  64. int err;
  65. char buf[256];
  66. int ret = -1;
  67. BIO *bio;
  68. cert = SSL_get_peer_certificate (ssl);
  69. if (!cert)
  70. {
  71. puts ("Error, no server certificate");
  72. return -1;
  73. }
  74. err = SSL_get_verify_result (ssl);
  75. if (err == X509_V_OK)
  76. return 0;
  77. printf ("Error, can't verify certificate: %s (%d)\n",
  78. X509_verify_cert_error_string (err), err);
  79. X509_NAME_oneline (X509_get_subject_name (cert), buf, sizeof (buf));
  80. printf ("\nSubject: %s\n", buf);
  81. X509_NAME_oneline (X509_get_issuer_name (cert), buf, sizeof (buf));
  82. printf ("Issuer: %s\n", buf);
  83. bio = BIO_new (BIO_s_mem ());
  84. ASN1_TIME_print (bio, X509_get_notBefore (cert));
  85. memset (buf, 0, sizeof (buf));
  86. BIO_read (bio, buf, sizeof (buf) - 1);
  87. printf ("Valid from: %s\n", buf);
  88. ASN1_TIME_print (bio, X509_get_notAfter (cert));
  89. memset (buf, 0, sizeof (buf));
  90. BIO_read (bio, buf, sizeof (buf) - 1);
  91. BIO_free (bio);
  92. printf (" to: %s\n", buf);
  93. printf
  94. ("\n*** WARNING *** There is no way to verify this certificate. It is\n"
  95. " possible that a hostile attacker has replaced the\n"
  96. " server certificate. Continue at your own risk!\n");
  97. printf ("\nAccept this certificate anyway? [no]: ");
  98. fflush (stdout);
  99. if (fgets (buf, sizeof (buf), stdin) && (buf[0] == 'y' || buf[0] == 'Y'))
  100. {
  101. ret = 0;
  102. puts ("\n*** Fine, but don't say I didn't warn you!\n");
  103. }
  104. return ret;
  105. }
  106. static int
  107. init_ssl (config_t * conf)
  108. {
  109. if (!conf->cert_file)
  110. {
  111. puts ("Error, CertificateFile not defined");
  112. return -1;
  113. }
  114. SSL_library_init ();
  115. SSL_load_error_strings ();
  116. SSLContext = SSL_CTX_new (SSLv23_client_method ());
  117. if (access (conf->cert_file, F_OK))
  118. {
  119. if (errno != ENOENT)
  120. {
  121. perror ("access");
  122. return -1;
  123. }
  124. puts
  125. ("*** Warning, CertificateFile doesn't exist, can't verify server certificates");
  126. }
  127. else
  128. if (!SSL_CTX_load_verify_locations
  129. (SSLContext, conf->cert_file, NULL))
  130. {
  131. printf ("Error, SSL_CTX_load_verify_locations: %s\n",
  132. ERR_error_string (ERR_get_error (), 0));
  133. return -1;
  134. }
  135. if (!conf->use_sslv2)
  136. SSL_CTX_set_options (SSLContext, SSL_OP_NO_SSLv2);
  137. if (!conf->use_sslv3)
  138. SSL_CTX_set_options (SSLContext, SSL_OP_NO_SSLv3);
  139. if (!conf->use_tlsv1)
  140. SSL_CTX_set_options (SSLContext, SSL_OP_NO_TLSv1);
  141. /* we check the result of the verification after SSL_connect() */
  142. SSL_CTX_set_verify (SSLContext, SSL_VERIFY_NONE, 0);
  143. return 0;
  144. }
  145. #endif /* HAVE_LIBSSL */
  146. static int
  147. socket_read (Socket_t * sock, char *buf, size_t len)
  148. {
  149. #if HAVE_LIBSSL
  150. if (sock->use_ssl)
  151. return SSL_read (sock->ssl, buf, len);
  152. #endif
  153. return read (sock->fd, buf, len);
  154. }
  155. static int
  156. socket_write (Socket_t * sock, char *buf, size_t len)
  157. {
  158. #if HAVE_LIBSSL
  159. if (sock->use_ssl)
  160. return SSL_write (sock->ssl, buf, len);
  161. #endif
  162. return write (sock->fd, buf, len);
  163. }
  164. /* simple line buffering */
  165. static int
  166. buffer_gets (buffer_t * b, char **s)
  167. {
  168. int n;
  169. int start = b->offset;
  170. *s = b->buf + start;
  171. for (;;)
  172. {
  173. /* make sure we have enough data to read the \r\n sequence */
  174. if (b->offset + 1 >= b->bytes)
  175. {
  176. if (start != 0)
  177. {
  178. /* shift down used bytes */
  179. *s = b->buf;
  180. assert (start <= b->bytes);
  181. n = b->bytes - start;
  182. if (n)
  183. memmove (b->buf, b->buf + start, n);
  184. b->offset -= start;
  185. b->bytes = n;
  186. start = 0;
  187. }
  188. n =
  189. socket_read (b->sock, b->buf + b->bytes,
  190. sizeof (b->buf) - b->bytes);
  191. if (n <= 0)
  192. {
  193. if (n == -1)
  194. perror ("read");
  195. else
  196. puts ("EOF");
  197. return -1;
  198. }
  199. b->bytes += n;
  200. }
  201. if (b->buf[b->offset] == '\r')
  202. {
  203. assert (b->offset + 1 < b->bytes);
  204. if (b->buf[b->offset + 1] == '\n')
  205. {
  206. b->buf[b->offset] = 0; /* terminate the string */
  207. b->offset += 2; /* next line */
  208. // assert (strchr (*s, '\r') == 0);
  209. return 0;
  210. }
  211. }
  212. b->offset++;
  213. }
  214. /* not reached */
  215. }
  216. static int
  217. parse_fetch (imap_t * imap, list_t * list)
  218. {
  219. list_t *tmp;
  220. unsigned int uid = 0;
  221. unsigned int mask = 0;
  222. unsigned int size = 0;
  223. message_t *cur;
  224. if (!is_list (list))
  225. return -1;
  226. for (tmp = list->child; tmp; tmp = tmp->next)
  227. {
  228. if (is_atom (tmp))
  229. {
  230. if (!strcmp ("UID", tmp->val))
  231. {
  232. tmp = tmp->next;
  233. if (is_atom (tmp))
  234. {
  235. uid = atoi (tmp->val);
  236. if (uid < imap->minuid)
  237. {
  238. /* already saw this message */
  239. return 0;
  240. }
  241. else if (uid > imap->maxuid)
  242. imap->maxuid = uid;
  243. }
  244. else
  245. puts ("Error, unable to parse UID");
  246. }
  247. else if (!strcmp ("FLAGS", tmp->val))
  248. {
  249. tmp = tmp->next;
  250. if (is_list (tmp))
  251. {
  252. list_t *flags = tmp->child;
  253. for (; flags; flags = flags->next)
  254. {
  255. if (is_atom (flags))
  256. {
  257. if (!strcmp ("\\Seen", flags->val))
  258. mask |= D_SEEN;
  259. else if (!strcmp ("\\Flagged", flags->val))
  260. mask |= D_FLAGGED;
  261. else if (!strcmp ("\\Deleted", flags->val))
  262. mask |= D_DELETED;
  263. else if (!strcmp ("\\Answered", flags->val))
  264. mask |= D_ANSWERED;
  265. else if (!strcmp ("\\Draft", flags->val))
  266. mask |= D_DRAFT;
  267. else if (!strcmp ("\\Recent", flags->val))
  268. mask |= D_RECENT;
  269. else
  270. printf ("Warning, unknown flag %s\n",
  271. flags->val);
  272. }
  273. else
  274. puts ("Error, unable to parse FLAGS list");
  275. }
  276. }
  277. else
  278. puts ("Error, unable to parse FLAGS");
  279. }
  280. else if (!strcmp ("RFC822.SIZE", tmp->val))
  281. {
  282. tmp = tmp->next;
  283. if (is_atom (tmp))
  284. size = atol (tmp->val);
  285. }
  286. }
  287. }
  288. cur = calloc (1, sizeof (message_t));
  289. cur->next = imap->msgs;
  290. imap->msgs = cur;
  291. if (mask & D_DELETED)
  292. imap->deleted++;
  293. cur->uid = uid;
  294. cur->flags = mask;
  295. cur->size = size;
  296. return 0;
  297. }
  298. static void
  299. parse_response_code (imap_t * imap, char *s)
  300. {
  301. char *arg;
  302. if (*s != '[')
  303. return; /* no response code */
  304. s++;
  305. arg = next_arg (&s);
  306. if (!strcmp ("UIDVALIDITY", arg))
  307. {
  308. arg = next_arg (&s);
  309. imap->uidvalidity = atol (arg);
  310. }
  311. else if (!strcmp ("ALERT", arg))
  312. {
  313. /* RFC2060 says that these messages MUST be displayed
  314. * to the user
  315. */
  316. fputs ("***ALERT*** ", stdout);
  317. puts (s);
  318. }
  319. }
  320. static int
  321. imap_exec (imap_t * imap, const char *fmt, ...)
  322. {
  323. va_list ap;
  324. char tmp[256];
  325. char buf[256];
  326. char *cmd;
  327. char *arg;
  328. char *arg1;
  329. va_start (ap, fmt);
  330. vsnprintf (tmp, sizeof (tmp), fmt, ap);
  331. va_end (ap);
  332. snprintf (buf, sizeof (buf), "%d %s\r\n", ++Tag, tmp);
  333. if (Verbose)
  334. fputs (buf, stdout);
  335. socket_write (imap->sock, buf, strlen (buf));
  336. for (;;)
  337. {
  338. if (buffer_gets (imap->buf, &cmd))
  339. return -1;
  340. if (Verbose)
  341. puts (cmd);
  342. arg = next_arg (&cmd);
  343. if (*arg == '*')
  344. {
  345. arg = next_arg (&cmd);
  346. if (!arg)
  347. {
  348. puts ("Error, unable to parse untagged command");
  349. return -1;
  350. }
  351. if (!strcmp ("NAMESPACE", arg))
  352. {
  353. imap->ns_personal = parse_list (cmd, &cmd);
  354. imap->ns_other = parse_list (cmd, &cmd);
  355. imap->ns_shared = parse_list (cmd, 0);
  356. }
  357. else if (!strcmp ("OK", arg) || !strcmp ("BAD", arg) ||
  358. !strcmp ("NO", arg) || !strcmp ("PREAUTH", arg) ||
  359. !strcmp ("BYE", arg))
  360. {
  361. parse_response_code (imap, cmd);
  362. }
  363. else if (!strcmp ("CAPABILITY", arg))
  364. {
  365. #if HAVE_LIBSSL
  366. while ((arg = next_arg (&cmd)))
  367. {
  368. if (!strcmp ("STARTTLS", arg))
  369. imap->have_starttls = 1;
  370. else if (!strcmp ("AUTH=CRAM-MD5", arg))
  371. imap->have_cram = 1;
  372. else if (!strcmp ("NAMESPACE", arg))
  373. imap->have_namespace = 1;
  374. }
  375. #endif
  376. }
  377. else if ((arg1 = next_arg (&cmd)))
  378. {
  379. if (!strcmp ("EXISTS", arg1))
  380. imap->count = atoi (arg);
  381. else if (!strcmp ("RECENT", arg1))
  382. imap->recent = atoi (arg);
  383. else if (!strcmp ("FETCH", arg1))
  384. {
  385. list_t *list;
  386. list = parse_list (cmd, 0);
  387. if (parse_fetch (imap, list))
  388. {
  389. free_list (list);
  390. return -1;
  391. }
  392. free_list (list);
  393. }
  394. }
  395. else
  396. {
  397. puts ("Error, unable to parse untagged command");
  398. return -1;
  399. }
  400. }
  401. #if HAVE_LIBSSL
  402. else if (*arg == '+')
  403. {
  404. char *resp;
  405. if (!imap->cram)
  406. {
  407. puts ("Error, not doing CRAM-MD5 authentication");
  408. return -1;
  409. }
  410. resp = cram (cmd, imap->box->user, imap->box->pass);
  411. socket_write (imap->sock, resp, strlen (resp));
  412. if (Verbose)
  413. puts (resp);
  414. socket_write (imap->sock, "\r\n", 2);
  415. free (resp);
  416. imap->cram = 0;
  417. }
  418. #endif
  419. else if ((size_t) atol (arg) != Tag)
  420. {
  421. puts ("wrong tag");
  422. return -1;
  423. }
  424. else
  425. {
  426. arg = next_arg (&cmd);
  427. parse_response_code (imap, cmd);
  428. if (!strcmp ("OK", arg))
  429. return 0;
  430. return -1;
  431. }
  432. }
  433. /* not reached */
  434. }
  435. /* `box' is the config info for the maildrop to sync. `minuid' is the
  436. * minimum UID to consider. in normal mode this will be 1, but in --fast
  437. * mode we only fetch messages newer than the last one seen in the local
  438. * mailbox.
  439. */
  440. imap_t *
  441. imap_open (config_t * box, unsigned int minuid, imap_t * imap)
  442. {
  443. int ret;
  444. int s;
  445. struct sockaddr_in sin;
  446. struct hostent *he;
  447. int reuse = 0;
  448. #if HAVE_LIBSSL
  449. int use_ssl = 0;
  450. #endif
  451. if (imap)
  452. {
  453. /* determine whether or not we can reuse the existing session */
  454. if (strcmp (box->host, imap->box->host) ||
  455. strcmp (box->user, imap->box->user) ||
  456. box->port != imap->box->port
  457. #if HAVE_LIBSSL
  458. /* ensure that security requirements are met */
  459. || (box->require_ssl ^ imap->box->require_ssl)
  460. || (box->require_cram ^ imap->box->require_cram)
  461. #endif
  462. )
  463. {
  464. /* can't reuse */
  465. imap_close (imap);
  466. imap = 0;
  467. }
  468. else
  469. {
  470. reuse = 1;
  471. /* reset mailbox-specific state info */
  472. imap->recent = 0;
  473. imap->deleted = 0;
  474. imap->count = 0;
  475. imap->maxuid = 0;
  476. free_message (imap->msgs);
  477. imap->msgs = 0;
  478. }
  479. }
  480. if (!imap)
  481. {
  482. imap = calloc (1, sizeof (imap_t));
  483. imap->sock = calloc (1, sizeof (Socket_t));
  484. imap->buf = calloc (1, sizeof (buffer_t));
  485. imap->buf->sock = imap->sock;
  486. }
  487. imap->box = box;
  488. imap->minuid = minuid;
  489. imap->prefix = "";
  490. if (!reuse)
  491. {
  492. /* open connection to IMAP server */
  493. memset (&sin, 0, sizeof (sin));
  494. sin.sin_port = htons (box->port);
  495. sin.sin_family = AF_INET;
  496. printf ("Resolving %s... ", box->host);
  497. fflush (stdout);
  498. he = gethostbyname (box->host);
  499. if (!he)
  500. {
  501. perror ("gethostbyname");
  502. return 0;
  503. }
  504. puts ("ok");
  505. sin.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  506. s = socket (PF_INET, SOCK_STREAM, 0);
  507. printf ("Connecting to %s:%hu... ", inet_ntoa (sin.sin_addr),
  508. ntohs (sin.sin_port));
  509. fflush (stdout);
  510. if (connect (s, (struct sockaddr *) &sin, sizeof (sin)))
  511. {
  512. perror ("connect");
  513. exit (1);
  514. }
  515. puts ("ok");
  516. imap->sock->fd = s;
  517. }
  518. do
  519. {
  520. /* if we are reusing the existing connection, we can skip the
  521. * authentication steps.
  522. */
  523. if (!reuse)
  524. {
  525. #if HAVE_LIBSSL
  526. if (!box->use_imaps)
  527. {
  528. /* let's see what this puppy can do... */
  529. if ((ret = imap_exec (imap, "CAPABILITY")))
  530. break;
  531. /* always try to select SSL support if available */
  532. if (imap->have_starttls)
  533. {
  534. if ((ret = imap_exec (imap, "STARTTLS")))
  535. break;
  536. use_ssl = 1;
  537. }
  538. if (!use_ssl)
  539. {
  540. if (box->require_ssl)
  541. {
  542. puts ("Error, SSL support not available");
  543. ret = -1;
  544. break;
  545. }
  546. else
  547. puts ("Warning, SSL support not available");
  548. }
  549. }
  550. else
  551. use_ssl = 1;
  552. if (use_ssl)
  553. {
  554. /* initialize SSL */
  555. if (init_ssl (box))
  556. {
  557. ret = -1;
  558. break;
  559. }
  560. imap->sock->ssl = SSL_new (SSLContext);
  561. SSL_set_fd (imap->sock->ssl, imap->sock->fd);
  562. ret = SSL_connect (imap->sock->ssl);
  563. if (ret <= 0)
  564. {
  565. ret = SSL_get_error (imap->sock->ssl, ret);
  566. printf ("Error, SSL_connect: %s\n",
  567. ERR_error_string (ret, 0));
  568. ret = -1;
  569. break;
  570. }
  571. /* verify the server certificate */
  572. if ((ret = verify_cert (imap->sock->ssl)))
  573. break;
  574. imap->sock->use_ssl = 1;
  575. puts ("SSL support enabled");
  576. if (box->use_imaps)
  577. if ((ret = imap_exec (imap, "CAPABILITY")))
  578. break;
  579. }
  580. #else
  581. if ((ret = imap_exec (imap, "CAPABILITY")))
  582. break;
  583. #endif
  584. puts ("Logging in...");
  585. #if HAVE_LIBSSL
  586. if (imap->have_cram)
  587. {
  588. puts ("Authenticating with CRAM-MD5");
  589. imap->cram = 1;
  590. if ((ret = imap_exec (imap, "AUTHENTICATE CRAM-MD5")))
  591. break;
  592. }
  593. else if (imap->box->require_cram)
  594. {
  595. puts
  596. ("Error, CRAM-MD5 authentication is not supported by server");
  597. ret = -1;
  598. break;
  599. }
  600. else
  601. #endif
  602. {
  603. #if HAVE_LIBSSL
  604. if (!use_ssl)
  605. #endif
  606. puts
  607. ("*** Warning *** Password is being sent in the clear");
  608. if (
  609. (ret =
  610. imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user,
  611. box->pass)))
  612. break;
  613. }
  614. /* get NAMESPACE info */
  615. if (box->use_namespace && imap->have_namespace)
  616. {
  617. if ((ret = imap_exec (imap, "NAMESPACE")))
  618. break;
  619. }
  620. } /* !reuse */
  621. /* XXX for now assume personal namespace */
  622. if (imap->box->use_namespace && is_list (imap->ns_personal) &&
  623. is_list (imap->ns_personal->child) &&
  624. is_atom (imap->ns_personal->child->child))
  625. {
  626. imap->prefix = imap->ns_personal->child->child->val;
  627. }
  628. fputs ("Selecting mailbox... ", stdout);
  629. fflush (stdout);
  630. if ((ret = imap_exec (imap, "SELECT \"%s%s\"", imap->prefix, box->box)))
  631. break;
  632. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  633. puts ("Reading IMAP mailbox index");
  634. if (imap->count > 0)
  635. {
  636. if ((ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  637. imap->minuid)))
  638. break;
  639. }
  640. }
  641. while (0);
  642. if (ret)
  643. {
  644. imap_close (imap);
  645. imap = 0;
  646. }
  647. return imap;
  648. }
  649. void
  650. imap_close (imap_t * imap)
  651. {
  652. puts ("Closing IMAP connection");
  653. imap_exec (imap, "LOGOUT");
  654. close (imap->sock->fd);
  655. free (imap->sock);
  656. free (imap->buf);
  657. free_message (imap->msgs);
  658. memset (imap, 0xff, sizeof (imap_t));
  659. free (imap);
  660. }
  661. /* write a buffer stripping all \r bytes */
  662. static int
  663. write_strip (int fd, char *buf, size_t len)
  664. {
  665. size_t start = 0;
  666. size_t end = 0;
  667. while (start < len)
  668. {
  669. while (end < len && buf[end] != '\r')
  670. end++;
  671. write (fd, buf + start, end - start);
  672. end++;
  673. start = end;
  674. }
  675. return 0;
  676. }
  677. static void
  678. send_server (Socket_t * sock, const char *fmt, ...)
  679. {
  680. char buf[128];
  681. char cmd[128];
  682. va_list ap;
  683. va_start (ap, fmt);
  684. vsnprintf (buf, sizeof (buf), fmt, ap);
  685. va_end (ap);
  686. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  687. socket_write (sock, cmd, strlen (cmd));
  688. if (Verbose)
  689. fputs (cmd, stdout);
  690. }
  691. int
  692. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  693. {
  694. char *cmd;
  695. char *arg;
  696. size_t bytes;
  697. size_t n;
  698. char buf[1024];
  699. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  700. for (;;)
  701. {
  702. if (buffer_gets (imap->buf, &cmd))
  703. return -1;
  704. if (Verbose)
  705. puts (cmd);
  706. if (*cmd == '*')
  707. {
  708. /* need to figure out how long the message is
  709. * * <msgno> FETCH (RFC822 {<size>}
  710. */
  711. next_arg (&cmd); /* * */
  712. next_arg (&cmd); /* <msgno> */
  713. next_arg (&cmd); /* FETCH */
  714. while ((arg = next_arg (&cmd)) && *arg != '{')
  715. ;
  716. if (!arg)
  717. {
  718. puts ("parse error getting size");
  719. return -1;
  720. }
  721. bytes = strtol (arg + 1, 0, 10);
  722. // printf ("receiving %d byte message\n", bytes);
  723. /* dump whats left over in the input buffer */
  724. n = imap->buf->bytes - imap->buf->offset;
  725. if (n > bytes)
  726. {
  727. /* the entire message fit in the buffer */
  728. n = bytes;
  729. }
  730. /* ick. we have to strip out the \r\n line endings, so
  731. * i can't just dump the raw bytes to disk.
  732. */
  733. write_strip (fd, imap->buf->buf + imap->buf->offset, n);
  734. bytes -= n;
  735. // printf ("wrote %d buffered bytes\n", n);
  736. /* mark that we used part of the buffer */
  737. imap->buf->offset += n;
  738. /* now read the rest of the message */
  739. while (bytes > 0)
  740. {
  741. n = bytes;
  742. if (n > sizeof (buf))
  743. n = sizeof (buf);
  744. n = socket_read (imap->sock, buf, n);
  745. if (n > 0)
  746. {
  747. // printf("imap_fetch_message:%d:read %d bytes\n", __LINE__, n);
  748. write_strip (fd, buf, n);
  749. bytes -= n;
  750. }
  751. else
  752. {
  753. if (n == (size_t) - 1)
  754. perror ("read");
  755. else
  756. puts ("EOF");
  757. return -1;
  758. }
  759. }
  760. // puts ("finished fetching msg");
  761. buffer_gets (imap->buf, &cmd);
  762. if (Verbose)
  763. puts (cmd); /* last part of line */
  764. }
  765. else
  766. {
  767. arg = next_arg (&cmd);
  768. if (!arg || (size_t) atoi (arg) != Tag)
  769. {
  770. puts ("wrong tag");
  771. return -1;
  772. }
  773. arg = next_arg (&cmd);
  774. if (!strcmp ("OK", arg))
  775. return 0;
  776. return -1;
  777. }
  778. }
  779. /* not reached */
  780. }
  781. /* add flags to existing flags */
  782. int
  783. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  784. {
  785. char buf[256];
  786. int i;
  787. buf[0] = 0;
  788. for (i = 0; i < D_MAX; i++)
  789. {
  790. if (flags & (1 << i))
  791. snprintf (buf + strlen (buf),
  792. sizeof (buf) - strlen (buf), "%s%s",
  793. (buf[0] != 0) ? " " : "", Flags[i]);
  794. }
  795. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  796. }
  797. int
  798. imap_expunge (imap_t * imap)
  799. {
  800. return imap_exec (imap, "EXPUNGE");
  801. }
  802. int
  803. imap_copy_message (imap_t * imap, unsigned int uid, const char *mailbox)
  804. {
  805. return imap_exec (imap, "UID COPY %u \"%s%s\"", uid, imap->prefix, mailbox);
  806. }
  807. int
  808. imap_append_message (imap_t * imap, int fd, message_t * msg)
  809. {
  810. char buf[1024];
  811. size_t len;
  812. size_t sofar = 0;
  813. int lines = 0;
  814. char flagstr[128];
  815. char *s;
  816. size_t i;
  817. size_t start, end;
  818. char *arg;
  819. /* ugh, we need to count the number of newlines */
  820. while (sofar < msg->size)
  821. {
  822. len = msg->size - sofar;
  823. if (len > sizeof (buf))
  824. len = sizeof (buf);
  825. len = read (fd, buf, len);
  826. if (len == (size_t) - 1)
  827. {
  828. perror ("read");
  829. return -1;
  830. }
  831. for (i = 0; i < len; i++)
  832. if (buf[i] == '\n')
  833. lines++;
  834. sofar += len;
  835. }
  836. flagstr[0] = 0;
  837. if (msg->flags)
  838. {
  839. strcpy (flagstr, "(");
  840. if (msg->flags & D_DELETED)
  841. snprintf (flagstr + strlen (flagstr),
  842. sizeof (flagstr) - strlen (flagstr), "%s\\Deleted",
  843. flagstr[1] ? " " : "");
  844. if (msg->flags & D_ANSWERED)
  845. snprintf (flagstr + strlen (flagstr),
  846. sizeof (flagstr) - strlen (flagstr), "%s\\Answered",
  847. flagstr[1] ? " " : "");
  848. if (msg->flags & D_SEEN)
  849. snprintf (flagstr + strlen (flagstr),
  850. sizeof (flagstr) - strlen (flagstr), "%s\\Seen",
  851. flagstr[1] ? " " : "");
  852. if (msg->flags & D_FLAGGED)
  853. snprintf (flagstr + strlen (flagstr),
  854. sizeof (flagstr) - strlen (flagstr), "%s\\Flagged",
  855. flagstr[1] ? " " : "");
  856. if (msg->flags & D_DRAFT)
  857. snprintf (flagstr + strlen (flagstr),
  858. sizeof (flagstr) - strlen (flagstr), "%s\\Draft",
  859. flagstr[1] ? " " : "");
  860. snprintf (flagstr + strlen (flagstr),
  861. sizeof (flagstr) - strlen (flagstr), ") ");
  862. }
  863. send_server (imap->sock, "APPEND %s%s %s{%d}\r\n",
  864. imap->prefix, imap->box->box, flagstr, msg->size + lines);
  865. socket_write (imap->sock, buf, strlen (buf));
  866. if (Verbose)
  867. fputs (buf, stdout);
  868. if (buffer_gets (imap->buf, &s))
  869. return -1;
  870. if (Verbose)
  871. puts (s);
  872. if (*s != '+')
  873. return -1;
  874. /* rewind */
  875. lseek (fd, 0, 0);
  876. sofar = 0;
  877. while (sofar < msg->size)
  878. {
  879. len = msg->size - sofar;
  880. if (len > sizeof (buf))
  881. len = sizeof (buf);
  882. len = read (fd, buf, len);
  883. if (len == (size_t) - 1)
  884. return -1;
  885. start = 0;
  886. while (start < len)
  887. {
  888. end = start;
  889. while (end < len && buf[end] != '\n')
  890. end++;
  891. if (start != end)
  892. socket_write (imap->sock, buf + start, end - start);
  893. /* if (Verbose)
  894. {
  895. buf[end] = 0;
  896. puts (buf + start);
  897. } */
  898. socket_write (imap->sock, "\r\n", 2);
  899. start = end + 1;
  900. }
  901. sofar += len;
  902. }
  903. socket_write (imap->sock, "\r\n", 2);
  904. for (;;)
  905. {
  906. if (buffer_gets (imap->buf, &s))
  907. return -1;
  908. if (Verbose)
  909. puts (s);
  910. arg = next_arg (&s);
  911. if (*arg == '*')
  912. {
  913. /* XXX just ignore it for now */
  914. }
  915. else if (atoi (arg) != (int) Tag)
  916. {
  917. puts ("wrong tag");
  918. return -1;
  919. }
  920. else
  921. {
  922. int uid;
  923. arg = next_arg (&s);
  924. if (strcmp (arg, "OK"))
  925. return -1;
  926. arg = next_arg (&s);
  927. if (*arg != '[')
  928. break;
  929. arg++;
  930. if (strcasecmp ("APPENDUID", arg))
  931. {
  932. puts ("Error, expected APPENDUID");
  933. break;
  934. }
  935. arg = next_arg (&s);
  936. if (!arg)
  937. break;
  938. if (atoi (arg) != (int) imap->uidvalidity)
  939. {
  940. puts ("Error, UIDVALIDITY doesn't match APPENDUID");
  941. return -1;
  942. }
  943. arg = next_arg (&s);
  944. if (!arg)
  945. break;
  946. uid = strtol (arg, &s, 10);
  947. if (*s != ']')
  948. {
  949. /* parse error */
  950. break;
  951. }
  952. return uid;
  953. }
  954. }
  955. return 0;
  956. }