drv_imap.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006 Oswald Buddenhagen <ossi@users.sf.net>
  5. * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  20. *
  21. * As a special exception, mbsync may be linked with the OpenSSL library,
  22. * despite that library's more restrictive license.
  23. */
  24. #include "isync.h"
  25. #include <assert.h>
  26. #include <unistd.h>
  27. #include <sys/mman.h>
  28. #include <sys/time.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <stddef.h>
  32. #include <limits.h>
  33. #include <errno.h>
  34. #include <string.h>
  35. #include <ctype.h>
  36. #include <sys/socket.h>
  37. #include <sys/ioctl.h>
  38. #ifdef HAVE_SYS_FILIO_H
  39. # include <sys/filio.h>
  40. #endif
  41. #include <netinet/in.h>
  42. #include <netinet/tcp.h>
  43. #include <arpa/inet.h>
  44. #include <netdb.h>
  45. #if HAVE_LIBSSL
  46. # include <openssl/ssl.h>
  47. # include <openssl/err.h>
  48. # include <openssl/hmac.h>
  49. #endif
  50. typedef struct imap_server_conf {
  51. struct imap_server_conf *next;
  52. char *name;
  53. char *tunnel;
  54. char *host;
  55. int port;
  56. char *user;
  57. char *pass;
  58. #if HAVE_LIBSSL
  59. char *cert_file;
  60. unsigned use_imaps:1;
  61. unsigned require_ssl:1;
  62. unsigned use_sslv2:1;
  63. unsigned use_sslv3:1;
  64. unsigned use_tlsv1:1;
  65. unsigned require_cram:1;
  66. #endif
  67. } imap_server_conf_t;
  68. typedef struct imap_store_conf {
  69. store_conf_t gen;
  70. imap_server_conf_t *server;
  71. unsigned use_namespace:1;
  72. } imap_store_conf_t;
  73. typedef struct imap_message {
  74. message_t gen;
  75. /* int seq; will be needed when expunges are tracked */
  76. } imap_message_t;
  77. #define NIL (void*)0x1
  78. #define LIST (void*)0x2
  79. typedef struct _list {
  80. struct _list *next, *child;
  81. char *val;
  82. int len;
  83. } list_t;
  84. typedef struct {
  85. int fd;
  86. #if HAVE_LIBSSL
  87. SSL *ssl;
  88. unsigned int use_ssl:1;
  89. #endif
  90. } Socket_t;
  91. typedef struct {
  92. Socket_t sock;
  93. int bytes;
  94. int offset;
  95. char buf[1024];
  96. } buffer_t;
  97. struct imap_cmd;
  98. #define max_in_progress 50 /* make this configurable? */
  99. typedef struct imap_store {
  100. store_t gen;
  101. const char *prefix;
  102. unsigned /*currentnc:1,*/ trashnc:1;
  103. int uidnext; /* from SELECT responses */
  104. unsigned got_namespace:1;
  105. list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
  106. message_t **msgapp; /* FETCH results */
  107. unsigned caps, rcaps; /* CAPABILITY results */
  108. /* command queue */
  109. int nexttag, num_in_progress, literal_pending;
  110. struct imap_cmd *in_progress, **in_progress_append;
  111. #if HAVE_LIBSSL
  112. SSL_CTX *SSLContext;
  113. #endif
  114. buffer_t buf; /* this is BIG, so put it last */
  115. } imap_store_t;
  116. struct imap_cmd_cb {
  117. int (*cont)( imap_store_t *ctx, struct imap_cmd *cmd, const char *prompt );
  118. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response);
  119. void *ctx;
  120. char *data;
  121. int dlen;
  122. int uid;
  123. unsigned create:1, trycreate:1;
  124. };
  125. struct imap_cmd {
  126. struct imap_cmd *next;
  127. struct imap_cmd_cb cb;
  128. char *cmd;
  129. int tag;
  130. };
  131. #define CAP(cap) (ctx->caps & (1 << (cap)))
  132. enum CAPABILITY {
  133. NOLOGIN = 0,
  134. UIDPLUS,
  135. LITERALPLUS,
  136. NAMESPACE,
  137. #if HAVE_LIBSSL
  138. CRAM,
  139. STARTTLS,
  140. #endif
  141. };
  142. static const char *cap_list[] = {
  143. "LOGINDISABLED",
  144. "UIDPLUS",
  145. "LITERAL+",
  146. "NAMESPACE",
  147. #if HAVE_LIBSSL
  148. "AUTH=CRAM-MD5",
  149. "STARTTLS",
  150. #endif
  151. };
  152. #define RESP_OK 0
  153. #define RESP_NO 1
  154. #define RESP_BAD 2
  155. static int get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd );
  156. static const char *Flags[] = {
  157. "Draft",
  158. "Flagged",
  159. "Answered",
  160. "Seen",
  161. "Deleted",
  162. };
  163. #if HAVE_LIBSSL
  164. /* this gets called when a certificate is to be verified */
  165. static int
  166. verify_cert( SSL *ssl )
  167. {
  168. X509 *cert;
  169. int err;
  170. char buf[256];
  171. BIO *bio;
  172. cert = SSL_get_peer_certificate( ssl );
  173. if (!cert) {
  174. error( "Error, no server certificate\n" );
  175. return -1;
  176. }
  177. err = SSL_get_verify_result( ssl );
  178. if (err == X509_V_OK)
  179. return 0;
  180. error( "Error, can't verify certificate: %s (%d)\n",
  181. X509_verify_cert_error_string(err), err );
  182. X509_NAME_oneline( X509_get_subject_name( cert ), buf, sizeof(buf) );
  183. info( "\nSubject: %s\n", buf );
  184. X509_NAME_oneline( X509_get_issuer_name( cert ), buf, sizeof(buf) );
  185. info( "Issuer: %s\n", buf );
  186. bio = BIO_new( BIO_s_mem() );
  187. ASN1_TIME_print( bio, X509_get_notBefore( cert ) );
  188. memset( buf, 0, sizeof(buf) );
  189. BIO_read( bio, buf, sizeof(buf) - 1 );
  190. info( "Valid from: %s\n", buf );
  191. ASN1_TIME_print( bio, X509_get_notAfter( cert ) );
  192. memset( buf, 0, sizeof(buf) );
  193. BIO_read( bio, buf, sizeof(buf) - 1 );
  194. BIO_free( bio );
  195. info( " to: %s\n", buf );
  196. fputs( "\n*** WARNING *** There is no way to verify this certificate. It is\n"
  197. " possible that a hostile attacker has replaced the\n"
  198. " server certificate. Continue at your own risk!\n"
  199. "\nAccept this certificate anyway? [no]: ", stderr );
  200. if (fgets( buf, sizeof(buf), stdin ) && (buf[0] == 'y' || buf[0] == 'Y')) {
  201. error( "\n*** Fine, but don't say I didn't warn you!\n\n" );
  202. return 0;
  203. }
  204. return -1;
  205. }
  206. static int
  207. init_ssl_ctx( imap_store_t *ctx )
  208. {
  209. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  210. SSL_METHOD *method;
  211. int options = 0;
  212. if (srvc->use_tlsv1 && !srvc->use_sslv2 && !srvc->use_sslv3)
  213. method = TLSv1_client_method();
  214. else
  215. method = SSLv23_client_method();
  216. ctx->SSLContext = SSL_CTX_new( method );
  217. if (!srvc->cert_file) {
  218. error( "Error, CertificateFile not defined\n" );
  219. return -1;
  220. } else if (!SSL_CTX_load_verify_locations( ctx->SSLContext, srvc->cert_file, NULL )) {
  221. error( "Error while loading certificate file '%s': %s\n",
  222. srvc->cert_file, ERR_error_string( ERR_get_error(), 0 ) );
  223. return -1;
  224. }
  225. if (!srvc->use_sslv2)
  226. options |= SSL_OP_NO_SSLv2;
  227. if (!srvc->use_sslv3)
  228. options |= SSL_OP_NO_SSLv3;
  229. if (!srvc->use_tlsv1)
  230. options |= SSL_OP_NO_TLSv1;
  231. SSL_CTX_set_options( ctx->SSLContext, options );
  232. /* we check the result of the verification after SSL_connect() */
  233. SSL_CTX_set_verify( ctx->SSLContext, SSL_VERIFY_NONE, 0 );
  234. return 0;
  235. }
  236. #endif /* HAVE_LIBSSL */
  237. static void
  238. socket_perror( const char *func, Socket_t *sock, int ret )
  239. {
  240. #if HAVE_LIBSSL
  241. int err;
  242. if (sock->use_ssl) {
  243. switch ((err = SSL_get_error( sock->ssl, ret ))) {
  244. case SSL_ERROR_SYSCALL:
  245. case SSL_ERROR_SSL:
  246. if ((err = ERR_get_error()) == 0) {
  247. if (ret == 0)
  248. error( "SSL_%s:got EOF\n", func );
  249. else
  250. error( "SSL_%s:%d:%s\n", func, errno, strerror(errno) );
  251. } else
  252. error( "SSL_%s:%d:%s\n", func, err, ERR_error_string( err, 0 ) );
  253. return;
  254. default:
  255. error( "SSL_%s:%d:unhandled SSL error\n", func, err );
  256. break;
  257. }
  258. return;
  259. }
  260. #else
  261. (void)sock;
  262. #endif
  263. if (ret < 0)
  264. perror( func );
  265. else
  266. error( "%s: unexpected EOF\n", func );
  267. }
  268. static int
  269. socket_read( Socket_t *sock, char *buf, int len )
  270. {
  271. int n =
  272. #if HAVE_LIBSSL
  273. sock->use_ssl ? SSL_read( sock->ssl, buf, len ) :
  274. #endif
  275. read( sock->fd, buf, len );
  276. if (n <= 0) {
  277. socket_perror( "read", sock, n );
  278. close( sock->fd );
  279. sock->fd = -1;
  280. }
  281. return n;
  282. }
  283. static int
  284. socket_write( Socket_t *sock, char *buf, int len )
  285. {
  286. int n =
  287. #if HAVE_LIBSSL
  288. sock->use_ssl ? SSL_write( sock->ssl, buf, len ) :
  289. #endif
  290. write( sock->fd, buf, len );
  291. if (n != len) {
  292. socket_perror( "write", sock, n );
  293. close( sock->fd );
  294. sock->fd = -1;
  295. }
  296. return n;
  297. }
  298. static int
  299. socket_pending( Socket_t *sock )
  300. {
  301. int num = -1;
  302. if (ioctl( sock->fd, FIONREAD, &num ) < 0)
  303. return -1;
  304. if (num > 0)
  305. return num;
  306. #if HAVE_LIBSSL
  307. if (sock->use_ssl)
  308. return SSL_pending( sock->ssl );
  309. #endif
  310. return 0;
  311. }
  312. /* simple line buffering */
  313. static int
  314. buffer_gets( buffer_t * b, char **s )
  315. {
  316. int n;
  317. int start = b->offset;
  318. *s = b->buf + start;
  319. for (;;) {
  320. /* make sure we have enough data to read the \r\n sequence */
  321. if (b->offset + 1 >= b->bytes) {
  322. if (start) {
  323. /* shift down used bytes */
  324. *s = b->buf;
  325. assert( start <= b->bytes );
  326. n = b->bytes - start;
  327. if (n)
  328. memcpy( b->buf, b->buf + start, n );
  329. b->offset -= start;
  330. b->bytes = n;
  331. start = 0;
  332. }
  333. n = socket_read( &b->sock, b->buf + b->bytes,
  334. sizeof(b->buf) - b->bytes );
  335. if (n <= 0)
  336. return -1;
  337. b->bytes += n;
  338. }
  339. if (b->buf[b->offset] == '\r') {
  340. assert( b->offset + 1 < b->bytes );
  341. if (b->buf[b->offset + 1] == '\n') {
  342. b->buf[b->offset] = 0; /* terminate the string */
  343. b->offset += 2; /* next line */
  344. if (DFlags & VERBOSE)
  345. puts( *s );
  346. return 0;
  347. }
  348. }
  349. b->offset++;
  350. }
  351. /* not reached */
  352. }
  353. static struct imap_cmd *
  354. v_issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb,
  355. const char *fmt, va_list ap )
  356. {
  357. struct imap_cmd *cmd;
  358. int n, bufl;
  359. char buf[1024];
  360. cmd = nfmalloc( sizeof(struct imap_cmd) );
  361. nfvasprintf( &cmd->cmd, fmt, ap );
  362. cmd->tag = ++ctx->nexttag;
  363. if (cb)
  364. cmd->cb = *cb;
  365. else
  366. memset( &cmd->cb, 0, sizeof(cmd->cb) );
  367. while (ctx->literal_pending)
  368. get_cmd_result( ctx, 0 );
  369. bufl = nfsnprintf( buf, sizeof(buf), cmd->cb.data ? CAP(LITERALPLUS) ?
  370. "%d %s{%d+}\r\n" : "%d %s{%d}\r\n" : "%d %s\r\n",
  371. cmd->tag, cmd->cmd, cmd->cb.dlen );
  372. if (DFlags & VERBOSE) {
  373. if (ctx->num_in_progress)
  374. printf( "(%d in progress) ", ctx->num_in_progress );
  375. if (memcmp( cmd->cmd, "LOGIN", 5 ))
  376. printf( ">>> %s", buf );
  377. else
  378. printf( ">>> %d LOGIN <user> <pass>\n", cmd->tag );
  379. }
  380. if (socket_write( &ctx->buf.sock, buf, bufl ) != bufl) {
  381. free( cmd->cmd );
  382. free( cmd );
  383. if (cb && cb->data)
  384. free( cb->data );
  385. return NULL;
  386. }
  387. if (cmd->cb.data) {
  388. if (CAP(LITERALPLUS)) {
  389. n = socket_write( &ctx->buf.sock, cmd->cb.data, cmd->cb.dlen );
  390. free( cmd->cb.data );
  391. if (n != cmd->cb.dlen ||
  392. (n = socket_write( &ctx->buf.sock, "\r\n", 2 )) != 2)
  393. {
  394. free( cmd->cmd );
  395. free( cmd );
  396. return NULL;
  397. }
  398. cmd->cb.data = 0;
  399. } else
  400. ctx->literal_pending = 1;
  401. } else if (cmd->cb.cont)
  402. ctx->literal_pending = 1;
  403. cmd->next = 0;
  404. *ctx->in_progress_append = cmd;
  405. ctx->in_progress_append = &cmd->next;
  406. ctx->num_in_progress++;
  407. return cmd;
  408. }
  409. static struct imap_cmd *
  410. issue_imap_cmd( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
  411. {
  412. struct imap_cmd *ret;
  413. va_list ap;
  414. va_start( ap, fmt );
  415. ret = v_issue_imap_cmd( ctx, cb, fmt, ap );
  416. va_end( ap );
  417. return ret;
  418. }
  419. static struct imap_cmd *
  420. issue_imap_cmd_w( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
  421. {
  422. struct imap_cmd *ret;
  423. va_list ap;
  424. va_start( ap, fmt );
  425. ret = v_issue_imap_cmd( ctx, cb, fmt, ap );
  426. va_end( ap );
  427. while (ctx->num_in_progress > max_in_progress ||
  428. socket_pending( &ctx->buf.sock ))
  429. get_cmd_result( ctx, 0 );
  430. return ret;
  431. }
  432. static int
  433. imap_exec( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
  434. {
  435. va_list ap;
  436. struct imap_cmd *cmdp;
  437. va_start( ap, fmt );
  438. cmdp = v_issue_imap_cmd( ctx, cb, fmt, ap );
  439. va_end( ap );
  440. if (!cmdp)
  441. return RESP_BAD;
  442. return get_cmd_result( ctx, cmdp );
  443. }
  444. static int
  445. imap_exec_b( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
  446. {
  447. va_list ap;
  448. struct imap_cmd *cmdp;
  449. va_start( ap, fmt );
  450. cmdp = v_issue_imap_cmd( ctx, cb, fmt, ap );
  451. va_end( ap );
  452. if (!cmdp)
  453. return DRV_STORE_BAD;
  454. switch (get_cmd_result( ctx, cmdp )) {
  455. case RESP_BAD: return DRV_STORE_BAD;
  456. case RESP_NO: return DRV_BOX_BAD;
  457. default: return DRV_OK;
  458. }
  459. }
  460. static int
  461. imap_exec_m( imap_store_t *ctx, struct imap_cmd_cb *cb, const char *fmt, ... )
  462. {
  463. va_list ap;
  464. struct imap_cmd *cmdp;
  465. va_start( ap, fmt );
  466. cmdp = v_issue_imap_cmd( ctx, cb, fmt, ap );
  467. va_end( ap );
  468. if (!cmdp)
  469. return DRV_STORE_BAD;
  470. switch (get_cmd_result( ctx, cmdp )) {
  471. case RESP_BAD: return DRV_STORE_BAD;
  472. case RESP_NO: return DRV_MSG_BAD;
  473. default: return DRV_OK;
  474. }
  475. }
  476. /*
  477. static void
  478. drain_imap_replies( imap_store_t *ctx )
  479. {
  480. while (ctx->num_in_progress)
  481. get_cmd_result( ctx, 0 );
  482. }
  483. */
  484. static int
  485. is_atom( list_t *list )
  486. {
  487. return list && list->val && list->val != NIL && list->val != LIST;
  488. }
  489. static int
  490. is_list( list_t *list )
  491. {
  492. return list && list->val == LIST;
  493. }
  494. static void
  495. free_list( list_t *list )
  496. {
  497. list_t *tmp;
  498. for (; list; list = tmp) {
  499. tmp = list->next;
  500. if (is_list( list ))
  501. free_list( list->child );
  502. else if (is_atom( list ))
  503. free( list->val );
  504. free( list );
  505. }
  506. }
  507. static int
  508. parse_imap_list_l( imap_store_t *ctx, char **sp, list_t **curp, int level )
  509. {
  510. list_t *cur;
  511. char *s = *sp, *p;
  512. int n, bytes;
  513. for (;;) {
  514. while (isspace( (unsigned char)*s ))
  515. s++;
  516. if (level && *s == ')') {
  517. s++;
  518. break;
  519. }
  520. *curp = cur = nfmalloc( sizeof(*cur) );
  521. curp = &cur->next;
  522. cur->val = 0; /* for clean bail */
  523. if (*s == '(') {
  524. /* sublist */
  525. s++;
  526. cur->val = LIST;
  527. if (parse_imap_list_l( ctx, &s, &cur->child, level + 1 ))
  528. goto bail;
  529. } else if (ctx && *s == '{') {
  530. /* literal */
  531. bytes = cur->len = strtol( s + 1, &s, 10 );
  532. if (*s != '}')
  533. goto bail;
  534. s = cur->val = nfmalloc( cur->len );
  535. /* dump whats left over in the input buffer */
  536. n = ctx->buf.bytes - ctx->buf.offset;
  537. if (n > bytes)
  538. /* the entire message fit in the buffer */
  539. n = bytes;
  540. memcpy( s, ctx->buf.buf + ctx->buf.offset, n );
  541. s += n;
  542. bytes -= n;
  543. /* mark that we used part of the buffer */
  544. ctx->buf.offset += n;
  545. /* now read the rest of the message */
  546. while (bytes > 0) {
  547. if ((n = socket_read (&ctx->buf.sock, s, bytes)) <= 0)
  548. goto bail;
  549. s += n;
  550. bytes -= n;
  551. }
  552. if (buffer_gets( &ctx->buf, &s ))
  553. goto bail;
  554. } else if (*s == '"') {
  555. /* quoted string */
  556. s++;
  557. p = s;
  558. for (; *s != '"'; s++)
  559. if (!*s)
  560. goto bail;
  561. cur->len = s - p;
  562. s++;
  563. cur->val = nfmalloc( cur->len + 1 );
  564. memcpy( cur->val, p, cur->len );
  565. cur->val[cur->len] = 0;
  566. } else {
  567. /* atom */
  568. p = s;
  569. for (; *s && !isspace( (unsigned char)*s ); s++)
  570. if (level && *s == ')')
  571. break;
  572. cur->len = s - p;
  573. if (cur->len == 3 && !memcmp ("NIL", p, 3))
  574. cur->val = NIL;
  575. else {
  576. cur->val = nfmalloc( cur->len + 1 );
  577. memcpy( cur->val, p, cur->len );
  578. cur->val[cur->len] = 0;
  579. }
  580. }
  581. if (!level)
  582. break;
  583. if (!*s)
  584. goto bail;
  585. }
  586. *sp = s;
  587. *curp = 0;
  588. return 0;
  589. bail:
  590. *curp = 0;
  591. return -1;
  592. }
  593. static list_t *
  594. parse_imap_list( imap_store_t *ctx, char **sp )
  595. {
  596. list_t *head;
  597. if (!parse_imap_list_l( ctx, sp, &head, 0 ))
  598. return head;
  599. free_list( head );
  600. return NULL;
  601. }
  602. static list_t *
  603. parse_list( char **sp )
  604. {
  605. return parse_imap_list( 0, sp );
  606. }
  607. static int
  608. parse_fetch( imap_store_t *ctx, char *cmd ) /* move this down */
  609. {
  610. list_t *tmp, *list, *flags;
  611. char *body = 0;
  612. imap_message_t *cur;
  613. msg_data_t *msgdata;
  614. struct imap_cmd *cmdp;
  615. int uid = 0, mask = 0, status = 0, size = 0;
  616. unsigned i;
  617. list = parse_imap_list( ctx, &cmd );
  618. if (!is_list( list )) {
  619. error( "IMAP error: bogus FETCH response\n" );
  620. free_list( list );
  621. return -1;
  622. }
  623. for (tmp = list->child; tmp; tmp = tmp->next) {
  624. if (is_atom( tmp )) {
  625. if (!strcmp( "UID", tmp->val )) {
  626. tmp = tmp->next;
  627. if (is_atom( tmp ))
  628. uid = atoi( tmp->val );
  629. else
  630. error( "IMAP error: unable to parse UID\n" );
  631. } else if (!strcmp( "FLAGS", tmp->val )) {
  632. tmp = tmp->next;
  633. if (is_list( tmp )) {
  634. for (flags = tmp->child; flags; flags = flags->next) {
  635. if (is_atom( flags )) {
  636. if (flags->val[0] == '\\') { /* ignore user-defined flags for now */
  637. if (!strcmp( "Recent", flags->val + 1)) {
  638. status |= M_RECENT;
  639. goto flagok;
  640. }
  641. for (i = 0; i < as(Flags); i++)
  642. if (!strcmp( Flags[i], flags->val + 1 )) {
  643. mask |= 1 << i;
  644. goto flagok;
  645. }
  646. error( "IMAP warning: unknown system flag %s\n", flags->val );
  647. }
  648. flagok: ;
  649. } else
  650. error( "IMAP error: unable to parse FLAGS list\n" );
  651. }
  652. status |= M_FLAGS;
  653. } else
  654. error( "IMAP error: unable to parse FLAGS\n" );
  655. } else if (!strcmp( "RFC822.SIZE", tmp->val )) {
  656. tmp = tmp->next;
  657. if (is_atom( tmp ))
  658. size = atoi( tmp->val );
  659. else
  660. error( "IMAP error: unable to parse RFC822.SIZE\n" );
  661. } else if (!strcmp( "BODY[]", tmp->val )) {
  662. tmp = tmp->next;
  663. if (is_atom( tmp )) {
  664. body = tmp->val;
  665. tmp->val = 0; /* don't free together with list */
  666. size = tmp->len;
  667. } else
  668. error( "IMAP error: unable to parse BODY[]\n" );
  669. }
  670. }
  671. }
  672. if (body) {
  673. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  674. if (cmdp->cb.uid == uid)
  675. goto gotuid;
  676. error( "IMAP error: unexpected FETCH response (UID %d)\n", uid );
  677. free_list( list );
  678. return -1;
  679. gotuid:
  680. msgdata = (msg_data_t *)cmdp->cb.ctx;
  681. msgdata->data = body;
  682. msgdata->len = size;
  683. if (status & M_FLAGS)
  684. msgdata->flags = mask;
  685. } else if (uid) { /* ignore async flag updates for now */
  686. /* XXX this will need sorting for out-of-order (multiple queries) */
  687. cur = nfcalloc( sizeof(*cur) );
  688. *ctx->msgapp = &cur->gen;
  689. ctx->msgapp = &cur->gen.next;
  690. cur->gen.next = 0;
  691. cur->gen.uid = uid;
  692. cur->gen.flags = mask;
  693. cur->gen.status = status;
  694. cur->gen.size = size;
  695. }
  696. free_list( list );
  697. return 0;
  698. }
  699. static void
  700. parse_capability( imap_store_t *ctx, char *cmd )
  701. {
  702. char *arg;
  703. unsigned i;
  704. ctx->caps = 0x80000000;
  705. while ((arg = next_arg( &cmd )))
  706. for (i = 0; i < as(cap_list); i++)
  707. if (!strcmp( cap_list[i], arg ))
  708. ctx->caps |= 1 << i;
  709. ctx->rcaps = ctx->caps;
  710. }
  711. static int
  712. parse_response_code( imap_store_t *ctx, struct imap_cmd_cb *cb, char *s )
  713. {
  714. char *arg, *p;
  715. if (*s != '[')
  716. return RESP_OK; /* no response code */
  717. s++;
  718. if (!(p = strchr( s, ']' ))) {
  719. error( "IMAP error: malformed response code\n" );
  720. return RESP_BAD;
  721. }
  722. *p++ = 0;
  723. arg = next_arg( &s );
  724. if (!strcmp( "UIDVALIDITY", arg )) {
  725. if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg ))) {
  726. error( "IMAP error: malformed UIDVALIDITY status\n" );
  727. return RESP_BAD;
  728. }
  729. } else if (!strcmp( "UIDNEXT", arg )) {
  730. if (!(arg = next_arg( &s )) || !(ctx->uidnext = atoi( arg ))) {
  731. error( "IMAP error: malformed NEXTUID status\n" );
  732. return RESP_BAD;
  733. }
  734. } else if (!strcmp( "CAPABILITY", arg )) {
  735. parse_capability( ctx, s );
  736. } else if (!strcmp( "ALERT", arg )) {
  737. /* RFC2060 says that these messages MUST be displayed
  738. * to the user
  739. */
  740. for (; isspace( (unsigned char)*p ); p++);
  741. error( "*** IMAP ALERT *** %s\n", p );
  742. } else if (cb && cb->ctx && !strcmp( "APPENDUID", arg )) {
  743. if (!(arg = next_arg( &s )) || !(ctx->gen.uidvalidity = atoi( arg )) ||
  744. !(arg = next_arg( &s )) || !(*(int *)cb->ctx = atoi( arg )))
  745. {
  746. error( "IMAP error: malformed APPENDUID status\n" );
  747. return RESP_BAD;
  748. }
  749. }
  750. return RESP_OK;
  751. }
  752. static void
  753. parse_search( imap_store_t *ctx, char *cmd )
  754. {
  755. char *arg;
  756. struct imap_cmd *cmdp;
  757. int uid;
  758. if (!(arg = next_arg( &cmd )))
  759. uid = -1;
  760. else if (!(uid = atoi( arg ))) {
  761. error( "IMAP error: malformed SEARCH response\n" );
  762. return;
  763. } else if (next_arg( &cmd )) {
  764. warn( "IMAP warning: SEARCH returns multiple matches\n" );
  765. uid = -1; /* to avoid havoc */
  766. }
  767. /* Find the first command that expects a UID - this is guaranteed
  768. * to come in-order, as there are no other means to identify which
  769. * SEARCH response belongs to which request.
  770. */
  771. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  772. if (cmdp->cb.uid == -1) {
  773. *(int *)cmdp->cb.ctx = uid;
  774. return;
  775. }
  776. error( "IMAP error: unexpected SEARCH response (UID %u)\n", uid );
  777. }
  778. static void
  779. parse_list_rsp( imap_store_t *ctx, char *cmd )
  780. {
  781. char *arg;
  782. list_t *list, *lp;
  783. int l;
  784. list = parse_list( &cmd );
  785. if (list->val == LIST)
  786. for (lp = list->child; lp; lp = lp->next)
  787. if (is_atom( lp ) && !strcasecmp( lp->val, "\\NoSelect" )) {
  788. free_list( list );
  789. return;
  790. }
  791. free_list( list );
  792. (void) next_arg( &cmd ); /* skip delimiter */
  793. arg = next_arg( &cmd );
  794. l = strlen( ctx->gen.conf->path );
  795. if (memcmp( arg, ctx->gen.conf->path, l ))
  796. return;
  797. arg += l;
  798. if (!memcmp( arg + strlen( arg ) - 5, ".lock", 5 )) /* workaround broken servers */
  799. return;
  800. add_string_list( &ctx->gen.boxes, arg );
  801. }
  802. static int
  803. get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd )
  804. {
  805. struct imap_cmd *cmdp, **pcmdp, *ncmdp;
  806. char *cmd, *arg, *arg1, *p;
  807. int n, resp, resp2, tag;
  808. for (;;) {
  809. if (buffer_gets( &ctx->buf, &cmd ))
  810. return RESP_BAD;
  811. arg = next_arg( &cmd );
  812. if (*arg == '*') {
  813. arg = next_arg( &cmd );
  814. if (!arg) {
  815. error( "IMAP error: unable to parse untagged response\n" );
  816. return RESP_BAD;
  817. }
  818. if (!strcmp( "NAMESPACE", arg )) {
  819. ctx->ns_personal = parse_list( &cmd );
  820. ctx->ns_other = parse_list( &cmd );
  821. ctx->ns_shared = parse_list( &cmd );
  822. } else if (!strcmp( "OK", arg ) || !strcmp( "BAD", arg ) ||
  823. !strcmp( "NO", arg ) || !strcmp( "BYE", arg )) {
  824. if ((resp = parse_response_code( ctx, 0, cmd )) != RESP_OK)
  825. return resp;
  826. } else if (!strcmp( "CAPABILITY", arg ))
  827. parse_capability( ctx, cmd );
  828. else if (!strcmp( "LIST", arg ))
  829. parse_list_rsp( ctx, cmd );
  830. else if (!strcmp( "SEARCH", arg ))
  831. parse_search( ctx, cmd );
  832. else if ((arg1 = next_arg( &cmd ))) {
  833. if (!strcmp( "EXISTS", arg1 ))
  834. ctx->gen.count = atoi( arg );
  835. else if (!strcmp( "RECENT", arg1 ))
  836. ctx->gen.recent = atoi( arg );
  837. else if(!strcmp ( "FETCH", arg1 )) {
  838. if (parse_fetch( ctx, cmd ))
  839. return RESP_BAD;
  840. }
  841. } else {
  842. error( "IMAP error: unable to parse untagged response\n" );
  843. return RESP_BAD;
  844. }
  845. } else if (!ctx->in_progress) {
  846. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  847. return RESP_BAD;
  848. } else if (*arg == '+') {
  849. /* This can happen only with the last command underway, as
  850. it enforces a round-trip. */
  851. cmdp = (struct imap_cmd *)((char *)ctx->in_progress_append -
  852. offsetof(struct imap_cmd, next));
  853. if (cmdp->cb.data) {
  854. n = socket_write( &ctx->buf.sock, cmdp->cb.data, cmdp->cb.dlen );
  855. free( cmdp->cb.data );
  856. cmdp->cb.data = 0;
  857. if (n != (int)cmdp->cb.dlen)
  858. return RESP_BAD;
  859. } else if (cmdp->cb.cont) {
  860. if (cmdp->cb.cont( ctx, cmdp, cmd ))
  861. return RESP_BAD;
  862. } else {
  863. error( "IMAP error: unexpected command continuation request\n" );
  864. return RESP_BAD;
  865. }
  866. if (socket_write( &ctx->buf.sock, "\r\n", 2 ) != 2)
  867. return RESP_BAD;
  868. if (!cmdp->cb.cont)
  869. ctx->literal_pending = 0;
  870. if (!tcmd)
  871. return DRV_OK;
  872. } else {
  873. tag = atoi( arg );
  874. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  875. if (cmdp->tag == tag)
  876. goto gottag;
  877. error( "IMAP error: unexpected tag %s\n", arg );
  878. return RESP_BAD;
  879. gottag:
  880. if (!(*pcmdp = cmdp->next))
  881. ctx->in_progress_append = pcmdp;
  882. ctx->num_in_progress--;
  883. if (cmdp->cb.cont || cmdp->cb.data)
  884. ctx->literal_pending = 0;
  885. arg = next_arg( &cmd );
  886. if (!strcmp( "OK", arg ))
  887. resp = DRV_OK;
  888. else {
  889. if (!strcmp( "NO", arg )) {
  890. if (cmdp->cb.create && cmd && (cmdp->cb.trycreate || !memcmp( cmd, "[TRYCREATE]", 11 ))) { /* SELECT, APPEND or UID COPY */
  891. p = strchr( cmdp->cmd, '"' );
  892. if (!issue_imap_cmd( ctx, 0, "CREATE %.*s", strchr( p + 1, '"' ) - p + 1, p )) {
  893. resp = RESP_BAD;
  894. goto normal;
  895. }
  896. /* not waiting here violates the spec, but a server that does not
  897. grok this nonetheless violates it too. */
  898. cmdp->cb.create = 0;
  899. if (!(ncmdp = issue_imap_cmd( ctx, &cmdp->cb, "%s", cmdp->cmd ))) {
  900. resp = RESP_BAD;
  901. goto normal;
  902. }
  903. free( cmdp->cmd );
  904. free( cmdp );
  905. if (!tcmd)
  906. return 0; /* ignored */
  907. if (cmdp == tcmd)
  908. tcmd = ncmdp;
  909. continue;
  910. }
  911. resp = RESP_NO;
  912. } else /*if (!strcmp( "BAD", arg ))*/
  913. resp = RESP_BAD;
  914. error( "IMAP command '%s' returned an error: %s %s\n",
  915. memcmp( cmdp->cmd, "LOGIN", 5 ) ? cmdp->cmd : "LOGIN <user> <pass>",
  916. arg, cmd ? cmd : "" );
  917. }
  918. if ((resp2 = parse_response_code( ctx, &cmdp->cb, cmd )) > resp)
  919. resp = resp2;
  920. normal:
  921. if (cmdp->cb.done)
  922. cmdp->cb.done( ctx, cmdp, resp );
  923. if (cmdp->cb.data)
  924. free( cmdp->cb.data );
  925. free( cmdp->cmd );
  926. free( cmdp );
  927. if (!tcmd || tcmd == cmdp)
  928. return resp;
  929. }
  930. }
  931. /* not reached */
  932. }
  933. static void
  934. imap_cancel_store( store_t *gctx )
  935. {
  936. imap_store_t *ctx = (imap_store_t *)gctx;
  937. free_generic_messages( gctx->msgs );
  938. free_string_list( ctx->gen.boxes );
  939. if (ctx->buf.sock.fd >= 0)
  940. close( ctx->buf.sock.fd );
  941. #ifdef HAVE_LIBSSL
  942. if (ctx->SSLContext)
  943. SSL_CTX_free( ctx->SSLContext );
  944. #endif
  945. free_list( ctx->ns_personal );
  946. free_list( ctx->ns_other );
  947. free_list( ctx->ns_shared );
  948. free( ctx );
  949. }
  950. static store_t *unowned;
  951. static void
  952. imap_disown_store( store_t *gctx )
  953. {
  954. free_generic_messages( gctx->msgs );
  955. gctx->msgs = 0;
  956. gctx->next = unowned;
  957. unowned = gctx;
  958. }
  959. static store_t *
  960. imap_own_store( store_conf_t *conf )
  961. {
  962. store_t *store, **storep;
  963. for (storep = &unowned; (store = *storep); storep = &store->next)
  964. if (store->conf == conf) {
  965. *storep = store->next;
  966. return store;
  967. }
  968. return 0;
  969. }
  970. static void
  971. imap_cleanup( void )
  972. {
  973. store_t *ctx, *nctx;
  974. for (ctx = unowned; ctx; ctx = nctx) {
  975. nctx = ctx->next;
  976. imap_exec( (imap_store_t *)ctx, 0, "LOGOUT" );
  977. imap_cancel_store( ctx );
  978. }
  979. }
  980. #ifdef HAVE_LIBSSL
  981. static int
  982. start_tls( imap_store_t *ctx )
  983. {
  984. int ret;
  985. static int ssl_inited;
  986. if (!ssl_inited) {
  987. SSL_library_init();
  988. SSL_load_error_strings();
  989. ssl_inited = 1;
  990. }
  991. if (init_ssl_ctx( ctx ))
  992. return 1;
  993. ctx->buf.sock.ssl = SSL_new( ctx->SSLContext );
  994. SSL_set_fd( ctx->buf.sock.ssl, ctx->buf.sock.fd );
  995. if ((ret = SSL_connect( ctx->buf.sock.ssl )) <= 0) {
  996. socket_perror( "connect", &ctx->buf.sock, ret );
  997. return 1;
  998. }
  999. /* verify the server certificate */
  1000. if (verify_cert( ctx->buf.sock.ssl ))
  1001. return 1;
  1002. ctx->buf.sock.use_ssl = 1;
  1003. info( "Connection is now encrypted\n" );
  1004. return 0;
  1005. }
  1006. #define ENCODED_SIZE(n) (4*((n+2)/3))
  1007. static char
  1008. hexchar( unsigned int b )
  1009. {
  1010. if (b < 10)
  1011. return '0' + b;
  1012. return 'a' + (b - 10);
  1013. }
  1014. /* XXX merge into do_cram_auth? */
  1015. static char *
  1016. cram( const char *challenge, const char *user, const char *pass )
  1017. {
  1018. HMAC_CTX hmac;
  1019. char hash[16];
  1020. char hex[33];
  1021. int i;
  1022. unsigned int hashlen = sizeof(hash);
  1023. char buf[256];
  1024. int len = strlen( challenge );
  1025. char *response = nfcalloc( 1 + len );
  1026. char *final;
  1027. /* response will always be smaller than challenge because we are
  1028. * decoding.
  1029. */
  1030. len = EVP_DecodeBlock( (unsigned char *)response, (unsigned char *)challenge, strlen( challenge ) );
  1031. HMAC_Init( &hmac, (unsigned char *) pass, strlen( pass ), EVP_md5() );
  1032. HMAC_Update( &hmac, (unsigned char *)response, strlen( response ) );
  1033. HMAC_Final( &hmac, (unsigned char *)hash, &hashlen );
  1034. assert( hashlen == sizeof(hash) );
  1035. free( response );
  1036. hex[32] = 0;
  1037. for (i = 0; i < 16; i++) {
  1038. hex[2 * i] = hexchar( (hash[i] >> 4) & 0xf );
  1039. hex[2 * i + 1] = hexchar( hash[i] & 0xf );
  1040. }
  1041. nfsnprintf( buf, sizeof(buf), "%s %s", user, hex );
  1042. len = strlen( buf );
  1043. len = ENCODED_SIZE( len ) + 1;
  1044. final = nfmalloc( len );
  1045. final[len - 1] = 0;
  1046. assert( EVP_EncodeBlock( (unsigned char *)final, (unsigned char *)buf, strlen( buf ) ) == len - 1 );
  1047. return final;
  1048. }
  1049. static int
  1050. do_cram_auth( imap_store_t *ctx, struct imap_cmd *cmdp, const char *prompt )
  1051. {
  1052. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1053. char *resp;
  1054. int n, l;
  1055. resp = cram( prompt, srvc->user, srvc->pass );
  1056. if (DFlags & VERBOSE)
  1057. printf( ">+> %s\n", resp );
  1058. l = strlen( resp );
  1059. n = socket_write( &ctx->buf.sock, resp, l );
  1060. free( resp );
  1061. if (n != l)
  1062. return -1;
  1063. cmdp->cb.cont = 0;
  1064. return 0;
  1065. }
  1066. #endif
  1067. static void
  1068. imap_open_store( store_conf_t *conf,
  1069. void (*cb)( store_t *srv, void *aux ), void *aux )
  1070. {
  1071. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1072. imap_server_conf_t *srvc = cfg->server;
  1073. imap_store_t *ctx;
  1074. store_t **ctxp;
  1075. char *arg, *rsp;
  1076. struct hostent *he;
  1077. struct sockaddr_in addr;
  1078. int s, a[2], preauth;
  1079. #if HAVE_LIBSSL
  1080. int use_ssl;
  1081. #endif
  1082. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1083. if (((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1084. *ctxp = ctx->gen.next;
  1085. /* One could ping the server here, but given that the idle timeout
  1086. * is at least 30 minutes, this sounds pretty pointless. */
  1087. free_string_list( ctx->gen.boxes );
  1088. ctx->gen.boxes = 0;
  1089. ctx->gen.listed = 0;
  1090. ctx->gen.conf = conf;
  1091. goto final;
  1092. }
  1093. ctx = nfcalloc( sizeof(*ctx) );
  1094. ctx->gen.conf = conf;
  1095. ctx->buf.sock.fd = -1;
  1096. ctx->in_progress_append = &ctx->in_progress;
  1097. /* open connection to IMAP server */
  1098. #if HAVE_LIBSSL
  1099. use_ssl = 0;
  1100. #endif
  1101. if (srvc->tunnel) {
  1102. infon( "Starting tunnel '%s'... ", srvc->tunnel );
  1103. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  1104. perror( "socketpair" );
  1105. exit( 1 );
  1106. }
  1107. if (fork() == 0) {
  1108. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  1109. _exit( 127 );
  1110. close( a[0] );
  1111. close( a[1] );
  1112. execl( "/bin/sh", "sh", "-c", srvc->tunnel, (char *)0 );
  1113. _exit( 127 );
  1114. }
  1115. close (a[0]);
  1116. ctx->buf.sock.fd = a[1];
  1117. info( "ok\n" );
  1118. } else {
  1119. memset( &addr, 0, sizeof(addr) );
  1120. addr.sin_port = htons( srvc->port ? srvc->port :
  1121. #ifdef HAVE_LIBSSL
  1122. srvc->use_imaps ? 993 :
  1123. #endif
  1124. 143 );
  1125. addr.sin_family = AF_INET;
  1126. infon( "Resolving %s... ", srvc->host );
  1127. he = gethostbyname( srvc->host );
  1128. if (!he) {
  1129. error( "IMAP error: Cannot resolve server '%s'\n", srvc->host );
  1130. goto bail;
  1131. }
  1132. info( "ok\n" );
  1133. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  1134. s = socket( PF_INET, SOCK_STREAM, 0 );
  1135. if (s < 0) {
  1136. perror( "socket" );
  1137. exit( 1 );
  1138. }
  1139. infon( "Connecting to %s:%hu... ", inet_ntoa( addr.sin_addr ), ntohs( addr.sin_port ) );
  1140. if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) {
  1141. close( s );
  1142. perror( "connect" );
  1143. goto bail;
  1144. }
  1145. info( "ok\n" );
  1146. ctx->buf.sock.fd = s;
  1147. }
  1148. #if HAVE_LIBSSL
  1149. if (srvc->use_imaps) {
  1150. if (start_tls( ctx ))
  1151. goto bail;
  1152. use_ssl = 1;
  1153. }
  1154. #endif
  1155. /* read the greeting string */
  1156. if (buffer_gets( &ctx->buf, &rsp )) {
  1157. error( "IMAP error: no greeting response\n" );
  1158. goto bail;
  1159. }
  1160. arg = next_arg( &rsp );
  1161. if (!arg || *arg != '*' || (arg = next_arg( &rsp )) == NULL) {
  1162. error( "IMAP error: invalid greeting response\n" );
  1163. goto bail;
  1164. }
  1165. preauth = 0;
  1166. if (!strcmp( "PREAUTH", arg ))
  1167. preauth = 1;
  1168. else if (strcmp( "OK", arg ) != 0) {
  1169. error( "IMAP error: unknown greeting response\n" );
  1170. goto bail;
  1171. }
  1172. parse_response_code( ctx, 0, rsp );
  1173. if (!ctx->caps && imap_exec( ctx, 0, "CAPABILITY" ) != RESP_OK)
  1174. goto bail;
  1175. if (!preauth) {
  1176. #if HAVE_LIBSSL
  1177. if (!srvc->use_imaps && (srvc->use_sslv2 || srvc->use_sslv3 || srvc->use_tlsv1)) {
  1178. /* always try to select SSL support if available */
  1179. if (CAP(STARTTLS)) {
  1180. if (imap_exec( ctx, 0, "STARTTLS" ) != RESP_OK)
  1181. goto bail;
  1182. if (start_tls( ctx ))
  1183. goto bail;
  1184. use_ssl = 1;
  1185. if (imap_exec( ctx, 0, "CAPABILITY" ) != RESP_OK)
  1186. goto bail;
  1187. } else {
  1188. if (srvc->require_ssl) {
  1189. error( "IMAP error: SSL support not available\n" );
  1190. goto bail;
  1191. } else
  1192. warn( "IMAP warning: SSL support not available\n" );
  1193. }
  1194. }
  1195. #endif
  1196. info ("Logging in...\n");
  1197. if (!srvc->user) {
  1198. error( "Skipping account %s, no user\n", srvc->name );
  1199. goto bail;
  1200. }
  1201. if (!srvc->pass) {
  1202. char prompt[80];
  1203. sprintf( prompt, "Password (%s): ", srvc->name );
  1204. arg = getpass( prompt );
  1205. if (!arg) {
  1206. perror( "getpass" );
  1207. exit( 1 );
  1208. }
  1209. if (!*arg) {
  1210. error( "Skipping account %s, no password\n", srvc->name );
  1211. goto bail;
  1212. }
  1213. /*
  1214. * getpass() returns a pointer to a static buffer. make a copy
  1215. * for long term storage.
  1216. */
  1217. srvc->pass = nfstrdup( arg );
  1218. }
  1219. #if HAVE_LIBSSL
  1220. if (CAP(CRAM)) {
  1221. struct imap_cmd_cb cbd;
  1222. info( "Authenticating with CRAM-MD5\n" );
  1223. memset( &cbd, 0, sizeof(cbd) );
  1224. cbd.cont = do_cram_auth;
  1225. if (imap_exec( ctx, &cbd, "AUTHENTICATE CRAM-MD5" ) != RESP_OK)
  1226. goto bail;
  1227. } else if (srvc->require_cram) {
  1228. error( "IMAP error: CRAM-MD5 authentication is not supported by server\n" );
  1229. goto bail;
  1230. } else
  1231. #endif
  1232. {
  1233. if (CAP(NOLOGIN)) {
  1234. error( "Skipping account %s, server forbids LOGIN\n", srvc->name );
  1235. goto bail;
  1236. }
  1237. #if HAVE_LIBSSL
  1238. if (!use_ssl)
  1239. #endif
  1240. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  1241. if (imap_exec( ctx, 0, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass ) != RESP_OK) {
  1242. error( "IMAP error: LOGIN failed\n" );
  1243. goto bail;
  1244. }
  1245. }
  1246. } /* !preauth */
  1247. final:
  1248. ctx->prefix = "";
  1249. if (*conf->path)
  1250. ctx->prefix = conf->path;
  1251. else if (cfg->use_namespace && CAP(NAMESPACE)) {
  1252. /* get NAMESPACE info */
  1253. if (!ctx->got_namespace) {
  1254. if (imap_exec( ctx, 0, "NAMESPACE" ) != RESP_OK) {
  1255. cb( 0, aux );
  1256. return;
  1257. }
  1258. ctx->got_namespace = 1;
  1259. }
  1260. /* XXX for now assume personal namespace */
  1261. if (is_list( ctx->ns_personal ) &&
  1262. is_list( ctx->ns_personal->child ) &&
  1263. is_atom( ctx->ns_personal->child->child ))
  1264. ctx->prefix = ctx->ns_personal->child->child->val;
  1265. }
  1266. ctx->trashnc = 1;
  1267. cb( &ctx->gen, aux );
  1268. return;
  1269. bail:
  1270. imap_cancel_store( &ctx->gen );
  1271. cb( 0, aux );
  1272. return;
  1273. }
  1274. static void
  1275. imap_prepare_paths( store_t *gctx )
  1276. {
  1277. free_generic_messages( gctx->msgs );
  1278. gctx->msgs = 0;
  1279. }
  1280. static void
  1281. imap_prepare_opts( store_t *gctx, int opts )
  1282. {
  1283. gctx->opts = opts;
  1284. }
  1285. static void
  1286. imap_select( store_t *gctx, int minuid, int maxuid, int *excs, int nexcs,
  1287. void (*cb)( int sts, void *aux ), void *aux )
  1288. {
  1289. imap_store_t *ctx = (imap_store_t *)gctx;
  1290. const char *prefix;
  1291. int ret, i, j, bl;
  1292. struct imap_cmd_cb cbd;
  1293. char buf[1000];
  1294. if (!strcmp( gctx->name, "INBOX" )) {
  1295. // ctx->currentnc = 0;
  1296. prefix = "";
  1297. } else {
  1298. // ctx->currentnc = 1; /* could use LIST results for that */
  1299. prefix = ctx->prefix;
  1300. }
  1301. memset( &cbd, 0, sizeof(cbd) );
  1302. cbd.create = (gctx->opts & OPEN_CREATE) != 0;
  1303. cbd.trycreate = 1;
  1304. if ((ret = imap_exec_b( ctx, &cbd, "SELECT \"%s%s\"", prefix, gctx->name )) != DRV_OK)
  1305. goto bail;
  1306. if (gctx->count) {
  1307. ctx->msgapp = &gctx->msgs;
  1308. sort_ints( excs, nexcs );
  1309. for (i = 0; i < nexcs; ) {
  1310. for (bl = 0; i < nexcs && bl < 960; i++) {
  1311. if (bl)
  1312. buf[bl++] = ',';
  1313. bl += sprintf( buf + bl, "%d", excs[i] );
  1314. j = i;
  1315. for (; i + 1 < nexcs && excs[i + 1] == excs[i] + 1; i++);
  1316. if (i != j)
  1317. bl += sprintf( buf + bl, ":%d", excs[i] );
  1318. }
  1319. if ((ret = imap_exec_b( ctx, 0, "UID FETCH %s (UID%s%s)", buf,
  1320. (gctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  1321. (gctx->opts & OPEN_SIZE) ? " RFC822.SIZE" : "" )) != DRV_OK)
  1322. goto bail;
  1323. }
  1324. if (maxuid == INT_MAX)
  1325. maxuid = ctx->uidnext ? ctx->uidnext - 1 : 1000000000;
  1326. if (maxuid >= minuid &&
  1327. (ret = imap_exec_b( ctx, 0, "UID FETCH %d:%d (UID%s%s)", minuid, maxuid,
  1328. (gctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  1329. (gctx->opts & OPEN_SIZE) ? " RFC822.SIZE" : "" )) != DRV_OK)
  1330. goto bail;
  1331. }
  1332. ret = DRV_OK;
  1333. bail:
  1334. if (excs)
  1335. free( excs );
  1336. cb( ret, aux );
  1337. }
  1338. static void
  1339. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data,
  1340. void (*cb)( int sts, void *aux ), void *aux )
  1341. {
  1342. struct imap_cmd_cb cbd;
  1343. memset( &cbd, 0, sizeof(cbd) );
  1344. cbd.uid = msg->uid;
  1345. cbd.ctx = data;
  1346. cb( imap_exec_m( (imap_store_t *)ctx, &cbd, "UID FETCH %d (%sBODY.PEEK[])",
  1347. msg->uid, (msg->status & M_FLAGS) ? "" : "FLAGS " ), aux );
  1348. }
  1349. static int
  1350. imap_make_flags( int flags, char *buf )
  1351. {
  1352. const char *s;
  1353. unsigned i, d;
  1354. for (i = d = 0; i < as(Flags); i++)
  1355. if (flags & (1 << i)) {
  1356. buf[d++] = ' ';
  1357. buf[d++] = '\\';
  1358. for (s = Flags[i]; *s; s++)
  1359. buf[d++] = *s;
  1360. }
  1361. buf[0] = '(';
  1362. buf[d++] = ')';
  1363. return d;
  1364. }
  1365. static int
  1366. imap_flags_helper( imap_store_t *ctx, int uid, char what, int flags)
  1367. {
  1368. char buf[256];
  1369. buf[imap_make_flags( flags, buf )] = 0;
  1370. return issue_imap_cmd_w( ctx, 0, "UID STORE %d %cFLAGS.SILENT %s", uid, what, buf ) ? DRV_OK : DRV_STORE_BAD;
  1371. }
  1372. static void
  1373. imap_set_flags( store_t *gctx, message_t *msg, int uid, int add, int del,
  1374. void (*cb)( int sts, void *aux ), void *aux )
  1375. {
  1376. imap_store_t *ctx = (imap_store_t *)gctx;
  1377. int ret;
  1378. if (msg) {
  1379. uid = msg->uid;
  1380. add &= ~msg->flags;
  1381. del &= msg->flags;
  1382. msg->flags |= add;
  1383. msg->flags &= ~del;
  1384. }
  1385. if ((!add || (ret = imap_flags_helper( ctx, uid, '+', add )) == DRV_OK) &&
  1386. (!del || (ret = imap_flags_helper( ctx, uid, '-', del )) == DRV_OK))
  1387. ret = DRV_OK;
  1388. cb( ret, aux );
  1389. }
  1390. static void
  1391. imap_close( store_t *ctx,
  1392. void (*cb)( int sts, void *aux ), void *aux )
  1393. {
  1394. cb( imap_exec_b( (imap_store_t *)ctx, 0, "CLOSE" ), aux );
  1395. }
  1396. static void
  1397. imap_trash_msg( store_t *gctx, message_t *msg,
  1398. void (*cb)( int sts, void *aux ), void *aux )
  1399. {
  1400. imap_store_t *ctx = (imap_store_t *)gctx;
  1401. struct imap_cmd_cb cbd;
  1402. memset( &cbd, 0, sizeof(cbd) );
  1403. cbd.create = 1;
  1404. cb( imap_exec_m( ctx, &cbd, "UID COPY %d \"%s%s\"",
  1405. msg->uid, ctx->prefix, gctx->conf->trash ), aux );
  1406. }
  1407. static void
  1408. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  1409. void (*cb)( int sts, int uid, void *aux ), void *aux )
  1410. {
  1411. imap_store_t *ctx = (imap_store_t *)gctx;
  1412. struct imap_cmd_cb cbd;
  1413. const char *prefix, *box;
  1414. int ret, d, uid;
  1415. char flagstr[128];
  1416. d = 0;
  1417. if (data->flags) {
  1418. d = imap_make_flags( data->flags, flagstr );
  1419. flagstr[d++] = ' ';
  1420. }
  1421. flagstr[d] = 0;
  1422. memset( &cbd, 0, sizeof(cbd) );
  1423. cbd.dlen = data->len;
  1424. cbd.data = data->data;
  1425. cbd.ctx = &uid;
  1426. uid = -2;
  1427. if (to_trash) {
  1428. box = gctx->conf->trash;
  1429. prefix = ctx->prefix;
  1430. cbd.create = 1;
  1431. if (ctx->trashnc)
  1432. ctx->caps = ctx->rcaps & ~(1 << LITERALPLUS);
  1433. } else {
  1434. box = gctx->name;
  1435. prefix = !strcmp( box, "INBOX" ) ? "" : ctx->prefix;
  1436. cbd.create = (gctx->opts & OPEN_CREATE) != 0;
  1437. /*if (ctx->currentnc)
  1438. ctx->caps = ctx->rcaps & ~(1 << LITERALPLUS);*/
  1439. }
  1440. ret = imap_exec_m( ctx, &cbd, "APPEND \"%s%s\" %s", prefix, box, flagstr );
  1441. ctx->caps = ctx->rcaps;
  1442. if (ret != DRV_OK) {
  1443. cb( ret, -1, aux );
  1444. return;
  1445. }
  1446. if (to_trash)
  1447. ctx->trashnc = 0;
  1448. else {
  1449. /*ctx->currentnc = 0;*/
  1450. }
  1451. cb( DRV_OK, uid, aux );
  1452. }
  1453. static void
  1454. imap_find_msg( store_t *gctx, const char *tuid,
  1455. void (*cb)( int sts, int uid, void *aux ), void *aux )
  1456. {
  1457. imap_store_t *ctx = (imap_store_t *)gctx;
  1458. struct imap_cmd_cb cbd;
  1459. int ret, uid;
  1460. memset( &cbd, 0, sizeof(cbd) );
  1461. cbd.uid = -1; /* we're looking for a UID */
  1462. cbd.ctx = &uid;
  1463. uid = -1; /* in case we get no SEARCH response at all */
  1464. if ((ret = imap_exec_m( ctx, &cbd, "UID SEARCH HEADER X-TUID %." stringify(TUIDL) "s", tuid )) != DRV_OK)
  1465. cb( ret, -1, aux );
  1466. else
  1467. cb( uid <= 0 ? DRV_MSG_BAD : DRV_OK, uid, aux );
  1468. }
  1469. static void
  1470. imap_list( store_t *gctx,
  1471. void (*cb)( int sts, void *aux ), void *aux )
  1472. {
  1473. imap_store_t *ctx = (imap_store_t *)gctx;
  1474. int ret;
  1475. if ((ret = imap_exec_b( ctx, 0, "LIST \"\" \"%s%%\"", ctx->prefix )) == DRV_OK)
  1476. gctx->listed = 1;
  1477. cb( ret, aux );
  1478. }
  1479. static void
  1480. imap_cancel( store_t *gctx,
  1481. void (*cb)( int sts, void *aux ), void *aux )
  1482. {
  1483. (void)gctx;
  1484. cb( DRV_OK, aux );
  1485. }
  1486. static void
  1487. imap_commit( store_t *gctx )
  1488. {
  1489. (void)gctx;
  1490. }
  1491. imap_server_conf_t *servers, **serverapp = &servers;
  1492. static int
  1493. imap_parse_store( conffile_t *cfg, store_conf_t **storep, int *err )
  1494. {
  1495. imap_store_conf_t *store;
  1496. imap_server_conf_t *server, *srv, sserver;
  1497. int acc_opt = 0;
  1498. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  1499. server = nfcalloc( sizeof(*server) );
  1500. server->name = nfstrdup( cfg->val );
  1501. *serverapp = server;
  1502. serverapp = &server->next;
  1503. store = 0;
  1504. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  1505. store = nfcalloc( sizeof(*store) );
  1506. store->gen.driver = &imap_driver;
  1507. store->gen.name = nfstrdup( cfg->val );
  1508. store->use_namespace = 1;
  1509. *storep = &store->gen;
  1510. memset( &sserver, 0, sizeof(sserver) );
  1511. server = &sserver;
  1512. } else
  1513. return 0;
  1514. #if HAVE_LIBSSL
  1515. /* this will probably annoy people, but its the best default just in
  1516. * case people forget to turn it on
  1517. */
  1518. server->require_ssl = 1;
  1519. server->use_tlsv1 = 1;
  1520. #endif
  1521. while (getcline( cfg ) && cfg->cmd) {
  1522. if (!strcasecmp( "Host", cfg->cmd )) {
  1523. /* The imap[s]: syntax is just a backwards compat hack. */
  1524. #if HAVE_LIBSSL
  1525. if (!memcmp( "imaps:", cfg->val, 6 )) {
  1526. cfg->val += 6;
  1527. server->use_imaps = 1;
  1528. server->use_sslv2 = 1;
  1529. server->use_sslv3 = 1;
  1530. } else
  1531. #endif
  1532. {
  1533. if (!memcmp( "imap:", cfg->val, 5 ))
  1534. cfg->val += 5;
  1535. }
  1536. if (!memcmp( "//", cfg->val, 2 ))
  1537. cfg->val += 2;
  1538. server->host = nfstrdup( cfg->val );
  1539. }
  1540. else if (!strcasecmp( "User", cfg->cmd ))
  1541. server->user = nfstrdup( cfg->val );
  1542. else if (!strcasecmp( "Pass", cfg->cmd ))
  1543. server->pass = nfstrdup( cfg->val );
  1544. else if (!strcasecmp( "Port", cfg->cmd ))
  1545. server->port = parse_int( cfg );
  1546. #if HAVE_LIBSSL
  1547. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  1548. server->cert_file = expand_strdup( cfg->val );
  1549. if (access( server->cert_file, R_OK )) {
  1550. error( "%s:%d: CertificateFile '%s': %s\n",
  1551. cfg->file, cfg->line, server->cert_file, strerror( errno ) );
  1552. *err = 1;
  1553. }
  1554. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  1555. server->require_ssl = parse_bool( cfg );
  1556. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  1557. server->use_imaps = parse_bool( cfg );
  1558. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  1559. server->use_sslv2 = parse_bool( cfg );
  1560. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  1561. server->use_sslv3 = parse_bool( cfg );
  1562. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  1563. server->use_tlsv1 = parse_bool( cfg );
  1564. else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  1565. server->require_cram = parse_bool( cfg );
  1566. #endif
  1567. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  1568. server->tunnel = nfstrdup( cfg->val );
  1569. else if (store) {
  1570. if (!strcasecmp( "Account", cfg->cmd )) {
  1571. for (srv = servers; srv; srv = srv->next)
  1572. if (srv->name && !strcmp( srv->name, cfg->val ))
  1573. goto gotsrv;
  1574. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  1575. *err = 1;
  1576. continue;
  1577. gotsrv:
  1578. store->server = srv;
  1579. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  1580. store->use_namespace = parse_bool( cfg );
  1581. else if (!strcasecmp( "Path", cfg->cmd ))
  1582. store->gen.path = nfstrdup( cfg->val );
  1583. else
  1584. parse_generic_store( &store->gen, cfg, err );
  1585. continue;
  1586. } else {
  1587. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  1588. *err = 1;
  1589. continue;
  1590. }
  1591. acc_opt = 1;
  1592. }
  1593. if (!store || !store->server) {
  1594. if (!server->tunnel && !server->host) {
  1595. if (store)
  1596. error( "IMAP store '%s' has incomplete/missing connection details\n", store->gen.name );
  1597. else
  1598. error( "IMAP account '%s' has incomplete/missing connection details\n", server->name );
  1599. *err = 1;
  1600. return 1;
  1601. }
  1602. }
  1603. if (store) {
  1604. if (!store->server) {
  1605. store->server = nfmalloc( sizeof(sserver) );
  1606. memcpy( store->server, &sserver, sizeof(sserver) );
  1607. } else if (acc_opt) {
  1608. error( "IMAP store '%s' has both Account and account-specific options\n", store->gen.name );
  1609. *err = 1;
  1610. }
  1611. }
  1612. return 1;
  1613. }
  1614. struct driver imap_driver = {
  1615. DRV_CRLF,
  1616. imap_parse_store,
  1617. imap_cleanup,
  1618. imap_open_store,
  1619. imap_disown_store,
  1620. imap_own_store,
  1621. imap_cancel_store,
  1622. imap_list,
  1623. imap_prepare_paths,
  1624. imap_prepare_opts,
  1625. imap_select,
  1626. imap_fetch_msg,
  1627. imap_store_msg,
  1628. imap_find_msg,
  1629. imap_set_flags,
  1630. imap_trash_msg,
  1631. imap_close,
  1632. imap_cancel,
  1633. imap_commit,
  1634. };