imap.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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 addr;
  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 (&addr, 0, sizeof (addr));
  552. addr.sin_port = htons (box->port);
  553. addr.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. addr.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 (addr.sin_addr),
  566. ntohs (addr.sin_port));
  567. fflush (stdout);
  568. if (connect (s, (struct sockaddr *) &addr, sizeof (addr)))
  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
  587. {
  588. /* let's see what this puppy can do... */
  589. if ((ret = imap_exec (imap, "CAPABILITY")))
  590. break;
  591. if (box->use_sslv2 || box->use_sslv3 || box->use_tlsv1)
  592. {
  593. /* always try to select SSL support if available */
  594. if (imap->have_starttls)
  595. {
  596. if ((ret = imap_exec (imap, "STARTTLS")))
  597. break;
  598. use_ssl = 1;
  599. }
  600. }
  601. }
  602. if (!use_ssl)
  603. {
  604. if (box->require_ssl)
  605. {
  606. puts ("Error, SSL support not available");
  607. ret = -1;
  608. break;
  609. }
  610. else
  611. puts ("Warning, SSL support not available");
  612. }
  613. else
  614. {
  615. /* initialize SSL */
  616. if (init_ssl (box))
  617. {
  618. ret = -1;
  619. break;
  620. }
  621. imap->sock->ssl = SSL_new (SSLContext);
  622. SSL_set_fd (imap->sock->ssl, imap->sock->fd);
  623. ret = SSL_connect (imap->sock->ssl);
  624. if (ret <= 0)
  625. {
  626. socket_perror ("connect", imap->sock, ret);
  627. break;
  628. }
  629. /* verify the server certificate */
  630. if ((ret = verify_cert (imap->sock->ssl)))
  631. break;
  632. /* to conform to RFC2595 we need to forget all information
  633. * retrieved from CAPABILITY invocations before STARTTLS.
  634. */
  635. imap->have_namespace = 0;
  636. imap->have_cram = 0;
  637. imap->have_starttls = 0;
  638. imap->sock->use_ssl = 1;
  639. puts ("SSL support enabled");
  640. if ((ret = imap_exec (imap, "CAPABILITY")))
  641. break;
  642. }
  643. #else
  644. if ((ret = imap_exec (imap, "CAPABILITY")))
  645. break;
  646. #endif
  647. puts ("Logging in...");
  648. #if HAVE_LIBSSL
  649. if (imap->have_cram)
  650. {
  651. puts ("Authenticating with CRAM-MD5");
  652. imap->cram = 1;
  653. if ((ret = imap_exec (imap, "AUTHENTICATE CRAM-MD5")))
  654. break;
  655. }
  656. else if (imap->box->require_cram)
  657. {
  658. puts
  659. ("Error, CRAM-MD5 authentication is not supported by server");
  660. ret = -1;
  661. break;
  662. }
  663. else
  664. #endif
  665. {
  666. #if HAVE_LIBSSL
  667. if (!use_ssl)
  668. #endif
  669. puts
  670. ("*** Warning *** Password is being sent in the clear");
  671. if (
  672. (ret =
  673. imap_exec (imap, "LOGIN \"%s\" \"%s\"", box->user,
  674. box->pass)))
  675. {
  676. puts ("Error, LOGIN failed");
  677. break;
  678. }
  679. }
  680. /* get NAMESPACE info */
  681. if (box->use_namespace && imap->have_namespace)
  682. {
  683. if ((ret = imap_exec (imap, "NAMESPACE")))
  684. break;
  685. }
  686. } /* !reuse */
  687. /* XXX for now assume personal namespace */
  688. if (imap->box->use_namespace && is_list (imap->ns_personal) &&
  689. is_list (imap->ns_personal->child) &&
  690. is_atom (imap->ns_personal->child->child))
  691. {
  692. imap->prefix = imap->ns_personal->child->child->val;
  693. }
  694. fputs ("Selecting mailbox... ", stdout);
  695. fflush (stdout);
  696. if (
  697. (ret =
  698. imap_exec (imap, "SELECT \"%s%s\"", imap->prefix, box->box)))
  699. break;
  700. printf ("%d messages, %d recent\n", imap->count, imap->recent);
  701. puts ("Reading IMAP mailbox index");
  702. if (imap->count > 0)
  703. {
  704. if ((ret = imap_exec (imap, "UID FETCH %d:* (FLAGS RFC822.SIZE)",
  705. imap->minuid)))
  706. break;
  707. }
  708. }
  709. while (0);
  710. if (ret)
  711. {
  712. imap_close (imap);
  713. imap = 0;
  714. }
  715. return imap;
  716. }
  717. void
  718. imap_close (imap_t * imap)
  719. {
  720. if (imap)
  721. {
  722. imap_exec (imap, "LOGOUT");
  723. close (imap->sock->fd);
  724. free (imap->sock);
  725. free (imap->buf);
  726. free_message (imap->msgs);
  727. memset (imap, 0xff, sizeof (imap_t));
  728. free (imap);
  729. }
  730. }
  731. /* write a buffer stripping all \r bytes */
  732. static int
  733. write_strip (int fd, char *buf, size_t len)
  734. {
  735. size_t start = 0;
  736. size_t end = 0;
  737. ssize_t n;
  738. while (start < len)
  739. {
  740. while (end < len && buf[end] != '\r')
  741. end++;
  742. n = write (fd, buf + start, end - start);
  743. if (n == -1)
  744. {
  745. perror ("write");
  746. return -1;
  747. }
  748. else if ((size_t) n != end - start)
  749. {
  750. /* short write, try again */
  751. start += n;
  752. }
  753. else
  754. {
  755. /* write complete */
  756. end++;
  757. start = end;
  758. }
  759. }
  760. return 0;
  761. }
  762. static int
  763. send_server (Socket_t * sock, const char *fmt, ...)
  764. {
  765. char buf[128];
  766. char cmd[128];
  767. va_list ap;
  768. int n;
  769. va_start (ap, fmt);
  770. vsnprintf (buf, sizeof (buf), fmt, ap);
  771. va_end (ap);
  772. snprintf (cmd, sizeof (cmd), "%d %s\r\n", ++Tag, buf);
  773. n = socket_write (sock, cmd, strlen (cmd));
  774. if (n <= 0)
  775. {
  776. socket_perror ("write", sock, n);
  777. return -1;
  778. }
  779. if (Verbose)
  780. fputs (cmd, stdout);
  781. return 0;
  782. }
  783. int
  784. imap_fetch_message (imap_t * imap, unsigned int uid, int fd)
  785. {
  786. char *cmd;
  787. char *arg;
  788. size_t bytes;
  789. size_t n;
  790. char buf[1024];
  791. send_server (imap->sock, "UID FETCH %d BODY.PEEK[]", uid);
  792. for (;;)
  793. {
  794. if (buffer_gets (imap->buf, &cmd))
  795. return -1;
  796. if (Verbose)
  797. puts (cmd);
  798. if (*cmd == '*')
  799. {
  800. /* need to figure out how long the message is
  801. * * <msgno> FETCH (RFC822 {<size>}
  802. */
  803. next_arg (&cmd); /* * */
  804. next_arg (&cmd); /* <msgno> */
  805. arg = next_arg (&cmd); /* FETCH */
  806. if (strcasecmp ("FETCH", arg) != 0)
  807. {
  808. /* this is likely an untagged response, such as when new
  809. * mail arrives in the middle of the session. just skip
  810. * it for now.
  811. *
  812. * eg.,
  813. * "* 4000 EXISTS"
  814. * "* 2 RECENT"
  815. *
  816. */
  817. printf ("skipping untagged response: %s\n", arg);
  818. continue;
  819. }
  820. while ((arg = next_arg (&cmd)) && *arg != '{')
  821. ;
  822. if (!arg)
  823. {
  824. puts ("parse error getting size");
  825. return -1;
  826. }
  827. bytes = strtol (arg + 1, 0, 10);
  828. /* dump whats left over in the input buffer */
  829. n = imap->buf->bytes - imap->buf->offset;
  830. if (n > bytes)
  831. {
  832. /* the entire message fit in the buffer */
  833. n = bytes;
  834. }
  835. /* ick. we have to strip out the \r\n line endings, so
  836. * i can't just dump the raw bytes to disk.
  837. */
  838. if (write_strip (fd, imap->buf->buf + imap->buf->offset, n))
  839. {
  840. /* write failed, message is not delivered */
  841. return -1;
  842. }
  843. bytes -= n;
  844. /* mark that we used part of the buffer */
  845. imap->buf->offset += n;
  846. /* now read the rest of the message */
  847. while (bytes > 0)
  848. {
  849. n = bytes;
  850. if (n > sizeof (buf))
  851. n = sizeof (buf);
  852. n = socket_read (imap->sock, buf, n);
  853. if (n > 0)
  854. {
  855. if (write_strip (fd, buf, n))
  856. {
  857. /* write failed */
  858. return -1;
  859. }
  860. bytes -= n;
  861. }
  862. else
  863. {
  864. socket_perror ("read", imap->sock, n);
  865. return -1;
  866. }
  867. }
  868. buffer_gets (imap->buf, &cmd);
  869. if (Verbose)
  870. puts (cmd); /* last part of line */
  871. }
  872. else
  873. {
  874. arg = next_arg (&cmd);
  875. if (!arg || (size_t) atoi (arg) != Tag)
  876. {
  877. puts ("wrong tag");
  878. return -1;
  879. }
  880. arg = next_arg (&cmd);
  881. if (!strcmp ("OK", arg))
  882. return 0;
  883. return -1;
  884. }
  885. }
  886. /* not reached */
  887. }
  888. /* add flags to existing flags */
  889. int
  890. imap_set_flags (imap_t * imap, unsigned int uid, unsigned int flags)
  891. {
  892. char buf[256];
  893. int i;
  894. buf[0] = 0;
  895. for (i = 0; i < D_MAX; i++)
  896. {
  897. if (flags & (1 << i))
  898. snprintf (buf + strlen (buf),
  899. sizeof (buf) - strlen (buf), "%s%s",
  900. (buf[0] != 0) ? " " : "", Flags[i]);
  901. }
  902. return imap_exec (imap, "UID STORE %d +FLAGS.SILENT (%s)", uid, buf);
  903. }
  904. int
  905. imap_expunge (imap_t * imap)
  906. {
  907. return imap_exec (imap, "EXPUNGE");
  908. }
  909. int
  910. imap_copy_message (imap_t * imap, unsigned int uid, const char *mailbox)
  911. {
  912. return imap_exec (imap, "UID COPY %u \"%s%s\"", uid, imap->prefix,
  913. mailbox);
  914. }
  915. int
  916. imap_append_message (imap_t * imap, int fd, message_t * msg)
  917. {
  918. char buf[1024];
  919. size_t len;
  920. size_t sofar = 0;
  921. int lines = 0;
  922. char flagstr[128];
  923. char *s;
  924. size_t i;
  925. size_t start, end;
  926. char *arg;
  927. /* ugh, we need to count the number of newlines */
  928. while (sofar < msg->size)
  929. {
  930. len = msg->size - sofar;
  931. if (len > sizeof (buf))
  932. len = sizeof (buf);
  933. len = read (fd, buf, len);
  934. if (len == (size_t) - 1)
  935. {
  936. perror ("read");
  937. return -1;
  938. }
  939. for (i = 0; i < len; i++)
  940. if (buf[i] == '\n')
  941. lines++;
  942. sofar += len;
  943. }
  944. flagstr[0] = 0;
  945. if (msg->flags)
  946. {
  947. strcpy (flagstr, "(");
  948. if (msg->flags & D_DELETED)
  949. snprintf (flagstr + strlen (flagstr),
  950. sizeof (flagstr) - strlen (flagstr), "%s\\Deleted",
  951. flagstr[1] ? " " : "");
  952. if (msg->flags & D_ANSWERED)
  953. snprintf (flagstr + strlen (flagstr),
  954. sizeof (flagstr) - strlen (flagstr), "%s\\Answered",
  955. flagstr[1] ? " " : "");
  956. if (msg->flags & D_SEEN)
  957. snprintf (flagstr + strlen (flagstr),
  958. sizeof (flagstr) - strlen (flagstr), "%s\\Seen",
  959. flagstr[1] ? " " : "");
  960. if (msg->flags & D_FLAGGED)
  961. snprintf (flagstr + strlen (flagstr),
  962. sizeof (flagstr) - strlen (flagstr), "%s\\Flagged",
  963. flagstr[1] ? " " : "");
  964. if (msg->flags & D_DRAFT)
  965. snprintf (flagstr + strlen (flagstr),
  966. sizeof (flagstr) - strlen (flagstr), "%s\\Draft",
  967. flagstr[1] ? " " : "");
  968. snprintf (flagstr + strlen (flagstr),
  969. sizeof (flagstr) - strlen (flagstr), ") ");
  970. }
  971. send_server (imap->sock, "APPEND %s%s %s{%d}",
  972. imap->prefix, imap->box->box, flagstr, msg->size + lines);
  973. if (buffer_gets (imap->buf, &s))
  974. return -1;
  975. if (Verbose)
  976. puts (s);
  977. if (*s != '+')
  978. {
  979. puts ("Error, expected `+' from server (aborting)");
  980. return -1;
  981. }
  982. /* rewind */
  983. lseek (fd, 0, 0);
  984. sofar = 0;
  985. while (sofar < msg->size)
  986. {
  987. len = msg->size - sofar;
  988. if (len > sizeof (buf))
  989. len = sizeof (buf);
  990. len = read (fd, buf, len);
  991. if (len == (size_t) - 1)
  992. return -1;
  993. start = 0;
  994. while (start < len)
  995. {
  996. end = start;
  997. while (end < len && buf[end] != '\n')
  998. end++;
  999. if (start != end)
  1000. socket_write (imap->sock, buf + start, end - start);
  1001. /* only send a crlf if we actually hit the end of a line. we
  1002. * might be in the middle of a line in which case we don't
  1003. * send one.
  1004. */
  1005. if (end != len)
  1006. socket_write (imap->sock, "\r\n", 2);
  1007. start = end + 1;
  1008. }
  1009. sofar += len;
  1010. }
  1011. socket_write (imap->sock, "\r\n", 2);
  1012. for (;;)
  1013. {
  1014. if (buffer_gets (imap->buf, &s))
  1015. return -1;
  1016. if (Verbose)
  1017. puts (s);
  1018. arg = next_arg (&s);
  1019. if (*arg == '*')
  1020. {
  1021. /* XXX just ignore it for now */
  1022. }
  1023. else if (atoi (arg) != (int) Tag)
  1024. {
  1025. puts ("wrong tag");
  1026. return -1;
  1027. }
  1028. else
  1029. {
  1030. int uid;
  1031. arg = next_arg (&s);
  1032. if (strcmp (arg, "OK"))
  1033. return -1;
  1034. arg = next_arg (&s);
  1035. if (*arg != '[')
  1036. break;
  1037. arg++;
  1038. if (strcasecmp ("APPENDUID", arg))
  1039. {
  1040. puts ("Error, expected APPENDUID");
  1041. break;
  1042. }
  1043. arg = next_arg (&s);
  1044. if (!arg)
  1045. break;
  1046. if (atoi (arg) != (int) imap->uidvalidity)
  1047. {
  1048. puts ("Error, UIDVALIDITY doesn't match APPENDUID");
  1049. return -1;
  1050. }
  1051. arg = next_arg (&s);
  1052. if (!arg)
  1053. break;
  1054. uid = strtol (arg, &s, 10);
  1055. if (*s != ']')
  1056. {
  1057. /* parse error */
  1058. break;
  1059. }
  1060. return uid;
  1061. }
  1062. }
  1063. return 0;
  1064. }