imap.c 24 KB

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