drv_imap.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006,2008,2010-2013 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, see <http://www.gnu.org/licenses/>.
  19. *
  20. * As a special exception, mbsync may be linked with the OpenSSL library,
  21. * despite that library's more restrictive license.
  22. */
  23. #include "isync.h"
  24. #include <assert.h>
  25. #include <unistd.h>
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <stddef.h>
  29. #include <limits.h>
  30. #include <string.h>
  31. #include <ctype.h>
  32. #include <sys/wait.h>
  33. typedef struct imap_server_conf {
  34. struct imap_server_conf *next;
  35. char *name;
  36. server_conf_t sconf;
  37. char *user;
  38. char *pass;
  39. char *pass_cmd;
  40. int max_in_progress;
  41. #ifdef HAVE_LIBSSL
  42. unsigned require_ssl:1;
  43. unsigned require_cram:1;
  44. #endif
  45. } imap_server_conf_t;
  46. typedef struct imap_store_conf {
  47. store_conf_t gen;
  48. imap_server_conf_t *server;
  49. unsigned use_namespace:1;
  50. char delimiter;
  51. } imap_store_conf_t;
  52. typedef struct imap_message {
  53. message_t gen;
  54. /* int seq; will be needed when expunges are tracked */
  55. } imap_message_t;
  56. #define NIL (void*)0x1
  57. #define LIST (void*)0x2
  58. typedef struct _list {
  59. struct _list *next, *child;
  60. char *val;
  61. int len;
  62. } list_t;
  63. #define MAX_LIST_DEPTH 5
  64. struct imap_store;
  65. typedef struct parse_list_state {
  66. list_t *head, **stack[MAX_LIST_DEPTH];
  67. int (*callback)( struct imap_store *ctx, list_t *list, char *cmd );
  68. int level, need_bytes;
  69. } parse_list_state_t;
  70. struct imap_cmd;
  71. typedef struct imap_store {
  72. store_t gen;
  73. const char *prefix;
  74. int ref_count;
  75. /* trash folder's existence is not confirmed yet */
  76. enum { TrashUnknown, TrashChecking, TrashKnown } trashnc;
  77. unsigned got_namespace:1;
  78. char delimiter; /* hierarchy delimiter */
  79. list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
  80. message_t **msgapp; /* FETCH results */
  81. unsigned caps; /* CAPABILITY results */
  82. parse_list_state_t parse_list_sts;
  83. /* command queue */
  84. int nexttag, num_in_progress;
  85. struct imap_cmd *pending, **pending_append;
  86. struct imap_cmd *in_progress, **in_progress_append;
  87. /* Used during sequential operations like connect */
  88. enum { GreetingPending = 0, GreetingBad, GreetingOk, GreetingPreauth } greeting;
  89. int canceling; /* imap_cancel() is in progress */
  90. union {
  91. void (*imap_open)( store_t *srv, void *aux );
  92. void (*imap_cancel)( void *aux );
  93. } callbacks;
  94. void *callback_aux;
  95. conn_t conn; /* this is BIG, so put it last */
  96. } imap_store_t;
  97. struct imap_cmd {
  98. struct imap_cmd *next;
  99. char *cmd;
  100. int tag;
  101. struct {
  102. /* Will be called on each continuation request until it resets this pointer.
  103. * Needs to invoke bad_callback and return -1 on error, otherwise return 0. */
  104. int (*cont)( imap_store_t *ctx, struct imap_cmd *cmd, const char *prompt );
  105. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response );
  106. char *data;
  107. int data_len;
  108. int uid; /* to identify fetch responses */
  109. unsigned
  110. high_prio:1, /* if command is queued, put it at the front of the queue. */
  111. to_trash:1, /* we are storing to trash, not current. */
  112. create:1, /* create the mailbox if we get an error ... */
  113. trycreate:1; /* ... but only if this is true or the server says so. */
  114. } param;
  115. };
  116. struct imap_cmd_simple {
  117. struct imap_cmd gen;
  118. void (*callback)( int sts, void *aux );
  119. void *callback_aux;
  120. };
  121. struct imap_cmd_fetch_msg {
  122. struct imap_cmd_simple gen;
  123. msg_data_t *msg_data;
  124. };
  125. struct imap_cmd_out_uid {
  126. struct imap_cmd gen;
  127. void (*callback)( int sts, int uid, void *aux );
  128. void *callback_aux;
  129. int out_uid;
  130. };
  131. struct imap_cmd_refcounted_state {
  132. void (*callback)( int sts, void *aux );
  133. void *callback_aux;
  134. int ref_count;
  135. int ret_val;
  136. };
  137. struct imap_cmd_refcounted {
  138. struct imap_cmd gen;
  139. struct imap_cmd_refcounted_state *state;
  140. };
  141. #define CAP(cap) (ctx->caps & (1 << (cap)))
  142. enum CAPABILITY {
  143. NOLOGIN = 0,
  144. #ifdef HAVE_LIBSSL
  145. CRAM,
  146. STARTTLS,
  147. #endif
  148. UIDPLUS,
  149. LITERALPLUS,
  150. NAMESPACE
  151. };
  152. static const char *cap_list[] = {
  153. "LOGINDISABLED",
  154. #ifdef HAVE_LIBSSL
  155. "AUTH=CRAM-MD5",
  156. "STARTTLS",
  157. #endif
  158. "UIDPLUS",
  159. "LITERAL+",
  160. "NAMESPACE"
  161. };
  162. #define RESP_OK 0
  163. #define RESP_NO 1
  164. #define RESP_CANCEL 2
  165. static INLINE void imap_ref( imap_store_t *ctx ) { ++ctx->ref_count; }
  166. static int imap_deref( imap_store_t *ctx );
  167. static void imap_invoke_bad_callback( imap_store_t *ctx );
  168. static const char *Flags[] = {
  169. "Draft",
  170. "Flagged",
  171. "Answered",
  172. "Seen",
  173. "Deleted",
  174. };
  175. static struct imap_cmd *
  176. new_imap_cmd( int size )
  177. {
  178. struct imap_cmd *cmd = nfmalloc( size );
  179. memset( &cmd->param, 0, sizeof(cmd->param) );
  180. return cmd;
  181. }
  182. #define INIT_IMAP_CMD(type, cmdp, cb, aux) \
  183. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  184. cmdp->callback = cb; \
  185. cmdp->callback_aux = aux;
  186. #define INIT_IMAP_CMD_X(type, cmdp, cb, aux) \
  187. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  188. cmdp->gen.callback = cb; \
  189. cmdp->gen.callback_aux = aux;
  190. static void
  191. done_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd, int response )
  192. {
  193. cmd->param.done( ctx, cmd, response );
  194. free( cmd->param.data );
  195. free( cmd->cmd );
  196. free( cmd );
  197. }
  198. static int
  199. send_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd )
  200. {
  201. int bufl, litplus;
  202. const char *buffmt;
  203. char buf[1024];
  204. cmd->tag = ++ctx->nexttag;
  205. if (!cmd->param.data) {
  206. buffmt = "%d %s\r\n";
  207. litplus = 0;
  208. } else if ((cmd->param.to_trash && ctx->trashnc == TrashUnknown) || !CAP(LITERALPLUS)) {
  209. buffmt = "%d %s{%d}\r\n";
  210. litplus = 0;
  211. } else {
  212. buffmt = "%d %s{%d+}\r\n";
  213. litplus = 1;
  214. }
  215. bufl = nfsnprintf( buf, sizeof(buf), buffmt,
  216. cmd->tag, cmd->cmd, cmd->param.data_len );
  217. if (DFlags & VERBOSE) {
  218. if (ctx->num_in_progress)
  219. printf( "(%d in progress) ", ctx->num_in_progress );
  220. if (memcmp( cmd->cmd, "LOGIN", 5 ))
  221. printf( ">>> %s", buf );
  222. else
  223. printf( ">>> %d LOGIN <user> <pass>\n", cmd->tag );
  224. fflush( stdout );
  225. }
  226. if (socket_write( &ctx->conn, buf, bufl, KeepOwn ) < 0)
  227. goto bail;
  228. if (litplus) {
  229. char *p = cmd->param.data;
  230. cmd->param.data = 0;
  231. if (socket_write( &ctx->conn, p, cmd->param.data_len, GiveOwn ) < 0 ||
  232. socket_write( &ctx->conn, "\r\n", 2, KeepOwn ) < 0)
  233. goto bail;
  234. }
  235. if (cmd->param.to_trash && ctx->trashnc == TrashUnknown)
  236. ctx->trashnc = TrashChecking;
  237. cmd->next = 0;
  238. *ctx->in_progress_append = cmd;
  239. ctx->in_progress_append = &cmd->next;
  240. ctx->num_in_progress++;
  241. return 0;
  242. bail:
  243. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  244. return -1;
  245. }
  246. static int
  247. cmd_submittable( imap_store_t *ctx, struct imap_cmd *cmd )
  248. {
  249. struct imap_cmd *cmdp;
  250. return !ctx->conn.write_buf &&
  251. !(ctx->in_progress &&
  252. (cmdp = (struct imap_cmd *)((char *)ctx->in_progress_append -
  253. offsetof(struct imap_cmd, next)), 1) &&
  254. (cmdp->param.cont || cmdp->param.data)) &&
  255. !(cmd->param.to_trash && ctx->trashnc == TrashChecking) &&
  256. ctx->num_in_progress < ((imap_store_conf_t *)ctx->gen.conf)->server->max_in_progress;
  257. }
  258. static int
  259. flush_imap_cmds( imap_store_t *ctx )
  260. {
  261. struct imap_cmd *cmd;
  262. while ((cmd = ctx->pending) && cmd_submittable( ctx, cmd )) {
  263. if (!(ctx->pending = cmd->next))
  264. ctx->pending_append = &ctx->pending;
  265. if (send_imap_cmd( ctx, cmd ) < 0)
  266. return -1;
  267. }
  268. return 0;
  269. }
  270. static void
  271. cancel_pending_imap_cmds( imap_store_t *ctx )
  272. {
  273. struct imap_cmd *cmd;
  274. while ((cmd = ctx->pending)) {
  275. if (!(ctx->pending = cmd->next))
  276. ctx->pending_append = &ctx->pending;
  277. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  278. }
  279. }
  280. static void
  281. cancel_submitted_imap_cmds( imap_store_t *ctx )
  282. {
  283. struct imap_cmd *cmd;
  284. while ((cmd = ctx->in_progress)) {
  285. ctx->in_progress = cmd->next;
  286. /* don't update num_in_progress and in_progress_append - store is dead */
  287. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  288. }
  289. }
  290. static int
  291. submit_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd )
  292. {
  293. assert( ctx );
  294. assert( ctx->gen.bad_callback );
  295. assert( cmd );
  296. assert( cmd->param.done );
  297. if ((ctx->pending && !cmd->param.high_prio) || !cmd_submittable( ctx, cmd )) {
  298. if (ctx->pending && cmd->param.high_prio) {
  299. cmd->next = ctx->pending;
  300. ctx->pending = cmd;
  301. } else {
  302. cmd->next = 0;
  303. *ctx->pending_append = cmd;
  304. ctx->pending_append = &cmd->next;
  305. }
  306. return 0;
  307. }
  308. return send_imap_cmd( ctx, cmd );
  309. }
  310. static int
  311. imap_exec( imap_store_t *ctx, struct imap_cmd *cmdp,
  312. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response ),
  313. const char *fmt, ... )
  314. {
  315. va_list ap;
  316. if (!cmdp)
  317. cmdp = new_imap_cmd( sizeof(*cmdp) );
  318. cmdp->param.done = done;
  319. va_start( ap, fmt );
  320. nfvasprintf( &cmdp->cmd, fmt, ap );
  321. va_end( ap );
  322. return submit_imap_cmd( ctx, cmdp );
  323. }
  324. static void
  325. transform_box_response( int *response )
  326. {
  327. switch (*response) {
  328. case RESP_CANCEL: *response = DRV_CANCELED; break;
  329. case RESP_NO: *response = DRV_BOX_BAD; break;
  330. default: *response = DRV_OK; break;
  331. }
  332. }
  333. static void
  334. imap_done_simple_box( imap_store_t *ctx ATTR_UNUSED,
  335. struct imap_cmd *cmd, int response )
  336. {
  337. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  338. transform_box_response( &response );
  339. cmdp->callback( response, cmdp->callback_aux );
  340. }
  341. static void
  342. transform_msg_response( int *response )
  343. {
  344. switch (*response) {
  345. case RESP_CANCEL: *response = DRV_CANCELED; break;
  346. case RESP_NO: *response = DRV_MSG_BAD; break;
  347. default: *response = DRV_OK; break;
  348. }
  349. }
  350. static void
  351. imap_done_simple_msg( imap_store_t *ctx ATTR_UNUSED,
  352. struct imap_cmd *cmd, int response )
  353. {
  354. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  355. transform_msg_response( &response );
  356. cmdp->callback( response, cmdp->callback_aux );
  357. }
  358. static struct imap_cmd_refcounted_state *
  359. imap_refcounted_new_state( void (*cb)( int, void * ), void *aux )
  360. {
  361. struct imap_cmd_refcounted_state *sts = nfmalloc( sizeof(*sts) );
  362. sts->callback = cb;
  363. sts->callback_aux = aux;
  364. sts->ref_count = 1; /* so forced sync does not cause an early exit */
  365. sts->ret_val = DRV_OK;
  366. return sts;
  367. }
  368. static struct imap_cmd *
  369. imap_refcounted_new_cmd( struct imap_cmd_refcounted_state *sts )
  370. {
  371. struct imap_cmd_refcounted *cmd = (struct imap_cmd_refcounted *)new_imap_cmd( sizeof(*cmd) );
  372. cmd->state = sts;
  373. sts->ref_count++;
  374. return &cmd->gen;
  375. }
  376. static void
  377. imap_refcounted_done( struct imap_cmd_refcounted_state *sts )
  378. {
  379. if (!--sts->ref_count) {
  380. sts->callback( sts->ret_val, sts->callback_aux );
  381. free( sts );
  382. }
  383. }
  384. static void
  385. imap_refcounted_done_box( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  386. {
  387. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  388. switch (response) {
  389. case RESP_CANCEL:
  390. sts->ret_val = DRV_CANCELED;
  391. break;
  392. case RESP_NO:
  393. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  394. sts->ret_val = DRV_BOX_BAD;
  395. break;
  396. }
  397. imap_refcounted_done( sts );
  398. }
  399. static char *
  400. next_arg( char **s )
  401. {
  402. char *ret;
  403. if (!s || !*s)
  404. return 0;
  405. while (isspace( (unsigned char) **s ))
  406. (*s)++;
  407. if (!**s) {
  408. *s = 0;
  409. return 0;
  410. }
  411. if (**s == '"') {
  412. ++*s;
  413. ret = *s;
  414. *s = strchr( *s, '"' );
  415. } else {
  416. ret = *s;
  417. while (**s && !isspace( (unsigned char) **s ))
  418. (*s)++;
  419. }
  420. if (*s) {
  421. if (**s)
  422. *(*s)++ = 0;
  423. if (!**s)
  424. *s = 0;
  425. }
  426. return ret;
  427. }
  428. static int
  429. is_atom( list_t *list )
  430. {
  431. return list && list->val && list->val != NIL && list->val != LIST;
  432. }
  433. static int
  434. is_list( list_t *list )
  435. {
  436. return list && list->val == LIST;
  437. }
  438. static void
  439. free_list( list_t *list )
  440. {
  441. list_t *tmp;
  442. for (; list; list = tmp) {
  443. tmp = list->next;
  444. if (is_list( list ))
  445. free_list( list->child );
  446. else if (is_atom( list ))
  447. free( list->val );
  448. free( list );
  449. }
  450. }
  451. enum {
  452. LIST_OK,
  453. LIST_PARTIAL,
  454. LIST_BAD
  455. };
  456. static int
  457. parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
  458. {
  459. list_t *cur, **curp;
  460. char *s = *sp, *p;
  461. int bytes;
  462. assert( sts );
  463. assert( sts->level > 0 );
  464. curp = sts->stack[--sts->level];
  465. bytes = sts->need_bytes;
  466. if (bytes >= 0) {
  467. sts->need_bytes = -1;
  468. if (!bytes)
  469. goto getline;
  470. cur = (list_t *)((char *)curp - offsetof(list_t, next));
  471. s = cur->val + cur->len - bytes;
  472. goto getbytes;
  473. }
  474. if (!s)
  475. return LIST_BAD;
  476. for (;;) {
  477. while (isspace( (unsigned char)*s ))
  478. s++;
  479. if (sts->level && *s == ')') {
  480. s++;
  481. curp = sts->stack[--sts->level];
  482. goto next;
  483. }
  484. *curp = cur = nfmalloc( sizeof(*cur) );
  485. cur->val = 0; /* for clean bail */
  486. curp = &cur->next;
  487. *curp = 0; /* ditto */
  488. if (*s == '(') {
  489. /* sublist */
  490. if (sts->level == MAX_LIST_DEPTH)
  491. goto bail;
  492. s++;
  493. cur->val = LIST;
  494. sts->stack[sts->level++] = curp;
  495. curp = &cur->child;
  496. *curp = 0; /* for clean bail */
  497. goto next2;
  498. } else if (ctx && *s == '{') {
  499. /* literal */
  500. bytes = cur->len = strtol( s + 1, &s, 10 );
  501. if (*s != '}' || *++s)
  502. goto bail;
  503. s = cur->val = nfmalloc( cur->len );
  504. getbytes:
  505. bytes -= socket_read( &ctx->conn, s, bytes );
  506. if (bytes > 0)
  507. goto postpone;
  508. if (DFlags & XVERBOSE) {
  509. puts( "=========" );
  510. fwrite( cur->val, cur->len, 1, stdout );
  511. puts( "=========" );
  512. fflush( stdout );
  513. }
  514. getline:
  515. if (!(s = socket_read_line( &ctx->conn )))
  516. goto postpone;
  517. } else if (*s == '"') {
  518. /* quoted string */
  519. s++;
  520. p = s;
  521. for (; *s != '"'; s++)
  522. if (!*s)
  523. goto bail;
  524. cur->len = s - p;
  525. s++;
  526. cur->val = nfmalloc( cur->len + 1 );
  527. memcpy( cur->val, p, cur->len );
  528. cur->val[cur->len] = 0;
  529. } else {
  530. /* atom */
  531. p = s;
  532. for (; *s && !isspace( (unsigned char)*s ); s++)
  533. if (sts->level && *s == ')')
  534. break;
  535. cur->len = s - p;
  536. if (cur->len == 3 && !memcmp ("NIL", p, 3))
  537. cur->val = NIL;
  538. else {
  539. cur->val = nfmalloc( cur->len + 1 );
  540. memcpy( cur->val, p, cur->len );
  541. cur->val[cur->len] = 0;
  542. }
  543. }
  544. next:
  545. if (!sts->level)
  546. break;
  547. next2:
  548. if (!*s)
  549. goto bail;
  550. }
  551. *sp = s;
  552. return LIST_OK;
  553. postpone:
  554. if (sts->level < MAX_LIST_DEPTH) {
  555. sts->stack[sts->level++] = curp;
  556. sts->need_bytes = bytes;
  557. return LIST_PARTIAL;
  558. }
  559. bail:
  560. free_list( sts->head );
  561. return LIST_BAD;
  562. }
  563. static void
  564. parse_list_init( parse_list_state_t *sts )
  565. {
  566. sts->need_bytes = -1;
  567. sts->level = 1;
  568. sts->head = 0;
  569. sts->stack[0] = &sts->head;
  570. }
  571. static int
  572. parse_list_continue( imap_store_t *ctx, char *s )
  573. {
  574. list_t *list;
  575. int resp;
  576. if ((resp = parse_imap_list( ctx, &s, &ctx->parse_list_sts )) != LIST_PARTIAL) {
  577. list = (resp == LIST_BAD) ? 0 : ctx->parse_list_sts.head;
  578. ctx->parse_list_sts.head = 0;
  579. resp = ctx->parse_list_sts.callback( ctx, list, s );
  580. }
  581. return resp;
  582. }
  583. static int
  584. parse_list( imap_store_t *ctx, char *s, int (*cb)( imap_store_t *ctx, list_t *list, char *s ) )
  585. {
  586. parse_list_init( &ctx->parse_list_sts );
  587. ctx->parse_list_sts.callback = cb;
  588. return parse_list_continue( ctx, s );
  589. }
  590. static int parse_namespace_rsp_p2( imap_store_t *, list_t *, char * );
  591. static int parse_namespace_rsp_p3( imap_store_t *, list_t *, char * );
  592. static int
  593. parse_namespace_rsp_fail( void )
  594. {
  595. error( "IMAP error: malformed NAMESPACE response\n" );
  596. return LIST_BAD;
  597. }
  598. static int
  599. parse_namespace_rsp( imap_store_t *ctx, list_t *list, char *s )
  600. {
  601. if (!(ctx->ns_personal = list))
  602. return parse_namespace_rsp_fail();
  603. return parse_list( ctx, s, parse_namespace_rsp_p2 );
  604. }
  605. static int
  606. parse_namespace_rsp_p2( imap_store_t *ctx, list_t *list, char *s )
  607. {
  608. if (!(ctx->ns_other = list))
  609. return parse_namespace_rsp_fail();
  610. return parse_list( ctx, s, parse_namespace_rsp_p3 );
  611. }
  612. static int
  613. parse_namespace_rsp_p3( imap_store_t *ctx, list_t *list, char *s ATTR_UNUSED )
  614. {
  615. if (!(ctx->ns_shared = list))
  616. return parse_namespace_rsp_fail();
  617. return LIST_OK;
  618. }
  619. static int
  620. parse_fetch_rsp( imap_store_t *ctx, list_t *list, char *s ATTR_UNUSED )
  621. {
  622. list_t *tmp, *flags;
  623. char *body = 0, *tuid = 0;
  624. imap_message_t *cur;
  625. msg_data_t *msgdata;
  626. struct imap_cmd *cmdp;
  627. int uid = 0, mask = 0, status = 0, size = 0;
  628. unsigned i;
  629. if (!is_list( list )) {
  630. error( "IMAP error: bogus FETCH response\n" );
  631. free_list( list );
  632. return LIST_BAD;
  633. }
  634. for (tmp = list->child; tmp; tmp = tmp->next) {
  635. if (is_atom( tmp )) {
  636. if (!strcmp( "UID", tmp->val )) {
  637. tmp = tmp->next;
  638. if (is_atom( tmp ))
  639. uid = atoi( tmp->val );
  640. else
  641. error( "IMAP error: unable to parse UID\n" );
  642. } else if (!strcmp( "FLAGS", tmp->val )) {
  643. tmp = tmp->next;
  644. if (is_list( tmp )) {
  645. for (flags = tmp->child; flags; flags = flags->next) {
  646. if (is_atom( flags )) {
  647. if (flags->val[0] == '\\') { /* ignore user-defined flags for now */
  648. if (!strcmp( "Recent", flags->val + 1)) {
  649. status |= M_RECENT;
  650. goto flagok;
  651. }
  652. for (i = 0; i < as(Flags); i++)
  653. if (!strcmp( Flags[i], flags->val + 1 )) {
  654. mask |= 1 << i;
  655. goto flagok;
  656. }
  657. if (flags->val[1] == 'X' && flags->val[2] == '-')
  658. goto flagok; /* ignore system flag extensions */
  659. error( "IMAP warning: unknown system flag %s\n", flags->val );
  660. }
  661. flagok: ;
  662. } else
  663. error( "IMAP error: unable to parse FLAGS list\n" );
  664. }
  665. status |= M_FLAGS;
  666. } else
  667. error( "IMAP error: unable to parse FLAGS\n" );
  668. } else if (!strcmp( "RFC822.SIZE", tmp->val )) {
  669. tmp = tmp->next;
  670. if (is_atom( tmp ))
  671. size = atoi( tmp->val );
  672. else
  673. error( "IMAP error: unable to parse RFC822.SIZE\n" );
  674. } else if (!strcmp( "BODY[]", tmp->val )) {
  675. tmp = tmp->next;
  676. if (is_atom( tmp )) {
  677. body = tmp->val;
  678. tmp->val = 0; /* don't free together with list */
  679. size = tmp->len;
  680. } else
  681. error( "IMAP error: unable to parse BODY[]\n" );
  682. } else if (!strcmp( "BODY[HEADER.FIELDS", tmp->val )) {
  683. tmp = tmp->next;
  684. if (is_list( tmp )) {
  685. tmp = tmp->next;
  686. if (!is_atom( tmp ) || strcmp( tmp->val, "]" ))
  687. goto bfail;
  688. tmp = tmp->next;
  689. if (!is_atom( tmp ) || memcmp( tmp->val, "X-TUID: ", 8 ))
  690. goto bfail;
  691. tuid = tmp->val + 8;
  692. } else {
  693. bfail:
  694. error( "IMAP error: unable to parse BODY[HEADER.FIELDS ...]\n" );
  695. }
  696. }
  697. }
  698. }
  699. if (body) {
  700. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  701. if (cmdp->param.uid == uid)
  702. goto gotuid;
  703. error( "IMAP error: unexpected FETCH response (UID %d)\n", uid );
  704. free_list( list );
  705. return LIST_BAD;
  706. gotuid:
  707. msgdata = ((struct imap_cmd_fetch_msg *)cmdp)->msg_data;
  708. msgdata->data = body;
  709. msgdata->len = size;
  710. if (status & M_FLAGS)
  711. msgdata->flags = mask;
  712. } else if (uid) { /* ignore async flag updates for now */
  713. /* XXX this will need sorting for out-of-order (multiple queries) */
  714. cur = nfcalloc( sizeof(*cur) );
  715. *ctx->msgapp = &cur->gen;
  716. ctx->msgapp = &cur->gen.next;
  717. cur->gen.next = 0;
  718. cur->gen.uid = uid;
  719. cur->gen.flags = mask;
  720. cur->gen.status = status;
  721. cur->gen.size = size;
  722. cur->gen.srec = 0;
  723. if (tuid)
  724. strncpy( cur->gen.tuid, tuid, TUIDL );
  725. else
  726. cur->gen.tuid[0] = 0;
  727. if (ctx->gen.uidnext <= uid) /* in case the server sends no UIDNEXT */
  728. ctx->gen.uidnext = uid + 1;
  729. }
  730. free_list( list );
  731. return LIST_OK;
  732. }
  733. static void
  734. parse_capability( imap_store_t *ctx, char *cmd )
  735. {
  736. char *arg;
  737. unsigned i;
  738. ctx->caps = 0x80000000;
  739. while ((arg = next_arg( &cmd )))
  740. for (i = 0; i < as(cap_list); i++)
  741. if (!strcmp( cap_list[i], arg ))
  742. ctx->caps |= 1 << i;
  743. }
  744. static int
  745. parse_response_code( imap_store_t *ctx, struct imap_cmd *cmd, char *s )
  746. {
  747. char *arg, *earg, *p;
  748. if (!s || *s != '[')
  749. return RESP_OK; /* no response code */
  750. s++;
  751. if (!(p = strchr( s, ']' ))) {
  752. error( "IMAP error: malformed response code\n" );
  753. return RESP_CANCEL;
  754. }
  755. *p++ = 0;
  756. arg = next_arg( &s );
  757. if (!strcmp( "UIDVALIDITY", arg )) {
  758. if (!(arg = next_arg( &s )) ||
  759. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg))
  760. {
  761. error( "IMAP error: malformed UIDVALIDITY status\n" );
  762. return RESP_CANCEL;
  763. }
  764. } else if (!strcmp( "UIDNEXT", arg )) {
  765. if (!(arg = next_arg( &s )) || !(ctx->gen.uidnext = atoi( arg ))) {
  766. error( "IMAP error: malformed NEXTUID status\n" );
  767. return RESP_CANCEL;
  768. }
  769. } else if (!strcmp( "CAPABILITY", arg )) {
  770. parse_capability( ctx, s );
  771. } else if (!strcmp( "ALERT", arg )) {
  772. /* RFC2060 says that these messages MUST be displayed
  773. * to the user
  774. */
  775. for (; isspace( (unsigned char)*p ); p++);
  776. error( "*** IMAP ALERT *** %s\n", p );
  777. } else if (cmd && !strcmp( "APPENDUID", arg )) {
  778. if (!(arg = next_arg( &s )) ||
  779. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg) ||
  780. !(arg = next_arg( &s )) ||
  781. !(((struct imap_cmd_out_uid *)cmd)->out_uid = atoi( arg )))
  782. {
  783. error( "IMAP error: malformed APPENDUID status\n" );
  784. return RESP_CANCEL;
  785. }
  786. }
  787. return RESP_OK;
  788. }
  789. static int parse_list_rsp_p2( imap_store_t *, list_t *, char * );
  790. static int
  791. parse_list_rsp( imap_store_t *ctx, list_t *list, char *cmd )
  792. {
  793. char *arg;
  794. list_t *lp;
  795. if (!is_list( list )) {
  796. error( "IMAP error: malformed LIST response\n" );
  797. free_list( list );
  798. return LIST_BAD;
  799. }
  800. for (lp = list->child; lp; lp = lp->next)
  801. if (is_atom( lp ) && !strcasecmp( lp->val, "\\NoSelect" )) {
  802. free_list( list );
  803. return LIST_OK;
  804. }
  805. free_list( list );
  806. arg = next_arg( &cmd );
  807. if (!ctx->delimiter)
  808. ctx->delimiter = *arg;
  809. return parse_list( ctx, cmd, parse_list_rsp_p2 );
  810. }
  811. static int
  812. parse_list_rsp_p2( imap_store_t *ctx, list_t *list, char *cmd ATTR_UNUSED )
  813. {
  814. char *arg;
  815. int l;
  816. if (!is_atom( list )) {
  817. error( "IMAP error: malformed LIST response\n" );
  818. free_list( list );
  819. return LIST_BAD;
  820. }
  821. arg = list->val;
  822. if (memcmp( arg, "INBOX", 5 ) || (arg[5] && arg[5] != ctx->delimiter)) {
  823. l = strlen( ctx->gen.conf->path );
  824. if (memcmp( arg, ctx->gen.conf->path, l ))
  825. goto skip;
  826. arg += l;
  827. if (!memcmp( arg, "INBOX", 5 ) && (!arg[5] || arg[5] == ctx->delimiter)) {
  828. if (!arg[5])
  829. warn( "IMAP warning: ignoring INBOX in %s\n", ctx->gen.conf->path );
  830. goto skip;
  831. }
  832. }
  833. if (!memcmp( arg + strlen( arg ) - 5, ".lock", 5 )) /* workaround broken servers */
  834. goto skip;
  835. if (map_name( arg, ctx->delimiter, '/') < 0) {
  836. warn( "IMAP warning: ignoring mailbox %s (reserved character '/' in name)\n", arg );
  837. goto skip;
  838. }
  839. add_string_list( &ctx->gen.boxes, arg );
  840. skip:
  841. free_list( list );
  842. return LIST_OK;
  843. }
  844. static int
  845. prepare_name( char *buf, const imap_store_t *ctx, const char *prefix, const char *name )
  846. {
  847. int pl;
  848. nfsnprintf( buf, 1024, "%s%n%s", prefix, &pl, name );
  849. switch (map_name( buf + pl, '/', ctx->delimiter )) {
  850. case -1:
  851. error( "IMAP error: mailbox name %s contains server's hierarchy delimiter\n", buf + pl );
  852. return -1;
  853. case -2:
  854. error( "IMAP error: server's hierarchy delimiter not known\n" );
  855. return -1;
  856. default:
  857. return 0;
  858. }
  859. }
  860. static int
  861. prepare_box( char *buf, const imap_store_t *ctx )
  862. {
  863. const char *name = ctx->gen.name;
  864. return prepare_name( buf, ctx,
  865. (!memcmp( name, "INBOX", 5 ) && (!name[5] || name[5] == '/')) ? "" : ctx->prefix, name );
  866. }
  867. static int
  868. prepare_trash( char *buf, const imap_store_t *ctx )
  869. {
  870. return prepare_name( buf, ctx, ctx->prefix, ctx->gen.conf->trash );
  871. }
  872. struct imap_cmd_trycreate {
  873. struct imap_cmd gen;
  874. struct imap_cmd *orig_cmd;
  875. };
  876. static void imap_open_store_greeted( imap_store_t * );
  877. static void get_cmd_result_p2( imap_store_t *, struct imap_cmd *, int );
  878. static void
  879. imap_socket_read( void *aux )
  880. {
  881. imap_store_t *ctx = (imap_store_t *)aux;
  882. struct imap_cmd *cmdp, **pcmdp;
  883. char *cmd, *arg, *arg1, *p;
  884. int resp, resp2, tag, greeted;
  885. greeted = ctx->greeting;
  886. for (;;) {
  887. if (ctx->parse_list_sts.level) {
  888. resp = parse_list_continue( ctx, 0 );
  889. listret:
  890. if (resp == LIST_PARTIAL)
  891. return;
  892. if (resp == LIST_BAD)
  893. break;
  894. continue;
  895. }
  896. if (!(cmd = socket_read_line( &ctx->conn )))
  897. return;
  898. arg = next_arg( &cmd );
  899. if (!arg) {
  900. error( "IMAP error: empty response\n" );
  901. break;
  902. }
  903. if (*arg == '*') {
  904. arg = next_arg( &cmd );
  905. if (!arg) {
  906. error( "IMAP error: malformed untagged response\n" );
  907. break;
  908. }
  909. if (!strcmp( "NAMESPACE", arg )) {
  910. resp = parse_list( ctx, cmd, parse_namespace_rsp );
  911. goto listret;
  912. } else if (ctx->greeting == GreetingPending && !strcmp( "PREAUTH", arg )) {
  913. ctx->greeting = GreetingPreauth;
  914. parse_response_code( ctx, 0, cmd );
  915. } else if (!strcmp( "OK", arg )) {
  916. ctx->greeting = GreetingOk;
  917. parse_response_code( ctx, 0, cmd );
  918. } else if (!strcmp( "BAD", arg ) || !strcmp( "NO", arg ) || !strcmp( "BYE", arg )) {
  919. ctx->greeting = GreetingBad;
  920. parse_response_code( ctx, 0, cmd );
  921. } else if (!strcmp( "CAPABILITY", arg )) {
  922. parse_capability( ctx, cmd );
  923. } else if (!strcmp( "LIST", arg )) {
  924. resp = parse_list( ctx, cmd, parse_list_rsp );
  925. goto listret;
  926. } else if ((arg1 = next_arg( &cmd ))) {
  927. if (!strcmp( "EXISTS", arg1 ))
  928. ctx->gen.count = atoi( arg );
  929. else if (!strcmp( "RECENT", arg1 ))
  930. ctx->gen.recent = atoi( arg );
  931. else if(!strcmp ( "FETCH", arg1 )) {
  932. resp = parse_list( ctx, cmd, parse_fetch_rsp );
  933. goto listret;
  934. }
  935. } else {
  936. error( "IMAP error: unrecognized untagged response '%s'\n", arg );
  937. break; /* this may mean anything, so prefer not to spam the log */
  938. }
  939. if (greeted == GreetingPending) {
  940. imap_ref( ctx );
  941. imap_open_store_greeted( ctx );
  942. if (imap_deref( ctx ))
  943. return;
  944. }
  945. continue;
  946. } else if (!ctx->in_progress) {
  947. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  948. break; /* this may mean anything, so prefer not to spam the log */
  949. } else if (*arg == '+') {
  950. /* This can happen only with the last command underway, as
  951. it enforces a round-trip. */
  952. cmdp = ctx->in_progress;
  953. if (cmdp->param.data) {
  954. if (cmdp->param.to_trash)
  955. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  956. p = cmdp->param.data;
  957. cmdp->param.data = 0;
  958. if (socket_write( &ctx->conn, p, cmdp->param.data_len, GiveOwn ) < 0)
  959. return;
  960. } else if (cmdp->param.cont) {
  961. if (cmdp->param.cont( ctx, cmdp, cmd ))
  962. return;
  963. } else {
  964. error( "IMAP error: unexpected command continuation request\n" );
  965. break;
  966. }
  967. if (socket_write( &ctx->conn, "\r\n", 2, KeepOwn ) < 0)
  968. return;
  969. } else {
  970. tag = atoi( arg );
  971. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  972. if (cmdp->tag == tag)
  973. goto gottag;
  974. error( "IMAP error: unexpected tag %s\n", arg );
  975. break;
  976. gottag:
  977. if (!(*pcmdp = cmdp->next))
  978. ctx->in_progress_append = pcmdp;
  979. ctx->num_in_progress--;
  980. arg = next_arg( &cmd );
  981. if (!arg) {
  982. error( "IMAP error: malformed tagged response\n" );
  983. break;
  984. }
  985. if (!strcmp( "OK", arg )) {
  986. if (cmdp->param.to_trash)
  987. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  988. resp = RESP_OK;
  989. } else {
  990. if (!strcmp( "NO", arg )) {
  991. if (cmdp->param.create &&
  992. (cmdp->param.trycreate ||
  993. (cmd && !memcmp( cmd, "[TRYCREATE]", 11 ))))
  994. { /* SELECT, APPEND or UID COPY */
  995. struct imap_cmd_trycreate *cmd2 =
  996. (struct imap_cmd_trycreate *)new_imap_cmd( sizeof(*cmd2) );
  997. cmd2->orig_cmd = cmdp;
  998. cmd2->gen.param.high_prio = 1;
  999. p = strchr( cmdp->cmd, '"' );
  1000. if (imap_exec( ctx, &cmd2->gen, get_cmd_result_p2,
  1001. "CREATE %.*s", strchr( p + 1, '"' ) - p + 1, p ) < 0)
  1002. return;
  1003. continue;
  1004. }
  1005. resp = RESP_NO;
  1006. } else /*if (!strcmp( "BAD", arg ))*/
  1007. resp = RESP_CANCEL;
  1008. error( "IMAP command '%s' returned an error: %s %s\n",
  1009. memcmp( cmdp->cmd, "LOGIN", 5 ) ? cmdp->cmd : "LOGIN <user> <pass>",
  1010. arg, cmd ? cmd : "" );
  1011. }
  1012. if ((resp2 = parse_response_code( ctx, cmdp, cmd )) > resp)
  1013. resp = resp2;
  1014. imap_ref( ctx );
  1015. if (resp == RESP_CANCEL)
  1016. imap_invoke_bad_callback( ctx );
  1017. done_imap_cmd( ctx, cmdp, resp );
  1018. if (imap_deref( ctx ))
  1019. return;
  1020. if (ctx->canceling && !ctx->in_progress) {
  1021. ctx->canceling = 0;
  1022. ctx->callbacks.imap_cancel( ctx->callback_aux );
  1023. return;
  1024. }
  1025. }
  1026. if (flush_imap_cmds( ctx ) < 0)
  1027. return;
  1028. }
  1029. imap_invoke_bad_callback( ctx );
  1030. }
  1031. static void
  1032. get_cmd_result_p2( imap_store_t *ctx, struct imap_cmd *cmd, int response )
  1033. {
  1034. struct imap_cmd_trycreate *cmdp = (struct imap_cmd_trycreate *)cmd;
  1035. struct imap_cmd *ocmd = cmdp->orig_cmd;
  1036. if (response != RESP_OK) {
  1037. done_imap_cmd( ctx, ocmd, response );
  1038. } else {
  1039. ctx->gen.uidnext = 1;
  1040. if (ocmd->param.to_trash)
  1041. ctx->trashnc = TrashKnown;
  1042. ocmd->param.create = 0;
  1043. ocmd->param.high_prio = 1;
  1044. submit_imap_cmd( ctx, ocmd );
  1045. }
  1046. }
  1047. /******************* imap_cancel_store *******************/
  1048. static void
  1049. imap_cancel_store( store_t *gctx )
  1050. {
  1051. imap_store_t *ctx = (imap_store_t *)gctx;
  1052. socket_close( &ctx->conn );
  1053. cancel_submitted_imap_cmds( ctx );
  1054. cancel_pending_imap_cmds( ctx );
  1055. free_generic_messages( ctx->gen.msgs );
  1056. free_string_list( ctx->gen.boxes );
  1057. free_list( ctx->ns_personal );
  1058. free_list( ctx->ns_other );
  1059. free_list( ctx->ns_shared );
  1060. imap_deref( ctx );
  1061. }
  1062. static int
  1063. imap_deref( imap_store_t *ctx )
  1064. {
  1065. if (!--ctx->ref_count) {
  1066. free( ctx );
  1067. return -1;
  1068. }
  1069. return 0;
  1070. }
  1071. static void
  1072. imap_invoke_bad_callback( imap_store_t *ctx )
  1073. {
  1074. ctx->gen.bad_callback( ctx->gen.bad_callback_aux );
  1075. }
  1076. /******************* imap_disown_store & imap_own_store *******************/
  1077. static store_t *unowned;
  1078. static void
  1079. imap_cancel_unowned( void *gctx )
  1080. {
  1081. store_t *store, **storep;
  1082. for (storep = &unowned; (store = *storep); storep = &store->next)
  1083. if (store == gctx) {
  1084. *storep = store->next;
  1085. break;
  1086. }
  1087. imap_cancel_store( gctx );
  1088. }
  1089. static void
  1090. imap_disown_store( store_t *gctx )
  1091. {
  1092. free_generic_messages( gctx->msgs );
  1093. gctx->msgs = 0;
  1094. set_bad_callback( gctx, imap_cancel_unowned, gctx );
  1095. gctx->next = unowned;
  1096. unowned = gctx;
  1097. }
  1098. static store_t *
  1099. imap_own_store( store_conf_t *conf )
  1100. {
  1101. store_t *store, **storep;
  1102. for (storep = &unowned; (store = *storep); storep = &store->next)
  1103. if (store->conf == conf) {
  1104. *storep = store->next;
  1105. return store;
  1106. }
  1107. return 0;
  1108. }
  1109. /******************* imap_cleanup *******************/
  1110. static void imap_cleanup_p2( imap_store_t *, struct imap_cmd *, int );
  1111. static void
  1112. imap_cleanup( void )
  1113. {
  1114. store_t *ctx, *nctx;
  1115. for (ctx = unowned; ctx; ctx = nctx) {
  1116. nctx = ctx->next;
  1117. set_bad_callback( ctx, (void (*)(void *))imap_cancel_store, ctx );
  1118. imap_exec( (imap_store_t *)ctx, 0, imap_cleanup_p2, "LOGOUT" );
  1119. }
  1120. }
  1121. static void
  1122. imap_cleanup_p2( imap_store_t *ctx,
  1123. struct imap_cmd *cmd ATTR_UNUSED, int response )
  1124. {
  1125. if (response != RESP_CANCEL)
  1126. imap_cancel_store( &ctx->gen );
  1127. }
  1128. /******************* imap_open_store *******************/
  1129. #ifdef HAVE_LIBSSL
  1130. static int
  1131. do_cram_auth( imap_store_t *ctx, struct imap_cmd *cmdp, const char *prompt )
  1132. {
  1133. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1134. char *resp;
  1135. int l;
  1136. cmdp->param.cont = 0;
  1137. cram( prompt, srvc->user, srvc->pass, &resp, &l );
  1138. if (DFlags & VERBOSE) {
  1139. printf( ">+> %s\n", resp );
  1140. fflush( stdout );
  1141. }
  1142. if (socket_write( &ctx->conn, resp, l, GiveOwn ) < 0)
  1143. return -1;
  1144. return socket_write( &ctx->conn, "\r\n", 2, KeepOwn );
  1145. }
  1146. #endif
  1147. static void imap_open_store_connected( int, void * );
  1148. #ifdef HAVE_LIBSSL
  1149. static void imap_open_store_tlsstarted1( int, void * );
  1150. #endif
  1151. static void imap_open_store_p2( imap_store_t *, struct imap_cmd *, int );
  1152. static void imap_open_store_authenticate( imap_store_t * );
  1153. #ifdef HAVE_LIBSSL
  1154. static void imap_open_store_authenticate_p2( imap_store_t *, struct imap_cmd *, int );
  1155. static void imap_open_store_tlsstarted2( int, void * );
  1156. static void imap_open_store_authenticate_p3( imap_store_t *, struct imap_cmd *, int );
  1157. #endif
  1158. static void imap_open_store_authenticate2( imap_store_t * );
  1159. static void imap_open_store_authenticate2_p2( imap_store_t *, struct imap_cmd *, int );
  1160. static void imap_open_store_namespace( imap_store_t * );
  1161. static void imap_open_store_namespace_p2( imap_store_t *, struct imap_cmd *, int );
  1162. static void imap_open_store_namespace2( imap_store_t * );
  1163. static void imap_open_store_finalize( imap_store_t * );
  1164. #ifdef HAVE_LIBSSL
  1165. static void imap_open_store_ssl_bail( imap_store_t * );
  1166. #endif
  1167. static void imap_open_store_bail( imap_store_t * );
  1168. static void
  1169. imap_open_store( store_conf_t *conf,
  1170. void (*cb)( store_t *srv, void *aux ), void *aux )
  1171. {
  1172. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1173. imap_server_conf_t *srvc = cfg->server;
  1174. imap_store_t *ctx;
  1175. store_t **ctxp;
  1176. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1177. if (((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1178. *ctxp = ctx->gen.next;
  1179. /* One could ping the server here, but given that the idle timeout
  1180. * is at least 30 minutes, this sounds pretty pointless. */
  1181. free_string_list( ctx->gen.boxes );
  1182. ctx->gen.boxes = 0;
  1183. ctx->gen.listed = 0;
  1184. ctx->gen.conf = conf;
  1185. ctx->delimiter = 0;
  1186. ctx->callbacks.imap_open = cb;
  1187. ctx->callback_aux = aux;
  1188. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1189. imap_open_store_namespace( ctx );
  1190. return;
  1191. }
  1192. ctx = nfcalloc( sizeof(*ctx) );
  1193. ctx->gen.conf = conf;
  1194. ctx->ref_count = 1;
  1195. ctx->callbacks.imap_open = cb;
  1196. ctx->callback_aux = aux;
  1197. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1198. ctx->in_progress_append = &ctx->in_progress;
  1199. ctx->pending_append = &ctx->pending;
  1200. socket_init( &ctx->conn, &srvc->sconf,
  1201. (void (*)( void * ))imap_invoke_bad_callback,
  1202. imap_socket_read, (int (*)(void *))flush_imap_cmds, ctx );
  1203. socket_connect( &ctx->conn, imap_open_store_connected );
  1204. }
  1205. static void
  1206. imap_open_store_connected( int ok, void *aux )
  1207. {
  1208. imap_store_t *ctx = (imap_store_t *)aux;
  1209. #ifdef HAVE_LIBSSL
  1210. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1211. imap_server_conf_t *srvc = cfg->server;
  1212. #endif
  1213. if (!ok)
  1214. imap_open_store_bail( ctx );
  1215. #ifdef HAVE_LIBSSL
  1216. else if (srvc->sconf.use_imaps)
  1217. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted1 );
  1218. #endif
  1219. }
  1220. #ifdef HAVE_LIBSSL
  1221. static void
  1222. imap_open_store_tlsstarted1( int ok, void *aux )
  1223. {
  1224. imap_store_t *ctx = (imap_store_t *)aux;
  1225. if (!ok)
  1226. imap_open_store_ssl_bail( ctx );
  1227. }
  1228. #endif
  1229. static void
  1230. imap_open_store_greeted( imap_store_t *ctx )
  1231. {
  1232. if (ctx->greeting == GreetingBad) {
  1233. error( "IMAP error: unknown greeting response\n" );
  1234. imap_open_store_bail( ctx );
  1235. return;
  1236. }
  1237. if (!ctx->caps)
  1238. imap_exec( ctx, 0, imap_open_store_p2, "CAPABILITY" );
  1239. else
  1240. imap_open_store_authenticate( ctx );
  1241. }
  1242. static void
  1243. imap_open_store_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1244. {
  1245. if (response == RESP_NO)
  1246. imap_open_store_bail( ctx );
  1247. else if (response == RESP_OK)
  1248. imap_open_store_authenticate( ctx );
  1249. }
  1250. static void
  1251. imap_open_store_authenticate( imap_store_t *ctx )
  1252. {
  1253. if (ctx->greeting != GreetingPreauth) {
  1254. #ifdef HAVE_LIBSSL
  1255. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1256. imap_server_conf_t *srvc = cfg->server;
  1257. if (!srvc->sconf.use_imaps &&
  1258. (srvc->sconf.use_sslv2 || srvc->sconf.use_sslv3 || srvc->sconf.use_tlsv1)) {
  1259. /* always try to select SSL support if available */
  1260. if (CAP(STARTTLS)) {
  1261. imap_exec( ctx, 0, imap_open_store_authenticate_p2, "STARTTLS" );
  1262. return;
  1263. } else {
  1264. if (srvc->require_ssl) {
  1265. error( "IMAP error: SSL support not available\n" );
  1266. imap_open_store_bail( ctx );
  1267. return;
  1268. } else {
  1269. warn( "IMAP warning: SSL support not available\n" );
  1270. }
  1271. }
  1272. }
  1273. #endif
  1274. imap_open_store_authenticate2( ctx );
  1275. } else {
  1276. imap_open_store_namespace( ctx );
  1277. }
  1278. }
  1279. #ifdef HAVE_LIBSSL
  1280. static void
  1281. imap_open_store_authenticate_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1282. {
  1283. if (response == RESP_NO)
  1284. imap_open_store_bail( ctx );
  1285. else if (response == RESP_OK)
  1286. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted2 );
  1287. }
  1288. static void
  1289. imap_open_store_tlsstarted2( int ok, void *aux )
  1290. {
  1291. imap_store_t *ctx = (imap_store_t *)aux;
  1292. if (!ok)
  1293. imap_open_store_ssl_bail( ctx );
  1294. else
  1295. imap_exec( ctx, 0, imap_open_store_authenticate_p3, "CAPABILITY" );
  1296. }
  1297. static void
  1298. imap_open_store_authenticate_p3( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1299. {
  1300. if (response == RESP_NO)
  1301. imap_open_store_bail( ctx );
  1302. else if (response == RESP_OK)
  1303. imap_open_store_authenticate2( ctx );
  1304. }
  1305. #endif
  1306. static void
  1307. imap_open_store_authenticate2( imap_store_t *ctx )
  1308. {
  1309. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1310. imap_server_conf_t *srvc = cfg->server;
  1311. char *arg;
  1312. info ("Logging in...\n");
  1313. if (!srvc->user) {
  1314. error( "Skipping account %s, no user\n", srvc->name );
  1315. goto bail;
  1316. }
  1317. if (srvc->pass_cmd) {
  1318. FILE *fp;
  1319. int ret;
  1320. char buffer[80];
  1321. if (!(fp = popen( srvc->pass_cmd, "r" ))) {
  1322. pipeerr:
  1323. sys_error( "Skipping account %s, password command failed", srvc->name );
  1324. goto bail;
  1325. }
  1326. if (!fgets( buffer, sizeof(buffer), fp ))
  1327. buffer[0] = 0;
  1328. if ((ret = pclose( fp )) < 0)
  1329. goto pipeerr;
  1330. if (ret) {
  1331. if (WIFSIGNALED( ret ))
  1332. error( "Skipping account %s, password command crashed\n", srvc->name );
  1333. else
  1334. error( "Skipping account %s, password command exited with status %d\n", srvc->name, WEXITSTATUS( ret ) );
  1335. goto bail;
  1336. }
  1337. if (!buffer[0]) {
  1338. error( "Skipping account %s, password command produced no output\n", srvc->name );
  1339. goto bail;
  1340. }
  1341. buffer[strcspn( buffer, "\n" )] = 0; /* Strip trailing newline */
  1342. free( srvc->pass ); /* From previous runs */
  1343. srvc->pass = nfstrdup( buffer );
  1344. } else if (!srvc->pass) {
  1345. char prompt[80];
  1346. sprintf( prompt, "Password (%s): ", srvc->name );
  1347. arg = getpass( prompt );
  1348. if (!arg) {
  1349. perror( "getpass" );
  1350. exit( 1 );
  1351. }
  1352. if (!*arg) {
  1353. error( "Skipping account %s, no password\n", srvc->name );
  1354. goto bail;
  1355. }
  1356. /*
  1357. * getpass() returns a pointer to a static buffer. make a copy
  1358. * for long term storage.
  1359. */
  1360. srvc->pass = nfstrdup( arg );
  1361. }
  1362. #ifdef HAVE_LIBSSL
  1363. if (CAP(CRAM)) {
  1364. struct imap_cmd *cmd = new_imap_cmd( sizeof(*cmd) );
  1365. info( "Authenticating with CRAM-MD5\n" );
  1366. cmd->param.cont = do_cram_auth;
  1367. imap_exec( ctx, cmd, imap_open_store_authenticate2_p2, "AUTHENTICATE CRAM-MD5" );
  1368. return;
  1369. }
  1370. if (srvc->require_cram) {
  1371. error( "IMAP error: CRAM-MD5 authentication is not supported by server\n" );
  1372. goto bail;
  1373. }
  1374. #endif
  1375. if (CAP(NOLOGIN)) {
  1376. error( "Skipping account %s, server forbids LOGIN\n", srvc->name );
  1377. goto bail;
  1378. }
  1379. #ifdef HAVE_LIBSSL
  1380. if (!ctx->conn.ssl)
  1381. #endif
  1382. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  1383. imap_exec( ctx, 0, imap_open_store_authenticate2_p2,
  1384. "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass );
  1385. return;
  1386. bail:
  1387. imap_open_store_bail( ctx );
  1388. }
  1389. static void
  1390. imap_open_store_authenticate2_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1391. {
  1392. if (response == RESP_NO)
  1393. imap_open_store_bail( ctx );
  1394. else if (response == RESP_OK)
  1395. imap_open_store_namespace( ctx );
  1396. }
  1397. static void
  1398. imap_open_store_namespace( imap_store_t *ctx )
  1399. {
  1400. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1401. ctx->prefix = cfg->gen.path;
  1402. ctx->delimiter = cfg->delimiter;
  1403. if (((!*ctx->prefix && cfg->use_namespace) || !cfg->delimiter) && CAP(NAMESPACE)) {
  1404. /* get NAMESPACE info */
  1405. if (!ctx->got_namespace)
  1406. imap_exec( ctx, 0, imap_open_store_namespace_p2, "NAMESPACE" );
  1407. else
  1408. imap_open_store_namespace2( ctx );
  1409. return;
  1410. }
  1411. imap_open_store_finalize( ctx );
  1412. }
  1413. static void
  1414. imap_open_store_namespace_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1415. {
  1416. if (response == RESP_NO) {
  1417. imap_open_store_bail( ctx );
  1418. } else if (response == RESP_OK) {
  1419. ctx->got_namespace = 1;
  1420. imap_open_store_namespace2( ctx );
  1421. }
  1422. }
  1423. static void
  1424. imap_open_store_namespace2( imap_store_t *ctx )
  1425. {
  1426. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1427. list_t *nsp, *nsp_1st, *nsp_1st_ns, *nsp_1st_dl;
  1428. /* XXX for now assume 1st personal namespace */
  1429. if (is_list( (nsp = ctx->ns_personal) ) &&
  1430. is_list( (nsp_1st = nsp->child) ) &&
  1431. is_atom( (nsp_1st_ns = nsp_1st->child) ) &&
  1432. is_atom( (nsp_1st_dl = nsp_1st_ns->next) ))
  1433. {
  1434. if (!*ctx->prefix && cfg->use_namespace)
  1435. ctx->prefix = nsp_1st_ns->val;
  1436. if (!ctx->delimiter)
  1437. ctx->delimiter = *nsp_1st_dl->val;
  1438. }
  1439. imap_open_store_finalize( ctx );
  1440. }
  1441. static void
  1442. imap_open_store_finalize( imap_store_t *ctx )
  1443. {
  1444. set_bad_callback( &ctx->gen, 0, 0 );
  1445. ctx->trashnc = TrashUnknown;
  1446. ctx->callbacks.imap_open( &ctx->gen, ctx->callback_aux );
  1447. }
  1448. #ifdef HAVE_LIBSSL
  1449. static void
  1450. imap_open_store_ssl_bail( imap_store_t *ctx )
  1451. {
  1452. /* This avoids that we try to send LOGOUT to an unusable socket. */
  1453. socket_close( &ctx->conn );
  1454. imap_open_store_bail( ctx );
  1455. }
  1456. #endif
  1457. static void
  1458. imap_open_store_bail( imap_store_t *ctx )
  1459. {
  1460. void (*cb)( store_t *srv, void *aux ) = ctx->callbacks.imap_open;
  1461. void *aux = ctx->callback_aux;
  1462. imap_cancel_store( &ctx->gen );
  1463. cb( 0, aux );
  1464. }
  1465. /******************* imap_prepare_opts *******************/
  1466. static void
  1467. imap_prepare_opts( store_t *gctx, int opts )
  1468. {
  1469. gctx->opts = opts;
  1470. }
  1471. /******************* imap_select *******************/
  1472. static void
  1473. imap_select( store_t *gctx, int create,
  1474. void (*cb)( int sts, void *aux ), void *aux )
  1475. {
  1476. imap_store_t *ctx = (imap_store_t *)gctx;
  1477. struct imap_cmd_simple *cmd;
  1478. char buf[1024];
  1479. free_generic_messages( gctx->msgs );
  1480. gctx->msgs = 0;
  1481. if (prepare_box( buf, ctx ) < 0) {
  1482. cb( DRV_BOX_BAD, aux );
  1483. return;
  1484. }
  1485. ctx->gen.uidnext = 0;
  1486. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1487. cmd->gen.param.create = create;
  1488. cmd->gen.param.trycreate = 1;
  1489. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  1490. "SELECT \"%s\"", buf );
  1491. }
  1492. /******************* imap_load *******************/
  1493. static int imap_submit_load( imap_store_t *, const char *, int, struct imap_cmd_refcounted_state * );
  1494. static void
  1495. imap_load( store_t *gctx, int minuid, int maxuid, int newuid, int *excs, int nexcs,
  1496. void (*cb)( int sts, void *aux ), void *aux )
  1497. {
  1498. imap_store_t *ctx = (imap_store_t *)gctx;
  1499. int i, j, bl;
  1500. char buf[1000];
  1501. if (!ctx->gen.count) {
  1502. free( excs );
  1503. cb( DRV_OK, aux );
  1504. } else {
  1505. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1506. ctx->msgapp = &ctx->gen.msgs;
  1507. sort_ints( excs, nexcs );
  1508. for (i = 0; i < nexcs; ) {
  1509. for (bl = 0; i < nexcs && bl < 960; i++) {
  1510. if (bl)
  1511. buf[bl++] = ',';
  1512. bl += sprintf( buf + bl, "%d", excs[i] );
  1513. j = i;
  1514. for (; i + 1 < nexcs && excs[i + 1] == excs[i] + 1; i++) {}
  1515. if (i != j)
  1516. bl += sprintf( buf + bl, ":%d", excs[i] );
  1517. }
  1518. if (imap_submit_load( ctx, buf, 0, sts ) < 0)
  1519. goto done;
  1520. }
  1521. if (maxuid == INT_MAX)
  1522. maxuid = ctx->gen.uidnext ? ctx->gen.uidnext - 1 : 1000000000;
  1523. if (maxuid >= minuid) {
  1524. if ((ctx->gen.opts & OPEN_FIND) && minuid < newuid) {
  1525. sprintf( buf, "%d:%d", minuid, newuid - 1 );
  1526. if (imap_submit_load( ctx, buf, 0, sts ) < 0)
  1527. goto done;
  1528. if (newuid > maxuid)
  1529. goto done;
  1530. sprintf( buf, "%d:%d", newuid, maxuid );
  1531. } else {
  1532. sprintf( buf, "%d:%d", minuid, maxuid );
  1533. }
  1534. imap_submit_load( ctx, buf, (ctx->gen.opts & OPEN_FIND), sts );
  1535. }
  1536. done:
  1537. free( excs );
  1538. imap_refcounted_done( sts );
  1539. }
  1540. }
  1541. static int
  1542. imap_submit_load( imap_store_t *ctx, const char *buf, int tuids, struct imap_cmd_refcounted_state *sts )
  1543. {
  1544. return imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  1545. "UID FETCH %s (UID%s%s%s)", buf,
  1546. (ctx->gen.opts & OPEN_FLAGS) ? " FLAGS" : "",
  1547. (ctx->gen.opts & OPEN_SIZE) ? " RFC822.SIZE" : "",
  1548. tuids ? " BODY.PEEK[HEADER.FIELDS (X-TUID)]" : "");
  1549. }
  1550. /******************* imap_fetch_msg *******************/
  1551. static void
  1552. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data,
  1553. void (*cb)( int sts, void *aux ), void *aux )
  1554. {
  1555. struct imap_cmd_fetch_msg *cmd;
  1556. INIT_IMAP_CMD_X(imap_cmd_fetch_msg, cmd, cb, aux)
  1557. cmd->gen.gen.param.uid = msg->uid;
  1558. cmd->msg_data = data;
  1559. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_done_simple_msg,
  1560. "UID FETCH %d (%sBODY.PEEK[])",
  1561. msg->uid, (msg->status & M_FLAGS) ? "" : "FLAGS " );
  1562. }
  1563. /******************* imap_set_flags *******************/
  1564. static void imap_set_flags_p2( imap_store_t *, struct imap_cmd *, int );
  1565. static int
  1566. imap_make_flags( int flags, char *buf )
  1567. {
  1568. const char *s;
  1569. unsigned i, d;
  1570. for (i = d = 0; i < as(Flags); i++)
  1571. if (flags & (1 << i)) {
  1572. buf[d++] = ' ';
  1573. buf[d++] = '\\';
  1574. for (s = Flags[i]; *s; s++)
  1575. buf[d++] = *s;
  1576. }
  1577. buf[0] = '(';
  1578. buf[d++] = ')';
  1579. return d;
  1580. }
  1581. static int
  1582. imap_flags_helper( imap_store_t *ctx, int uid, char what, int flags,
  1583. struct imap_cmd_refcounted_state *sts )
  1584. {
  1585. char buf[256];
  1586. buf[imap_make_flags( flags, buf )] = 0;
  1587. return imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_set_flags_p2,
  1588. "UID STORE %d %cFLAGS.SILENT %s", uid, what, buf );
  1589. }
  1590. static void
  1591. imap_set_flags( store_t *gctx, message_t *msg, int uid, int add, int del,
  1592. void (*cb)( int sts, void *aux ), void *aux )
  1593. {
  1594. imap_store_t *ctx = (imap_store_t *)gctx;
  1595. if (msg) {
  1596. uid = msg->uid;
  1597. add &= ~msg->flags;
  1598. del &= msg->flags;
  1599. msg->flags |= add;
  1600. msg->flags &= ~del;
  1601. }
  1602. if (add || del) {
  1603. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1604. if ((add && imap_flags_helper( ctx, uid, '+', add, sts ) < 0) ||
  1605. (del && imap_flags_helper( ctx, uid, '-', del, sts ) < 0)) {}
  1606. imap_refcounted_done( sts );
  1607. } else {
  1608. cb( DRV_OK, aux );
  1609. }
  1610. }
  1611. static void
  1612. imap_set_flags_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1613. {
  1614. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  1615. switch (response) {
  1616. case RESP_CANCEL:
  1617. sts->ret_val = DRV_CANCELED;
  1618. break;
  1619. case RESP_NO:
  1620. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  1621. sts->ret_val = DRV_MSG_BAD;
  1622. break;
  1623. }
  1624. imap_refcounted_done( sts );
  1625. }
  1626. /******************* imap_close *******************/
  1627. static void
  1628. imap_close( store_t *gctx,
  1629. void (*cb)( int sts, void *aux ), void *aux )
  1630. {
  1631. imap_store_t *ctx = (imap_store_t *)gctx;
  1632. if (CAP(UIDPLUS)) {
  1633. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1634. message_t *msg, *fmsg, *nmsg;
  1635. int bl;
  1636. char buf[1000];
  1637. for (msg = ctx->gen.msgs; ; ) {
  1638. for (bl = 0; msg && bl < 960; msg = msg->next) {
  1639. if (!(msg->flags & F_DELETED))
  1640. continue;
  1641. if (bl)
  1642. buf[bl++] = ',';
  1643. bl += sprintf( buf + bl, "%d", msg->uid );
  1644. fmsg = msg;
  1645. for (; (nmsg = msg->next) && (nmsg->flags & F_DELETED); msg = nmsg) {}
  1646. if (msg != fmsg)
  1647. bl += sprintf( buf + bl, ":%d", msg->uid );
  1648. }
  1649. if (!bl)
  1650. break;
  1651. if (imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  1652. "UID EXPUNGE %s", buf ) < 0)
  1653. break;
  1654. }
  1655. imap_refcounted_done( sts );
  1656. } else {
  1657. /* This is inherently racy: it may cause messages which other clients
  1658. * marked as deleted to be expunged without being trashed. */
  1659. struct imap_cmd_simple *cmd;
  1660. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1661. imap_exec( ctx, &cmd->gen, imap_done_simple_box, "CLOSE" );
  1662. }
  1663. }
  1664. /******************* imap_trash_msg *******************/
  1665. static void
  1666. imap_trash_msg( store_t *gctx, message_t *msg,
  1667. void (*cb)( int sts, void *aux ), void *aux )
  1668. {
  1669. imap_store_t *ctx = (imap_store_t *)gctx;
  1670. struct imap_cmd_simple *cmd;
  1671. char buf[1024];
  1672. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1673. cmd->gen.param.create = 1;
  1674. cmd->gen.param.to_trash = 1;
  1675. if (prepare_trash( buf, ctx ) < 0) {
  1676. cb( DRV_BOX_BAD, aux );
  1677. return;
  1678. }
  1679. imap_exec( ctx, &cmd->gen, imap_done_simple_msg,
  1680. "UID COPY %d \"%s\"", msg->uid, buf );
  1681. }
  1682. /******************* imap_store_msg *******************/
  1683. static void imap_store_msg_p2( imap_store_t *, struct imap_cmd *, int );
  1684. static void
  1685. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  1686. void (*cb)( int sts, int uid, void *aux ), void *aux )
  1687. {
  1688. imap_store_t *ctx = (imap_store_t *)gctx;
  1689. struct imap_cmd_out_uid *cmd;
  1690. int d;
  1691. char flagstr[128], buf[1024];
  1692. d = 0;
  1693. if (data->flags) {
  1694. d = imap_make_flags( data->flags, flagstr );
  1695. flagstr[d++] = ' ';
  1696. }
  1697. flagstr[d] = 0;
  1698. INIT_IMAP_CMD(imap_cmd_out_uid, cmd, cb, aux)
  1699. cmd->gen.param.data_len = data->len;
  1700. cmd->gen.param.data = data->data;
  1701. cmd->out_uid = -2;
  1702. if (to_trash) {
  1703. cmd->gen.param.create = 1;
  1704. cmd->gen.param.to_trash = 1;
  1705. if (prepare_trash( buf, ctx ) < 0) {
  1706. cb( DRV_BOX_BAD, -1, aux );
  1707. return;
  1708. }
  1709. } else {
  1710. if (prepare_box( buf, ctx ) < 0) {
  1711. cb( DRV_BOX_BAD, -1, aux );
  1712. return;
  1713. }
  1714. }
  1715. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  1716. "APPEND \"%s\" %s", buf, flagstr );
  1717. }
  1718. static void
  1719. imap_store_msg_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1720. {
  1721. struct imap_cmd_out_uid *cmdp = (struct imap_cmd_out_uid *)cmd;
  1722. transform_msg_response( &response );
  1723. cmdp->callback( response, cmdp->out_uid, cmdp->callback_aux );
  1724. }
  1725. /******************* imap_find_new_msgs *******************/
  1726. static void
  1727. imap_find_new_msgs( store_t *gctx,
  1728. void (*cb)( int sts, void *aux ), void *aux )
  1729. {
  1730. imap_store_t *ctx = (imap_store_t *)gctx;
  1731. struct imap_cmd_simple *cmd;
  1732. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1733. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_done_simple_box,
  1734. "UID FETCH %d:1000000000 (UID BODY.PEEK[HEADER.FIELDS (X-TUID)])", ctx->gen.uidnext );
  1735. }
  1736. /******************* imap_list *******************/
  1737. static void
  1738. imap_list( store_t *gctx, int flags,
  1739. void (*cb)( int sts, void *aux ), void *aux )
  1740. {
  1741. imap_store_t *ctx = (imap_store_t *)gctx;
  1742. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1743. if (((flags & LIST_PATH) &&
  1744. imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  1745. "LIST \"\" \"%s*\"", ctx->prefix ) < 0) ||
  1746. ((flags & LIST_INBOX) && (!(flags & LIST_PATH) || *ctx->prefix) &&
  1747. imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  1748. "LIST \"\" INBOX*" ) < 0))
  1749. {}
  1750. imap_refcounted_done( sts );
  1751. }
  1752. /******************* imap_cancel *******************/
  1753. static void
  1754. imap_cancel( store_t *gctx,
  1755. void (*cb)( void *aux ), void *aux )
  1756. {
  1757. imap_store_t *ctx = (imap_store_t *)gctx;
  1758. cancel_pending_imap_cmds( ctx );
  1759. if (ctx->in_progress) {
  1760. ctx->canceling = 1;
  1761. ctx->callbacks.imap_cancel = cb;
  1762. ctx->callback_aux = aux;
  1763. } else {
  1764. cb( aux );
  1765. }
  1766. }
  1767. /******************* imap_commit *******************/
  1768. static void
  1769. imap_commit( store_t *gctx )
  1770. {
  1771. (void)gctx;
  1772. }
  1773. /******************* imap_parse_store *******************/
  1774. imap_server_conf_t *servers, **serverapp = &servers;
  1775. static int
  1776. imap_parse_store( conffile_t *cfg, store_conf_t **storep )
  1777. {
  1778. imap_store_conf_t *store;
  1779. imap_server_conf_t *server, *srv, sserver;
  1780. int acc_opt = 0;
  1781. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  1782. server = nfcalloc( sizeof(*server) );
  1783. server->name = nfstrdup( cfg->val );
  1784. *serverapp = server;
  1785. serverapp = &server->next;
  1786. store = 0;
  1787. *storep = 0;
  1788. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  1789. store = nfcalloc( sizeof(*store) );
  1790. store->gen.driver = &imap_driver;
  1791. store->gen.name = nfstrdup( cfg->val );
  1792. store->use_namespace = 1;
  1793. *storep = &store->gen;
  1794. memset( &sserver, 0, sizeof(sserver) );
  1795. server = &sserver;
  1796. } else
  1797. return 0;
  1798. #ifdef HAVE_LIBSSL
  1799. /* this will probably annoy people, but its the best default just in
  1800. * case people forget to turn it on
  1801. */
  1802. server->require_ssl = 1;
  1803. server->sconf.use_tlsv1 = 1;
  1804. #endif
  1805. server->max_in_progress = INT_MAX;
  1806. while (getcline( cfg ) && cfg->cmd) {
  1807. if (!strcasecmp( "Host", cfg->cmd )) {
  1808. /* The imap[s]: syntax is just a backwards compat hack. */
  1809. #ifdef HAVE_LIBSSL
  1810. if (!memcmp( "imaps:", cfg->val, 6 )) {
  1811. cfg->val += 6;
  1812. server->sconf.use_imaps = 1;
  1813. server->sconf.use_sslv2 = 1;
  1814. server->sconf.use_sslv3 = 1;
  1815. } else
  1816. #endif
  1817. {
  1818. if (!memcmp( "imap:", cfg->val, 5 ))
  1819. cfg->val += 5;
  1820. }
  1821. if (!memcmp( "//", cfg->val, 2 ))
  1822. cfg->val += 2;
  1823. server->sconf.host = nfstrdup( cfg->val );
  1824. }
  1825. else if (!strcasecmp( "User", cfg->cmd ))
  1826. server->user = nfstrdup( cfg->val );
  1827. else if (!strcasecmp( "Pass", cfg->cmd ))
  1828. server->pass = nfstrdup( cfg->val );
  1829. else if (!strcasecmp( "PassCmd", cfg->cmd ))
  1830. server->pass_cmd = nfstrdup( cfg->val );
  1831. else if (!strcasecmp( "Port", cfg->cmd ))
  1832. server->sconf.port = parse_int( cfg );
  1833. else if (!strcasecmp( "PipelineDepth", cfg->cmd )) {
  1834. if ((server->max_in_progress = parse_int( cfg )) < 1) {
  1835. error( "%s:%d: PipelineDepth must be at least 1\n", cfg->file, cfg->line );
  1836. cfg->err = 1;
  1837. }
  1838. }
  1839. #ifdef HAVE_LIBSSL
  1840. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  1841. server->sconf.cert_file = expand_strdup( cfg->val );
  1842. if (access( server->sconf.cert_file, R_OK )) {
  1843. sys_error( "%s:%d: CertificateFile '%s'",
  1844. cfg->file, cfg->line, server->sconf.cert_file );
  1845. cfg->err = 1;
  1846. }
  1847. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  1848. server->require_ssl = parse_bool( cfg );
  1849. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  1850. server->sconf.use_imaps = parse_bool( cfg );
  1851. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  1852. server->sconf.use_sslv2 = parse_bool( cfg );
  1853. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  1854. server->sconf.use_sslv3 = parse_bool( cfg );
  1855. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  1856. server->sconf.use_tlsv1 = parse_bool( cfg );
  1857. else if (!strcasecmp( "UseTLSv1.1", cfg->cmd ))
  1858. server->sconf.use_tlsv11 = parse_bool( cfg );
  1859. else if (!strcasecmp( "UseTLSv1.2", cfg->cmd ))
  1860. server->sconf.use_tlsv12 = parse_bool( cfg );
  1861. else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  1862. server->require_cram = parse_bool( cfg );
  1863. #endif
  1864. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  1865. server->sconf.tunnel = nfstrdup( cfg->val );
  1866. else if (store) {
  1867. if (!strcasecmp( "Account", cfg->cmd )) {
  1868. for (srv = servers; srv; srv = srv->next)
  1869. if (srv->name && !strcmp( srv->name, cfg->val ))
  1870. goto gotsrv;
  1871. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  1872. cfg->err = 1;
  1873. continue;
  1874. gotsrv:
  1875. store->server = srv;
  1876. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  1877. store->use_namespace = parse_bool( cfg );
  1878. else if (!strcasecmp( "Path", cfg->cmd ))
  1879. store->gen.path = nfstrdup( cfg->val );
  1880. else if (!strcasecmp( "PathDelimiter", cfg->cmd ))
  1881. store->delimiter = *cfg->val;
  1882. else
  1883. parse_generic_store( &store->gen, cfg );
  1884. continue;
  1885. } else {
  1886. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  1887. cfg->err = 1;
  1888. continue;
  1889. }
  1890. acc_opt = 1;
  1891. }
  1892. if (!store || !store->server) {
  1893. if (!server->sconf.tunnel && !server->sconf.host) {
  1894. if (store)
  1895. error( "IMAP store '%s' has incomplete/missing connection details\n", store->gen.name );
  1896. else
  1897. error( "IMAP account '%s' has incomplete/missing connection details\n", server->name );
  1898. cfg->err = 1;
  1899. return 1;
  1900. }
  1901. if (server->pass && server->pass_cmd) {
  1902. if (store)
  1903. error( "IMAP store '%s' has both Pass and PassCmd\n", store->gen.name );
  1904. else
  1905. error( "IMAP account '%s' has both Pass and PassCmd\n", server->name );
  1906. cfg->err = 1;
  1907. return 1;
  1908. }
  1909. }
  1910. if (store) {
  1911. if (!store->server) {
  1912. store->server = nfmalloc( sizeof(sserver) );
  1913. memcpy( store->server, &sserver, sizeof(sserver) );
  1914. store->server->name = store->gen.name;
  1915. } else if (acc_opt) {
  1916. error( "IMAP store '%s' has both Account and account-specific options\n", store->gen.name );
  1917. cfg->err = 1;
  1918. }
  1919. }
  1920. return 1;
  1921. }
  1922. struct driver imap_driver = {
  1923. DRV_CRLF,
  1924. imap_parse_store,
  1925. imap_cleanup,
  1926. imap_open_store,
  1927. imap_disown_store,
  1928. imap_own_store,
  1929. imap_cancel_store,
  1930. imap_list,
  1931. imap_prepare_opts,
  1932. imap_select,
  1933. imap_load,
  1934. imap_fetch_msg,
  1935. imap_store_msg,
  1936. imap_find_new_msgs,
  1937. imap_set_flags,
  1938. imap_trash_msg,
  1939. imap_close,
  1940. imap_cancel,
  1941. imap_commit,
  1942. };