drv_imap.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2004 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. list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
  105. string_list_t *boxes; /* LIST results */
  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->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_close_store( store_t *gctx )
  935. {
  936. imap_store_t *ctx = (imap_store_t *)gctx;
  937. free_generic_messages( gctx->msgs );
  938. if (ctx->buf.sock.fd != -1) {
  939. imap_exec( ctx, 0, "LOGOUT" );
  940. close( ctx->buf.sock.fd );
  941. }
  942. #ifdef HAVE_LIBSSL
  943. if (ctx->SSLContext)
  944. SSL_CTX_free( ctx->SSLContext );
  945. #endif
  946. free_list( ctx->ns_personal );
  947. free_list( ctx->ns_other );
  948. free_list( ctx->ns_shared );
  949. free( ctx );
  950. }
  951. #ifdef HAVE_LIBSSL
  952. static int
  953. start_tls( imap_store_t *ctx )
  954. {
  955. int ret;
  956. static int ssl_inited;
  957. if (!ssl_inited) {
  958. SSL_library_init();
  959. SSL_load_error_strings();
  960. ssl_inited = 1;
  961. }
  962. if (init_ssl_ctx( ctx ))
  963. return 1;
  964. ctx->buf.sock.ssl = SSL_new( ctx->SSLContext );
  965. SSL_set_fd( ctx->buf.sock.ssl, ctx->buf.sock.fd );
  966. if ((ret = SSL_connect( ctx->buf.sock.ssl )) <= 0) {
  967. socket_perror( "connect", &ctx->buf.sock, ret );
  968. return 1;
  969. }
  970. /* verify the server certificate */
  971. if (verify_cert( ctx->buf.sock.ssl ))
  972. return 1;
  973. ctx->buf.sock.use_ssl = 1;
  974. info( "Connection is now encrypted\n" );
  975. return 0;
  976. }
  977. #define ENCODED_SIZE(n) (4*((n+2)/3))
  978. static char
  979. hexchar( unsigned int b )
  980. {
  981. if (b < 10)
  982. return '0' + b;
  983. return 'a' + (b - 10);
  984. }
  985. /* XXX merge into do_cram_auth? */
  986. static char *
  987. cram( const char *challenge, const char *user, const char *pass )
  988. {
  989. HMAC_CTX hmac;
  990. char hash[16];
  991. char hex[33];
  992. int i;
  993. unsigned int hashlen = sizeof(hash);
  994. char buf[256];
  995. int len = strlen( challenge );
  996. char *response = nfcalloc( 1 + len );
  997. char *final;
  998. /* response will always be smaller than challenge because we are
  999. * decoding.
  1000. */
  1001. len = EVP_DecodeBlock( (unsigned char *)response, (unsigned char *)challenge, strlen( challenge ) );
  1002. HMAC_Init( &hmac, (unsigned char *) pass, strlen( pass ), EVP_md5() );
  1003. HMAC_Update( &hmac, (unsigned char *)response, strlen( response ) );
  1004. HMAC_Final( &hmac, (unsigned char *)hash, &hashlen );
  1005. assert( hashlen == sizeof(hash) );
  1006. free( response );
  1007. hex[32] = 0;
  1008. for (i = 0; i < 16; i++) {
  1009. hex[2 * i] = hexchar( (hash[i] >> 4) & 0xf );
  1010. hex[2 * i + 1] = hexchar( hash[i] & 0xf );
  1011. }
  1012. nfsnprintf( buf, sizeof(buf), "%s %s", user, hex );
  1013. len = strlen( buf );
  1014. len = ENCODED_SIZE( len ) + 1;
  1015. final = nfmalloc( len );
  1016. final[len - 1] = 0;
  1017. assert( EVP_EncodeBlock( (unsigned char *)final, (unsigned char *)buf, strlen( buf ) ) == len - 1 );
  1018. return final;
  1019. }
  1020. static int
  1021. do_cram_auth( imap_store_t *ctx, struct imap_cmd *cmdp, const char *prompt )
  1022. {
  1023. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1024. char *resp;
  1025. int n, l;
  1026. resp = cram( prompt, srvc->user, srvc->pass );
  1027. if (DFlags & VERBOSE)
  1028. printf( ">+> %s\n", resp );
  1029. l = strlen( resp );
  1030. n = socket_write( &ctx->buf.sock, resp, l );
  1031. free( resp );
  1032. if (n != l)
  1033. return -1;
  1034. cmdp->cb.cont = 0;
  1035. return 0;
  1036. }
  1037. #endif
  1038. static store_t *
  1039. imap_open_store( store_conf_t *conf, store_t *oldctx )
  1040. {
  1041. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1042. imap_server_conf_t *srvc = cfg->server;
  1043. imap_store_t *ctx = (imap_store_t *)oldctx;
  1044. char *arg, *rsp;
  1045. struct hostent *he;
  1046. struct sockaddr_in addr;
  1047. int s, a[2], preauth;
  1048. #if HAVE_LIBSSL
  1049. int use_ssl;
  1050. #endif
  1051. if (ctx) {
  1052. if (((imap_store_conf_t *)(ctx->gen.conf))->server == cfg->server) {
  1053. ctx->gen.conf = conf;
  1054. goto final;
  1055. }
  1056. imap_close_store( &ctx->gen );
  1057. }
  1058. ctx = nfcalloc( sizeof(*ctx) );
  1059. ctx->gen.conf = conf;
  1060. ctx->buf.sock.fd = -1;
  1061. ctx->in_progress_append = &ctx->in_progress;
  1062. /* open connection to IMAP server */
  1063. #if HAVE_LIBSSL
  1064. use_ssl = 0;
  1065. #endif
  1066. if (srvc->tunnel) {
  1067. infon( "Starting tunnel '%s'... ", srvc->tunnel );
  1068. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  1069. perror( "socketpair" );
  1070. exit( 1 );
  1071. }
  1072. if (fork() == 0) {
  1073. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  1074. _exit( 127 );
  1075. close( a[0] );
  1076. close( a[1] );
  1077. execl( "/bin/sh", "sh", "-c", srvc->tunnel, (char *)0 );
  1078. _exit( 127 );
  1079. }
  1080. close (a[0]);
  1081. ctx->buf.sock.fd = a[1];
  1082. info( "ok\n" );
  1083. } else {
  1084. memset( &addr, 0, sizeof(addr) );
  1085. addr.sin_port = htons( srvc->port );
  1086. addr.sin_family = AF_INET;
  1087. infon( "Resolving %s... ", srvc->host );
  1088. he = gethostbyname( srvc->host );
  1089. if (!he) {
  1090. perror( "gethostbyname" );
  1091. goto bail;
  1092. }
  1093. info( "ok\n" );
  1094. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  1095. s = socket( PF_INET, SOCK_STREAM, 0 );
  1096. infon( "Connecting to %s:%hu... ", inet_ntoa( addr.sin_addr ), ntohs( addr.sin_port ) );
  1097. if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) {
  1098. close( s );
  1099. perror( "connect" );
  1100. goto bail;
  1101. }
  1102. info( "ok\n" );
  1103. ctx->buf.sock.fd = s;
  1104. #if HAVE_LIBSSL
  1105. if (srvc->use_imaps) {
  1106. if (start_tls( ctx ))
  1107. goto bail;
  1108. use_ssl = 1;
  1109. }
  1110. #endif
  1111. }
  1112. /* read the greeting string */
  1113. if (buffer_gets( &ctx->buf, &rsp )) {
  1114. error( "IMAP error: no greeting response\n" );
  1115. goto bail;
  1116. }
  1117. arg = next_arg( &rsp );
  1118. if (!arg || *arg != '*' || (arg = next_arg( &rsp )) == NULL) {
  1119. error( "IMAP error: invalid greeting response\n" );
  1120. goto bail;
  1121. }
  1122. preauth = 0;
  1123. if (!strcmp( "PREAUTH", arg ))
  1124. preauth = 1;
  1125. else if (strcmp( "OK", arg ) != 0) {
  1126. error( "IMAP error: unknown greeting response\n" );
  1127. goto bail;
  1128. }
  1129. parse_response_code( ctx, 0, rsp );
  1130. if (!ctx->caps && imap_exec( ctx, 0, "CAPABILITY" ) != RESP_OK)
  1131. goto bail;
  1132. if (!preauth) {
  1133. #if HAVE_LIBSSL
  1134. if (!srvc->use_imaps && (srvc->use_sslv2 || srvc->use_sslv3 || srvc->use_tlsv1)) {
  1135. /* always try to select SSL support if available */
  1136. if (CAP(STARTTLS)) {
  1137. if (imap_exec( ctx, 0, "STARTTLS" ) != RESP_OK)
  1138. goto bail;
  1139. if (start_tls( ctx ))
  1140. goto bail;
  1141. use_ssl = 1;
  1142. if (imap_exec( ctx, 0, "CAPABILITY" ) != RESP_OK)
  1143. goto bail;
  1144. } else {
  1145. if (srvc->require_ssl) {
  1146. error( "IMAP error: SSL support not available\n" );
  1147. goto bail;
  1148. } else
  1149. warn( "IMAP warning: SSL support not available\n" );
  1150. }
  1151. }
  1152. #endif
  1153. info ("Logging in...\n");
  1154. if (!srvc->user) {
  1155. error( "Skipping server %s, no user\n", srvc->host );
  1156. goto bail;
  1157. }
  1158. if (!srvc->pass) {
  1159. char prompt[80];
  1160. sprintf( prompt, "Password (%s@%s): ", srvc->user, srvc->host );
  1161. arg = getpass( prompt );
  1162. if (!arg) {
  1163. perror( "getpass" );
  1164. exit( 1 );
  1165. }
  1166. if (!*arg) {
  1167. error( "Skipping account %s@%s, no password\n", srvc->user, srvc->host );
  1168. goto bail;
  1169. }
  1170. /*
  1171. * getpass() returns a pointer to a static buffer. make a copy
  1172. * for long term storage.
  1173. */
  1174. srvc->pass = nfstrdup( arg );
  1175. }
  1176. #if HAVE_LIBSSL
  1177. if (CAP(CRAM)) {
  1178. struct imap_cmd_cb cb;
  1179. info( "Authenticating with CRAM-MD5\n" );
  1180. memset( &cb, 0, sizeof(cb) );
  1181. cb.cont = do_cram_auth;
  1182. if (imap_exec( ctx, &cb, "AUTHENTICATE CRAM-MD5" ) != RESP_OK)
  1183. goto bail;
  1184. } else if (srvc->require_cram) {
  1185. error( "IMAP error: CRAM-MD5 authentication is not supported by server\n" );
  1186. goto bail;
  1187. } else
  1188. #endif
  1189. {
  1190. if (CAP(NOLOGIN)) {
  1191. error( "Skipping account %s@%s, server forbids LOGIN\n", srvc->user, srvc->host );
  1192. goto bail;
  1193. }
  1194. #if HAVE_LIBSSL
  1195. if (!use_ssl)
  1196. #endif
  1197. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  1198. if (imap_exec( ctx, 0, "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass ) != RESP_OK) {
  1199. error( "IMAP error: LOGIN failed\n" );
  1200. goto bail;
  1201. }
  1202. }
  1203. } /* !preauth */
  1204. final:
  1205. ctx->prefix = "";
  1206. if (*conf->path)
  1207. ctx->prefix = conf->path;
  1208. else if (cfg->use_namespace && CAP(NAMESPACE)) {
  1209. /* get NAMESPACE info */
  1210. if (imap_exec( ctx, 0, "NAMESPACE" ) != RESP_OK)
  1211. goto bail;
  1212. /* XXX for now assume personal namespace */
  1213. if (is_list( ctx->ns_personal ) &&
  1214. is_list( ctx->ns_personal->child ) &&
  1215. is_atom( ctx->ns_personal->child->child ))
  1216. ctx->prefix = ctx->ns_personal->child->child->val;
  1217. }
  1218. ctx->trashnc = 1;
  1219. return &ctx->gen;
  1220. bail:
  1221. imap_close_store( &ctx->gen );
  1222. return 0;
  1223. }
  1224. static void
  1225. imap_prepare_paths( store_t *gctx )
  1226. {
  1227. free_generic_messages( gctx->msgs );
  1228. gctx->msgs = 0;
  1229. }
  1230. static void
  1231. imap_prepare_opts( store_t *gctx, int opts )
  1232. {
  1233. gctx->opts = opts;
  1234. }
  1235. static int
  1236. imap_select( store_t *gctx, int minuid, int maxuid, int *excs, int nexcs )
  1237. {
  1238. imap_store_t *ctx = (imap_store_t *)gctx;
  1239. const char *prefix;
  1240. int ret, i, j, bl;
  1241. struct imap_cmd_cb cb;
  1242. char buf[1000];
  1243. if (!strcmp( gctx->name, "INBOX" )) {
  1244. // ctx->currentnc = 0;
  1245. prefix = "";
  1246. } else {
  1247. // ctx->currentnc = 1; /* could use LIST results for that */
  1248. prefix = ctx->prefix;
  1249. }
  1250. memset( &cb, 0, sizeof(cb) );
  1251. cb.create = (gctx->opts & OPEN_CREATE) != 0;
  1252. cb.trycreate = 1;
  1253. if ((ret = imap_exec_b( ctx, &cb, "SELECT \"%s%s\"", prefix, gctx->name )) != DRV_OK)
  1254. goto bail;
  1255. if (gctx->count) {
  1256. ctx->msgapp = &gctx->msgs;
  1257. sort_ints( excs, nexcs );
  1258. for (i = 0; i < nexcs; ) {
  1259. for (bl = 0; i < nexcs && bl < 960; i++) {
  1260. if (bl)
  1261. buf[bl++] = ',';
  1262. bl += sprintf( buf + bl, "%d", excs[i] );
  1263. j = i;
  1264. for (; i + 1 < nexcs && excs[i + 1] == excs[i] + 1; i++);
  1265. if (i != j)
  1266. bl += sprintf( buf + bl, ":%d", excs[i] );
  1267. }
  1268. if ((ret = imap_exec_b( ctx, 0, "UID FETCH %s (UID%s%s)", buf,
  1269. (gctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  1270. (gctx->opts & OPEN_SIZE) ? " RFC822.SIZE" : "" )) != DRV_OK)
  1271. goto bail;
  1272. }
  1273. if (maxuid == INT_MAX)
  1274. maxuid = ctx->uidnext ? ctx->uidnext - 1 : 1000000000;
  1275. if (maxuid >= minuid &&
  1276. (ret = imap_exec_b( ctx, 0, "UID FETCH %d:%d (UID%s%s)", minuid, maxuid,
  1277. (gctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  1278. (gctx->opts & OPEN_SIZE) ? " RFC822.SIZE" : "" )) != DRV_OK)
  1279. goto bail;
  1280. }
  1281. ret = DRV_OK;
  1282. bail:
  1283. if (excs)
  1284. free( excs );
  1285. return ret;
  1286. }
  1287. static int
  1288. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data )
  1289. {
  1290. struct imap_cmd_cb cb;
  1291. memset( &cb, 0, sizeof(cb) );
  1292. cb.uid = msg->uid;
  1293. cb.ctx = data;
  1294. return imap_exec_m( (imap_store_t *)ctx, &cb, "UID FETCH %d (%sBODY.PEEK[])",
  1295. msg->uid, (msg->status & M_FLAGS) ? "" : "FLAGS " );
  1296. }
  1297. static int
  1298. imap_make_flags( int flags, char *buf )
  1299. {
  1300. const char *s;
  1301. unsigned i, d;
  1302. for (i = d = 0; i < as(Flags); i++)
  1303. if (flags & (1 << i)) {
  1304. buf[d++] = ' ';
  1305. buf[d++] = '\\';
  1306. for (s = Flags[i]; *s; s++)
  1307. buf[d++] = *s;
  1308. }
  1309. buf[0] = '(';
  1310. buf[d++] = ')';
  1311. return d;
  1312. }
  1313. static int
  1314. imap_flags_helper( imap_store_t *ctx, int uid, char what, int flags)
  1315. {
  1316. char buf[256];
  1317. buf[imap_make_flags( flags, buf )] = 0;
  1318. return issue_imap_cmd_w( ctx, 0, "UID STORE %d %cFLAGS.SILENT %s", uid, what, buf ) ? DRV_OK : DRV_STORE_BAD;
  1319. }
  1320. static int
  1321. imap_set_flags( store_t *gctx, message_t *msg, int uid, int add, int del )
  1322. {
  1323. imap_store_t *ctx = (imap_store_t *)gctx;
  1324. int ret;
  1325. if (msg) {
  1326. uid = msg->uid;
  1327. add &= ~msg->flags;
  1328. del &= msg->flags;
  1329. msg->flags |= add;
  1330. msg->flags &= ~del;
  1331. }
  1332. if ((!add || (ret = imap_flags_helper( ctx, uid, '+', add )) == DRV_OK) &&
  1333. (!del || (ret = imap_flags_helper( ctx, uid, '-', del )) == DRV_OK))
  1334. return DRV_OK;
  1335. return ret;
  1336. }
  1337. static int
  1338. imap_close( store_t *ctx )
  1339. {
  1340. return imap_exec_b( (imap_store_t *)ctx, 0, "CLOSE" );
  1341. }
  1342. static int
  1343. imap_trash_msg( store_t *gctx, message_t *msg )
  1344. {
  1345. imap_store_t *ctx = (imap_store_t *)gctx;
  1346. struct imap_cmd_cb cb;
  1347. memset( &cb, 0, sizeof(cb) );
  1348. cb.create = 1;
  1349. return imap_exec_m( ctx, &cb, "UID COPY %d \"%s%s\"",
  1350. msg->uid, ctx->prefix, gctx->conf->trash );
  1351. }
  1352. static int
  1353. imap_store_msg( store_t *gctx, msg_data_t *data, int *uid )
  1354. {
  1355. imap_store_t *ctx = (imap_store_t *)gctx;
  1356. struct imap_cmd_cb cb;
  1357. const char *prefix, *box;
  1358. int ret, d;
  1359. char flagstr[128];
  1360. d = 0;
  1361. if (data->flags) {
  1362. d = imap_make_flags( data->flags, flagstr );
  1363. flagstr[d++] = ' ';
  1364. }
  1365. flagstr[d] = 0;
  1366. memset( &cb, 0, sizeof(cb) );
  1367. cb.dlen = data->len;
  1368. cb.data = data->data;
  1369. if (!uid) {
  1370. box = gctx->conf->trash;
  1371. prefix = ctx->prefix;
  1372. cb.create = 1;
  1373. if (ctx->trashnc)
  1374. ctx->caps = ctx->rcaps & ~(1 << LITERALPLUS);
  1375. } else {
  1376. box = gctx->name;
  1377. prefix = !strcmp( box, "INBOX" ) ? "" : ctx->prefix;
  1378. cb.create = (gctx->opts & OPEN_CREATE) != 0;
  1379. /*if (ctx->currentnc)
  1380. ctx->caps = ctx->rcaps & ~(1 << LITERALPLUS);*/
  1381. *uid = -2;
  1382. }
  1383. cb.ctx = uid;
  1384. ret = imap_exec_m( ctx, &cb, "APPEND \"%s%s\" %s", prefix, box, flagstr );
  1385. ctx->caps = ctx->rcaps;
  1386. if (ret != DRV_OK)
  1387. return ret;
  1388. if (!uid)
  1389. ctx->trashnc = 0;
  1390. else {
  1391. /*ctx->currentnc = 0;*/
  1392. gctx->count++;
  1393. }
  1394. return DRV_OK;
  1395. }
  1396. static int
  1397. imap_find_msg( store_t *gctx, const char *tuid, int *uid )
  1398. {
  1399. imap_store_t *ctx = (imap_store_t *)gctx;
  1400. struct imap_cmd_cb cb;
  1401. int ret;
  1402. memset( &cb, 0, sizeof(cb) );
  1403. cb.ctx = uid;
  1404. cb.uid = -1; /* we're looking for a UID */
  1405. *uid = -1; /* in case we get no SEARCH response at all */
  1406. if ((ret = imap_exec_m( ctx, &cb, "UID SEARCH HEADER X-TUID %." stringify(TUIDL) "s", tuid )) != DRV_OK)
  1407. return ret;
  1408. return *uid < 0 ? DRV_MSG_BAD : DRV_OK;
  1409. }
  1410. static int
  1411. imap_list( store_t *gctx, string_list_t **retb )
  1412. {
  1413. imap_store_t *ctx = (imap_store_t *)gctx;
  1414. int ret;
  1415. ctx->boxes = 0;
  1416. if ((ret = imap_exec_b( ctx, 0, "LIST \"\" \"%s%%\"", ctx->prefix )) != DRV_OK)
  1417. return ret;
  1418. *retb = ctx->boxes;
  1419. return DRV_OK;
  1420. }
  1421. static int
  1422. imap_check( store_t *gctx )
  1423. {
  1424. (void) gctx;
  1425. /* flush queue here */
  1426. return DRV_OK;
  1427. }
  1428. imap_server_conf_t *servers, **serverapp = &servers;
  1429. static int
  1430. imap_parse_store( conffile_t *cfg, store_conf_t **storep, int *err )
  1431. {
  1432. imap_store_conf_t *store;
  1433. imap_server_conf_t *server, *srv, sserver;
  1434. int acc_opt = 0;
  1435. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  1436. server = nfcalloc( sizeof(*server) );
  1437. server->name = nfstrdup( cfg->val );
  1438. *serverapp = server;
  1439. serverapp = &server->next;
  1440. store = 0;
  1441. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  1442. store = nfcalloc( sizeof(*store) );
  1443. store->gen.driver = &imap_driver;
  1444. store->gen.name = nfstrdup( cfg->val );
  1445. store->use_namespace = 1;
  1446. *storep = &store->gen;
  1447. memset( &sserver, 0, sizeof(sserver) );
  1448. server = &sserver;
  1449. } else
  1450. return 0;
  1451. #if HAVE_LIBSSL
  1452. /* this will probably annoy people, but its the best default just in
  1453. * case people forget to turn it on
  1454. */
  1455. server->require_ssl = 1;
  1456. server->use_tlsv1 = 1;
  1457. #endif
  1458. while (getcline( cfg ) && cfg->cmd) {
  1459. if (!strcasecmp( "Host", cfg->cmd )) {
  1460. #if HAVE_LIBSSL
  1461. if (!memcmp( "imaps:", cfg->val, 6 )) {
  1462. cfg->val += 6;
  1463. server->use_imaps = 1;
  1464. server->use_sslv2 = 1;
  1465. server->use_sslv3 = 1;
  1466. if (!server->port)
  1467. server->port = 993;
  1468. } else
  1469. #endif
  1470. {
  1471. if (!memcmp( "imap:", cfg->val, 5 ))
  1472. cfg->val += 5;
  1473. if (!server->port)
  1474. server->port = 143;
  1475. }
  1476. if (!memcmp( "//", cfg->val, 2 ))
  1477. cfg->val += 2;
  1478. server->host = nfstrdup( cfg->val );
  1479. }
  1480. else if (!strcasecmp( "User", cfg->cmd ))
  1481. server->user = nfstrdup( cfg->val );
  1482. else if (!strcasecmp( "Pass", cfg->cmd ))
  1483. server->pass = nfstrdup( cfg->val );
  1484. else if (!strcasecmp( "Port", cfg->cmd ))
  1485. server->port = parse_int( cfg );
  1486. #if HAVE_LIBSSL
  1487. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  1488. server->cert_file = expand_strdup( cfg->val );
  1489. if (access( server->cert_file, R_OK )) {
  1490. error( "%s:%d: CertificateFile '%s': %s\n",
  1491. cfg->file, cfg->line, server->cert_file, strerror( errno ) );
  1492. *err = 1;
  1493. }
  1494. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  1495. server->require_ssl = parse_bool( cfg );
  1496. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  1497. server->use_sslv2 = parse_bool( cfg );
  1498. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  1499. server->use_sslv3 = parse_bool( cfg );
  1500. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  1501. server->use_tlsv1 = parse_bool( cfg );
  1502. else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  1503. server->require_cram = parse_bool( cfg );
  1504. #endif
  1505. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  1506. server->tunnel = nfstrdup( cfg->val );
  1507. else if (store) {
  1508. if (!strcasecmp( "Account", cfg->cmd )) {
  1509. for (srv = servers; srv; srv = srv->next)
  1510. if (srv->name && !strcmp( srv->name, cfg->val ))
  1511. goto gotsrv;
  1512. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  1513. *err = 1;
  1514. continue;
  1515. gotsrv:
  1516. store->server = srv;
  1517. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  1518. store->use_namespace = parse_bool( cfg );
  1519. else if (!strcasecmp( "Path", cfg->cmd ))
  1520. store->gen.path = nfstrdup( cfg->val );
  1521. else
  1522. parse_generic_store( &store->gen, cfg, err );
  1523. continue;
  1524. } else {
  1525. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  1526. *err = 1;
  1527. continue;
  1528. }
  1529. acc_opt = 1;
  1530. }
  1531. if (!store || !store->server) {
  1532. if (!server->tunnel && !server->host) {
  1533. if (store)
  1534. error( "IMAP store '%s' has incomplete/missing connection details\n", store->gen.name );
  1535. else
  1536. error( "IMAP account '%s' has incomplete/missing connection details\n", server->name );
  1537. *err = 1;
  1538. return 1;
  1539. }
  1540. }
  1541. if (store) {
  1542. if (!store->server) {
  1543. store->server = nfmalloc( sizeof(sserver) );
  1544. memcpy( store->server, &sserver, sizeof(sserver) );
  1545. } else if (acc_opt) {
  1546. error( "IMAP store '%s' has both Account and account-specific options\n", store->gen.name );
  1547. *err = 1;
  1548. }
  1549. }
  1550. return 1;
  1551. }
  1552. struct driver imap_driver = {
  1553. DRV_CRLF,
  1554. imap_parse_store,
  1555. imap_open_store,
  1556. imap_close_store,
  1557. imap_list,
  1558. imap_prepare_paths,
  1559. imap_prepare_opts,
  1560. imap_select,
  1561. imap_fetch_msg,
  1562. imap_store_msg,
  1563. imap_find_msg,
  1564. imap_set_flags,
  1565. imap_trash_msg,
  1566. imap_check,
  1567. imap_close
  1568. };