imap.c 26 KB

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