drv_imap.c 78 KB

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