imap.c 24 KB

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