drv_imap.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  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 "driver.h"
  24. #include "socket.h"
  25. #include <assert.h>
  26. #include <unistd.h>
  27. #include <stdlib.h>
  28. #include <stdio.h>
  29. #include <stddef.h>
  30. #include <limits.h>
  31. #include <string.h>
  32. #include <ctype.h>
  33. #include <time.h>
  34. #include <sys/wait.h>
  35. #ifdef HAVE_LIBSASL
  36. # include <sasl/sasl.h>
  37. # include <sasl/saslutil.h>
  38. #endif
  39. #ifdef HAVE_LIBSSL
  40. enum { SSL_None, SSL_STARTTLS, SSL_IMAPS };
  41. #endif
  42. typedef struct imap_server_conf {
  43. struct imap_server_conf *next;
  44. char *name;
  45. server_conf_t sconf;
  46. char *user;
  47. char *pass;
  48. char *pass_cmd;
  49. int max_in_progress;
  50. string_list_t *auth_mechs;
  51. #ifdef HAVE_LIBSSL
  52. char ssl_type;
  53. #endif
  54. } imap_server_conf_t;
  55. typedef struct imap_store_conf {
  56. store_conf_t gen;
  57. imap_server_conf_t *server;
  58. char *delimiter;
  59. char use_namespace;
  60. } imap_store_conf_t;
  61. typedef struct imap_message {
  62. message_t gen;
  63. /* int seq; will be needed when expunges are tracked */
  64. } imap_message_t;
  65. #define NIL (void*)0x1
  66. #define LIST (void*)0x2
  67. typedef struct _list {
  68. struct _list *next, *child;
  69. char *val;
  70. int len;
  71. } list_t;
  72. #define MAX_LIST_DEPTH 5
  73. struct imap_store;
  74. typedef struct parse_list_state {
  75. list_t *head, **stack[MAX_LIST_DEPTH];
  76. int (*callback)( struct imap_store *ctx, list_t *list, char *cmd );
  77. int level, need_bytes;
  78. } parse_list_state_t;
  79. struct imap_cmd;
  80. typedef struct imap_store {
  81. store_t gen;
  82. const char *label; /* foreign */
  83. const char *prefix;
  84. const char *name;
  85. int ref_count;
  86. /* trash folder's existence is not confirmed yet */
  87. enum { TrashUnknown, TrashChecking, TrashKnown } trashnc;
  88. uint got_namespace:1;
  89. char *delimiter; /* hierarchy delimiter */
  90. list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
  91. message_t **msgapp; /* FETCH results */
  92. uint caps; /* CAPABILITY results */
  93. string_list_t *auth_mechs;
  94. parse_list_state_t parse_list_sts;
  95. /* command queue */
  96. int nexttag, num_in_progress;
  97. struct imap_cmd *pending, **pending_append;
  98. struct imap_cmd *in_progress, **in_progress_append;
  99. /* Used during sequential operations like connect */
  100. enum { GreetingPending = 0, GreetingBad, GreetingOk, GreetingPreauth } greeting;
  101. int canceling; /* imap_cancel() is in progress */
  102. union {
  103. void (*imap_open)( store_t *srv, void *aux );
  104. void (*imap_cancel)( void *aux );
  105. } callbacks;
  106. void *callback_aux;
  107. #ifdef HAVE_LIBSASL
  108. sasl_conn_t *sasl;
  109. int sasl_cont;
  110. #endif
  111. conn_t conn; /* this is BIG, so put it last */
  112. } imap_store_t;
  113. struct imap_cmd {
  114. struct imap_cmd *next;
  115. char *cmd;
  116. int tag;
  117. struct {
  118. /* Will be called on each continuation request until it resets this pointer.
  119. * Needs to invoke bad_callback and return -1 on error, otherwise return 0. */
  120. int (*cont)( imap_store_t *ctx, struct imap_cmd *cmd, const char *prompt );
  121. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response );
  122. char *data;
  123. int data_len;
  124. int uid; /* to identify fetch responses */
  125. char high_prio; /* if command is queued, put it at the front of the queue. */
  126. char to_trash; /* we are storing to trash, not current. */
  127. char create; /* create the mailbox if we get an error ... */
  128. char trycreate; /* ... but only if this is true or the server says so. */
  129. } param;
  130. };
  131. struct imap_cmd_simple {
  132. struct imap_cmd gen;
  133. void (*callback)( int sts, void *aux );
  134. void *callback_aux;
  135. };
  136. struct imap_cmd_fetch_msg {
  137. struct imap_cmd_simple gen;
  138. msg_data_t *msg_data;
  139. };
  140. struct imap_cmd_out_uid {
  141. struct imap_cmd gen;
  142. void (*callback)( int sts, int uid, void *aux );
  143. void *callback_aux;
  144. int out_uid;
  145. };
  146. struct imap_cmd_find_new {
  147. struct imap_cmd_simple gen;
  148. int uid;
  149. };
  150. struct imap_cmd_refcounted_state {
  151. void (*callback)( int sts, void *aux );
  152. void *callback_aux;
  153. int ref_count;
  154. int ret_val;
  155. };
  156. struct imap_cmd_refcounted {
  157. struct imap_cmd gen;
  158. struct imap_cmd_refcounted_state *state;
  159. };
  160. #define CAP(cap) (ctx->caps & (1 << (cap)))
  161. enum CAPABILITY {
  162. NOLOGIN = 0,
  163. #ifdef HAVE_LIBSASL
  164. SASLIR,
  165. #endif
  166. #ifdef HAVE_LIBSSL
  167. STARTTLS,
  168. #endif
  169. UIDPLUS,
  170. LITERALPLUS,
  171. MOVE,
  172. NAMESPACE,
  173. COMPRESS_DEFLATE
  174. };
  175. static const char *cap_list[] = {
  176. "LOGINDISABLED",
  177. #ifdef HAVE_LIBSASL
  178. "SASL-IR",
  179. #endif
  180. #ifdef HAVE_LIBSSL
  181. "STARTTLS",
  182. #endif
  183. "UIDPLUS",
  184. "LITERAL+",
  185. "MOVE",
  186. "NAMESPACE",
  187. "COMPRESS=DEFLATE"
  188. };
  189. #define RESP_OK 0
  190. #define RESP_NO 1
  191. #define RESP_CANCEL 2
  192. static INLINE void imap_ref( imap_store_t *ctx ) { ++ctx->ref_count; }
  193. static int imap_deref( imap_store_t *ctx );
  194. static void imap_invoke_bad_callback( imap_store_t *ctx );
  195. static const char *Flags[] = {
  196. "Draft",
  197. "Flagged",
  198. "Answered",
  199. "Seen",
  200. "Deleted",
  201. };
  202. static struct imap_cmd *
  203. new_imap_cmd( int size )
  204. {
  205. struct imap_cmd *cmd = nfmalloc( size );
  206. memset( &cmd->param, 0, sizeof(cmd->param) );
  207. return cmd;
  208. }
  209. #define INIT_IMAP_CMD(type, cmdp, cb, aux) \
  210. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  211. cmdp->callback = cb; \
  212. cmdp->callback_aux = aux;
  213. #define INIT_IMAP_CMD_X(type, cmdp, cb, aux) \
  214. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  215. cmdp->gen.callback = cb; \
  216. cmdp->gen.callback_aux = aux;
  217. static void
  218. done_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd, int response )
  219. {
  220. cmd->param.done( ctx, cmd, response );
  221. free( cmd->param.data );
  222. free( cmd->cmd );
  223. free( cmd );
  224. }
  225. static int
  226. send_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd )
  227. {
  228. int bufl, litplus, iovcnt = 1;
  229. const char *buffmt;
  230. conn_iovec_t iov[3];
  231. char buf[1024];
  232. cmd->tag = ++ctx->nexttag;
  233. if (!cmd->param.data) {
  234. buffmt = "%d %s\r\n";
  235. litplus = 0;
  236. } else if ((cmd->param.to_trash && ctx->trashnc == TrashUnknown) || !CAP(LITERALPLUS) || cmd->param.data_len >= 100*1024) {
  237. buffmt = "%d %s{%d}\r\n";
  238. litplus = 0;
  239. } else {
  240. buffmt = "%d %s{%d+}\r\n";
  241. litplus = 1;
  242. }
  243. bufl = nfsnprintf( buf, sizeof(buf), buffmt,
  244. cmd->tag, cmd->cmd, cmd->param.data_len );
  245. if (DFlags & VERBOSE) {
  246. if (ctx->num_in_progress)
  247. printf( "(%d in progress) ", ctx->num_in_progress );
  248. if (!starts_with( cmd->cmd, -1, "LOGIN", 5 ))
  249. printf( "%s>>> %s", ctx->label, buf );
  250. else
  251. printf( "%s>>> %d LOGIN <user> <pass>\n", ctx->label, cmd->tag );
  252. fflush( stdout );
  253. }
  254. iov[0].buf = buf;
  255. iov[0].len = bufl;
  256. iov[0].takeOwn = KeepOwn;
  257. if (litplus) {
  258. iov[1].buf = cmd->param.data;
  259. iov[1].len = cmd->param.data_len;
  260. iov[1].takeOwn = GiveOwn;
  261. cmd->param.data = 0;
  262. iov[2].buf = "\r\n";
  263. iov[2].len = 2;
  264. iov[2].takeOwn = KeepOwn;
  265. iovcnt = 3;
  266. }
  267. if (socket_write( &ctx->conn, iov, iovcnt ) < 0)
  268. goto bail;
  269. if (cmd->param.to_trash && ctx->trashnc == TrashUnknown)
  270. ctx->trashnc = TrashChecking;
  271. cmd->next = 0;
  272. *ctx->in_progress_append = cmd;
  273. ctx->in_progress_append = &cmd->next;
  274. ctx->num_in_progress++;
  275. return 0;
  276. bail:
  277. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  278. return -1;
  279. }
  280. static int
  281. cmd_submittable( imap_store_t *ctx, struct imap_cmd *cmd )
  282. {
  283. struct imap_cmd *cmdp;
  284. return !ctx->conn.write_buf &&
  285. !(ctx->in_progress &&
  286. (cmdp = (struct imap_cmd *)((char *)ctx->in_progress_append -
  287. offsetof(struct imap_cmd, next)), 1) &&
  288. (cmdp->param.cont || cmdp->param.data)) &&
  289. !(cmd->param.to_trash && ctx->trashnc == TrashChecking) &&
  290. ctx->num_in_progress < ((imap_store_conf_t *)ctx->gen.conf)->server->max_in_progress;
  291. }
  292. static int
  293. flush_imap_cmds( imap_store_t *ctx )
  294. {
  295. struct imap_cmd *cmd;
  296. while ((cmd = ctx->pending) && cmd_submittable( ctx, cmd )) {
  297. if (!(ctx->pending = cmd->next))
  298. ctx->pending_append = &ctx->pending;
  299. if (send_imap_cmd( ctx, cmd ) < 0)
  300. return -1;
  301. }
  302. return 0;
  303. }
  304. static void
  305. cancel_pending_imap_cmds( imap_store_t *ctx )
  306. {
  307. struct imap_cmd *cmd;
  308. while ((cmd = ctx->pending)) {
  309. if (!(ctx->pending = cmd->next))
  310. ctx->pending_append = &ctx->pending;
  311. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  312. }
  313. }
  314. static void
  315. cancel_submitted_imap_cmds( imap_store_t *ctx )
  316. {
  317. struct imap_cmd *cmd;
  318. while ((cmd = ctx->in_progress)) {
  319. ctx->in_progress = cmd->next;
  320. /* don't update num_in_progress and in_progress_append - store is dead */
  321. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  322. }
  323. }
  324. static int
  325. submit_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd )
  326. {
  327. assert( ctx );
  328. assert( ctx->gen.bad_callback );
  329. assert( cmd );
  330. assert( cmd->param.done );
  331. if ((ctx->pending && !cmd->param.high_prio) || !cmd_submittable( ctx, cmd )) {
  332. if (ctx->pending && cmd->param.high_prio) {
  333. cmd->next = ctx->pending;
  334. ctx->pending = cmd;
  335. } else {
  336. cmd->next = 0;
  337. *ctx->pending_append = cmd;
  338. ctx->pending_append = &cmd->next;
  339. }
  340. return 0;
  341. }
  342. return send_imap_cmd( ctx, cmd );
  343. }
  344. /* Minimal printf() replacement that supports an %\s format sequence to print backslash-escaped
  345. * string literals. Note that this does not automatically add quotes around the printed string,
  346. * so it is possible to concatenate multiple segments. */
  347. static char *
  348. imap_vprintf( const char *fmt, va_list ap )
  349. {
  350. const char *s, *es;
  351. char *d, *ed;
  352. int maxlen;
  353. char c;
  354. char buf[1024]; /* Minimal supported command buffer size per IMAP spec. */
  355. d = buf;
  356. ed = d + sizeof(buf);
  357. s = fmt;
  358. for (;;) {
  359. c = *fmt;
  360. if (!c || c == '%') {
  361. int l = fmt - s;
  362. if (d + l > ed)
  363. oob();
  364. memcpy( d, s, l );
  365. d += l;
  366. if (!c) {
  367. l = d - buf;
  368. ed = nfmalloc( l + 1 );
  369. memcpy( ed, buf, l );
  370. ed[l] = 0;
  371. return ed;
  372. }
  373. maxlen = INT_MAX;
  374. c = *++fmt;
  375. if (c == '\\') {
  376. c = *++fmt;
  377. if (c != 's') {
  378. fputs( "Fatal: unsupported escaped format specifier. Please report a bug.\n", stderr );
  379. abort();
  380. }
  381. s = va_arg( ap, const char * );
  382. while ((c = *s++)) {
  383. if (d + 2 > ed)
  384. oob();
  385. if (c == '\\' || c == '"')
  386. *d++ = '\\';
  387. *d++ = c;
  388. }
  389. } else { /* \\ cannot be combined with anything else. */
  390. if (c == '.') {
  391. c = *++fmt;
  392. if (c != '*') {
  393. fputs( "Fatal: unsupported string length specification. Please report a bug.\n", stderr );
  394. abort();
  395. }
  396. maxlen = va_arg( ap , int );
  397. c = *++fmt;
  398. }
  399. if (c == 'c') {
  400. if (d + 1 > ed)
  401. oob();
  402. *d++ = (char)va_arg( ap , int );
  403. } else if (c == 's') {
  404. s = va_arg( ap, const char * );
  405. es = memchr( s, 0, maxlen );
  406. l = es ? es - s : maxlen;
  407. if (d + l > ed)
  408. oob();
  409. memcpy( d, s, l );
  410. d += l;
  411. } else if (c == 'd') {
  412. d += nfsnprintf( d, ed - d, "%d", va_arg( ap , int ) );
  413. } else {
  414. fputs( "Fatal: unsupported format specifier. Please report a bug.\n", stderr );
  415. abort();
  416. }
  417. }
  418. s = ++fmt;
  419. } else {
  420. fmt++;
  421. }
  422. }
  423. }
  424. static int
  425. imap_exec( imap_store_t *ctx, struct imap_cmd *cmdp,
  426. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response ),
  427. const char *fmt, ... )
  428. {
  429. va_list ap;
  430. if (!cmdp)
  431. cmdp = new_imap_cmd( sizeof(*cmdp) );
  432. cmdp->param.done = done;
  433. va_start( ap, fmt );
  434. cmdp->cmd = imap_vprintf( fmt, ap );
  435. va_end( ap );
  436. return submit_imap_cmd( ctx, cmdp );
  437. }
  438. static void
  439. transform_box_response( int *response )
  440. {
  441. switch (*response) {
  442. case RESP_CANCEL: *response = DRV_CANCELED; break;
  443. case RESP_NO: *response = DRV_BOX_BAD; break;
  444. default: *response = DRV_OK; break;
  445. }
  446. }
  447. static void
  448. imap_done_simple_box( imap_store_t *ctx ATTR_UNUSED,
  449. struct imap_cmd *cmd, int response )
  450. {
  451. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  452. transform_box_response( &response );
  453. cmdp->callback( response, cmdp->callback_aux );
  454. }
  455. static void
  456. transform_msg_response( int *response )
  457. {
  458. switch (*response) {
  459. case RESP_CANCEL: *response = DRV_CANCELED; break;
  460. case RESP_NO: *response = DRV_MSG_BAD; break;
  461. default: *response = DRV_OK; break;
  462. }
  463. }
  464. static void
  465. imap_done_simple_msg( imap_store_t *ctx ATTR_UNUSED,
  466. struct imap_cmd *cmd, int response )
  467. {
  468. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  469. transform_msg_response( &response );
  470. cmdp->callback( response, cmdp->callback_aux );
  471. }
  472. static struct imap_cmd_refcounted_state *
  473. imap_refcounted_new_state( void (*cb)( int, void * ), void *aux )
  474. {
  475. struct imap_cmd_refcounted_state *sts = nfmalloc( sizeof(*sts) );
  476. sts->callback = cb;
  477. sts->callback_aux = aux;
  478. sts->ref_count = 1; /* so forced sync does not cause an early exit */
  479. sts->ret_val = DRV_OK;
  480. return sts;
  481. }
  482. static struct imap_cmd *
  483. imap_refcounted_new_cmd( struct imap_cmd_refcounted_state *sts )
  484. {
  485. struct imap_cmd_refcounted *cmd = (struct imap_cmd_refcounted *)new_imap_cmd( sizeof(*cmd) );
  486. cmd->state = sts;
  487. sts->ref_count++;
  488. return &cmd->gen;
  489. }
  490. static void
  491. imap_refcounted_done( struct imap_cmd_refcounted_state *sts )
  492. {
  493. if (!--sts->ref_count) {
  494. sts->callback( sts->ret_val, sts->callback_aux );
  495. free( sts );
  496. }
  497. }
  498. static void
  499. imap_refcounted_done_box( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  500. {
  501. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  502. switch (response) {
  503. case RESP_CANCEL:
  504. sts->ret_val = DRV_CANCELED;
  505. break;
  506. case RESP_NO:
  507. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  508. sts->ret_val = DRV_BOX_BAD;
  509. break;
  510. }
  511. imap_refcounted_done( sts );
  512. }
  513. static const char *
  514. imap_strchr( const char *s, char tc )
  515. {
  516. for (;; s++) {
  517. char c = *s;
  518. if (c == '\\')
  519. c = *++s;
  520. if (!c)
  521. return 0;
  522. if (c == tc)
  523. return s;
  524. }
  525. }
  526. static char *
  527. next_arg( char **ps )
  528. {
  529. char *ret, *s, *d;
  530. char c;
  531. assert( ps );
  532. s = *ps;
  533. if (!s)
  534. return 0;
  535. while (isspace( (uchar)*s ))
  536. s++;
  537. if (!*s) {
  538. *ps = 0;
  539. return 0;
  540. }
  541. if (*s == '"') {
  542. s++;
  543. ret = d = s;
  544. while ((c = *s++) != '"') {
  545. if (c == '\\')
  546. c = *s++;
  547. if (!c) {
  548. *ps = 0;
  549. return 0;
  550. }
  551. *d++ = c;
  552. }
  553. *d = 0;
  554. } else {
  555. ret = s;
  556. while ((c = *s)) {
  557. if (isspace( (uchar)c )) {
  558. *s++ = 0;
  559. break;
  560. }
  561. s++;
  562. }
  563. }
  564. if (!*s)
  565. s = 0;
  566. *ps = s;
  567. return ret;
  568. }
  569. static int
  570. is_atom( list_t *list )
  571. {
  572. return list && list->val && list->val != NIL && list->val != LIST;
  573. }
  574. static int
  575. is_list( list_t *list )
  576. {
  577. return list && list->val == LIST;
  578. }
  579. static void
  580. free_list( list_t *list )
  581. {
  582. list_t *tmp;
  583. for (; list; list = tmp) {
  584. tmp = list->next;
  585. if (is_list( list ))
  586. free_list( list->child );
  587. else if (is_atom( list ))
  588. free( list->val );
  589. free( list );
  590. }
  591. }
  592. enum {
  593. LIST_OK,
  594. LIST_PARTIAL,
  595. LIST_BAD
  596. };
  597. static int
  598. parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
  599. {
  600. list_t *cur, **curp;
  601. char *s = *sp, *d, *p;
  602. int bytes;
  603. char c;
  604. assert( sts );
  605. assert( sts->level > 0 );
  606. curp = sts->stack[--sts->level];
  607. bytes = sts->need_bytes;
  608. if (bytes >= 0) {
  609. sts->need_bytes = -1;
  610. if (!bytes)
  611. goto getline;
  612. cur = (list_t *)((char *)curp - offsetof(list_t, next));
  613. s = cur->val + cur->len - bytes;
  614. goto getbytes;
  615. }
  616. if (!s)
  617. return LIST_BAD;
  618. for (;;) {
  619. while (isspace( (uchar)*s ))
  620. s++;
  621. if (sts->level && *s == ')') {
  622. s++;
  623. curp = sts->stack[--sts->level];
  624. goto next;
  625. }
  626. *curp = cur = nfmalloc( sizeof(*cur) );
  627. cur->val = 0; /* for clean bail */
  628. curp = &cur->next;
  629. *curp = 0; /* ditto */
  630. if (*s == '(') {
  631. /* sublist */
  632. if (sts->level == MAX_LIST_DEPTH)
  633. goto bail;
  634. s++;
  635. cur->val = LIST;
  636. sts->stack[sts->level++] = curp;
  637. curp = &cur->child;
  638. *curp = 0; /* for clean bail */
  639. goto next2;
  640. } else if (ctx && *s == '{') {
  641. /* literal */
  642. bytes = cur->len = strtol( s + 1, &s, 10 );
  643. if (*s != '}' || *++s)
  644. goto bail;
  645. s = cur->val = nfmalloc( cur->len + 1 );
  646. s[cur->len] = 0;
  647. getbytes:
  648. bytes -= socket_read( &ctx->conn, s, bytes );
  649. if (bytes > 0)
  650. goto postpone;
  651. if (DFlags & XVERBOSE) {
  652. printf( "%s=========\n", ctx->label );
  653. fwrite( cur->val, cur->len, 1, stdout );
  654. printf( "%s=========\n", ctx->label );
  655. fflush( stdout );
  656. }
  657. getline:
  658. if (!(s = socket_read_line( &ctx->conn )))
  659. goto postpone;
  660. if (DFlags & VERBOSE) {
  661. printf( "%s%s\n", ctx->label, s );
  662. fflush( stdout );
  663. }
  664. } else if (*s == '"') {
  665. /* quoted string */
  666. s++;
  667. p = d = s;
  668. while ((c = *s++) != '"') {
  669. if (c == '\\')
  670. c = *s++;
  671. if (!c)
  672. goto bail;
  673. *d++ = c;
  674. }
  675. cur->len = d - p;
  676. cur->val = nfmalloc( cur->len + 1 );
  677. memcpy( cur->val, p, cur->len );
  678. cur->val[cur->len] = 0;
  679. } else {
  680. /* atom */
  681. p = s;
  682. for (; *s && !isspace( (uchar)*s ); s++)
  683. if (sts->level && *s == ')')
  684. break;
  685. cur->len = s - p;
  686. if (equals( p, cur->len, "NIL", 3 ))
  687. cur->val = NIL;
  688. else {
  689. cur->val = nfmalloc( cur->len + 1 );
  690. memcpy( cur->val, p, cur->len );
  691. cur->val[cur->len] = 0;
  692. }
  693. }
  694. next:
  695. if (!sts->level)
  696. break;
  697. next2:
  698. if (!*s)
  699. goto bail;
  700. }
  701. *sp = s;
  702. return LIST_OK;
  703. postpone:
  704. if (sts->level < MAX_LIST_DEPTH) {
  705. sts->stack[sts->level++] = curp;
  706. sts->need_bytes = bytes;
  707. return LIST_PARTIAL;
  708. }
  709. bail:
  710. free_list( sts->head );
  711. return LIST_BAD;
  712. }
  713. static void
  714. parse_list_init( parse_list_state_t *sts )
  715. {
  716. sts->need_bytes = -1;
  717. sts->level = 1;
  718. sts->head = 0;
  719. sts->stack[0] = &sts->head;
  720. }
  721. static int
  722. parse_list_continue( imap_store_t *ctx, char *s )
  723. {
  724. list_t *list;
  725. int resp;
  726. if ((resp = parse_imap_list( ctx, &s, &ctx->parse_list_sts )) != LIST_PARTIAL) {
  727. list = (resp == LIST_BAD) ? 0 : ctx->parse_list_sts.head;
  728. ctx->parse_list_sts.head = 0;
  729. resp = ctx->parse_list_sts.callback( ctx, list, s );
  730. }
  731. return resp;
  732. }
  733. static int
  734. parse_list( imap_store_t *ctx, char *s, int (*cb)( imap_store_t *ctx, list_t *list, char *s ) )
  735. {
  736. parse_list_init( &ctx->parse_list_sts );
  737. ctx->parse_list_sts.callback = cb;
  738. return parse_list_continue( ctx, s );
  739. }
  740. static int parse_namespace_rsp_p2( imap_store_t *, list_t *, char * );
  741. static int parse_namespace_rsp_p3( imap_store_t *, list_t *, char * );
  742. static int
  743. parse_namespace_rsp_fail( void )
  744. {
  745. error( "IMAP error: malformed NAMESPACE response\n" );
  746. return LIST_BAD;
  747. }
  748. static int
  749. parse_namespace_rsp( imap_store_t *ctx, list_t *list, char *s )
  750. {
  751. if (!(ctx->ns_personal = list))
  752. return parse_namespace_rsp_fail();
  753. return parse_list( ctx, s, parse_namespace_rsp_p2 );
  754. }
  755. static int
  756. parse_namespace_rsp_p2( imap_store_t *ctx, list_t *list, char *s )
  757. {
  758. if (!(ctx->ns_other = list))
  759. return parse_namespace_rsp_fail();
  760. return parse_list( ctx, s, parse_namespace_rsp_p3 );
  761. }
  762. static int
  763. parse_namespace_rsp_p3( imap_store_t *ctx, list_t *list, char *s ATTR_UNUSED )
  764. {
  765. if (!(ctx->ns_shared = list))
  766. return parse_namespace_rsp_fail();
  767. return LIST_OK;
  768. }
  769. static time_t
  770. parse_date( const char *str )
  771. {
  772. char *end;
  773. time_t date;
  774. int hours, mins;
  775. struct tm datetime;
  776. memset( &datetime, 0, sizeof(datetime) );
  777. if (!(end = strptime( str, "%d-%b-%Y %H:%M:%S ", &datetime )))
  778. return -1;
  779. if ((date = timegm( &datetime )) == -1)
  780. return -1;
  781. if (sscanf( end, "%3d%2d", &hours, &mins ) != 2)
  782. return -1;
  783. return date - (hours * 60 + mins) * 60;
  784. }
  785. static int
  786. parse_fetch_rsp( imap_store_t *ctx, list_t *list, char *s ATTR_UNUSED )
  787. {
  788. list_t *tmp, *flags;
  789. char *body = 0, *tuid = 0;
  790. imap_message_t *cur;
  791. msg_data_t *msgdata;
  792. struct imap_cmd *cmdp;
  793. int uid = 0, mask = 0, status = 0, size = 0;
  794. uint i;
  795. time_t date = 0;
  796. if (!is_list( list )) {
  797. error( "IMAP error: bogus FETCH response\n" );
  798. free_list( list );
  799. return LIST_BAD;
  800. }
  801. for (tmp = list->child; tmp; tmp = tmp->next) {
  802. if (is_atom( tmp )) {
  803. if (!strcmp( "UID", tmp->val )) {
  804. tmp = tmp->next;
  805. if (is_atom( tmp ))
  806. uid = atoi( tmp->val );
  807. else
  808. error( "IMAP error: unable to parse UID\n" );
  809. } else if (!strcmp( "FLAGS", tmp->val )) {
  810. tmp = tmp->next;
  811. if (is_list( tmp )) {
  812. for (flags = tmp->child; flags; flags = flags->next) {
  813. if (is_atom( flags )) {
  814. if (flags->val[0] == '\\') { /* ignore user-defined flags for now */
  815. if (!strcmp( "Recent", flags->val + 1)) {
  816. status |= M_RECENT;
  817. goto flagok;
  818. }
  819. for (i = 0; i < as(Flags); i++)
  820. if (!strcmp( Flags[i], flags->val + 1 )) {
  821. mask |= 1 << i;
  822. goto flagok;
  823. }
  824. if (flags->val[1] == 'X' && flags->val[2] == '-')
  825. goto flagok; /* ignore system flag extensions */
  826. error( "IMAP warning: unknown system flag %s\n", flags->val );
  827. }
  828. flagok: ;
  829. } else
  830. error( "IMAP error: unable to parse FLAGS list\n" );
  831. }
  832. status |= M_FLAGS;
  833. } else
  834. error( "IMAP error: unable to parse FLAGS\n" );
  835. } else if (!strcmp( "INTERNALDATE", tmp->val )) {
  836. tmp = tmp->next;
  837. if (is_atom( tmp )) {
  838. if ((date = parse_date( tmp->val )) == -1)
  839. error( "IMAP error: unable to parse INTERNALDATE format\n" );
  840. } else
  841. error( "IMAP error: unable to parse INTERNALDATE\n" );
  842. } else if (!strcmp( "RFC822.SIZE", tmp->val )) {
  843. tmp = tmp->next;
  844. if (is_atom( tmp ))
  845. size = atoi( tmp->val );
  846. else
  847. error( "IMAP error: unable to parse RFC822.SIZE\n" );
  848. } else if (!strcmp( "BODY[]", tmp->val )) {
  849. tmp = tmp->next;
  850. if (is_atom( tmp )) {
  851. body = tmp->val;
  852. tmp->val = 0; /* don't free together with list */
  853. size = tmp->len;
  854. } else
  855. error( "IMAP error: unable to parse BODY[]\n" );
  856. } else if (!strcmp( "BODY[HEADER.FIELDS", tmp->val )) {
  857. tmp = tmp->next;
  858. if (is_list( tmp )) {
  859. tmp = tmp->next;
  860. if (!is_atom( tmp ) || strcmp( tmp->val, "]" ))
  861. goto bfail;
  862. tmp = tmp->next;
  863. if (!is_atom( tmp ))
  864. goto bfail;
  865. if (starts_with( tmp->val, tmp->len, "X-TUID: ", 8 ))
  866. tuid = tmp->val + 8;
  867. } else {
  868. bfail:
  869. error( "IMAP error: unable to parse BODY[HEADER.FIELDS ...]\n" );
  870. }
  871. }
  872. }
  873. }
  874. if (body) {
  875. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  876. if (cmdp->param.uid == uid)
  877. goto gotuid;
  878. error( "IMAP error: unexpected FETCH response (UID %d)\n", uid );
  879. free_list( list );
  880. return LIST_BAD;
  881. gotuid:
  882. msgdata = ((struct imap_cmd_fetch_msg *)cmdp)->msg_data;
  883. msgdata->data = body;
  884. msgdata->len = size;
  885. msgdata->date = date;
  886. if (status & M_FLAGS)
  887. msgdata->flags = mask;
  888. } else if (uid) { /* ignore async flag updates for now */
  889. /* XXX this will need sorting for out-of-order (multiple queries) */
  890. cur = nfcalloc( sizeof(*cur) );
  891. *ctx->msgapp = &cur->gen;
  892. ctx->msgapp = &cur->gen.next;
  893. cur->gen.next = 0;
  894. cur->gen.uid = uid;
  895. cur->gen.flags = mask;
  896. cur->gen.status = status;
  897. cur->gen.size = size;
  898. cur->gen.srec = 0;
  899. if (tuid)
  900. strncpy( cur->gen.tuid, tuid, TUIDL );
  901. else
  902. cur->gen.tuid[0] = 0;
  903. if (ctx->gen.uidnext <= uid) /* in case the server sends no UIDNEXT */
  904. ctx->gen.uidnext = uid + 1;
  905. }
  906. free_list( list );
  907. return LIST_OK;
  908. }
  909. static void
  910. parse_capability( imap_store_t *ctx, char *cmd )
  911. {
  912. char *arg;
  913. uint i;
  914. free_string_list( ctx->auth_mechs );
  915. ctx->auth_mechs = 0;
  916. ctx->caps = 0x80000000;
  917. while ((arg = next_arg( &cmd ))) {
  918. if (starts_with( arg, -1, "AUTH=", 5 )) {
  919. add_string_list( &ctx->auth_mechs, arg + 5 );
  920. } else {
  921. for (i = 0; i < as(cap_list); i++)
  922. if (!strcmp( cap_list[i], arg ))
  923. ctx->caps |= 1 << i;
  924. }
  925. }
  926. if (!CAP(NOLOGIN))
  927. add_string_list( &ctx->auth_mechs, "LOGIN" );
  928. }
  929. static int
  930. parse_response_code( imap_store_t *ctx, struct imap_cmd *cmd, char *s )
  931. {
  932. char *arg, *earg, *p;
  933. if (!s || *s != '[')
  934. return RESP_OK; /* no response code */
  935. s++;
  936. if (!(p = strchr( s, ']' ))) {
  937. bad_resp:
  938. error( "IMAP error: malformed response code\n" );
  939. return RESP_CANCEL;
  940. }
  941. *p++ = 0;
  942. if (!(arg = next_arg( &s )))
  943. goto bad_resp;
  944. if (!strcmp( "UIDVALIDITY", arg )) {
  945. if (!(arg = next_arg( &s )) ||
  946. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg))
  947. {
  948. error( "IMAP error: malformed UIDVALIDITY status\n" );
  949. return RESP_CANCEL;
  950. }
  951. } else if (!strcmp( "UIDNEXT", arg )) {
  952. if (!(arg = next_arg( &s )) || !(ctx->gen.uidnext = atoi( arg ))) {
  953. error( "IMAP error: malformed NEXTUID status\n" );
  954. return RESP_CANCEL;
  955. }
  956. } else if (!strcmp( "CAPABILITY", arg )) {
  957. parse_capability( ctx, s );
  958. } else if (!strcmp( "ALERT", arg )) {
  959. /* RFC2060 says that these messages MUST be displayed
  960. * to the user
  961. */
  962. for (; isspace( (uchar)*p ); p++);
  963. error( "*** IMAP ALERT *** %s\n", p );
  964. } else if (cmd && !strcmp( "APPENDUID", arg )) {
  965. if (!(arg = next_arg( &s )) ||
  966. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg) ||
  967. !(arg = next_arg( &s )) ||
  968. !(((struct imap_cmd_out_uid *)cmd)->out_uid = atoi( arg )))
  969. {
  970. error( "IMAP error: malformed APPENDUID status\n" );
  971. return RESP_CANCEL;
  972. }
  973. }
  974. return RESP_OK;
  975. }
  976. static int parse_list_rsp_p2( imap_store_t *, list_t *, char * );
  977. static int
  978. parse_list_rsp( imap_store_t *ctx, list_t *list, char *cmd )
  979. {
  980. char *arg;
  981. list_t *lp;
  982. if (!is_list( list )) {
  983. free_list( list );
  984. bad_list:
  985. error( "IMAP error: malformed LIST response\n" );
  986. return LIST_BAD;
  987. }
  988. for (lp = list->child; lp; lp = lp->next)
  989. if (is_atom( lp ) && !strcasecmp( lp->val, "\\NoSelect" )) {
  990. free_list( list );
  991. return LIST_OK;
  992. }
  993. free_list( list );
  994. if (!(arg = next_arg( &cmd )))
  995. goto bad_list;
  996. if (!ctx->delimiter)
  997. ctx->delimiter = nfstrdup( arg );
  998. return parse_list( ctx, cmd, parse_list_rsp_p2 );
  999. }
  1000. static int
  1001. is_inbox( imap_store_t *ctx, const char *arg, int argl )
  1002. {
  1003. int i;
  1004. char c;
  1005. if (!starts_with( arg, argl, "INBOX", 5 ))
  1006. return 0;
  1007. if (arg[5])
  1008. for (i = 0; (c = ctx->delimiter[i]); i++)
  1009. if (arg[i + 5] != c)
  1010. return 0;
  1011. return 1;
  1012. }
  1013. static int
  1014. parse_list_rsp_p2( imap_store_t *ctx, list_t *list, char *cmd ATTR_UNUSED )
  1015. {
  1016. string_list_t *narg;
  1017. char *arg;
  1018. int argl, l;
  1019. if (!is_atom( list )) {
  1020. error( "IMAP error: malformed LIST response\n" );
  1021. free_list( list );
  1022. return LIST_BAD;
  1023. }
  1024. arg = list->val;
  1025. argl = list->len;
  1026. if (!is_inbox( ctx, arg, argl ) && (l = strlen( ctx->prefix ))) {
  1027. if (!starts_with( arg, argl, ctx->prefix, l ))
  1028. goto skip;
  1029. arg += l;
  1030. argl -= l;
  1031. if (is_inbox( ctx, arg, argl )) {
  1032. if (!arg[5])
  1033. warn( "IMAP warning: ignoring INBOX in %s\n", ctx->prefix );
  1034. goto skip;
  1035. }
  1036. }
  1037. if (argl >= 5 && !memcmp( arg + argl - 5, ".lock", 5 )) /* workaround broken servers */
  1038. goto skip;
  1039. if (map_name( arg, (char **)&narg, offsetof(string_list_t, string), ctx->delimiter, "/") < 0) {
  1040. warn( "IMAP warning: ignoring mailbox %s (reserved character '/' in name)\n", arg );
  1041. goto skip;
  1042. }
  1043. narg->next = ctx->gen.boxes;
  1044. ctx->gen.boxes = narg;
  1045. skip:
  1046. free_list( list );
  1047. return LIST_OK;
  1048. }
  1049. static int
  1050. prepare_name( char **buf, const imap_store_t *ctx, const char *prefix, const char *name )
  1051. {
  1052. int pl = strlen( prefix );
  1053. switch (map_name( name, buf, pl, "/", ctx->delimiter )) {
  1054. case -1:
  1055. error( "IMAP error: mailbox name %s contains server's hierarchy delimiter\n", name );
  1056. return -1;
  1057. case -2:
  1058. error( "IMAP error: server's hierarchy delimiter not known\n" );
  1059. return -1;
  1060. default:
  1061. memcpy( *buf, prefix, pl );
  1062. return 0;
  1063. }
  1064. }
  1065. static int
  1066. prepare_box( char **buf, const imap_store_t *ctx )
  1067. {
  1068. const char *name = ctx->name;
  1069. return prepare_name( buf, ctx,
  1070. (starts_with( name, -1, "INBOX", 5 ) && (!name[5] || name[5] == '/')) ? "" : ctx->prefix, name );
  1071. }
  1072. static int
  1073. prepare_trash( char **buf, const imap_store_t *ctx )
  1074. {
  1075. return prepare_name( buf, ctx, ctx->prefix, ctx->gen.conf->trash );
  1076. }
  1077. struct imap_cmd_trycreate {
  1078. struct imap_cmd gen;
  1079. struct imap_cmd *orig_cmd;
  1080. };
  1081. static void imap_open_store_greeted( imap_store_t * );
  1082. static void get_cmd_result_p2( imap_store_t *, struct imap_cmd *, int );
  1083. static void
  1084. imap_socket_read( void *aux )
  1085. {
  1086. imap_store_t *ctx = (imap_store_t *)aux;
  1087. struct imap_cmd *cmdp, **pcmdp;
  1088. char *cmd, *arg, *arg1, *p;
  1089. int resp, resp2, tag;
  1090. conn_iovec_t iov[2];
  1091. for (;;) {
  1092. if (ctx->parse_list_sts.level) {
  1093. resp = parse_list_continue( ctx, 0 );
  1094. listret:
  1095. if (resp == LIST_PARTIAL)
  1096. return;
  1097. if (resp == LIST_BAD)
  1098. break;
  1099. continue;
  1100. }
  1101. if (!(cmd = socket_read_line( &ctx->conn )))
  1102. return;
  1103. if (DFlags & VERBOSE) {
  1104. printf( "%s%s\n", ctx->label, cmd );
  1105. fflush( stdout );
  1106. }
  1107. arg = next_arg( &cmd );
  1108. if (!arg) {
  1109. error( "IMAP error: empty response\n" );
  1110. break;
  1111. }
  1112. if (*arg == '*') {
  1113. arg = next_arg( &cmd );
  1114. if (!arg) {
  1115. error( "IMAP error: malformed untagged response\n" );
  1116. break;
  1117. }
  1118. if (ctx->greeting == GreetingPending && !strcmp( "PREAUTH", arg )) {
  1119. parse_response_code( ctx, 0, cmd );
  1120. ctx->greeting = GreetingPreauth;
  1121. dogreet:
  1122. imap_ref( ctx );
  1123. imap_open_store_greeted( ctx );
  1124. if (imap_deref( ctx ))
  1125. return;
  1126. } else if (!strcmp( "OK", arg )) {
  1127. parse_response_code( ctx, 0, cmd );
  1128. if (ctx->greeting == GreetingPending) {
  1129. ctx->greeting = GreetingOk;
  1130. goto dogreet;
  1131. }
  1132. } else if (!strcmp( "BYE", arg )) {
  1133. if (ctx->conn.state != SCK_CLOSING) {
  1134. ctx->conn.state = SCK_CLOSING;
  1135. ctx->greeting = GreetingBad;
  1136. error( "IMAP error: unexpected BYE response: %s\n", cmd );
  1137. }
  1138. /* We just wait for the server to close the connection now. */
  1139. } else if (ctx->greeting == GreetingPending) {
  1140. error( "IMAP error: bogus greeting response %s\n", arg );
  1141. break;
  1142. } else if (!strcmp( "NO", arg )) {
  1143. warn( "Warning from IMAP server: %s\n", cmd );
  1144. } else if (!strcmp( "BAD", arg )) {
  1145. error( "Error from IMAP server: %s\n", cmd );
  1146. } else if (!strcmp( "CAPABILITY", arg )) {
  1147. parse_capability( ctx, cmd );
  1148. } else if (!strcmp( "LIST", arg )) {
  1149. resp = parse_list( ctx, cmd, parse_list_rsp );
  1150. goto listret;
  1151. } else if (!strcmp( "NAMESPACE", arg )) {
  1152. resp = parse_list( ctx, cmd, parse_namespace_rsp );
  1153. goto listret;
  1154. } else if ((arg1 = next_arg( &cmd ))) {
  1155. if (!strcmp( "EXISTS", arg1 ))
  1156. ctx->gen.count = atoi( arg );
  1157. else if (!strcmp( "RECENT", arg1 ))
  1158. ctx->gen.recent = atoi( arg );
  1159. else if(!strcmp ( "FETCH", arg1 )) {
  1160. resp = parse_list( ctx, cmd, parse_fetch_rsp );
  1161. goto listret;
  1162. }
  1163. } else {
  1164. error( "IMAP error: unrecognized untagged response '%s'\n", arg );
  1165. break; /* this may mean anything, so prefer not to spam the log */
  1166. }
  1167. continue;
  1168. } else if (!ctx->in_progress) {
  1169. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  1170. break; /* this may mean anything, so prefer not to spam the log */
  1171. } else if (*arg == '+') {
  1172. /* This can happen only with the last command underway, as
  1173. it enforces a round-trip. */
  1174. cmdp = ctx->in_progress;
  1175. if (cmdp->param.data) {
  1176. if (cmdp->param.to_trash)
  1177. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1178. iov[0].buf = cmdp->param.data;
  1179. iov[0].len = cmdp->param.data_len;
  1180. iov[0].takeOwn = GiveOwn;
  1181. cmdp->param.data = 0;
  1182. iov[1].buf = "\r\n";
  1183. iov[1].len = 2;
  1184. iov[1].takeOwn = KeepOwn;
  1185. if (socket_write( &ctx->conn, iov, 2 ) < 0)
  1186. return;
  1187. } else if (cmdp->param.cont) {
  1188. if (cmdp->param.cont( ctx, cmdp, cmd ))
  1189. return;
  1190. } else {
  1191. error( "IMAP error: unexpected command continuation request\n" );
  1192. break;
  1193. }
  1194. } else {
  1195. tag = atoi( arg );
  1196. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  1197. if (cmdp->tag == tag)
  1198. goto gottag;
  1199. error( "IMAP error: unexpected tag %s\n", arg );
  1200. break;
  1201. gottag:
  1202. if (!(*pcmdp = cmdp->next))
  1203. ctx->in_progress_append = pcmdp;
  1204. ctx->num_in_progress--;
  1205. arg = next_arg( &cmd );
  1206. if (!arg) {
  1207. error( "IMAP error: malformed tagged response\n" );
  1208. break;
  1209. }
  1210. if (!strcmp( "OK", arg )) {
  1211. if (cmdp->param.to_trash)
  1212. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1213. resp = RESP_OK;
  1214. } else {
  1215. if (!strcmp( "NO", arg )) {
  1216. if (cmdp->param.create &&
  1217. (cmdp->param.trycreate ||
  1218. (cmd && starts_with( cmd, -1, "[TRYCREATE]", 11 ))))
  1219. { /* SELECT, APPEND or UID COPY */
  1220. struct imap_cmd_trycreate *cmd2 =
  1221. (struct imap_cmd_trycreate *)new_imap_cmd( sizeof(*cmd2) );
  1222. cmd2->orig_cmd = cmdp;
  1223. cmd2->gen.param.high_prio = 1;
  1224. p = strchr( cmdp->cmd, '"' );
  1225. if (imap_exec( ctx, &cmd2->gen, get_cmd_result_p2,
  1226. "CREATE %.*s", imap_strchr( p + 1, '"' ) - p + 1, p ) < 0)
  1227. return;
  1228. continue;
  1229. }
  1230. resp = RESP_NO;
  1231. } else /*if (!strcmp( "BAD", arg ))*/
  1232. resp = RESP_CANCEL;
  1233. error( "IMAP command '%s' returned an error: %s %s\n",
  1234. !starts_with( cmdp->cmd, -1, "LOGIN", 5 ) ? cmdp->cmd : "LOGIN <user> <pass>",
  1235. arg, cmd ? cmd : "" );
  1236. }
  1237. if ((resp2 = parse_response_code( ctx, cmdp, cmd )) > resp)
  1238. resp = resp2;
  1239. imap_ref( ctx );
  1240. if (resp == RESP_CANCEL)
  1241. imap_invoke_bad_callback( ctx );
  1242. done_imap_cmd( ctx, cmdp, resp );
  1243. if (imap_deref( ctx ))
  1244. return;
  1245. if (ctx->canceling && !ctx->in_progress) {
  1246. ctx->canceling = 0;
  1247. ctx->callbacks.imap_cancel( ctx->callback_aux );
  1248. return;
  1249. }
  1250. }
  1251. if (flush_imap_cmds( ctx ) < 0)
  1252. return;
  1253. }
  1254. imap_invoke_bad_callback( ctx );
  1255. }
  1256. static void
  1257. get_cmd_result_p2( imap_store_t *ctx, struct imap_cmd *cmd, int response )
  1258. {
  1259. struct imap_cmd_trycreate *cmdp = (struct imap_cmd_trycreate *)cmd;
  1260. struct imap_cmd *ocmd = cmdp->orig_cmd;
  1261. if (response != RESP_OK) {
  1262. done_imap_cmd( ctx, ocmd, response );
  1263. } else {
  1264. ctx->gen.uidnext = 1;
  1265. if (ocmd->param.to_trash)
  1266. ctx->trashnc = TrashKnown;
  1267. ocmd->param.create = 0;
  1268. ocmd->param.high_prio = 1;
  1269. submit_imap_cmd( ctx, ocmd );
  1270. }
  1271. }
  1272. /******************* imap_cancel_store *******************/
  1273. static void
  1274. imap_cancel_store( store_t *gctx )
  1275. {
  1276. imap_store_t *ctx = (imap_store_t *)gctx;
  1277. #ifdef HAVE_LIBSASL
  1278. sasl_dispose( &ctx->sasl );
  1279. #endif
  1280. socket_close( &ctx->conn );
  1281. cancel_submitted_imap_cmds( ctx );
  1282. cancel_pending_imap_cmds( ctx );
  1283. free_generic_messages( ctx->gen.msgs );
  1284. free_string_list( ctx->gen.boxes );
  1285. free_list( ctx->ns_personal );
  1286. free_list( ctx->ns_other );
  1287. free_list( ctx->ns_shared );
  1288. free_string_list( ctx->auth_mechs );
  1289. free( ctx->delimiter );
  1290. imap_deref( ctx );
  1291. }
  1292. static int
  1293. imap_deref( imap_store_t *ctx )
  1294. {
  1295. if (!--ctx->ref_count) {
  1296. free( ctx );
  1297. return -1;
  1298. }
  1299. return 0;
  1300. }
  1301. static void
  1302. imap_invoke_bad_callback( imap_store_t *ctx )
  1303. {
  1304. ctx->gen.bad_callback( ctx->gen.bad_callback_aux );
  1305. }
  1306. /******************* imap_disown_store *******************/
  1307. static store_t *unowned;
  1308. static void
  1309. imap_cancel_unowned( void *gctx )
  1310. {
  1311. store_t *store, **storep;
  1312. for (storep = &unowned; (store = *storep); storep = &store->next)
  1313. if (store == gctx) {
  1314. *storep = store->next;
  1315. break;
  1316. }
  1317. imap_cancel_store( gctx );
  1318. }
  1319. static void
  1320. imap_disown_store( store_t *gctx )
  1321. {
  1322. free_generic_messages( gctx->msgs );
  1323. gctx->msgs = 0;
  1324. set_bad_callback( gctx, imap_cancel_unowned, gctx );
  1325. gctx->next = unowned;
  1326. unowned = gctx;
  1327. }
  1328. /******************* imap_cleanup *******************/
  1329. static void imap_cleanup_p2( imap_store_t *, struct imap_cmd *, int );
  1330. static void
  1331. imap_cleanup( void )
  1332. {
  1333. store_t *ctx, *nctx;
  1334. for (ctx = unowned; ctx; ctx = nctx) {
  1335. nctx = ctx->next;
  1336. set_bad_callback( ctx, (void (*)(void *))imap_cancel_store, ctx );
  1337. ((imap_store_t *)ctx)->conn.state = SCK_CLOSING;
  1338. imap_exec( (imap_store_t *)ctx, 0, imap_cleanup_p2, "LOGOUT" );
  1339. }
  1340. }
  1341. static void
  1342. imap_cleanup_p2( imap_store_t *ctx,
  1343. struct imap_cmd *cmd ATTR_UNUSED, int response )
  1344. {
  1345. if (response == RESP_NO)
  1346. imap_cancel_store( &ctx->gen );
  1347. }
  1348. /******************* imap_open_store *******************/
  1349. static void imap_open_store_connected( int, void * );
  1350. #ifdef HAVE_LIBSSL
  1351. static void imap_open_store_tlsstarted1( int, void * );
  1352. #endif
  1353. static void imap_open_store_p2( imap_store_t *, struct imap_cmd *, int );
  1354. static void imap_open_store_authenticate( imap_store_t * );
  1355. #ifdef HAVE_LIBSSL
  1356. static void imap_open_store_authenticate_p2( imap_store_t *, struct imap_cmd *, int );
  1357. static void imap_open_store_tlsstarted2( int, void * );
  1358. static void imap_open_store_authenticate_p3( imap_store_t *, struct imap_cmd *, int );
  1359. #endif
  1360. static void imap_open_store_authenticate2( imap_store_t * );
  1361. static void imap_open_store_authenticate2_p2( imap_store_t *, struct imap_cmd *, int );
  1362. static void imap_open_store_namespace( imap_store_t * );
  1363. static void imap_open_store_namespace_p2( imap_store_t *, struct imap_cmd *, int );
  1364. static void imap_open_store_namespace2( imap_store_t * );
  1365. #ifdef HAVE_LIBZ
  1366. static void imap_open_store_compress_p2( imap_store_t *, struct imap_cmd *, int );
  1367. #endif
  1368. static void imap_open_store_finalize( imap_store_t * );
  1369. #ifdef HAVE_LIBSSL
  1370. static void imap_open_store_ssl_bail( imap_store_t * );
  1371. #endif
  1372. static void imap_open_store_bail( imap_store_t * );
  1373. static void
  1374. imap_open_store( store_conf_t *conf, const char *label,
  1375. void (*cb)( store_t *srv, void *aux ), void *aux )
  1376. {
  1377. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1378. imap_server_conf_t *srvc = cfg->server;
  1379. imap_store_t *ctx;
  1380. store_t **ctxp;
  1381. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1382. if (ctx->gen.conf == conf) {
  1383. *ctxp = ctx->gen.next;
  1384. ctx->label = label;
  1385. cb( &ctx->gen, aux );
  1386. return;
  1387. }
  1388. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1389. if (((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1390. *ctxp = ctx->gen.next;
  1391. ctx->label = label;
  1392. /* One could ping the server here, but given that the idle timeout
  1393. * is at least 30 minutes, this sounds pretty pointless. */
  1394. free_string_list( ctx->gen.boxes );
  1395. ctx->gen.boxes = 0;
  1396. ctx->gen.listed = 0;
  1397. ctx->gen.conf = conf;
  1398. free( ctx->delimiter );
  1399. ctx->delimiter = 0;
  1400. ctx->callbacks.imap_open = cb;
  1401. ctx->callback_aux = aux;
  1402. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1403. imap_open_store_namespace( ctx );
  1404. return;
  1405. }
  1406. ctx = nfcalloc( sizeof(*ctx) );
  1407. ctx->gen.conf = conf;
  1408. ctx->label = label;
  1409. ctx->ref_count = 1;
  1410. ctx->callbacks.imap_open = cb;
  1411. ctx->callback_aux = aux;
  1412. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1413. ctx->in_progress_append = &ctx->in_progress;
  1414. ctx->pending_append = &ctx->pending;
  1415. socket_init( &ctx->conn, &srvc->sconf,
  1416. (void (*)( void * ))imap_invoke_bad_callback,
  1417. imap_socket_read, (int (*)(void *))flush_imap_cmds, ctx );
  1418. socket_connect( &ctx->conn, imap_open_store_connected );
  1419. }
  1420. static void
  1421. imap_open_store_connected( int ok, void *aux )
  1422. {
  1423. imap_store_t *ctx = (imap_store_t *)aux;
  1424. #ifdef HAVE_LIBSSL
  1425. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1426. imap_server_conf_t *srvc = cfg->server;
  1427. #endif
  1428. if (!ok)
  1429. imap_open_store_bail( ctx );
  1430. #ifdef HAVE_LIBSSL
  1431. else if (srvc->ssl_type == SSL_IMAPS)
  1432. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted1 );
  1433. #endif
  1434. }
  1435. #ifdef HAVE_LIBSSL
  1436. static void
  1437. imap_open_store_tlsstarted1( int ok, void *aux )
  1438. {
  1439. imap_store_t *ctx = (imap_store_t *)aux;
  1440. if (!ok)
  1441. imap_open_store_ssl_bail( ctx );
  1442. }
  1443. #endif
  1444. static void
  1445. imap_open_store_greeted( imap_store_t *ctx )
  1446. {
  1447. if (!ctx->caps)
  1448. imap_exec( ctx, 0, imap_open_store_p2, "CAPABILITY" );
  1449. else
  1450. imap_open_store_authenticate( ctx );
  1451. }
  1452. static void
  1453. imap_open_store_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1454. {
  1455. if (response == RESP_NO)
  1456. imap_open_store_bail( ctx );
  1457. else if (response == RESP_OK)
  1458. imap_open_store_authenticate( ctx );
  1459. }
  1460. static void
  1461. imap_open_store_authenticate( imap_store_t *ctx )
  1462. {
  1463. #ifdef HAVE_LIBSSL
  1464. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1465. imap_server_conf_t *srvc = cfg->server;
  1466. #endif
  1467. if (ctx->greeting != GreetingPreauth) {
  1468. #ifdef HAVE_LIBSSL
  1469. if (srvc->ssl_type == SSL_STARTTLS) {
  1470. if (CAP(STARTTLS)) {
  1471. imap_exec( ctx, 0, imap_open_store_authenticate_p2, "STARTTLS" );
  1472. return;
  1473. } else {
  1474. error( "IMAP error: SSL support not available\n" );
  1475. imap_open_store_bail( ctx );
  1476. return;
  1477. }
  1478. }
  1479. #endif
  1480. imap_open_store_authenticate2( ctx );
  1481. } else {
  1482. #ifdef HAVE_LIBSSL
  1483. if (srvc->ssl_type == SSL_STARTTLS) {
  1484. error( "IMAP error: SSL support not available\n" );
  1485. imap_open_store_bail( ctx );
  1486. return;
  1487. }
  1488. #endif
  1489. imap_open_store_namespace( ctx );
  1490. }
  1491. }
  1492. #ifdef HAVE_LIBSSL
  1493. static void
  1494. imap_open_store_authenticate_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1495. {
  1496. if (response == RESP_NO)
  1497. imap_open_store_bail( ctx );
  1498. else if (response == RESP_OK)
  1499. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted2 );
  1500. }
  1501. static void
  1502. imap_open_store_tlsstarted2( int ok, void *aux )
  1503. {
  1504. imap_store_t *ctx = (imap_store_t *)aux;
  1505. if (!ok)
  1506. imap_open_store_ssl_bail( ctx );
  1507. else
  1508. imap_exec( ctx, 0, imap_open_store_authenticate_p3, "CAPABILITY" );
  1509. }
  1510. static void
  1511. imap_open_store_authenticate_p3( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1512. {
  1513. if (response == RESP_NO)
  1514. imap_open_store_bail( ctx );
  1515. else if (response == RESP_OK)
  1516. imap_open_store_authenticate2( ctx );
  1517. }
  1518. #endif
  1519. static const char *
  1520. ensure_user( imap_server_conf_t *srvc )
  1521. {
  1522. if (!srvc->user) {
  1523. error( "Skipping account %s, no user\n", srvc->name );
  1524. return 0;
  1525. }
  1526. return srvc->user;
  1527. }
  1528. static const char *
  1529. ensure_password( imap_server_conf_t *srvc )
  1530. {
  1531. if (srvc->pass_cmd) {
  1532. FILE *fp;
  1533. int ret;
  1534. char buffer[80];
  1535. if (!(fp = popen( srvc->pass_cmd, "r" ))) {
  1536. pipeerr:
  1537. sys_error( "Skipping account %s, password command failed", srvc->name );
  1538. return 0;
  1539. }
  1540. if (!fgets( buffer, sizeof(buffer), fp ))
  1541. buffer[0] = 0;
  1542. if ((ret = pclose( fp )) < 0)
  1543. goto pipeerr;
  1544. if (ret) {
  1545. if (WIFSIGNALED( ret ))
  1546. error( "Skipping account %s, password command crashed\n", srvc->name );
  1547. else
  1548. error( "Skipping account %s, password command exited with status %d\n", srvc->name, WEXITSTATUS( ret ) );
  1549. return 0;
  1550. }
  1551. if (!buffer[0]) {
  1552. error( "Skipping account %s, password command produced no output\n", srvc->name );
  1553. return 0;
  1554. }
  1555. buffer[strcspn( buffer, "\n" )] = 0; /* Strip trailing newline */
  1556. free( srvc->pass ); /* From previous runs */
  1557. srvc->pass = nfstrdup( buffer );
  1558. } else if (!srvc->pass) {
  1559. char *pass, prompt[80];
  1560. sprintf( prompt, "Password (%s): ", srvc->name );
  1561. pass = getpass( prompt );
  1562. if (!pass) {
  1563. perror( "getpass" );
  1564. exit( 1 );
  1565. }
  1566. if (!*pass) {
  1567. error( "Skipping account %s, no password\n", srvc->name );
  1568. return 0;
  1569. }
  1570. /* getpass() returns a pointer to a static buffer. Make a copy for long term storage. */
  1571. srvc->pass = nfstrdup( pass );
  1572. }
  1573. return srvc->pass;
  1574. }
  1575. #ifdef HAVE_LIBSASL
  1576. static sasl_callback_t sasl_callbacks[] = {
  1577. { SASL_CB_USER, NULL, NULL },
  1578. { SASL_CB_PASS, NULL, NULL },
  1579. { SASL_CB_LIST_END, NULL, NULL }
  1580. };
  1581. static int
  1582. process_sasl_interact( sasl_interact_t *interact, imap_server_conf_t *srvc )
  1583. {
  1584. const char *val;
  1585. for (;; ++interact) {
  1586. switch (interact->id) {
  1587. case SASL_CB_LIST_END:
  1588. return 0;
  1589. case SASL_CB_USER:
  1590. val = ensure_user( srvc );
  1591. break;
  1592. case SASL_CB_PASS:
  1593. val = ensure_password( srvc );
  1594. break;
  1595. default:
  1596. error( "Error: Unknown SASL interaction ID\n" );
  1597. return -1;
  1598. }
  1599. if (!val)
  1600. return -1;
  1601. interact->result = val;
  1602. interact->len = strlen( val );
  1603. }
  1604. }
  1605. static int
  1606. process_sasl_step( imap_store_t *ctx, int rc, const char *in, uint in_len,
  1607. sasl_interact_t *interact, const char **out, uint *out_len )
  1608. {
  1609. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1610. while (rc == SASL_INTERACT) {
  1611. if (process_sasl_interact( interact, srvc ) < 0)
  1612. return -1;
  1613. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, out, out_len );
  1614. }
  1615. if (rc == SASL_CONTINUE) {
  1616. ctx->sasl_cont = 1;
  1617. } else if (rc == SASL_OK) {
  1618. ctx->sasl_cont = 0;
  1619. } else {
  1620. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  1621. return -1;
  1622. }
  1623. return 0;
  1624. }
  1625. static int
  1626. decode_sasl_data( const char *prompt, char **in, uint *in_len )
  1627. {
  1628. if (prompt) {
  1629. int rc;
  1630. uint prompt_len = strlen( prompt );
  1631. /* We're decoding, the output will be shorter than prompt_len. */
  1632. *in = nfmalloc( prompt_len );
  1633. rc = sasl_decode64( prompt, prompt_len, *in, prompt_len, in_len );
  1634. if (rc != SASL_OK) {
  1635. free( *in );
  1636. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1637. return -1;
  1638. }
  1639. } else {
  1640. *in = NULL;
  1641. *in_len = 0;
  1642. }
  1643. return 0;
  1644. }
  1645. static int
  1646. encode_sasl_data( const char *out, uint out_len, char **enc, uint *enc_len )
  1647. {
  1648. int rc;
  1649. uint enc_len_max = ((out_len + 2) / 3) * 4 + 1;
  1650. *enc = nfmalloc( enc_len_max );
  1651. rc = sasl_encode64( out, out_len, *enc, enc_len_max, enc_len );
  1652. if (rc != SASL_OK) {
  1653. free( *enc );
  1654. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1655. return -1;
  1656. }
  1657. return 0;
  1658. }
  1659. static int
  1660. do_sasl_auth( imap_store_t *ctx, struct imap_cmd *cmdp ATTR_UNUSED, const char *prompt )
  1661. {
  1662. int rc, ret, iovcnt = 0;
  1663. uint in_len, out_len, enc_len;
  1664. const char *out;
  1665. char *in, *enc;
  1666. sasl_interact_t *interact = NULL;
  1667. conn_iovec_t iov[2];
  1668. if (!ctx->sasl_cont) {
  1669. error( "Error: IMAP wants more steps despite successful SASL authentication.\n" );
  1670. goto bail;
  1671. }
  1672. if (decode_sasl_data( prompt, &in, &in_len ) < 0)
  1673. goto bail;
  1674. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, &out, &out_len );
  1675. ret = process_sasl_step( ctx, rc, in, in_len, interact, &out, &out_len );
  1676. free( in );
  1677. if (ret < 0)
  1678. goto bail;
  1679. if (out) {
  1680. if (encode_sasl_data( out, out_len, &enc, &enc_len ) < 0)
  1681. goto bail;
  1682. iov[0].buf = enc;
  1683. iov[0].len = enc_len;
  1684. iov[0].takeOwn = GiveOwn;
  1685. iovcnt = 1;
  1686. if (DFlags & VERBOSE) {
  1687. printf( "%s>+> %s\n", ctx->label, enc );
  1688. fflush( stdout );
  1689. }
  1690. } else {
  1691. if (DFlags & VERBOSE) {
  1692. printf( "%s>+>\n", ctx->label );
  1693. fflush( stdout );
  1694. }
  1695. }
  1696. iov[iovcnt].buf = "\r\n";
  1697. iov[iovcnt].len = 2;
  1698. iov[iovcnt].takeOwn = KeepOwn;
  1699. iovcnt++;
  1700. return socket_write( &ctx->conn, iov, iovcnt );
  1701. bail:
  1702. imap_open_store_bail( ctx );
  1703. return -1;
  1704. }
  1705. static void
  1706. done_sasl_auth( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1707. {
  1708. if (response == RESP_OK && ctx->sasl_cont) {
  1709. sasl_interact_t *interact = NULL;
  1710. const char *out;
  1711. uint out_len;
  1712. int rc = sasl_client_step( ctx->sasl, NULL, 0, &interact, &out, &out_len );
  1713. if (process_sasl_step( ctx, rc, NULL, 0, interact, &out, &out_len ) < 0)
  1714. warn( "Warning: SASL reported failure despite successful IMAP authentication. Ignoring...\n" );
  1715. else if (out)
  1716. warn( "Warning: SASL wants more steps despite successful IMAP authentication. Ignoring...\n" );
  1717. }
  1718. imap_open_store_authenticate2_p2( ctx, NULL, response );
  1719. }
  1720. #endif
  1721. static void
  1722. imap_open_store_authenticate2( imap_store_t *ctx )
  1723. {
  1724. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1725. imap_server_conf_t *srvc = cfg->server;
  1726. string_list_t *mech, *cmech;
  1727. int auth_login = 0;
  1728. #ifdef HAVE_LIBSASL
  1729. char saslmechs[1024], *saslend = saslmechs;
  1730. #endif
  1731. info( "Logging in...\n" );
  1732. for (mech = srvc->auth_mechs; mech; mech = mech->next) {
  1733. int any = !strcmp( mech->string, "*" );
  1734. for (cmech = ctx->auth_mechs; cmech; cmech = cmech->next) {
  1735. if (any || !strcasecmp( mech->string, cmech->string )) {
  1736. if (!strcasecmp( cmech->string, "LOGIN" )) {
  1737. #ifdef HAVE_LIBSSL
  1738. if (ctx->conn.ssl || !any)
  1739. #endif
  1740. auth_login = 1;
  1741. } else {
  1742. #ifdef HAVE_LIBSASL
  1743. int len = strlen( cmech->string );
  1744. if (saslend + len + 2 > saslmechs + sizeof(saslmechs))
  1745. oob();
  1746. *saslend++ = ' ';
  1747. memcpy( saslend, cmech->string, len + 1 );
  1748. saslend += len;
  1749. #else
  1750. error( "IMAP error: authentication mechanism %s is not supported\n", cmech->string );
  1751. goto bail;
  1752. #endif
  1753. }
  1754. }
  1755. }
  1756. }
  1757. #ifdef HAVE_LIBSASL
  1758. if (saslend != saslmechs) {
  1759. int rc;
  1760. uint out_len = 0;
  1761. char *enc = NULL;
  1762. const char *gotmech = NULL, *out = NULL;
  1763. sasl_interact_t *interact = NULL;
  1764. struct imap_cmd *cmd;
  1765. static int sasl_inited;
  1766. if (!sasl_inited) {
  1767. rc = sasl_client_init( sasl_callbacks );
  1768. if (rc != SASL_OK) {
  1769. saslbail:
  1770. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1771. goto bail;
  1772. }
  1773. sasl_inited = 1;
  1774. }
  1775. rc = sasl_client_new( "imap", srvc->sconf.host, NULL, NULL, NULL, 0, &ctx->sasl );
  1776. if (rc != SASL_OK) {
  1777. if (!ctx->sasl)
  1778. goto saslbail;
  1779. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  1780. goto bail;
  1781. }
  1782. rc = sasl_client_start( ctx->sasl, saslmechs + 1, &interact, CAP(SASLIR) ? &out : NULL, &out_len, &gotmech );
  1783. if (gotmech)
  1784. info( "Authenticating with SASL mechanism %s...\n", gotmech );
  1785. /* Technically, we are supposed to loop over sasl_client_start(),
  1786. * but it just calls sasl_client_step() anyway. */
  1787. if (process_sasl_step( ctx, rc, NULL, 0, interact, CAP(SASLIR) ? &out : NULL, &out_len ) < 0)
  1788. goto bail;
  1789. if (out) {
  1790. if (!out_len)
  1791. enc = nfstrdup( "=" ); /* A zero-length initial response is encoded as padding. */
  1792. else if (encode_sasl_data( out, out_len, &enc, NULL ) < 0)
  1793. goto bail;
  1794. }
  1795. cmd = new_imap_cmd( sizeof(*cmd) );
  1796. cmd->param.cont = do_sasl_auth;
  1797. imap_exec( ctx, cmd, done_sasl_auth, enc ? "AUTHENTICATE %s %s" : "AUTHENTICATE %s", gotmech, enc );
  1798. free( enc );
  1799. return;
  1800. }
  1801. #endif
  1802. if (auth_login) {
  1803. if (!ensure_user( srvc ) || !ensure_password( srvc ))
  1804. goto bail;
  1805. info( "Logging in...\n" );
  1806. #ifdef HAVE_LIBSSL
  1807. if (!ctx->conn.ssl)
  1808. #endif
  1809. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  1810. imap_exec( ctx, 0, imap_open_store_authenticate2_p2,
  1811. "LOGIN \"%\\s\" \"%\\s\"", srvc->user, srvc->pass );
  1812. return;
  1813. }
  1814. error( "IMAP error: server supports no acceptable authentication mechanism\n" );
  1815. bail:
  1816. imap_open_store_bail( ctx );
  1817. }
  1818. static void
  1819. imap_open_store_authenticate2_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1820. {
  1821. if (response == RESP_NO)
  1822. imap_open_store_bail( ctx );
  1823. else if (response == RESP_OK)
  1824. imap_open_store_namespace( ctx );
  1825. }
  1826. static void
  1827. imap_open_store_namespace( imap_store_t *ctx )
  1828. {
  1829. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1830. ctx->prefix = cfg->gen.path;
  1831. ctx->delimiter = cfg->delimiter ? nfstrdup( cfg->delimiter ) : 0;
  1832. if (((!ctx->prefix && cfg->use_namespace) || !cfg->delimiter) && CAP(NAMESPACE)) {
  1833. /* get NAMESPACE info */
  1834. if (!ctx->got_namespace)
  1835. imap_exec( ctx, 0, imap_open_store_namespace_p2, "NAMESPACE" );
  1836. else
  1837. imap_open_store_namespace2( ctx );
  1838. return;
  1839. }
  1840. imap_open_store_finalize( ctx );
  1841. }
  1842. static void
  1843. imap_open_store_namespace_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1844. {
  1845. if (response == RESP_NO) {
  1846. imap_open_store_bail( ctx );
  1847. } else if (response == RESP_OK) {
  1848. ctx->got_namespace = 1;
  1849. imap_open_store_namespace2( ctx );
  1850. }
  1851. }
  1852. static void
  1853. imap_open_store_namespace2( imap_store_t *ctx )
  1854. {
  1855. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1856. list_t *nsp, *nsp_1st, *nsp_1st_ns, *nsp_1st_dl;
  1857. /* XXX for now assume 1st personal namespace */
  1858. if (is_list( (nsp = ctx->ns_personal) ) &&
  1859. is_list( (nsp_1st = nsp->child) ) &&
  1860. is_atom( (nsp_1st_ns = nsp_1st->child) ) &&
  1861. is_atom( (nsp_1st_dl = nsp_1st_ns->next) ))
  1862. {
  1863. if (!ctx->prefix && cfg->use_namespace)
  1864. ctx->prefix = nsp_1st_ns->val;
  1865. if (!ctx->delimiter)
  1866. ctx->delimiter = nfstrdup( nsp_1st_dl->val );
  1867. #ifdef HAVE_LIBZ
  1868. if (CAP(COMPRESS_DEFLATE)) { /* XXX make that configurable */
  1869. imap_exec( ctx, 0, imap_open_store_compress_p2, "COMPRESS DEFLATE" );
  1870. return;
  1871. }
  1872. #endif
  1873. imap_open_store_finalize( ctx );
  1874. } else {
  1875. imap_open_store_bail( ctx );
  1876. }
  1877. }
  1878. #ifdef HAVE_LIBZ
  1879. static void
  1880. imap_open_store_compress_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1881. {
  1882. if (response == RESP_NO) {
  1883. /* We already reported an error, but it's not fatal to us. */
  1884. imap_open_store_finalize( ctx );
  1885. } else if (response == RESP_OK) {
  1886. socket_start_deflate( &ctx->conn );
  1887. imap_open_store_finalize( ctx );
  1888. }
  1889. }
  1890. #endif
  1891. static void
  1892. imap_open_store_finalize( imap_store_t *ctx )
  1893. {
  1894. set_bad_callback( &ctx->gen, 0, 0 );
  1895. if (!ctx->prefix)
  1896. ctx->prefix = "";
  1897. ctx->trashnc = TrashUnknown;
  1898. ctx->callbacks.imap_open( &ctx->gen, ctx->callback_aux );
  1899. }
  1900. #ifdef HAVE_LIBSSL
  1901. static void
  1902. imap_open_store_ssl_bail( imap_store_t *ctx )
  1903. {
  1904. /* This avoids that we try to send LOGOUT to an unusable socket. */
  1905. socket_close( &ctx->conn );
  1906. imap_open_store_bail( ctx );
  1907. }
  1908. #endif
  1909. static void
  1910. imap_open_store_bail( imap_store_t *ctx )
  1911. {
  1912. void (*cb)( store_t *srv, void *aux ) = ctx->callbacks.imap_open;
  1913. void *aux = ctx->callback_aux;
  1914. imap_cancel_store( &ctx->gen );
  1915. cb( 0, aux );
  1916. }
  1917. /******************* imap_open_box *******************/
  1918. static int
  1919. imap_select_box( store_t *gctx, const char *name )
  1920. {
  1921. imap_store_t *ctx = (imap_store_t *)gctx;
  1922. free_generic_messages( gctx->msgs );
  1923. gctx->msgs = 0;
  1924. ctx->msgapp = &gctx->msgs;
  1925. ctx->name = name;
  1926. return DRV_OK;
  1927. }
  1928. static void
  1929. imap_open_box( store_t *gctx, int create,
  1930. void (*cb)( int sts, void *aux ), void *aux )
  1931. {
  1932. imap_store_t *ctx = (imap_store_t *)gctx;
  1933. struct imap_cmd_simple *cmd;
  1934. char *buf;
  1935. if (prepare_box( &buf, ctx ) < 0) {
  1936. cb( DRV_BOX_BAD, aux );
  1937. return;
  1938. }
  1939. ctx->gen.uidnext = 0;
  1940. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1941. cmd->gen.param.create = create;
  1942. cmd->gen.param.trycreate = 1;
  1943. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  1944. "SELECT \"%\\s\"", buf );
  1945. free( buf );
  1946. }
  1947. /******************* imap_load_box *******************/
  1948. static void
  1949. imap_prepare_load_box( store_t *gctx, int opts )
  1950. {
  1951. gctx->opts = opts;
  1952. }
  1953. static int imap_submit_load( imap_store_t *, const char *, int, struct imap_cmd_refcounted_state * );
  1954. static void
  1955. imap_load_box( store_t *gctx, int minuid, int maxuid, int newuid, int *excs, int nexcs,
  1956. void (*cb)( int sts, void *aux ), void *aux )
  1957. {
  1958. imap_store_t *ctx = (imap_store_t *)gctx;
  1959. int i, j, bl;
  1960. char buf[1000];
  1961. if (!ctx->gen.count) {
  1962. free( excs );
  1963. cb( DRV_OK, aux );
  1964. } else {
  1965. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1966. sort_ints( excs, nexcs );
  1967. for (i = 0; i < nexcs; ) {
  1968. for (bl = 0; i < nexcs && bl < 960; i++) {
  1969. if (bl)
  1970. buf[bl++] = ',';
  1971. bl += sprintf( buf + bl, "%d", excs[i] );
  1972. j = i;
  1973. for (; i + 1 < nexcs && excs[i + 1] == excs[i] + 1; i++) {}
  1974. if (i != j)
  1975. bl += sprintf( buf + bl, ":%d", excs[i] );
  1976. }
  1977. if (imap_submit_load( ctx, buf, 0, sts ) < 0)
  1978. goto done;
  1979. }
  1980. if (maxuid == INT_MAX)
  1981. maxuid = ctx->gen.uidnext ? ctx->gen.uidnext - 1 : 1000000000;
  1982. if (maxuid >= minuid) {
  1983. if ((ctx->gen.opts & OPEN_FIND) && minuid < newuid) {
  1984. sprintf( buf, "%d:%d", minuid, newuid - 1 );
  1985. if (imap_submit_load( ctx, buf, 0, sts ) < 0)
  1986. goto done;
  1987. if (newuid > maxuid)
  1988. goto done;
  1989. sprintf( buf, "%d:%d", newuid, maxuid );
  1990. } else {
  1991. sprintf( buf, "%d:%d", minuid, maxuid );
  1992. }
  1993. imap_submit_load( ctx, buf, (ctx->gen.opts & OPEN_FIND), sts );
  1994. }
  1995. done:
  1996. free( excs );
  1997. imap_refcounted_done( sts );
  1998. }
  1999. }
  2000. static int
  2001. imap_submit_load( imap_store_t *ctx, const char *buf, int tuids, struct imap_cmd_refcounted_state *sts )
  2002. {
  2003. return imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  2004. "UID FETCH %s (UID%s%s%s)", buf,
  2005. (ctx->gen.opts & OPEN_FLAGS) ? " FLAGS" : "",
  2006. (ctx->gen.opts & OPEN_SIZE) ? " RFC822.SIZE" : "",
  2007. tuids ? " BODY.PEEK[HEADER.FIELDS (X-TUID)]" : "");
  2008. }
  2009. /******************* imap_fetch_msg *******************/
  2010. static void imap_fetch_msg_p2( imap_store_t *ctx, struct imap_cmd *gcmd, int response );
  2011. static void
  2012. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data,
  2013. void (*cb)( int sts, void *aux ), void *aux )
  2014. {
  2015. struct imap_cmd_fetch_msg *cmd;
  2016. INIT_IMAP_CMD_X(imap_cmd_fetch_msg, cmd, cb, aux)
  2017. cmd->gen.gen.param.uid = msg->uid;
  2018. cmd->msg_data = data;
  2019. data->data = 0;
  2020. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_fetch_msg_p2,
  2021. "UID FETCH %d (%s%sBODY.PEEK[])", msg->uid,
  2022. !(msg->status & M_FLAGS) ? "FLAGS " : "",
  2023. (data->date== -1) ? "INTERNALDATE " : "" );
  2024. }
  2025. static void
  2026. imap_fetch_msg_p2( imap_store_t *ctx, struct imap_cmd *gcmd, int response )
  2027. {
  2028. struct imap_cmd_fetch_msg *cmd = (struct imap_cmd_fetch_msg *)gcmd;
  2029. if (response == RESP_OK && !cmd->msg_data->data) {
  2030. /* The FETCH succeeded, but there is no message with this UID. */
  2031. response = RESP_NO;
  2032. }
  2033. imap_done_simple_msg( ctx, gcmd, response );
  2034. }
  2035. /******************* imap_set_msg_flags *******************/
  2036. static void imap_set_flags_p2( imap_store_t *, struct imap_cmd *, int );
  2037. static int
  2038. imap_make_flags( int flags, char *buf )
  2039. {
  2040. const char *s;
  2041. uint i, d;
  2042. for (i = d = 0; i < as(Flags); i++)
  2043. if (flags & (1 << i)) {
  2044. buf[d++] = ' ';
  2045. buf[d++] = '\\';
  2046. for (s = Flags[i]; *s; s++)
  2047. buf[d++] = *s;
  2048. }
  2049. buf[0] = '(';
  2050. buf[d++] = ')';
  2051. return d;
  2052. }
  2053. static int
  2054. imap_flags_helper( imap_store_t *ctx, int uid, char what, int flags,
  2055. struct imap_cmd_refcounted_state *sts )
  2056. {
  2057. char buf[256];
  2058. buf[imap_make_flags( flags, buf )] = 0;
  2059. return imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_set_flags_p2,
  2060. "UID STORE %d %cFLAGS.SILENT %s", uid, what, buf );
  2061. }
  2062. static void
  2063. imap_set_msg_flags( store_t *gctx, message_t *msg, int uid, int add, int del,
  2064. void (*cb)( int sts, void *aux ), void *aux )
  2065. {
  2066. imap_store_t *ctx = (imap_store_t *)gctx;
  2067. if (msg) {
  2068. uid = msg->uid;
  2069. add &= ~msg->flags;
  2070. del &= msg->flags;
  2071. msg->flags |= add;
  2072. msg->flags &= ~del;
  2073. }
  2074. if (add || del) {
  2075. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  2076. if ((add && imap_flags_helper( ctx, uid, '+', add, sts ) < 0) ||
  2077. (del && imap_flags_helper( ctx, uid, '-', del, sts ) < 0)) {}
  2078. imap_refcounted_done( sts );
  2079. } else {
  2080. cb( DRV_OK, aux );
  2081. }
  2082. }
  2083. static void
  2084. imap_set_flags_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  2085. {
  2086. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  2087. switch (response) {
  2088. case RESP_CANCEL:
  2089. sts->ret_val = DRV_CANCELED;
  2090. break;
  2091. case RESP_NO:
  2092. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  2093. sts->ret_val = DRV_MSG_BAD;
  2094. break;
  2095. }
  2096. imap_refcounted_done( sts );
  2097. }
  2098. /******************* imap_close_box *******************/
  2099. static void
  2100. imap_close_box( store_t *gctx,
  2101. void (*cb)( int sts, void *aux ), void *aux )
  2102. {
  2103. imap_store_t *ctx = (imap_store_t *)gctx;
  2104. if (ctx->gen.conf->trash && CAP(UIDPLUS)) {
  2105. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  2106. message_t *msg, *fmsg, *nmsg;
  2107. int bl;
  2108. char buf[1000];
  2109. for (msg = ctx->gen.msgs; ; ) {
  2110. for (bl = 0; msg && bl < 960; msg = msg->next) {
  2111. if (!(msg->flags & F_DELETED))
  2112. continue;
  2113. if (bl)
  2114. buf[bl++] = ',';
  2115. bl += sprintf( buf + bl, "%d", msg->uid );
  2116. fmsg = msg;
  2117. for (; (nmsg = msg->next) && (nmsg->flags & F_DELETED); msg = nmsg) {}
  2118. if (msg != fmsg)
  2119. bl += sprintf( buf + bl, ":%d", msg->uid );
  2120. }
  2121. if (!bl)
  2122. break;
  2123. if (imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  2124. "UID EXPUNGE %s", buf ) < 0)
  2125. break;
  2126. }
  2127. imap_refcounted_done( sts );
  2128. } else {
  2129. /* This is inherently racy: it may cause messages which other clients
  2130. * marked as deleted to be expunged without being trashed. */
  2131. struct imap_cmd_simple *cmd;
  2132. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  2133. imap_exec( ctx, &cmd->gen, imap_done_simple_box, "CLOSE" );
  2134. }
  2135. }
  2136. /******************* imap_trash_msg *******************/
  2137. static void
  2138. imap_trash_msg( store_t *gctx, message_t *msg,
  2139. void (*cb)( int sts, void *aux ), void *aux )
  2140. {
  2141. imap_store_t *ctx = (imap_store_t *)gctx;
  2142. struct imap_cmd_simple *cmd;
  2143. char *buf;
  2144. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  2145. cmd->gen.param.create = 1;
  2146. cmd->gen.param.to_trash = 1;
  2147. if (prepare_trash( &buf, ctx ) < 0) {
  2148. cb( DRV_BOX_BAD, aux );
  2149. return;
  2150. }
  2151. imap_exec( ctx, &cmd->gen, imap_done_simple_msg,
  2152. CAP(MOVE) ? "UID MOVE %d \"%\\s\"" : "UID COPY %d \"%\\s\"", msg->uid, buf );
  2153. free( buf );
  2154. }
  2155. /******************* imap_store_msg *******************/
  2156. static void imap_store_msg_p2( imap_store_t *, struct imap_cmd *, int );
  2157. static size_t
  2158. my_strftime( char *s, size_t max, const char *fmt, const struct tm *tm )
  2159. {
  2160. return strftime( s, max, fmt, tm );
  2161. }
  2162. static void
  2163. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  2164. void (*cb)( int sts, int uid, void *aux ), void *aux )
  2165. {
  2166. imap_store_t *ctx = (imap_store_t *)gctx;
  2167. struct imap_cmd_out_uid *cmd;
  2168. char *buf;
  2169. int d;
  2170. char flagstr[128], datestr[64];
  2171. d = 0;
  2172. if (data->flags) {
  2173. d = imap_make_flags( data->flags, flagstr );
  2174. flagstr[d++] = ' ';
  2175. }
  2176. flagstr[d] = 0;
  2177. INIT_IMAP_CMD(imap_cmd_out_uid, cmd, cb, aux)
  2178. cmd->gen.param.data_len = data->len;
  2179. cmd->gen.param.data = data->data;
  2180. cmd->out_uid = -2;
  2181. if (to_trash) {
  2182. cmd->gen.param.create = 1;
  2183. cmd->gen.param.to_trash = 1;
  2184. if (prepare_trash( &buf, ctx ) < 0) {
  2185. cb( DRV_BOX_BAD, -1, aux );
  2186. return;
  2187. }
  2188. } else {
  2189. if (prepare_box( &buf, ctx ) < 0) {
  2190. cb( DRV_BOX_BAD, -1, aux );
  2191. return;
  2192. }
  2193. }
  2194. if (data->date) {
  2195. /* configure ensures that %z actually works. */
  2196. my_strftime( datestr, sizeof(datestr), "%d-%b-%Y %H:%M:%S %z", localtime( &data->date ) );
  2197. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2198. "APPEND \"%\\s\" %s\"%\\s\" ", buf, flagstr, datestr );
  2199. } else {
  2200. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2201. "APPEND \"%\\s\" %s", buf, flagstr );
  2202. }
  2203. free( buf );
  2204. }
  2205. static void
  2206. imap_store_msg_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  2207. {
  2208. struct imap_cmd_out_uid *cmdp = (struct imap_cmd_out_uid *)cmd;
  2209. transform_msg_response( &response );
  2210. cmdp->callback( response, cmdp->out_uid, cmdp->callback_aux );
  2211. }
  2212. /******************* imap_find_new_msgs *******************/
  2213. static void imap_find_new_msgs_p2( imap_store_t *, struct imap_cmd *, int );
  2214. static void
  2215. imap_find_new_msgs( store_t *gctx, int newuid,
  2216. void (*cb)( int sts, void *aux ), void *aux )
  2217. {
  2218. imap_store_t *ctx = (imap_store_t *)gctx;
  2219. struct imap_cmd_find_new *cmd;
  2220. INIT_IMAP_CMD_X(imap_cmd_find_new, cmd, cb, aux)
  2221. cmd->uid = newuid;
  2222. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_find_new_msgs_p2, "CHECK" );
  2223. }
  2224. static void
  2225. imap_find_new_msgs_p2( imap_store_t *ctx, struct imap_cmd *gcmd, int response )
  2226. {
  2227. struct imap_cmd_find_new *cmdp = (struct imap_cmd_find_new *)gcmd;
  2228. struct imap_cmd_simple *cmd;
  2229. if (response != RESP_OK) {
  2230. imap_done_simple_box( ctx, gcmd, response );
  2231. return;
  2232. }
  2233. INIT_IMAP_CMD(imap_cmd_simple, cmd, cmdp->gen.callback, cmdp->gen.callback_aux)
  2234. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_done_simple_box,
  2235. "UID FETCH %d:1000000000 (UID BODY.PEEK[HEADER.FIELDS (X-TUID)])", cmdp->uid );
  2236. }
  2237. /******************* imap_list_store *******************/
  2238. static void
  2239. imap_list_store( store_t *gctx, int flags,
  2240. void (*cb)( int sts, void *aux ), void *aux )
  2241. {
  2242. imap_store_t *ctx = (imap_store_t *)gctx;
  2243. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  2244. if (((flags & LIST_PATH) &&
  2245. imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  2246. "LIST \"\" \"%\\s*\"", ctx->prefix ) < 0) ||
  2247. ((flags & LIST_INBOX) && (!(flags & LIST_PATH) || *ctx->prefix) &&
  2248. imap_exec( ctx, imap_refcounted_new_cmd( sts ), imap_refcounted_done_box,
  2249. "LIST \"\" INBOX*" ) < 0))
  2250. {}
  2251. imap_refcounted_done( sts );
  2252. }
  2253. /******************* imap_cancel_cmds *******************/
  2254. static void
  2255. imap_cancel_cmds( store_t *gctx,
  2256. void (*cb)( void *aux ), void *aux )
  2257. {
  2258. imap_store_t *ctx = (imap_store_t *)gctx;
  2259. cancel_pending_imap_cmds( ctx );
  2260. if (ctx->in_progress) {
  2261. ctx->canceling = 1;
  2262. ctx->callbacks.imap_cancel = cb;
  2263. ctx->callback_aux = aux;
  2264. } else {
  2265. cb( aux );
  2266. }
  2267. }
  2268. /******************* imap_commit_cmds *******************/
  2269. static void
  2270. imap_commit_cmds( store_t *gctx )
  2271. {
  2272. (void)gctx;
  2273. }
  2274. /******************* imap_parse_store *******************/
  2275. imap_server_conf_t *servers, **serverapp = &servers;
  2276. static int
  2277. imap_parse_store( conffile_t *cfg, store_conf_t **storep )
  2278. {
  2279. imap_store_conf_t *store;
  2280. imap_server_conf_t *server, *srv, sserver;
  2281. const char *type, *name, *arg;
  2282. int acc_opt = 0;
  2283. #ifdef HAVE_LIBSSL
  2284. /* Legacy SSL options */
  2285. int require_ssl = -1, use_imaps = -1;
  2286. int use_sslv2 = -1, use_sslv3 = -1, use_tlsv1 = -1, use_tlsv11 = -1, use_tlsv12 = -1;
  2287. int require_cram = -1;
  2288. #endif
  2289. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  2290. server = nfcalloc( sizeof(*server) );
  2291. server->name = nfstrdup( cfg->val );
  2292. *serverapp = server;
  2293. serverapp = &server->next;
  2294. store = 0;
  2295. *storep = 0;
  2296. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  2297. store = nfcalloc( sizeof(*store) );
  2298. store->gen.driver = &imap_driver;
  2299. store->gen.name = nfstrdup( cfg->val );
  2300. store->use_namespace = 1;
  2301. *storep = &store->gen;
  2302. memset( &sserver, 0, sizeof(sserver) );
  2303. server = &sserver;
  2304. } else
  2305. return 0;
  2306. #ifdef HAVE_LIBSSL
  2307. server->ssl_type = -1;
  2308. server->sconf.ssl_versions = -1;
  2309. server->sconf.system_certs = 1;
  2310. #endif
  2311. server->max_in_progress = INT_MAX;
  2312. while (getcline( cfg ) && cfg->cmd) {
  2313. if (!strcasecmp( "Host", cfg->cmd )) {
  2314. /* The imap[s]: syntax is just a backwards compat hack. */
  2315. arg = cfg->val;
  2316. #ifdef HAVE_LIBSSL
  2317. if (starts_with( arg, -1, "imaps:", 6 )) {
  2318. arg += 6;
  2319. server->ssl_type = SSL_IMAPS;
  2320. if (server->sconf.ssl_versions == -1)
  2321. server->sconf.ssl_versions = SSLv2 | SSLv3 | TLSv1;
  2322. } else
  2323. #endif
  2324. if (starts_with( arg, -1, "imap:", 5 ))
  2325. arg += 5;
  2326. if (starts_with( arg, -1, "//", 2 ))
  2327. arg += 2;
  2328. if (arg != cfg->val)
  2329. warn( "%s:%d: Notice: URL notation is deprecated; use a plain host name and possibly 'SSLType IMAPS' instead\n", cfg->file, cfg->line );
  2330. server->sconf.host = nfstrdup( arg );
  2331. }
  2332. else if (!strcasecmp( "User", cfg->cmd ))
  2333. server->user = nfstrdup( cfg->val );
  2334. else if (!strcasecmp( "Pass", cfg->cmd ))
  2335. server->pass = nfstrdup( cfg->val );
  2336. else if (!strcasecmp( "PassCmd", cfg->cmd ))
  2337. server->pass_cmd = nfstrdup( cfg->val );
  2338. else if (!strcasecmp( "Port", cfg->cmd ))
  2339. server->sconf.port = parse_int( cfg );
  2340. else if (!strcasecmp( "PipelineDepth", cfg->cmd )) {
  2341. if ((server->max_in_progress = parse_int( cfg )) < 1) {
  2342. error( "%s:%d: PipelineDepth must be at least 1\n", cfg->file, cfg->line );
  2343. cfg->err = 1;
  2344. }
  2345. }
  2346. #ifdef HAVE_LIBSSL
  2347. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  2348. server->sconf.cert_file = expand_strdup( cfg->val );
  2349. if (access( server->sconf.cert_file, R_OK )) {
  2350. sys_error( "%s:%d: CertificateFile '%s'",
  2351. cfg->file, cfg->line, server->sconf.cert_file );
  2352. cfg->err = 1;
  2353. }
  2354. } else if (!strcasecmp( "SystemCertificates", cfg->cmd )) {
  2355. server->sconf.system_certs = parse_bool( cfg );
  2356. } else if (!strcasecmp( "SSLType", cfg->cmd )) {
  2357. if (!strcasecmp( "None", cfg->val )) {
  2358. server->ssl_type = SSL_None;
  2359. } else if (!strcasecmp( "STARTTLS", cfg->val )) {
  2360. server->ssl_type = SSL_STARTTLS;
  2361. } else if (!strcasecmp( "IMAPS", cfg->val )) {
  2362. server->ssl_type = SSL_IMAPS;
  2363. } else {
  2364. error( "%s:%d: Invalid SSL type\n", cfg->file, cfg->line );
  2365. cfg->err = 1;
  2366. }
  2367. } else if (!strcasecmp( "SSLVersion", cfg->cmd ) ||
  2368. !strcasecmp( "SSLVersions", cfg->cmd )) {
  2369. server->sconf.ssl_versions = 0;
  2370. arg = cfg->val;
  2371. do {
  2372. if (!strcasecmp( "SSLv2", arg )) {
  2373. server->sconf.ssl_versions |= SSLv2;
  2374. } else if (!strcasecmp( "SSLv3", arg )) {
  2375. server->sconf.ssl_versions |= SSLv3;
  2376. } else if (!strcasecmp( "TLSv1", arg )) {
  2377. server->sconf.ssl_versions |= TLSv1;
  2378. } else if (!strcasecmp( "TLSv1.1", arg )) {
  2379. server->sconf.ssl_versions |= TLSv1_1;
  2380. } else if (!strcasecmp( "TLSv1.2", arg )) {
  2381. server->sconf.ssl_versions |= TLSv1_2;
  2382. } else {
  2383. error( "%s:%d: Unrecognized SSL version\n", cfg->file, cfg->line );
  2384. cfg->err = 1;
  2385. }
  2386. } while ((arg = get_arg( cfg, ARG_OPTIONAL, 0 )));
  2387. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  2388. require_ssl = parse_bool( cfg );
  2389. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  2390. use_imaps = parse_bool( cfg );
  2391. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  2392. use_sslv2 = parse_bool( cfg );
  2393. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  2394. use_sslv3 = parse_bool( cfg );
  2395. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  2396. use_tlsv1 = parse_bool( cfg );
  2397. else if (!strcasecmp( "UseTLSv1.1", cfg->cmd ))
  2398. use_tlsv11 = parse_bool( cfg );
  2399. else if (!strcasecmp( "UseTLSv1.2", cfg->cmd ))
  2400. use_tlsv12 = parse_bool( cfg );
  2401. else if (!strcasecmp( "AuthMech", cfg->cmd ) ||
  2402. !strcasecmp( "AuthMechs", cfg->cmd )) {
  2403. arg = cfg->val;
  2404. do
  2405. add_string_list( &server->auth_mechs, arg );
  2406. while ((arg = get_arg( cfg, ARG_OPTIONAL, 0 )));
  2407. } else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  2408. require_cram = parse_bool( cfg );
  2409. #endif
  2410. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  2411. server->sconf.tunnel = nfstrdup( cfg->val );
  2412. else if (store) {
  2413. if (!strcasecmp( "Account", cfg->cmd )) {
  2414. for (srv = servers; srv; srv = srv->next)
  2415. if (srv->name && !strcmp( srv->name, cfg->val ))
  2416. goto gotsrv;
  2417. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  2418. cfg->err = 1;
  2419. continue;
  2420. gotsrv:
  2421. store->server = srv;
  2422. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  2423. store->use_namespace = parse_bool( cfg );
  2424. else if (!strcasecmp( "Path", cfg->cmd ))
  2425. store->gen.path = nfstrdup( cfg->val );
  2426. else if (!strcasecmp( "PathDelimiter", cfg->cmd ))
  2427. store->delimiter = nfstrdup( cfg->val );
  2428. else
  2429. parse_generic_store( &store->gen, cfg );
  2430. continue;
  2431. } else {
  2432. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  2433. cfg->err = 1;
  2434. continue;
  2435. }
  2436. acc_opt = 1;
  2437. }
  2438. if (store)
  2439. type = "IMAP store", name = store->gen.name;
  2440. else
  2441. type = "IMAP account", name = server->name;
  2442. if (!store || !store->server) {
  2443. if (!server->sconf.tunnel && !server->sconf.host) {
  2444. error( "%s '%s' has neither Tunnel nor Host\n", type, name );
  2445. cfg->err = 1;
  2446. return 1;
  2447. }
  2448. if (server->pass && server->pass_cmd) {
  2449. error( "%s '%s' has both Pass and PassCmd\n", type, name );
  2450. cfg->err = 1;
  2451. return 1;
  2452. }
  2453. #ifdef HAVE_LIBSSL
  2454. if ((use_sslv2 & use_sslv3 & use_tlsv1 & use_tlsv11 & use_tlsv12) != -1 || use_imaps >= 0 || require_ssl >= 0) {
  2455. if (server->ssl_type >= 0 || server->sconf.ssl_versions >= 0) {
  2456. error( "%s '%s': The deprecated UseSSL*, UseTLS*, UseIMAPS, and RequireSSL options are mutually exlusive with SSLType and SSLVersions.\n", type, name );
  2457. cfg->err = 1;
  2458. return 1;
  2459. }
  2460. warn( "Notice: %s '%s': UseSSL*, UseTLS*, UseIMAPS, and RequireSSL are deprecated. Use SSLType and SSLVersions instead.\n", type, name );
  2461. server->sconf.ssl_versions =
  2462. (use_sslv2 != 1 ? 0 : SSLv2) |
  2463. (use_sslv3 != 1 ? 0 : SSLv3) |
  2464. (use_tlsv1 == 0 ? 0 : TLSv1) |
  2465. (use_tlsv11 != 1 ? 0 : TLSv1_1) |
  2466. (use_tlsv12 != 1 ? 0 : TLSv1_2);
  2467. if (use_imaps == 1) {
  2468. server->ssl_type = SSL_IMAPS;
  2469. } else if (require_ssl) {
  2470. server->ssl_type = SSL_STARTTLS;
  2471. } else if (!server->sconf.ssl_versions) {
  2472. server->ssl_type = SSL_None;
  2473. } else {
  2474. warn( "Notice: %s '%s': 'RequireSSL no' is being ignored\n", type, name );
  2475. server->ssl_type = SSL_STARTTLS;
  2476. }
  2477. if (server->ssl_type != SSL_None && !server->sconf.ssl_versions) {
  2478. error( "%s '%s' requires SSL but no SSL versions enabled\n", type, name );
  2479. cfg->err = 1;
  2480. return 1;
  2481. }
  2482. } else {
  2483. if (server->sconf.ssl_versions < 0)
  2484. server->sconf.ssl_versions = TLSv1; /* Most compatible and still reasonably secure. */
  2485. if (server->ssl_type < 0)
  2486. server->ssl_type = server->sconf.tunnel ? SSL_None : SSL_STARTTLS;
  2487. }
  2488. #endif
  2489. #ifdef HAVE_LIBSSL
  2490. if (require_cram >= 0) {
  2491. if (server->auth_mechs) {
  2492. error( "%s '%s': The deprecated RequireCRAM option is mutually exlusive with AuthMech.\n", type, name );
  2493. cfg->err = 1;
  2494. return 1;
  2495. }
  2496. warn( "Notice: %s '%s': RequireCRAM is deprecated. Use AuthMech instead.\n", type, name );
  2497. if (require_cram)
  2498. add_string_list(&server->auth_mechs, "CRAM-MD5");
  2499. }
  2500. #endif
  2501. if (!server->auth_mechs)
  2502. add_string_list( &server->auth_mechs, "*" );
  2503. if (!server->sconf.port)
  2504. server->sconf.port =
  2505. #ifdef HAVE_LIBSSL
  2506. server->ssl_type == SSL_IMAPS ? 993 :
  2507. #endif
  2508. 143;
  2509. }
  2510. if (store) {
  2511. if (!store->server) {
  2512. store->server = nfmalloc( sizeof(sserver) );
  2513. memcpy( store->server, &sserver, sizeof(sserver) );
  2514. store->server->name = store->gen.name;
  2515. } else if (acc_opt) {
  2516. error( "%s '%s' has both Account and account-specific options\n", type, name );
  2517. cfg->err = 1;
  2518. }
  2519. }
  2520. return 1;
  2521. }
  2522. struct driver imap_driver = {
  2523. DRV_CRLF | DRV_VERBOSE,
  2524. imap_parse_store,
  2525. imap_cleanup,
  2526. imap_open_store,
  2527. imap_disown_store,
  2528. imap_cancel_store,
  2529. imap_list_store,
  2530. imap_select_box,
  2531. imap_open_box,
  2532. imap_prepare_load_box,
  2533. imap_load_box,
  2534. imap_fetch_msg,
  2535. imap_store_msg,
  2536. imap_find_new_msgs,
  2537. imap_set_msg_flags,
  2538. imap_trash_msg,
  2539. imap_close_box,
  2540. imap_cancel_cmds,
  2541. imap_commit_cmds,
  2542. };