drv_imap.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660
  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_MACOS_KEYCHAIN
  40. # include <Security/Security.h>
  41. #endif
  42. #ifdef HAVE_LIBSSL
  43. enum { SSL_None, SSL_STARTTLS, SSL_IMAPS };
  44. #endif
  45. typedef struct imap_server_conf {
  46. struct imap_server_conf *next;
  47. char *name;
  48. server_conf_t sconf;
  49. char *user;
  50. char *user_cmd;
  51. char *pass;
  52. char *pass_cmd;
  53. int max_in_progress;
  54. uint cap_mask;
  55. string_list_t *auth_mechs;
  56. #ifdef HAVE_LIBSSL
  57. char ssl_type;
  58. #endif
  59. #ifdef HAVE_MACOS_KEYCHAIN
  60. char use_keychain;
  61. #endif
  62. char failed;
  63. } imap_server_conf_t;
  64. typedef struct {
  65. store_conf_t gen;
  66. imap_server_conf_t *server;
  67. char delimiter;
  68. char use_namespace;
  69. char use_lsub;
  70. } imap_store_conf_t;
  71. typedef struct {
  72. message_t gen;
  73. /* uint seq; will be needed when expunges are tracked */
  74. } imap_message_t;
  75. #define NIL (void*)0x1
  76. #define LIST (void*)0x2
  77. typedef struct _list {
  78. struct _list *next, *child;
  79. char *val;
  80. uint len;
  81. } list_t;
  82. #define MAX_LIST_DEPTH 5
  83. typedef struct imap_store imap_store_t;
  84. typedef struct {
  85. list_t *head, **stack[MAX_LIST_DEPTH];
  86. int (*callback)( imap_store_t *ctx, list_t *list, char *cmd );
  87. int level, need_bytes;
  88. } parse_list_state_t;
  89. typedef struct imap_cmd imap_cmd_t;
  90. struct imap_store {
  91. store_t gen;
  92. const char *label; /* foreign */
  93. const char *prefix;
  94. const char *name;
  95. uint ref_count;
  96. uint opts;
  97. enum { SST_BAD, SST_HALF, SST_GOOD } state;
  98. /* trash folder's existence is not confirmed yet */
  99. enum { TrashUnknown, TrashChecking, TrashKnown } trashnc;
  100. uint got_namespace:1;
  101. uint has_forwarded:1;
  102. char delimiter[2]; /* hierarchy delimiter */
  103. char *ns_prefix, ns_delimiter; /* NAMESPACE info */
  104. string_list_t *boxes; // _list results
  105. char listed; // was _list already run with these flags?
  106. // note that the message counts do _not_ reflect stats from msgs,
  107. // but mailbox totals. also, don't trust them beyond the initial load.
  108. int total_msgs, recent_msgs;
  109. uint uidvalidity, uidnext;
  110. message_t *msgs;
  111. message_t **msgapp; /* FETCH results */
  112. uint caps; /* CAPABILITY results */
  113. string_list_t *auth_mechs;
  114. parse_list_state_t parse_list_sts;
  115. /* command queue */
  116. imap_cmd_t *pending, **pending_append;
  117. imap_cmd_t *in_progress, **in_progress_append;
  118. imap_cmd_t *wait_check, **wait_check_append;
  119. int nexttag, num_in_progress, num_wait_check;
  120. uint buffer_mem; /* memory currently occupied by buffers in the queue */
  121. /* Used during sequential operations like connect */
  122. enum { GreetingPending = 0, GreetingBad, GreetingOk, GreetingPreauth } greeting;
  123. int expectBYE; /* LOGOUT is in progress */
  124. int expectEOF; /* received LOGOUT's OK or unsolicited BYE */
  125. int canceling; /* imap_cancel() is in progress */
  126. union {
  127. void (*imap_open)( int sts, void *aux );
  128. void (*imap_cancel)( void *aux );
  129. } callbacks;
  130. void *callback_aux;
  131. #ifdef HAVE_LIBSASL
  132. sasl_conn_t *sasl;
  133. int sasl_cont;
  134. #endif
  135. void (*bad_callback)( void *aux );
  136. void *bad_callback_aux;
  137. conn_t conn; /* this is BIG, so put it last */
  138. };
  139. struct imap_cmd {
  140. struct imap_cmd *next;
  141. char *cmd;
  142. int tag;
  143. struct {
  144. /* Will be called on each continuation request until it resets this pointer.
  145. * Needs to invoke bad_callback and return -1 on error, otherwise return 0. */
  146. int (*cont)( imap_store_t *ctx, imap_cmd_t *cmd, const char *prompt );
  147. void (*done)( imap_store_t *ctx, imap_cmd_t *cmd, int response );
  148. char *data;
  149. uint data_len;
  150. uint uid; /* to identify fetch responses */
  151. char high_prio; /* if command is queued, put it at the front of the queue. */
  152. char wait_check; // Don't report success until subsequent CHECK success.
  153. char to_trash; /* we are storing to trash, not current. */
  154. char create; /* create the mailbox if we get an error which suggests so. */
  155. char failok; /* Don't complain about NO response. */
  156. char lastuid; /* querying the last UID in the mailbox. */
  157. } param;
  158. };
  159. typedef struct {
  160. imap_cmd_t gen;
  161. void (*callback)( int sts, void *aux );
  162. void *callback_aux;
  163. } imap_cmd_simple_t;
  164. typedef struct {
  165. imap_cmd_simple_t gen;
  166. msg_data_t *msg_data;
  167. } imap_cmd_fetch_msg_t;
  168. typedef struct {
  169. imap_cmd_t gen;
  170. void (*callback)( int sts, uint uid, void *aux );
  171. void *callback_aux;
  172. uint out_uid;
  173. } imap_cmd_out_uid_t;
  174. typedef struct {
  175. imap_cmd_t gen;
  176. void (*callback)( int sts, message_t *msgs, void *aux );
  177. void *callback_aux;
  178. message_t **out_msgs;
  179. uint uid;
  180. } imap_cmd_find_new_t;
  181. typedef struct {
  182. uint ref_count;
  183. int ret_val;
  184. } imap_cmd_refcounted_state_t;
  185. typedef struct {
  186. imap_cmd_t gen;
  187. imap_cmd_refcounted_state_t *state;
  188. } imap_cmd_refcounted_t;
  189. #define CAP(cap) (ctx->caps & (1 << (cap)))
  190. enum CAPABILITY {
  191. NOLOGIN = 0,
  192. #ifdef HAVE_LIBSASL
  193. SASLIR,
  194. #endif
  195. #ifdef HAVE_LIBSSL
  196. STARTTLS,
  197. #endif
  198. UIDPLUS,
  199. LITERALPLUS,
  200. MOVE,
  201. NAMESPACE,
  202. COMPRESS_DEFLATE
  203. };
  204. static const char *cap_list[] = {
  205. "LOGINDISABLED",
  206. #ifdef HAVE_LIBSASL
  207. "SASL-IR",
  208. #endif
  209. #ifdef HAVE_LIBSSL
  210. "STARTTLS",
  211. #endif
  212. "UIDPLUS",
  213. "LITERAL+",
  214. "MOVE",
  215. "NAMESPACE",
  216. "COMPRESS=DEFLATE"
  217. };
  218. #define RESP_OK 0
  219. #define RESP_NO 1
  220. #define RESP_CANCEL 2
  221. static INLINE void imap_ref( imap_store_t *ctx ) { ++ctx->ref_count; }
  222. static int imap_deref( imap_store_t *ctx );
  223. static void imap_invoke_bad_callback( imap_store_t *ctx );
  224. /* Keep the mailbox driver flag definitions in sync: */
  225. /* grep for MAILBOX_DRIVER_FLAG */
  226. /* The order is according to alphabetical maildir flag sort */
  227. static const char *Flags[] = {
  228. "\\Draft", /* 'D' */
  229. "\\Flagged", /* 'F' */
  230. "$Forwarded", /* 'P' */
  231. "\\Answered", /* 'R' */
  232. "\\Seen", /* 'S' */
  233. "\\Deleted", /* 'T' */
  234. };
  235. static imap_cmd_t *
  236. new_imap_cmd( uint size )
  237. {
  238. imap_cmd_t *cmd = nfmalloc( size );
  239. memset( &cmd->param, 0, sizeof(cmd->param) );
  240. return cmd;
  241. }
  242. #define INIT_IMAP_CMD(type, cmdp, cb, aux) \
  243. cmdp = (type *)new_imap_cmd( sizeof(*cmdp) ); \
  244. cmdp->callback = cb; \
  245. cmdp->callback_aux = aux;
  246. #define INIT_IMAP_CMD_X(type, cmdp, cb, aux) \
  247. cmdp = (type *)new_imap_cmd( sizeof(*cmdp) ); \
  248. cmdp->gen.callback = cb; \
  249. cmdp->gen.callback_aux = aux;
  250. static void
  251. done_imap_cmd( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  252. {
  253. if (cmd->param.wait_check)
  254. ctx->num_wait_check--;
  255. cmd->param.done( ctx, cmd, response );
  256. if (cmd->param.data) {
  257. free( cmd->param.data );
  258. ctx->buffer_mem -= cmd->param.data_len;
  259. }
  260. free( cmd->cmd );
  261. free( cmd );
  262. }
  263. static void
  264. send_imap_cmd( imap_store_t *ctx, imap_cmd_t *cmd )
  265. {
  266. int litplus, iovcnt = 1;
  267. int bufl;
  268. const char *buffmt;
  269. conn_iovec_t iov[3];
  270. char buf[4096];
  271. cmd->tag = ++ctx->nexttag;
  272. if (!cmd->param.data) {
  273. buffmt = "%d %s\r\n";
  274. litplus = 0;
  275. } else if ((cmd->param.to_trash && ctx->trashnc == TrashUnknown) || !CAP(LITERALPLUS) || cmd->param.data_len >= 100*1024) {
  276. buffmt = "%d %s{%d}\r\n";
  277. litplus = 0;
  278. } else {
  279. buffmt = "%d %s{%d+}\r\n";
  280. litplus = 1;
  281. }
  282. DIAG_PUSH
  283. DIAG_DISABLE("-Wformat-nonliteral")
  284. bufl = nfsnprintf( buf, sizeof(buf), buffmt,
  285. cmd->tag, cmd->cmd, cmd->param.data_len );
  286. DIAG_POP
  287. if (DFlags & DEBUG_NET) {
  288. if (ctx->num_in_progress)
  289. printf( "(%d in progress) ", ctx->num_in_progress );
  290. if (starts_with( cmd->cmd, -1, "LOGIN", 5 ))
  291. printf( "%s>>> %d LOGIN <user> <pass>\n", ctx->label, cmd->tag );
  292. else if (starts_with( cmd->cmd, -1, "AUTHENTICATE PLAIN", 18 ))
  293. printf( "%s>>> %d AUTHENTICATE PLAIN <authdata>\n", ctx->label, cmd->tag );
  294. else
  295. printf( "%s>>> %s", ctx->label, buf );
  296. fflush( stdout );
  297. }
  298. iov[0].buf = buf;
  299. iov[0].len = (uint)bufl;
  300. iov[0].takeOwn = KeepOwn;
  301. if (litplus) {
  302. if (DFlags & DEBUG_NET_ALL) {
  303. printf( "%s>>>>>>>>>\n", ctx->label );
  304. fwrite( cmd->param.data, cmd->param.data_len, 1, stdout );
  305. printf( "%s>>>>>>>>>\n", ctx->label );
  306. fflush( stdout );
  307. }
  308. iov[1].buf = cmd->param.data;
  309. iov[1].len = cmd->param.data_len;
  310. iov[1].takeOwn = GiveOwn;
  311. cmd->param.data = NULL;
  312. ctx->buffer_mem -= cmd->param.data_len;
  313. iov[2].buf = "\r\n";
  314. iov[2].len = 2;
  315. iov[2].takeOwn = KeepOwn;
  316. iovcnt = 3;
  317. }
  318. socket_write( &ctx->conn, iov, iovcnt );
  319. if (cmd->param.to_trash && ctx->trashnc == TrashUnknown)
  320. ctx->trashnc = TrashChecking;
  321. cmd->next = NULL;
  322. *ctx->in_progress_append = cmd;
  323. ctx->in_progress_append = &cmd->next;
  324. ctx->num_in_progress++;
  325. socket_expect_activity( &ctx->conn, 1 );
  326. }
  327. static int
  328. cmd_sendable( imap_store_t *ctx, imap_cmd_t *cmd )
  329. {
  330. if (ctx->conn.write_buf) {
  331. /* Don't build up a long queue in the socket, so we can
  332. * control when the commands are actually sent.
  333. * This allows reliable cancelation of pending commands,
  334. * injecting commands in front of other pending commands,
  335. * and keeping num_in_progress accurate. */
  336. return 0;
  337. }
  338. if (ctx->in_progress) {
  339. /* If the last command in flight ... */
  340. imap_cmd_t *cmdp = (imap_cmd_t *)((char *)ctx->in_progress_append -
  341. offsetof(imap_cmd_t, next));
  342. if (cmdp->param.cont || cmdp->param.data) {
  343. /* ... is expected to trigger a continuation request, we need to
  344. * wait for that round-trip before sending the next command. */
  345. return 0;
  346. }
  347. }
  348. if (cmd->param.to_trash && ctx->trashnc == TrashChecking) {
  349. /* Don't build a queue of MOVE/COPY/APPEND commands that may all fail. */
  350. return 0;
  351. }
  352. if (ctx->num_in_progress >= ((imap_store_conf_t *)ctx->gen.conf)->server->max_in_progress) {
  353. /* Too many commands in flight. */
  354. return 0;
  355. }
  356. return 1;
  357. }
  358. static void
  359. flush_imap_cmds( imap_store_t *ctx )
  360. {
  361. imap_cmd_t *cmd;
  362. if ((cmd = ctx->pending) && cmd_sendable( ctx, cmd )) {
  363. if (!(ctx->pending = cmd->next))
  364. ctx->pending_append = &ctx->pending;
  365. send_imap_cmd( ctx, cmd );
  366. }
  367. }
  368. static void
  369. finalize_checked_imap_cmds( imap_store_t *ctx, int resp )
  370. {
  371. imap_cmd_t *cmd;
  372. while ((cmd = ctx->wait_check)) {
  373. if (!(ctx->wait_check = cmd->next))
  374. ctx->wait_check_append = &ctx->wait_check;
  375. done_imap_cmd( ctx, cmd, resp );
  376. }
  377. }
  378. static void
  379. cancel_pending_imap_cmds( imap_store_t *ctx )
  380. {
  381. imap_cmd_t *cmd;
  382. while ((cmd = ctx->pending)) {
  383. if (!(ctx->pending = cmd->next))
  384. ctx->pending_append = &ctx->pending;
  385. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  386. }
  387. }
  388. static void
  389. cancel_sent_imap_cmds( imap_store_t *ctx )
  390. {
  391. imap_cmd_t *cmd;
  392. socket_expect_activity( &ctx->conn, 0 );
  393. while ((cmd = ctx->in_progress)) {
  394. ctx->in_progress = cmd->next;
  395. /* don't update num_in_progress and in_progress_append - store is dead */
  396. done_imap_cmd( ctx, cmd, RESP_CANCEL );
  397. }
  398. }
  399. static void
  400. submit_imap_cmd( imap_store_t *ctx, imap_cmd_t *cmd )
  401. {
  402. assert( ctx );
  403. assert( ctx->bad_callback );
  404. assert( cmd );
  405. assert( cmd->param.done );
  406. if (cmd->param.wait_check)
  407. ctx->num_wait_check++;
  408. if ((ctx->pending && !cmd->param.high_prio) || !cmd_sendable( ctx, cmd )) {
  409. if (ctx->pending && cmd->param.high_prio) {
  410. cmd->next = ctx->pending;
  411. ctx->pending = cmd;
  412. } else {
  413. cmd->next = NULL;
  414. *ctx->pending_append = cmd;
  415. ctx->pending_append = &cmd->next;
  416. }
  417. } else {
  418. send_imap_cmd( ctx, cmd );
  419. }
  420. }
  421. /* Minimal printf() replacement that supports an %\s format sequence to print backslash-escaped
  422. * string literals. Note that this does not automatically add quotes around the printed string,
  423. * so it is possible to concatenate multiple segments. */
  424. static char *
  425. imap_vprintf( const char *fmt, va_list ap )
  426. {
  427. const char *s;
  428. char *d, *ed;
  429. char c;
  430. char buf[4096];
  431. d = buf;
  432. ed = d + sizeof(buf);
  433. s = fmt;
  434. for (;;) {
  435. c = *fmt;
  436. if (!c || c == '%') {
  437. uint l = fmt - s;
  438. if (d + l > ed)
  439. oob();
  440. memcpy( d, s, l );
  441. d += l;
  442. if (!c)
  443. return nfstrndup( buf, (size_t)(d - buf) );
  444. uint maxlen = UINT_MAX;
  445. c = *++fmt;
  446. if (c == '\\') {
  447. c = *++fmt;
  448. if (c != 's') {
  449. fputs( "Fatal: unsupported escaped format specifier. Please report a bug.\n", stderr );
  450. abort();
  451. }
  452. s = va_arg( ap, const char * );
  453. while ((c = *s++)) {
  454. if (d + 2 > ed)
  455. oob();
  456. if (c == '\\' || c == '"')
  457. *d++ = '\\';
  458. *d++ = c;
  459. }
  460. } else { /* \\ cannot be combined with anything else. */
  461. if (c == '.') {
  462. c = *++fmt;
  463. if (c != '*') {
  464. fputs( "Fatal: unsupported string length specification. Please report a bug.\n", stderr );
  465. abort();
  466. }
  467. maxlen = va_arg( ap, uint );
  468. c = *++fmt;
  469. }
  470. if (c == 'c') {
  471. if (d + 1 > ed)
  472. oob();
  473. *d++ = (char)va_arg( ap , int );
  474. } else if (c == 's') {
  475. s = va_arg( ap, const char * );
  476. l = strnlen( s, maxlen );
  477. if (d + l > ed)
  478. oob();
  479. memcpy( d, s, l );
  480. d += l;
  481. } else if (c == 'd') {
  482. d += nfsnprintf( d, ed - d, "%d", va_arg( ap , int ) );
  483. } else if (c == 'u') {
  484. d += nfsnprintf( d, ed - d, "%u", va_arg( ap , uint ) );
  485. } else {
  486. fputs( "Fatal: unsupported format specifier. Please report a bug.\n", stderr );
  487. abort();
  488. }
  489. }
  490. s = ++fmt;
  491. } else {
  492. fmt++;
  493. }
  494. }
  495. }
  496. static void
  497. imap_exec( imap_store_t *ctx, imap_cmd_t *cmdp,
  498. void (*done)( imap_store_t *ctx, imap_cmd_t *cmd, int response ),
  499. const char *fmt, ... )
  500. {
  501. va_list ap;
  502. if (!cmdp)
  503. cmdp = new_imap_cmd( sizeof(*cmdp) );
  504. cmdp->param.done = done;
  505. va_start( ap, fmt );
  506. cmdp->cmd = imap_vprintf( fmt, ap );
  507. va_end( ap );
  508. submit_imap_cmd( ctx, cmdp );
  509. }
  510. static void
  511. transform_box_response( int *response )
  512. {
  513. switch (*response) {
  514. case RESP_CANCEL: *response = DRV_CANCELED; break;
  515. case RESP_NO: *response = DRV_BOX_BAD; break;
  516. default: *response = DRV_OK; break;
  517. }
  518. }
  519. static void
  520. imap_done_simple_box( imap_store_t *ctx ATTR_UNUSED,
  521. imap_cmd_t *cmd, int response )
  522. {
  523. imap_cmd_simple_t *cmdp = (imap_cmd_simple_t *)cmd;
  524. transform_box_response( &response );
  525. cmdp->callback( response, cmdp->callback_aux );
  526. }
  527. static void
  528. transform_msg_response( int *response )
  529. {
  530. switch (*response) {
  531. case RESP_CANCEL: *response = DRV_CANCELED; break;
  532. case RESP_NO: *response = DRV_MSG_BAD; break;
  533. default: *response = DRV_OK; break;
  534. }
  535. }
  536. static void
  537. imap_done_simple_msg( imap_store_t *ctx ATTR_UNUSED,
  538. imap_cmd_t *cmd, int response )
  539. {
  540. imap_cmd_simple_t *cmdp = (imap_cmd_simple_t *)cmd;
  541. transform_msg_response( &response );
  542. cmdp->callback( response, cmdp->callback_aux );
  543. }
  544. static imap_cmd_refcounted_state_t *
  545. imap_refcounted_new_state( uint sz )
  546. {
  547. imap_cmd_refcounted_state_t *sts = nfmalloc( sz );
  548. sts->ref_count = 1; /* so forced sync does not cause an early exit */
  549. sts->ret_val = DRV_OK;
  550. return sts;
  551. }
  552. #define INIT_REFCOUNTED_STATE(type, sts, cb, aux) \
  553. type *sts = (type *)imap_refcounted_new_state( sizeof(type) ); \
  554. sts->callback = cb; \
  555. sts->callback_aux = aux;
  556. static imap_cmd_t *
  557. imap_refcounted_new_cmd( imap_cmd_refcounted_state_t *sts )
  558. {
  559. imap_cmd_refcounted_t *cmd = (imap_cmd_refcounted_t *)new_imap_cmd( sizeof(*cmd) );
  560. cmd->state = sts;
  561. sts->ref_count++;
  562. return &cmd->gen;
  563. }
  564. #define DONE_REFCOUNTED_STATE(sts) \
  565. if (!--sts->gen.ref_count) { \
  566. sts->callback( sts->gen.ret_val, sts->callback_aux ); \
  567. free( sts ); \
  568. }
  569. #define DONE_REFCOUNTED_STATE_ARGS(sts, finalize, ...) \
  570. if (!--sts->gen.ref_count) { \
  571. finalize \
  572. sts->callback( sts->gen.ret_val, __VA_ARGS__, sts->callback_aux ); \
  573. free( sts ); \
  574. }
  575. static void
  576. transform_refcounted_box_response( imap_cmd_refcounted_state_t *sts, int response )
  577. {
  578. switch (response) {
  579. case RESP_CANCEL:
  580. sts->ret_val = DRV_CANCELED;
  581. break;
  582. case RESP_NO:
  583. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  584. sts->ret_val = DRV_BOX_BAD;
  585. break;
  586. }
  587. }
  588. static void
  589. transform_refcounted_msg_response( imap_cmd_refcounted_state_t *sts, int response )
  590. {
  591. switch (response) {
  592. case RESP_CANCEL:
  593. sts->ret_val = DRV_CANCELED;
  594. break;
  595. case RESP_NO:
  596. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  597. sts->ret_val = DRV_MSG_BAD;
  598. break;
  599. }
  600. }
  601. static const char *
  602. imap_strchr( const char *s, char tc )
  603. {
  604. for (;; s++) {
  605. char c = *s;
  606. if (c == '\\')
  607. c = *++s;
  608. if (!c)
  609. return NULL;
  610. if (c == tc)
  611. return s;
  612. }
  613. }
  614. static char *
  615. next_arg( char **ps )
  616. {
  617. char *ret, *s, *d;
  618. char c;
  619. assert( ps );
  620. s = *ps;
  621. if (!s)
  622. return NULL;
  623. while (isspace( (uchar)*s ))
  624. s++;
  625. if (!*s) {
  626. *ps = NULL;
  627. return NULL;
  628. }
  629. if (*s == '"') {
  630. s++;
  631. ret = d = s;
  632. while ((c = *s++) != '"') {
  633. if (c == '\\')
  634. c = *s++;
  635. if (!c) {
  636. *ps = NULL;
  637. return NULL;
  638. }
  639. *d++ = c;
  640. }
  641. *d = 0;
  642. } else {
  643. ret = s;
  644. while ((c = *s)) {
  645. if (isspace( (uchar)c )) {
  646. *s++ = 0;
  647. break;
  648. }
  649. s++;
  650. }
  651. }
  652. if (!*s)
  653. s = NULL;
  654. *ps = s;
  655. return ret;
  656. }
  657. static int
  658. is_opt_atom( list_t *list )
  659. {
  660. return list && list->val && list->val != LIST;
  661. }
  662. static int
  663. is_atom( list_t *list )
  664. {
  665. return list && list->val && list->val != NIL && list->val != LIST;
  666. }
  667. static int
  668. is_list( list_t *list )
  669. {
  670. return list && list->val == LIST;
  671. }
  672. static void
  673. free_list( list_t *list )
  674. {
  675. list_t *tmp;
  676. for (; list; list = tmp) {
  677. tmp = list->next;
  678. if (is_list( list ))
  679. free_list( list->child );
  680. else if (is_atom( list ))
  681. free( list->val );
  682. free( list );
  683. }
  684. }
  685. enum {
  686. LIST_OK,
  687. LIST_PARTIAL,
  688. LIST_BAD
  689. };
  690. static int
  691. parse_imap_list( imap_store_t *ctx, char **sp, parse_list_state_t *sts )
  692. {
  693. list_t *cur, **curp;
  694. char *s = *sp, *d, *p;
  695. int n, bytes;
  696. char c;
  697. assert( sts );
  698. assert( sts->level > 0 );
  699. curp = sts->stack[--sts->level];
  700. bytes = sts->need_bytes;
  701. if (bytes >= 0) {
  702. sts->need_bytes = -1;
  703. if (!bytes)
  704. goto getline;
  705. cur = (list_t *)((char *)curp - offsetof(list_t, next));
  706. s = cur->val + cur->len - bytes;
  707. goto getbytes;
  708. }
  709. if (!s)
  710. return LIST_BAD;
  711. for (;;) {
  712. while (isspace( (uchar)*s ))
  713. s++;
  714. if (sts->level && *s == ')') {
  715. s++;
  716. curp = sts->stack[--sts->level];
  717. goto next;
  718. }
  719. *curp = cur = nfmalloc( sizeof(*cur) );
  720. cur->val = NULL; /* for clean bail */
  721. curp = &cur->next;
  722. *curp = NULL; /* ditto */
  723. if (*s == '(') {
  724. /* sublist */
  725. if (sts->level == MAX_LIST_DEPTH)
  726. goto bail;
  727. s++;
  728. cur->val = LIST;
  729. sts->stack[sts->level++] = curp;
  730. curp = &cur->child;
  731. *curp = NULL; /* for clean bail */
  732. goto next2;
  733. } else if (ctx && *s == '{') {
  734. /* literal */
  735. bytes = (int)(cur->len = strtoul( s + 1, &s, 10 ));
  736. if (*s != '}' || *++s)
  737. goto bail;
  738. s = cur->val = nfmalloc( cur->len + 1 );
  739. s[cur->len] = 0;
  740. getbytes:
  741. n = socket_read( &ctx->conn, s, (uint)bytes );
  742. if (n < 0) {
  743. badeof:
  744. error( "IMAP error: unexpected EOF from %s\n", ctx->conn.name );
  745. goto bail;
  746. }
  747. bytes -= n;
  748. if (bytes > 0)
  749. goto postpone;
  750. if (DFlags & DEBUG_NET_ALL) {
  751. printf( "%s=========\n", ctx->label );
  752. fwrite( cur->val, cur->len, 1, stdout );
  753. printf( "%s=========\n", ctx->label );
  754. fflush( stdout );
  755. }
  756. getline:
  757. if (!(s = socket_read_line( &ctx->conn )))
  758. goto postpone;
  759. if (s == (void *)~0)
  760. goto badeof;
  761. if (DFlags & DEBUG_NET) {
  762. printf( "%s%s\n", ctx->label, s );
  763. fflush( stdout );
  764. }
  765. } else if (*s == '"') {
  766. /* quoted string */
  767. s++;
  768. p = d = s;
  769. while ((c = *s++) != '"') {
  770. if (c == '\\')
  771. c = *s++;
  772. if (!c)
  773. goto bail;
  774. *d++ = c;
  775. }
  776. cur->len = (uint)(d - p);
  777. cur->val = nfstrndup( p, cur->len );
  778. } else {
  779. /* atom */
  780. p = s;
  781. for (; *s && !isspace( (uchar)*s ); s++)
  782. if (sts->level && *s == ')')
  783. break;
  784. cur->len = (uint)(s - p);
  785. if (equals( p, (int)cur->len, "NIL", 3 ))
  786. cur->val = NIL;
  787. else
  788. cur->val = nfstrndup( p, cur->len );
  789. }
  790. next:
  791. if (!sts->level)
  792. break;
  793. next2:
  794. if (!*s)
  795. goto bail;
  796. }
  797. *sp = s;
  798. return LIST_OK;
  799. postpone:
  800. if (sts->level < MAX_LIST_DEPTH) {
  801. sts->stack[sts->level++] = curp;
  802. sts->need_bytes = bytes;
  803. return LIST_PARTIAL;
  804. }
  805. bail:
  806. free_list( sts->head );
  807. return LIST_BAD;
  808. }
  809. static void
  810. parse_list_init( parse_list_state_t *sts )
  811. {
  812. sts->need_bytes = -1;
  813. sts->level = 1;
  814. sts->head = NULL;
  815. sts->stack[0] = &sts->head;
  816. }
  817. static int
  818. parse_list_continue( imap_store_t *ctx, char *s )
  819. {
  820. list_t *list;
  821. int resp;
  822. if ((resp = parse_imap_list( ctx, &s, &ctx->parse_list_sts )) != LIST_PARTIAL) {
  823. list = (resp == LIST_BAD) ? NULL : ctx->parse_list_sts.head;
  824. ctx->parse_list_sts.head = NULL;
  825. resp = ctx->parse_list_sts.callback( ctx, list, s );
  826. free_list( list );
  827. }
  828. return resp;
  829. }
  830. static int
  831. parse_list( imap_store_t *ctx, char *s, int (*cb)( imap_store_t *ctx, list_t *list, char *s ) )
  832. {
  833. parse_list_init( &ctx->parse_list_sts );
  834. ctx->parse_list_sts.callback = cb;
  835. return parse_list_continue( ctx, s );
  836. }
  837. static int parse_namespace_rsp_p2( imap_store_t *, list_t *, char * );
  838. static int parse_namespace_rsp_p3( imap_store_t *, list_t *, char * );
  839. static int
  840. parse_namespace_rsp( imap_store_t *ctx, list_t *list, char *s )
  841. {
  842. // We use only the 1st personal namespace. Making this configurable
  843. // would not add value over just specifying Path.
  844. if (!list) {
  845. bad:
  846. error( "IMAP error: malformed NAMESPACE response\n" );
  847. return LIST_BAD;
  848. }
  849. if (list->val != NIL) {
  850. if (list->val != LIST)
  851. goto bad;
  852. list_t *nsp_1st = list->child;
  853. if (nsp_1st->val != LIST)
  854. goto bad;
  855. list_t *nsp_1st_ns = nsp_1st->child;
  856. if (!is_atom( nsp_1st_ns ))
  857. goto bad;
  858. ctx->ns_prefix = nsp_1st_ns->val;
  859. nsp_1st_ns->val = NULL;
  860. list_t *nsp_1st_dl = nsp_1st_ns->next;
  861. if (!is_opt_atom( nsp_1st_dl ))
  862. goto bad;
  863. if (is_atom( nsp_1st_dl ))
  864. ctx->ns_delimiter = nsp_1st_dl->val[0];
  865. // Namespace response extensions may follow here; we don't care.
  866. }
  867. return parse_list( ctx, s, parse_namespace_rsp_p2 );
  868. }
  869. static int
  870. parse_namespace_rsp_p2( imap_store_t *ctx, list_t *list ATTR_UNUSED, char *s )
  871. {
  872. return parse_list( ctx, s, parse_namespace_rsp_p3 );
  873. }
  874. static int
  875. parse_namespace_rsp_p3( imap_store_t *ctx ATTR_UNUSED, list_t *list ATTR_UNUSED, char *s ATTR_UNUSED )
  876. {
  877. return LIST_OK;
  878. }
  879. static time_t
  880. parse_date( const char *str )
  881. {
  882. char *end;
  883. time_t date;
  884. int hours, mins;
  885. struct tm datetime;
  886. memset( &datetime, 0, sizeof(datetime) );
  887. if (!(end = strptime( str, "%e-%b-%Y %H:%M:%S ", &datetime )))
  888. return -1;
  889. if ((date = timegm( &datetime )) == -1)
  890. return -1;
  891. if (sscanf( end, "%3d%2d", &hours, &mins ) != 2)
  892. return -1;
  893. return date - (hours * 60 + mins) * 60;
  894. }
  895. static int
  896. parse_fetched_flags( list_t *list, uchar *flags, uchar *status )
  897. {
  898. for (; list; list = list->next) {
  899. if (!is_atom( list )) {
  900. error( "IMAP error: unable to parse FLAGS list\n" );
  901. return 0;
  902. }
  903. if (list->val[0] != '\\' && list->val[0] != '$')
  904. continue;
  905. if (!strcmp( "\\Recent", list->val )) {
  906. *status |= M_RECENT;
  907. goto flagok;
  908. }
  909. for (uint i = 0; i < as(Flags); i++) {
  910. if (!strcmp( Flags[i], list->val )) {
  911. *flags |= 1 << i;
  912. goto flagok;
  913. }
  914. }
  915. if (list->val[0] == '$')
  916. goto flagok; // Ignore unknown user-defined flags (keywords)
  917. if (list->val[1] == 'X' && list->val[2] == '-')
  918. goto flagok; // Ignore system flag extensions
  919. warn( "IMAP warning: unknown system flag %s\n", list->val );
  920. flagok: ;
  921. }
  922. *status |= M_FLAGS;
  923. return 1;
  924. }
  925. static void
  926. parse_fetched_header( char *val, uint uid, char **tuid, char **msgid )
  927. {
  928. char *end;
  929. int off, in_msgid = 0;
  930. for (; (end = strchr( val, '\n' )); val = end + 1) {
  931. int len = (int)(end - val);
  932. if (len && end[-1] == '\r')
  933. len--;
  934. if (!len)
  935. break;
  936. if (starts_with_upper( val, len, "X-TUID: ", 8 )) {
  937. if (len < 8 + TUIDL) {
  938. warn( "IMAP warning: malformed X-TUID header (UID %u)\n", uid );
  939. continue;
  940. }
  941. *tuid = val + 8;
  942. in_msgid = 0;
  943. continue;
  944. }
  945. if (starts_with_upper( val, len, "MESSAGE-ID:", 11 )) {
  946. off = 11;
  947. } else if (in_msgid) {
  948. if (!isspace( val[0] )) {
  949. in_msgid = 0;
  950. continue;
  951. }
  952. off = 1;
  953. } else {
  954. continue;
  955. }
  956. while (off < len && isspace( val[off] ))
  957. off++;
  958. if (off == len) {
  959. in_msgid = 1;
  960. continue;
  961. }
  962. *msgid = nfstrndup( val + off, (size_t)(len - off) );
  963. in_msgid = 0;
  964. }
  965. }
  966. static int
  967. parse_fetch_rsp( imap_store_t *ctx, list_t *list, char *s ATTR_UNUSED )
  968. {
  969. list_t *body = NULL, *tmp;
  970. char *tuid = NULL, *msgid = NULL, *ep;
  971. imap_message_t *cur;
  972. msg_data_t *msgdata;
  973. imap_cmd_t *cmdp;
  974. uchar mask = 0, status = 0;
  975. uint uid = 0, need_uid = 0, size = 0;
  976. time_t date = 0;
  977. if (!is_list( list )) {
  978. error( "IMAP error: bogus FETCH response\n" );
  979. return LIST_BAD;
  980. }
  981. for (tmp = list->child; tmp; tmp = tmp->next) {
  982. if (!is_atom( tmp )) {
  983. error( "IMAP error: bogus item name in FETCH response\n" );
  984. goto ffail;
  985. }
  986. const char *name = tmp->val;
  987. tmp = tmp->next;
  988. if (!strcmp( "UID", name )) {
  989. if (!is_atom( tmp ) || (uid = strtoul( tmp->val, &ep, 10 ), *ep)) {
  990. error( "IMAP error: unable to parse UID\n" );
  991. goto ffail;
  992. }
  993. continue; // This *is* the UID.
  994. } else if (!strcmp( "FLAGS", name )) {
  995. if (!is_list( tmp )) {
  996. error( "IMAP error: unable to parse FLAGS\n" );
  997. goto ffail;
  998. }
  999. if (!parse_fetched_flags( tmp->child, &mask, &status ))
  1000. goto ffail;
  1001. continue; // This may legitimately come without UID.
  1002. } else if (!strcmp( "INTERNALDATE", name )) {
  1003. if (!is_atom( tmp )) {
  1004. error( "IMAP error: unable to parse INTERNALDATE\n" );
  1005. goto ffail;
  1006. }
  1007. if ((date = parse_date( tmp->val )) == -1) {
  1008. error( "IMAP error: unable to parse INTERNALDATE format\n" );
  1009. goto ffail;
  1010. }
  1011. } else if (!strcmp( "RFC822.SIZE", name )) {
  1012. if (!is_atom( tmp ) || (size = strtoul( tmp->val, &ep, 10 ), *ep)) {
  1013. error( "IMAP error: unable to parse RFC822.SIZE\n" );
  1014. goto ffail;
  1015. }
  1016. } else if (!strcmp( "BODY[]", name ) || !strcmp( "BODY[HEADER]", name )) {
  1017. if (!is_atom( tmp )) {
  1018. error( "IMAP error: unable to parse BODY[]\n" );
  1019. goto ffail;
  1020. }
  1021. body = tmp;
  1022. } else if (!strcmp( "BODY[HEADER.FIELDS", name )) {
  1023. if (!is_list( tmp )) {
  1024. bfail:
  1025. error( "IMAP error: unable to parse BODY[HEADER.FIELDS ...]\n" );
  1026. goto ffail;
  1027. }
  1028. tmp = tmp->next;
  1029. if (!is_atom( tmp ) || strcmp( tmp->val, "]" ))
  1030. goto bfail;
  1031. tmp = tmp->next;
  1032. if (!is_atom( tmp ))
  1033. goto bfail;
  1034. parse_fetched_header( tmp->val, uid, &tuid, &msgid );
  1035. }
  1036. need_uid = 1;
  1037. }
  1038. if (!uid) {
  1039. if (need_uid) {
  1040. error( "IMAP error: received payload without UID\n" );
  1041. goto ffail;
  1042. }
  1043. // Ignore async flag updates for now.
  1044. } else if ((cmdp = ctx->in_progress) && cmdp->param.lastuid) {
  1045. if (need_uid || (status & M_FLAGS)) {
  1046. error( "IMAP error: received extraneous data in response to UID query\n" );
  1047. goto ffail;
  1048. }
  1049. // Workaround for server not sending UIDNEXT and/or APPENDUID.
  1050. ctx->uidnext = uid + 1;
  1051. } else if (body) {
  1052. if (tuid || msgid) { // Only those that leak; ignore others.
  1053. error( "IMAP error: received extraneous data with full message\n" );
  1054. goto ffail;
  1055. }
  1056. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  1057. if (cmdp->param.uid == uid)
  1058. goto gotuid;
  1059. error( "IMAP error: unexpected FETCH response (UID %u)\n", uid );
  1060. return LIST_BAD;
  1061. gotuid:
  1062. msgdata = ((imap_cmd_fetch_msg_t *)cmdp)->msg_data;
  1063. msgdata->data = body->val;
  1064. body->val = NULL; // Don't free together with list.
  1065. msgdata->len = body->len;
  1066. msgdata->date = date;
  1067. if (status & M_FLAGS)
  1068. msgdata->flags = mask;
  1069. } else {
  1070. cur = nfcalloc( sizeof(*cur) );
  1071. *ctx->msgapp = &cur->gen;
  1072. ctx->msgapp = &cur->gen.next;
  1073. cur->gen.next = NULL;
  1074. cur->gen.uid = uid;
  1075. cur->gen.flags = mask;
  1076. cur->gen.status = status;
  1077. cur->gen.size = size;
  1078. cur->gen.srec = NULL;
  1079. cur->gen.msgid = msgid;
  1080. if (tuid)
  1081. memcpy( cur->gen.tuid, tuid, TUIDL );
  1082. else
  1083. cur->gen.tuid[0] = 0;
  1084. }
  1085. return LIST_OK;
  1086. ffail:
  1087. free( tuid );
  1088. free( msgid );
  1089. return LIST_BAD;
  1090. }
  1091. static void
  1092. parse_capability( imap_store_t *ctx, char *cmd )
  1093. {
  1094. char *arg;
  1095. uint i;
  1096. free_string_list( ctx->auth_mechs );
  1097. ctx->auth_mechs = NULL;
  1098. ctx->caps = 0x80000000;
  1099. while ((arg = next_arg( &cmd ))) {
  1100. if (starts_with( arg, -1, "AUTH=", 5 )) {
  1101. add_string_list( &ctx->auth_mechs, arg + 5 );
  1102. } else {
  1103. for (i = 0; i < as(cap_list); i++)
  1104. if (!strcmp( cap_list[i], arg ))
  1105. ctx->caps |= 1 << i;
  1106. }
  1107. }
  1108. ctx->caps &= ~((imap_store_conf_t *)ctx->gen.conf)->server->cap_mask;
  1109. if (!CAP(NOLOGIN))
  1110. add_string_list( &ctx->auth_mechs, "LOGIN" );
  1111. }
  1112. static int
  1113. parse_response_code( imap_store_t *ctx, imap_cmd_t *cmd, char *s )
  1114. {
  1115. char *arg, *earg, *p;
  1116. if (!s || *s != '[')
  1117. return RESP_OK; /* no response code */
  1118. s++;
  1119. if (!(p = strchr( s, ']' ))) {
  1120. bad_resp:
  1121. error( "IMAP error: malformed response code\n" );
  1122. return RESP_CANCEL;
  1123. }
  1124. *p++ = 0;
  1125. if (!(arg = next_arg( &s )))
  1126. goto bad_resp;
  1127. if (!strcmp( "UIDVALIDITY", arg )) {
  1128. if (!(arg = next_arg( &s )) ||
  1129. (ctx->uidvalidity = strtoul( arg, &earg, 10 ), *earg))
  1130. {
  1131. error( "IMAP error: malformed UIDVALIDITY status\n" );
  1132. return RESP_CANCEL;
  1133. }
  1134. } else if (!strcmp( "UIDNEXT", arg )) {
  1135. if (!(arg = next_arg( &s )) ||
  1136. (ctx->uidnext = strtoul( arg, &earg, 10 ), *earg))
  1137. {
  1138. error( "IMAP error: malformed UIDNEXT status\n" );
  1139. return RESP_CANCEL;
  1140. }
  1141. } else if (!strcmp( "CAPABILITY", arg )) {
  1142. parse_capability( ctx, s );
  1143. } else if (!strcmp( "ALERT", arg )) {
  1144. /* RFC2060 says that these messages MUST be displayed
  1145. * to the user
  1146. */
  1147. for (; isspace( (uchar)*p ); p++);
  1148. error( "*** IMAP ALERT *** %s\n", p );
  1149. } else if (cmd && !strcmp( "APPENDUID", arg )) {
  1150. if (!(arg = next_arg( &s )) ||
  1151. (ctx->uidvalidity = strtoul( arg, &earg, 10 ), *earg) ||
  1152. !(arg = next_arg( &s )) ||
  1153. (((imap_cmd_out_uid_t *)cmd)->out_uid = strtoul( arg, &earg, 10 ), *earg))
  1154. {
  1155. error( "IMAP error: malformed APPENDUID status\n" );
  1156. return RESP_CANCEL;
  1157. }
  1158. } else if (!strcmp( "PERMANENTFLAGS", arg )) {
  1159. parse_list_init( &ctx->parse_list_sts );
  1160. if (parse_imap_list( NULL, &s, &ctx->parse_list_sts ) != LIST_OK) {
  1161. error( "IMAP error: malformed PERMANENTFLAGS status\n" );
  1162. return RESP_CANCEL;
  1163. }
  1164. int ret = RESP_OK;
  1165. for (list_t *tmp = ctx->parse_list_sts.head->child; tmp; tmp = tmp->next) {
  1166. if (!is_atom( tmp )) {
  1167. error( "IMAP error: malformed PERMANENTFLAGS status item\n" );
  1168. ret = RESP_CANCEL;
  1169. break;
  1170. }
  1171. if (!strcmp( tmp->val, "\\*" ) || !strcmp( tmp->val, "$Forwarded" )) {
  1172. ctx->has_forwarded = 1;
  1173. break;
  1174. }
  1175. }
  1176. free_list( ctx->parse_list_sts.head );
  1177. ctx->parse_list_sts.head = NULL;
  1178. return ret;
  1179. }
  1180. return RESP_OK;
  1181. }
  1182. static int parse_list_rsp_p1( imap_store_t *, list_t *, char * );
  1183. static int parse_list_rsp_p2( imap_store_t *, list_t *, char * );
  1184. static int
  1185. parse_list_rsp( imap_store_t *ctx, list_t *list, char *cmd )
  1186. {
  1187. list_t *lp;
  1188. if (!is_list( list )) {
  1189. error( "IMAP error: malformed LIST response\n" );
  1190. return LIST_BAD;
  1191. }
  1192. for (lp = list->child; lp; lp = lp->next)
  1193. if (is_atom( lp ) && !strcasecmp( lp->val, "\\NoSelect" ))
  1194. return LIST_OK;
  1195. return parse_list( ctx, cmd, parse_list_rsp_p1 );
  1196. }
  1197. static int
  1198. parse_list_rsp_p1( imap_store_t *ctx, list_t *list, char *cmd ATTR_UNUSED )
  1199. {
  1200. if (!is_opt_atom( list )) {
  1201. error( "IMAP error: malformed LIST response\n" );
  1202. return LIST_BAD;
  1203. }
  1204. if (!ctx->delimiter[0] && is_atom( list ))
  1205. ctx->delimiter[0] = list->val[0];
  1206. return parse_list( ctx, cmd, parse_list_rsp_p2 );
  1207. }
  1208. // Use this to check whether a full path refers to the actual IMAP INBOX.
  1209. static int
  1210. is_inbox( imap_store_t *ctx, const char *arg, int argl )
  1211. {
  1212. if (!starts_with_upper( arg, argl, "INBOX", 5 ))
  1213. return 0;
  1214. if (arg[5] && arg[5] != ctx->delimiter[0])
  1215. return 0;
  1216. return 1;
  1217. }
  1218. // Use this to check whether a path fragment collides with the canonical INBOX.
  1219. static int
  1220. is_INBOX( imap_store_t *ctx, const char *arg, int argl )
  1221. {
  1222. if (!starts_with( arg, argl, "INBOX", 5 ))
  1223. return 0;
  1224. if (arg[5] && arg[5] != ctx->delimiter[0])
  1225. return 0;
  1226. return 1;
  1227. }
  1228. static int
  1229. parse_list_rsp_p2( imap_store_t *ctx, list_t *list, char *cmd ATTR_UNUSED )
  1230. {
  1231. string_list_t *narg;
  1232. char *arg;
  1233. int argl;
  1234. uint l;
  1235. if (!is_atom( list )) {
  1236. error( "IMAP error: malformed LIST response\n" );
  1237. return LIST_BAD;
  1238. }
  1239. arg = list->val;
  1240. argl = (int)list->len;
  1241. if (is_inbox( ctx, arg, argl )) {
  1242. // The server might be weird and have a non-uppercase INBOX. It
  1243. // may legitimately do so, but we need the canonical spelling.
  1244. memcpy( arg, "INBOX", 5 );
  1245. } else if ((l = strlen( ctx->prefix ))) {
  1246. if (!starts_with( arg, argl, ctx->prefix, l ))
  1247. return LIST_OK;
  1248. arg += l;
  1249. argl -= l;
  1250. // A folder named "INBOX" would be indistinguishable from the
  1251. // actual INBOX after prefix stripping, so drop it. This applies
  1252. // only to the fully uppercased spelling, as our canonical box
  1253. // names are case-sensitive (unlike IMAP's INBOX).
  1254. if (is_INBOX( ctx, arg, argl )) {
  1255. if (!arg[5]) // No need to complain about subfolders as well.
  1256. warn( "IMAP warning: ignoring INBOX in %s\n", ctx->prefix );
  1257. return LIST_OK;
  1258. }
  1259. }
  1260. if (argl >= 5 && !memcmp( arg + argl - 5, ".lock", 5 )) /* workaround broken servers */
  1261. return LIST_OK;
  1262. if (map_name( arg, (char **)&narg, offsetof(string_list_t, string), ctx->delimiter, "/") < 0) {
  1263. warn( "IMAP warning: ignoring mailbox %s (reserved character '/' in name)\n", arg );
  1264. return LIST_OK;
  1265. }
  1266. narg->next = ctx->boxes;
  1267. ctx->boxes = narg;
  1268. return LIST_OK;
  1269. }
  1270. static int
  1271. prepare_name( char **buf, const imap_store_t *ctx, const char *prefix, const char *name )
  1272. {
  1273. uint pl = strlen( prefix );
  1274. switch (map_name( name, buf, pl, "/", ctx->delimiter )) {
  1275. case -1:
  1276. error( "IMAP error: mailbox name %s contains server's hierarchy delimiter\n", name );
  1277. return -1;
  1278. case -2:
  1279. error( "IMAP error: server's hierarchy delimiter not known\n" );
  1280. return -1;
  1281. default:
  1282. memcpy( *buf, prefix, pl );
  1283. return 0;
  1284. }
  1285. }
  1286. static int
  1287. prepare_box( char **buf, const imap_store_t *ctx )
  1288. {
  1289. const char *name = ctx->name;
  1290. const char *pfx = ctx->prefix;
  1291. if (starts_with_upper( name, -1, "INBOX", 5 ) && (!name[5] || name[5] == '/')) {
  1292. if (!memcmp( name, "INBOX", 5 )) {
  1293. pfx = "";
  1294. } else if (!*pfx) {
  1295. error( "IMAP error: cannot use unqualified '%s'. Did you mean INBOX?", name );
  1296. return -1;
  1297. }
  1298. }
  1299. return prepare_name( buf, ctx, pfx, name );
  1300. }
  1301. static int
  1302. prepare_trash( char **buf, const imap_store_t *ctx )
  1303. {
  1304. return prepare_name( buf, ctx, ctx->prefix, ctx->gen.conf->trash );
  1305. }
  1306. typedef struct {
  1307. imap_cmd_t gen;
  1308. imap_cmd_t *orig_cmd;
  1309. } imap_cmd_trycreate_t;
  1310. static void imap_open_store_greeted( imap_store_t * );
  1311. static void get_cmd_result_p2( imap_store_t *, imap_cmd_t *, int );
  1312. static void
  1313. imap_socket_read( void *aux )
  1314. {
  1315. imap_store_t *ctx = (imap_store_t *)aux;
  1316. imap_cmd_t *cmdp, **pcmdp;
  1317. char *cmd, *arg, *arg1, *p;
  1318. int resp, resp2, tag;
  1319. conn_iovec_t iov[2];
  1320. for (;;) {
  1321. if (ctx->parse_list_sts.level) {
  1322. resp = parse_list_continue( ctx, NULL );
  1323. listret:
  1324. if (resp == LIST_PARTIAL)
  1325. return;
  1326. if (resp == LIST_BAD)
  1327. break;
  1328. continue;
  1329. }
  1330. if (!(cmd = socket_read_line( &ctx->conn )))
  1331. return;
  1332. if (cmd == (void *)~0) {
  1333. if (!ctx->expectEOF)
  1334. error( "IMAP error: unexpected EOF from %s\n", ctx->conn.name );
  1335. /* A clean shutdown sequence ends with bad_callback as well (see imap_cleanup()). */
  1336. break;
  1337. }
  1338. if (DFlags & DEBUG_NET) {
  1339. printf( "%s%s\n", ctx->label, cmd );
  1340. fflush( stdout );
  1341. }
  1342. arg = next_arg( &cmd );
  1343. if (!arg) {
  1344. error( "IMAP error: empty response\n" );
  1345. break;
  1346. }
  1347. if (*arg == '*') {
  1348. arg = next_arg( &cmd );
  1349. if (!arg) {
  1350. error( "IMAP error: malformed untagged response\n" );
  1351. break;
  1352. }
  1353. if (ctx->greeting == GreetingPending && !strcmp( "PREAUTH", arg )) {
  1354. parse_response_code( ctx, NULL, cmd );
  1355. ctx->greeting = GreetingPreauth;
  1356. dogreet:
  1357. imap_ref( ctx );
  1358. imap_open_store_greeted( ctx );
  1359. if (imap_deref( ctx ))
  1360. return;
  1361. } else if (!strcmp( "OK", arg )) {
  1362. parse_response_code( ctx, NULL, cmd );
  1363. if (ctx->greeting == GreetingPending) {
  1364. ctx->greeting = GreetingOk;
  1365. goto dogreet;
  1366. }
  1367. } else if (!strcmp( "BYE", arg )) {
  1368. if (!ctx->expectBYE) {
  1369. ctx->greeting = GreetingBad;
  1370. error( "IMAP error: unexpected BYE response: %s\n", cmd );
  1371. /* We just wait for the server to close the connection now. */
  1372. ctx->expectEOF = 1;
  1373. } else {
  1374. /* We still need to wait for the LOGOUT's tagged OK. */
  1375. }
  1376. } else if (ctx->greeting == GreetingPending) {
  1377. error( "IMAP error: bogus greeting response %s\n", arg );
  1378. break;
  1379. } else if (!strcmp( "NO", arg )) {
  1380. warn( "Warning from IMAP server: %s\n", cmd );
  1381. } else if (!strcmp( "BAD", arg )) {
  1382. error( "Error from IMAP server: %s\n", cmd );
  1383. } else if (!strcmp( "CAPABILITY", arg )) {
  1384. parse_capability( ctx, cmd );
  1385. } else if (!strcmp( "LIST", arg ) || !strcmp( "LSUB", arg )) {
  1386. resp = parse_list( ctx, cmd, parse_list_rsp );
  1387. goto listret;
  1388. } else if (!strcmp( "NAMESPACE", arg )) {
  1389. resp = parse_list( ctx, cmd, parse_namespace_rsp );
  1390. goto listret;
  1391. } else if ((arg1 = next_arg( &cmd ))) {
  1392. if (!strcmp( "EXISTS", arg1 ))
  1393. ctx->total_msgs = atoi( arg );
  1394. else if (!strcmp( "RECENT", arg1 ))
  1395. ctx->recent_msgs = atoi( arg );
  1396. else if(!strcmp ( "FETCH", arg1 )) {
  1397. resp = parse_list( ctx, cmd, parse_fetch_rsp );
  1398. goto listret;
  1399. }
  1400. } else {
  1401. error( "IMAP error: unrecognized untagged response '%s'\n", arg );
  1402. break; /* this may mean anything, so prefer not to spam the log */
  1403. }
  1404. continue;
  1405. } else if (!ctx->in_progress) {
  1406. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  1407. break; /* this may mean anything, so prefer not to spam the log */
  1408. } else if (*arg == '+') {
  1409. socket_expect_activity( &ctx->conn, 0 );
  1410. /* There can be any number of commands in flight, but only the last
  1411. * one can require a continuation, as it enforces a round-trip. */
  1412. cmdp = (imap_cmd_t *)((char *)ctx->in_progress_append -
  1413. offsetof(imap_cmd_t, next));
  1414. if (cmdp->param.data) {
  1415. if (cmdp->param.to_trash)
  1416. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1417. if (DFlags & DEBUG_NET_ALL) {
  1418. printf( "%s>>>>>>>>>\n", ctx->label );
  1419. fwrite( cmdp->param.data, cmdp->param.data_len, 1, stdout );
  1420. printf( "%s>>>>>>>>>\n", ctx->label );
  1421. fflush( stdout );
  1422. }
  1423. iov[0].buf = cmdp->param.data;
  1424. iov[0].len = cmdp->param.data_len;
  1425. iov[0].takeOwn = GiveOwn;
  1426. cmdp->param.data = NULL;
  1427. ctx->buffer_mem -= cmdp->param.data_len;
  1428. iov[1].buf = "\r\n";
  1429. iov[1].len = 2;
  1430. iov[1].takeOwn = KeepOwn;
  1431. socket_write( &ctx->conn, iov, 2 );
  1432. } else if (cmdp->param.cont) {
  1433. if (cmdp->param.cont( ctx, cmdp, cmd ))
  1434. return;
  1435. } else {
  1436. error( "IMAP error: unexpected command continuation request\n" );
  1437. break;
  1438. }
  1439. socket_expect_activity( &ctx->conn, 1 );
  1440. } else {
  1441. tag = atoi( arg );
  1442. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  1443. if (cmdp->tag == tag)
  1444. goto gottag;
  1445. error( "IMAP error: unexpected tag %s\n", arg );
  1446. break;
  1447. gottag:
  1448. if (!(*pcmdp = cmdp->next))
  1449. ctx->in_progress_append = pcmdp;
  1450. if (!--ctx->num_in_progress)
  1451. socket_expect_activity( &ctx->conn, 0 );
  1452. arg = next_arg( &cmd );
  1453. if (!arg) {
  1454. error( "IMAP error: malformed tagged response\n" );
  1455. break;
  1456. }
  1457. if (!strcmp( "OK", arg )) {
  1458. if (cmdp->param.to_trash)
  1459. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1460. resp = RESP_OK;
  1461. } else {
  1462. if (!strcmp( "NO", arg )) {
  1463. if (cmdp->param.create && cmd && starts_with( cmd, -1, "[TRYCREATE]", 11 )) { /* APPEND or UID COPY */
  1464. imap_cmd_trycreate_t *cmd2 =
  1465. (imap_cmd_trycreate_t *)new_imap_cmd( sizeof(*cmd2) );
  1466. cmd2->orig_cmd = cmdp;
  1467. cmd2->gen.param.high_prio = 1;
  1468. p = strchr( cmdp->cmd, '"' );
  1469. imap_exec( ctx, &cmd2->gen, get_cmd_result_p2,
  1470. "CREATE %.*s", imap_strchr( p + 1, '"' ) - p + 1, p );
  1471. continue;
  1472. }
  1473. resp = RESP_NO;
  1474. if (cmdp->param.failok)
  1475. goto doresp;
  1476. } else /*if (!strcmp( "BAD", arg ))*/
  1477. resp = RESP_CANCEL;
  1478. error( "IMAP command '%s' returned an error: %s %s\n",
  1479. starts_with( cmdp->cmd, -1, "LOGIN", 5 ) ?
  1480. "LOGIN <user> <pass>" :
  1481. starts_with( cmdp->cmd, -1, "AUTHENTICATE PLAIN", 18 ) ?
  1482. "AUTHENTICATE PLAIN <authdata>" :
  1483. cmdp->cmd,
  1484. arg, cmd ? cmd : "" );
  1485. }
  1486. doresp:
  1487. if ((resp2 = parse_response_code( ctx, cmdp, cmd )) > resp)
  1488. resp = resp2;
  1489. imap_ref( ctx );
  1490. if (resp == RESP_CANCEL)
  1491. imap_invoke_bad_callback( ctx );
  1492. if (resp == RESP_OK && cmdp->param.wait_check) {
  1493. cmdp->next = NULL;
  1494. *ctx->wait_check_append = cmdp;
  1495. ctx->wait_check_append = &cmdp->next;
  1496. } else {
  1497. done_imap_cmd( ctx, cmdp, resp );
  1498. }
  1499. if (imap_deref( ctx ))
  1500. return;
  1501. if (ctx->canceling && !ctx->in_progress) {
  1502. ctx->canceling = 0;
  1503. ctx->callbacks.imap_cancel( ctx->callback_aux );
  1504. return;
  1505. }
  1506. }
  1507. flush_imap_cmds( ctx );
  1508. }
  1509. imap_invoke_bad_callback( ctx );
  1510. }
  1511. static void
  1512. get_cmd_result_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  1513. {
  1514. imap_cmd_trycreate_t *cmdp = (imap_cmd_trycreate_t *)cmd;
  1515. imap_cmd_t *ocmd = cmdp->orig_cmd;
  1516. if (response != RESP_OK) {
  1517. done_imap_cmd( ctx, ocmd, response );
  1518. } else {
  1519. assert( !ocmd->param.wait_check );
  1520. ctx->uidnext = 1;
  1521. if (ocmd->param.to_trash)
  1522. ctx->trashnc = TrashKnown;
  1523. ocmd->param.create = 0;
  1524. ocmd->param.high_prio = 1;
  1525. submit_imap_cmd( ctx, ocmd );
  1526. }
  1527. }
  1528. /******************* imap_cancel_store *******************/
  1529. static void
  1530. imap_cancel_store( store_t *gctx )
  1531. {
  1532. imap_store_t *ctx = (imap_store_t *)gctx;
  1533. #ifdef HAVE_LIBSASL
  1534. sasl_dispose( &ctx->sasl );
  1535. #endif
  1536. socket_close( &ctx->conn );
  1537. finalize_checked_imap_cmds( ctx, RESP_CANCEL );
  1538. cancel_sent_imap_cmds( ctx );
  1539. cancel_pending_imap_cmds( ctx );
  1540. free( ctx->ns_prefix );
  1541. free_string_list( ctx->auth_mechs );
  1542. free_generic_messages( ctx->msgs );
  1543. free_string_list( ctx->boxes );
  1544. imap_deref( ctx );
  1545. }
  1546. static int
  1547. imap_deref( imap_store_t *ctx )
  1548. {
  1549. if (!--ctx->ref_count) {
  1550. free( ctx );
  1551. return -1;
  1552. }
  1553. return 0;
  1554. }
  1555. static void
  1556. imap_set_bad_callback( store_t *gctx, void (*cb)( void *aux ), void *aux )
  1557. {
  1558. imap_store_t *ctx = (imap_store_t *)gctx;
  1559. ctx->bad_callback = cb;
  1560. ctx->bad_callback_aux = aux;
  1561. }
  1562. static void
  1563. imap_invoke_bad_callback( imap_store_t *ctx )
  1564. {
  1565. ctx->bad_callback( ctx->bad_callback_aux );
  1566. }
  1567. /******************* imap_free_store *******************/
  1568. static store_t *unowned;
  1569. static void
  1570. imap_cancel_unowned( void *gctx )
  1571. {
  1572. store_t *store, **storep;
  1573. for (storep = &unowned; (store = *storep); storep = &store->next)
  1574. if (store == gctx) {
  1575. *storep = store->next;
  1576. break;
  1577. }
  1578. imap_cancel_store( gctx );
  1579. }
  1580. static void
  1581. imap_free_store( store_t *gctx )
  1582. {
  1583. imap_store_t *ctx = (imap_store_t *)gctx;
  1584. assert( !ctx->pending && !ctx->in_progress && !ctx->wait_check );
  1585. free_generic_messages( ctx->msgs );
  1586. ctx->msgs = NULL;
  1587. imap_set_bad_callback( gctx, imap_cancel_unowned, gctx );
  1588. gctx->next = unowned;
  1589. unowned = gctx;
  1590. }
  1591. /******************* imap_cleanup *******************/
  1592. static void imap_cleanup_p2( imap_store_t *, imap_cmd_t *, int );
  1593. static void
  1594. imap_cleanup( void )
  1595. {
  1596. store_t *ctx, *nctx;
  1597. for (ctx = unowned; ctx; ctx = nctx) {
  1598. nctx = ctx->next;
  1599. imap_set_bad_callback( ctx, (void (*)(void *))imap_cancel_store, ctx );
  1600. if (((imap_store_t *)ctx)->state != SST_BAD) {
  1601. ((imap_store_t *)ctx)->expectBYE = 1;
  1602. imap_exec( (imap_store_t *)ctx, NULL, imap_cleanup_p2, "LOGOUT" );
  1603. } else {
  1604. imap_cancel_store( ctx );
  1605. }
  1606. }
  1607. }
  1608. static void
  1609. imap_cleanup_p2( imap_store_t *ctx,
  1610. imap_cmd_t *cmd ATTR_UNUSED, int response )
  1611. {
  1612. if (response == RESP_NO)
  1613. imap_cancel_store( &ctx->gen );
  1614. else if (response == RESP_OK)
  1615. ctx->expectEOF = 1;
  1616. }
  1617. /******************* imap_open_store *******************/
  1618. static void imap_open_store_connected( int, void * );
  1619. #ifdef HAVE_LIBSSL
  1620. static void imap_open_store_tlsstarted1( int, void * );
  1621. #endif
  1622. static void imap_open_store_p2( imap_store_t *, imap_cmd_t *, int );
  1623. static void imap_open_store_authenticate( imap_store_t * );
  1624. #ifdef HAVE_LIBSSL
  1625. static void imap_open_store_authenticate_p2( imap_store_t *, imap_cmd_t *, int );
  1626. static void imap_open_store_tlsstarted2( int, void * );
  1627. static void imap_open_store_authenticate_p3( imap_store_t *, imap_cmd_t *, int );
  1628. #endif
  1629. static void imap_open_store_authenticate2( imap_store_t * );
  1630. static void imap_open_store_authenticate2_p2( imap_store_t *, imap_cmd_t *, int );
  1631. static void imap_open_store_compress( imap_store_t * );
  1632. #ifdef HAVE_LIBZ
  1633. static void imap_open_store_compress_p2( imap_store_t *, imap_cmd_t *, int );
  1634. #endif
  1635. static void imap_open_store_namespace( imap_store_t * );
  1636. static void imap_open_store_namespace_p2( imap_store_t *, imap_cmd_t *, int );
  1637. static void imap_open_store_namespace2( imap_store_t * );
  1638. static void imap_open_store_finalize( imap_store_t * );
  1639. #ifdef HAVE_LIBSSL
  1640. static void imap_open_store_ssl_bail( imap_store_t * );
  1641. #endif
  1642. static void imap_open_store_bail( imap_store_t *, int );
  1643. static store_t *
  1644. imap_alloc_store( store_conf_t *conf, const char *label )
  1645. {
  1646. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1647. imap_server_conf_t *srvc = cfg->server;
  1648. imap_store_t *ctx;
  1649. store_t **ctxp;
  1650. /* First try to recycle a whole store. */
  1651. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1652. if (ctx->state == SST_GOOD && ctx->gen.conf == conf) {
  1653. *ctxp = ctx->gen.next;
  1654. ctx->label = label;
  1655. return &ctx->gen;
  1656. }
  1657. /* Then try to recycle a server connection. */
  1658. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1659. if (ctx->state != SST_BAD && ((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1660. *ctxp = ctx->gen.next;
  1661. free_string_list( ctx->boxes );
  1662. ctx->boxes = NULL;
  1663. ctx->listed = 0;
  1664. /* One could ping the server here, but given that the idle timeout
  1665. * is at least 30 minutes, this sounds pretty pointless. */
  1666. ctx->state = SST_HALF;
  1667. goto gotsrv;
  1668. }
  1669. /* Finally, schedule opening a new server connection. */
  1670. ctx = nfcalloc( sizeof(*ctx) );
  1671. ctx->gen.driver = &imap_driver;
  1672. ctx->ref_count = 1;
  1673. socket_init( &ctx->conn, &srvc->sconf,
  1674. (void (*)( void * ))imap_invoke_bad_callback,
  1675. imap_socket_read, (void (*)(void *))flush_imap_cmds, ctx );
  1676. ctx->in_progress_append = &ctx->in_progress;
  1677. ctx->pending_append = &ctx->pending;
  1678. ctx->wait_check_append = &ctx->wait_check;
  1679. gotsrv:
  1680. ctx->gen.conf = conf;
  1681. ctx->label = label;
  1682. return &ctx->gen;
  1683. }
  1684. static void
  1685. imap_connect_store( store_t *gctx,
  1686. void (*cb)( int sts, void *aux ), void *aux )
  1687. {
  1688. imap_store_t *ctx = (imap_store_t *)gctx;
  1689. if (ctx->state == SST_GOOD) {
  1690. cb( DRV_OK, aux );
  1691. } else {
  1692. ctx->callbacks.imap_open = cb;
  1693. ctx->callback_aux = aux;
  1694. if (ctx->state == SST_HALF)
  1695. imap_open_store_namespace( ctx );
  1696. else
  1697. socket_connect( &ctx->conn, imap_open_store_connected );
  1698. }
  1699. }
  1700. static void
  1701. imap_open_store_connected( int ok, void *aux )
  1702. {
  1703. imap_store_t *ctx = (imap_store_t *)aux;
  1704. #ifdef HAVE_LIBSSL
  1705. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1706. imap_server_conf_t *srvc = cfg->server;
  1707. #endif
  1708. if (!ok)
  1709. imap_open_store_bail( ctx, FAIL_WAIT );
  1710. #ifdef HAVE_LIBSSL
  1711. else if (srvc->ssl_type == SSL_IMAPS)
  1712. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted1 );
  1713. #endif
  1714. else
  1715. socket_expect_activity( &ctx->conn, 1 );
  1716. }
  1717. #ifdef HAVE_LIBSSL
  1718. static void
  1719. imap_open_store_tlsstarted1( int ok, void *aux )
  1720. {
  1721. imap_store_t *ctx = (imap_store_t *)aux;
  1722. if (!ok)
  1723. imap_open_store_ssl_bail( ctx );
  1724. else
  1725. socket_expect_activity( &ctx->conn, 1 );
  1726. }
  1727. #endif
  1728. static void
  1729. imap_open_store_greeted( imap_store_t *ctx )
  1730. {
  1731. socket_expect_activity( &ctx->conn, 0 );
  1732. if (!ctx->caps)
  1733. imap_exec( ctx, NULL, imap_open_store_p2, "CAPABILITY" );
  1734. else
  1735. imap_open_store_authenticate( ctx );
  1736. }
  1737. static void
  1738. imap_open_store_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1739. {
  1740. if (response == RESP_NO)
  1741. imap_open_store_bail( ctx, FAIL_FINAL );
  1742. else if (response == RESP_OK)
  1743. imap_open_store_authenticate( ctx );
  1744. }
  1745. static void
  1746. imap_open_store_authenticate( imap_store_t *ctx )
  1747. {
  1748. #ifdef HAVE_LIBSSL
  1749. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1750. imap_server_conf_t *srvc = cfg->server;
  1751. #endif
  1752. if (ctx->greeting != GreetingPreauth) {
  1753. #ifdef HAVE_LIBSSL
  1754. if (srvc->ssl_type == SSL_STARTTLS) {
  1755. if (CAP(STARTTLS)) {
  1756. imap_exec( ctx, NULL, imap_open_store_authenticate_p2, "STARTTLS" );
  1757. return;
  1758. } else {
  1759. error( "IMAP error: SSL support not available\n" );
  1760. imap_open_store_bail( ctx, FAIL_FINAL );
  1761. return;
  1762. }
  1763. }
  1764. #endif
  1765. imap_open_store_authenticate2( ctx );
  1766. } else {
  1767. #ifdef HAVE_LIBSSL
  1768. if (srvc->ssl_type == SSL_STARTTLS) {
  1769. error( "IMAP error: SSL support not available\n" );
  1770. imap_open_store_bail( ctx, FAIL_FINAL );
  1771. return;
  1772. }
  1773. #endif
  1774. imap_open_store_compress( ctx );
  1775. }
  1776. }
  1777. #ifdef HAVE_LIBSSL
  1778. static void
  1779. imap_open_store_authenticate_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1780. {
  1781. if (response == RESP_NO)
  1782. imap_open_store_bail( ctx, FAIL_FINAL );
  1783. else if (response == RESP_OK)
  1784. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted2 );
  1785. }
  1786. static void
  1787. imap_open_store_tlsstarted2( int ok, void *aux )
  1788. {
  1789. imap_store_t *ctx = (imap_store_t *)aux;
  1790. if (!ok)
  1791. imap_open_store_ssl_bail( ctx );
  1792. else
  1793. imap_exec( ctx, NULL, imap_open_store_authenticate_p3, "CAPABILITY" );
  1794. }
  1795. static void
  1796. imap_open_store_authenticate_p3( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1797. {
  1798. if (response == RESP_NO)
  1799. imap_open_store_bail( ctx, FAIL_FINAL );
  1800. else if (response == RESP_OK)
  1801. imap_open_store_authenticate2( ctx );
  1802. }
  1803. #endif
  1804. static char *
  1805. cred_from_cmd( const char *cred, const char *cmd, const char *srv_name )
  1806. {
  1807. FILE *fp;
  1808. int ret;
  1809. char buffer[8192]; // Hopefully more than enough room for XOAUTH2, etc. tokens
  1810. if (*cmd == '+') {
  1811. flushn();
  1812. cmd++;
  1813. }
  1814. if (!(fp = popen( cmd, "r" ))) {
  1815. pipeerr:
  1816. sys_error( "Skipping account %s, %s failed", srv_name, cred );
  1817. return NULL;
  1818. }
  1819. if (!fgets( buffer, sizeof(buffer), fp ))
  1820. buffer[0] = 0;
  1821. if ((ret = pclose( fp )) < 0)
  1822. goto pipeerr;
  1823. if (ret) {
  1824. if (WIFSIGNALED( ret ))
  1825. error( "Skipping account %s, %s crashed\n", srv_name, cred );
  1826. else
  1827. error( "Skipping account %s, %s exited with status %d\n", srv_name, cred, WEXITSTATUS( ret ) );
  1828. return NULL;
  1829. }
  1830. if (!buffer[0]) {
  1831. error( "Skipping account %s, %s produced no output\n", srv_name, cred );
  1832. return NULL;
  1833. }
  1834. buffer[strcspn( buffer, "\n" )] = 0; /* Strip trailing newline */
  1835. return nfstrdup( buffer );
  1836. }
  1837. static const char *
  1838. ensure_user( imap_server_conf_t *srvc )
  1839. {
  1840. if (!srvc->user) {
  1841. if (srvc->user_cmd) {
  1842. srvc->user = cred_from_cmd( "UserCmd", srvc->user_cmd, srvc->name );
  1843. } else {
  1844. error( "Skipping account %s, no user\n", srvc->name );
  1845. }
  1846. }
  1847. return srvc->user;
  1848. }
  1849. static const char *
  1850. ensure_password( imap_server_conf_t *srvc )
  1851. {
  1852. if (!srvc->pass) {
  1853. if (srvc->pass_cmd) {
  1854. srvc->pass = cred_from_cmd( "PassCmd", srvc->pass_cmd, srvc->name );
  1855. #ifdef HAVE_MACOS_KEYCHAIN
  1856. } else if (srvc->use_keychain) {
  1857. void *password_data;
  1858. UInt32 password_length;
  1859. OSStatus ret = SecKeychainFindInternetPassword(
  1860. NULL, // keychainOrArray
  1861. strlen( srvc->sconf.host ), srvc->sconf.host,
  1862. 0, NULL, // securityDomain
  1863. strlen( srvc->user ), srvc->user,
  1864. 0, NULL, // path
  1865. 0, // port - we could use it, but it seems pointless
  1866. kSecProtocolTypeIMAP,
  1867. kSecAuthenticationTypeDefault,
  1868. &password_length, &password_data,
  1869. NULL ); // itemRef
  1870. if (ret != errSecSuccess) {
  1871. CFStringRef errmsg = SecCopyErrorMessageString( ret, NULL );
  1872. error( "Looking up Keychain failed: %s\n",
  1873. CFStringGetCStringPtr( errmsg, kCFStringEncodingUTF8 ) );
  1874. CFRelease( errmsg );
  1875. return NULL;
  1876. }
  1877. srvc->pass = nfstrndup( password_data, password_length );
  1878. SecKeychainItemFreeContent( NULL, password_data );
  1879. #endif /* HAVE_MACOS_KEYCHAIN */
  1880. } else {
  1881. flushn();
  1882. char prompt[80];
  1883. sprintf( prompt, "Password (%s): ", srvc->name );
  1884. char *pass = getpass( prompt );
  1885. if (!pass) {
  1886. perror( "getpass" );
  1887. exit( 1 );
  1888. }
  1889. if (!*pass) {
  1890. error( "Skipping account %s, no password\n", srvc->name );
  1891. return NULL;
  1892. }
  1893. /* getpass() returns a pointer to a static buffer. Make a copy for long term storage. */
  1894. srvc->pass = nfstrdup( pass );
  1895. }
  1896. }
  1897. return srvc->pass;
  1898. }
  1899. #ifdef HAVE_LIBSASL
  1900. static sasl_callback_t sasl_callbacks[] = {
  1901. { SASL_CB_USER, NULL, NULL },
  1902. { SASL_CB_AUTHNAME, NULL, NULL },
  1903. { SASL_CB_PASS, NULL, NULL },
  1904. { SASL_CB_LIST_END, NULL, NULL }
  1905. };
  1906. static int
  1907. process_sasl_interact( sasl_interact_t *interact, imap_server_conf_t *srvc )
  1908. {
  1909. const char *val;
  1910. for (;; ++interact) {
  1911. switch (interact->id) {
  1912. case SASL_CB_LIST_END:
  1913. return 0;
  1914. case SASL_CB_USER:
  1915. case SASL_CB_AUTHNAME:
  1916. val = ensure_user( srvc );
  1917. break;
  1918. case SASL_CB_PASS:
  1919. val = ensure_password( srvc );
  1920. break;
  1921. default:
  1922. error( "Error: Unknown SASL interaction ID\n" );
  1923. return -1;
  1924. }
  1925. if (!val)
  1926. return -1;
  1927. interact->result = val;
  1928. interact->len = strlen( val );
  1929. }
  1930. }
  1931. static int
  1932. process_sasl_step( imap_store_t *ctx, int rc, const char *in, uint in_len,
  1933. sasl_interact_t *interact, const char **out, uint *out_len )
  1934. {
  1935. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1936. while (rc == SASL_INTERACT) {
  1937. if (process_sasl_interact( interact, srvc ) < 0)
  1938. return -1;
  1939. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, out, out_len );
  1940. }
  1941. if (rc == SASL_CONTINUE) {
  1942. ctx->sasl_cont = 1;
  1943. } else if (rc == SASL_OK) {
  1944. ctx->sasl_cont = 0;
  1945. } else {
  1946. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  1947. return -1;
  1948. }
  1949. return 0;
  1950. }
  1951. static int
  1952. decode_sasl_data( const char *prompt, char **in, uint *in_len )
  1953. {
  1954. if (prompt) {
  1955. int rc;
  1956. uint prompt_len = strlen( prompt );
  1957. /* We're decoding, the output will be shorter than prompt_len. */
  1958. *in = nfmalloc( prompt_len );
  1959. rc = sasl_decode64( prompt, prompt_len, *in, prompt_len, in_len );
  1960. if (rc != SASL_OK) {
  1961. free( *in );
  1962. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1963. return -1;
  1964. }
  1965. } else {
  1966. *in = NULL;
  1967. *in_len = 0;
  1968. }
  1969. return 0;
  1970. }
  1971. static int
  1972. encode_sasl_data( const char *out, uint out_len, char **enc, uint *enc_len )
  1973. {
  1974. int rc;
  1975. uint enc_len_max = ((out_len + 2) / 3) * 4 + 1;
  1976. *enc = nfmalloc( enc_len_max );
  1977. rc = sasl_encode64( out, out_len, *enc, enc_len_max, enc_len );
  1978. if (rc != SASL_OK) {
  1979. free( *enc );
  1980. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1981. return -1;
  1982. }
  1983. return 0;
  1984. }
  1985. static int
  1986. do_sasl_auth( imap_store_t *ctx, imap_cmd_t *cmdp ATTR_UNUSED, const char *prompt )
  1987. {
  1988. int rc, ret, iovcnt = 0;
  1989. uint in_len, out_len, enc_len;
  1990. const char *out;
  1991. char *in, *enc;
  1992. sasl_interact_t *interact = NULL;
  1993. conn_iovec_t iov[2];
  1994. if (!ctx->sasl_cont) {
  1995. error( "Error: IMAP wants more steps despite successful SASL authentication.\n" );
  1996. goto bail;
  1997. }
  1998. if (decode_sasl_data( prompt, &in, &in_len ) < 0)
  1999. goto bail;
  2000. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, &out, &out_len );
  2001. ret = process_sasl_step( ctx, rc, in, in_len, interact, &out, &out_len );
  2002. free( in );
  2003. if (ret < 0)
  2004. goto bail;
  2005. if (out) {
  2006. if (encode_sasl_data( out, out_len, &enc, &enc_len ) < 0)
  2007. goto bail;
  2008. iov[0].buf = enc;
  2009. iov[0].len = enc_len;
  2010. iov[0].takeOwn = GiveOwn;
  2011. iovcnt = 1;
  2012. if (DFlags & DEBUG_NET) {
  2013. printf( "%s>+> %s\n", ctx->label, enc );
  2014. fflush( stdout );
  2015. }
  2016. } else {
  2017. if (DFlags & DEBUG_NET) {
  2018. printf( "%s>+>\n", ctx->label );
  2019. fflush( stdout );
  2020. }
  2021. }
  2022. iov[iovcnt].buf = "\r\n";
  2023. iov[iovcnt].len = 2;
  2024. iov[iovcnt].takeOwn = KeepOwn;
  2025. iovcnt++;
  2026. socket_write( &ctx->conn, iov, iovcnt );
  2027. return 0;
  2028. bail:
  2029. imap_open_store_bail( ctx, FAIL_FINAL );
  2030. return -1;
  2031. }
  2032. static void
  2033. done_sasl_auth( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2034. {
  2035. if (response == RESP_OK && ctx->sasl_cont) {
  2036. sasl_interact_t *interact = NULL;
  2037. const char *out;
  2038. uint out_len;
  2039. int rc = sasl_client_step( ctx->sasl, NULL, 0, &interact, &out, &out_len );
  2040. if (process_sasl_step( ctx, rc, NULL, 0, interact, &out, &out_len ) < 0)
  2041. warn( "Warning: SASL reported failure despite successful IMAP authentication. Ignoring...\n" );
  2042. else if (out_len > 0)
  2043. warn( "Warning: SASL wants more steps despite successful IMAP authentication. Ignoring...\n" );
  2044. }
  2045. imap_open_store_authenticate2_p2( ctx, NULL, response );
  2046. }
  2047. #endif
  2048. static void
  2049. imap_open_store_authenticate2( imap_store_t *ctx )
  2050. {
  2051. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2052. imap_server_conf_t *srvc = cfg->server;
  2053. string_list_t *mech, *cmech;
  2054. int auth_login = 0;
  2055. int skipped_login = 0;
  2056. #ifdef HAVE_LIBSASL
  2057. const char *saslavail;
  2058. char saslmechs[1024], *saslend = saslmechs;
  2059. #endif
  2060. // Ensure that there are no leftovers from previous runs. This is needed in case
  2061. // the credentials have a timing dependency or otherwise lose validity after use.
  2062. if (srvc->user_cmd) {
  2063. free( srvc->user );
  2064. srvc->user = NULL;
  2065. }
  2066. if (srvc->pass_cmd) {
  2067. free( srvc->pass );
  2068. srvc->pass = NULL;
  2069. }
  2070. info( "Logging in...\n" );
  2071. for (mech = srvc->auth_mechs; mech; mech = mech->next) {
  2072. int any = !strcmp( mech->string, "*" );
  2073. for (cmech = ctx->auth_mechs; cmech; cmech = cmech->next) {
  2074. if (any || !strcasecmp( mech->string, cmech->string )) {
  2075. if (!strcasecmp( cmech->string, "LOGIN" )) {
  2076. #ifdef HAVE_LIBSSL
  2077. if (ctx->conn.ssl || !any)
  2078. #else
  2079. if (!any)
  2080. #endif
  2081. auth_login = 1;
  2082. else
  2083. skipped_login = 1;
  2084. #ifdef HAVE_LIBSASL
  2085. } else {
  2086. uint len = strlen( cmech->string );
  2087. if (saslend + len + 2 > saslmechs + sizeof(saslmechs))
  2088. oob();
  2089. *saslend++ = ' ';
  2090. memcpy( saslend, cmech->string, len + 1 );
  2091. saslend += len;
  2092. #endif
  2093. }
  2094. }
  2095. }
  2096. }
  2097. #ifdef HAVE_LIBSASL
  2098. if (saslend != saslmechs) {
  2099. int rc;
  2100. uint out_len = 0;
  2101. char *enc = NULL;
  2102. const char *gotmech = NULL, *out = NULL;
  2103. sasl_interact_t *interact = NULL;
  2104. imap_cmd_t *cmd;
  2105. static int sasl_inited;
  2106. if (!sasl_inited) {
  2107. rc = sasl_client_init( sasl_callbacks );
  2108. if (rc != SASL_OK) {
  2109. saslbail:
  2110. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  2111. goto bail;
  2112. }
  2113. sasl_inited = 1;
  2114. }
  2115. rc = sasl_client_new( "imap", srvc->sconf.host, NULL, NULL, NULL, 0, &ctx->sasl );
  2116. if (rc != SASL_OK) {
  2117. if (rc == SASL_NOMECH)
  2118. goto notsasl;
  2119. if (!ctx->sasl)
  2120. goto saslbail;
  2121. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  2122. goto bail;
  2123. }
  2124. rc = sasl_client_start( ctx->sasl, saslmechs + 1, &interact, CAP(SASLIR) ? &out : NULL, &out_len, &gotmech );
  2125. if (rc == SASL_NOMECH)
  2126. goto notsasl;
  2127. if (gotmech)
  2128. info( "Authenticating with SASL mechanism %s...\n", gotmech );
  2129. /* Technically, we are supposed to loop over sasl_client_start(),
  2130. * but it just calls sasl_client_step() anyway. */
  2131. if (process_sasl_step( ctx, rc, NULL, 0, interact, CAP(SASLIR) ? &out : NULL, &out_len ) < 0)
  2132. goto bail;
  2133. if (out) {
  2134. if (!out_len)
  2135. enc = nfstrdup( "=" ); /* A zero-length initial response is encoded as padding. */
  2136. else if (encode_sasl_data( out, out_len, &enc, NULL ) < 0)
  2137. goto bail;
  2138. }
  2139. cmd = new_imap_cmd( sizeof(*cmd) );
  2140. cmd->param.cont = do_sasl_auth;
  2141. imap_exec( ctx, cmd, done_sasl_auth, enc ? "AUTHENTICATE %s %s" : "AUTHENTICATE %s", gotmech, enc );
  2142. free( enc );
  2143. return;
  2144. notsasl:
  2145. if (!ctx->sasl || sasl_listmech( ctx->sasl, NULL, "", " ", "", &saslavail, NULL, NULL ) != SASL_OK)
  2146. saslavail = "(none)"; /* EXTERNAL is always there anyway. */
  2147. if (!auth_login) {
  2148. error( "IMAP error: selected SASL mechanism(s) not available;\n"
  2149. " selected:%s\n available: %s\n", saslmechs, saslavail );
  2150. goto skipnote;
  2151. }
  2152. info( "NOT using available SASL mechanism(s): %s\n", saslavail );
  2153. sasl_dispose( &ctx->sasl );
  2154. }
  2155. #endif
  2156. if (auth_login) {
  2157. if (!ensure_user( srvc ) || !ensure_password( srvc ))
  2158. goto bail;
  2159. #ifdef HAVE_LIBSSL
  2160. if (!ctx->conn.ssl)
  2161. #endif
  2162. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  2163. imap_exec( ctx, NULL, imap_open_store_authenticate2_p2,
  2164. "LOGIN \"%\\s\" \"%\\s\"", srvc->user, srvc->pass );
  2165. return;
  2166. }
  2167. error( "IMAP error: server supports no acceptable authentication mechanism\n" );
  2168. #ifdef HAVE_LIBSASL
  2169. skipnote:
  2170. #endif
  2171. if (skipped_login)
  2172. error( "Note: not using LOGIN because connection is not encrypted;\n"
  2173. " use 'AuthMechs LOGIN' explicitly to force it.\n" );
  2174. bail:
  2175. imap_open_store_bail( ctx, FAIL_FINAL );
  2176. }
  2177. static void
  2178. imap_open_store_authenticate2_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2179. {
  2180. if (response == RESP_NO)
  2181. imap_open_store_bail( ctx, FAIL_FINAL );
  2182. else if (response == RESP_OK)
  2183. imap_open_store_compress( ctx );
  2184. }
  2185. static void
  2186. imap_open_store_compress( imap_store_t *ctx )
  2187. {
  2188. #ifdef HAVE_LIBZ
  2189. if (CAP(COMPRESS_DEFLATE)) {
  2190. imap_exec( ctx, NULL, imap_open_store_compress_p2, "COMPRESS DEFLATE" );
  2191. return;
  2192. }
  2193. #endif
  2194. imap_open_store_namespace( ctx );
  2195. }
  2196. #ifdef HAVE_LIBZ
  2197. static void
  2198. imap_open_store_compress_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2199. {
  2200. if (response == RESP_NO) {
  2201. /* We already reported an error, but it's not fatal to us. */
  2202. imap_open_store_namespace( ctx );
  2203. } else if (response == RESP_OK) {
  2204. socket_start_deflate( &ctx->conn );
  2205. imap_open_store_namespace( ctx );
  2206. }
  2207. }
  2208. #endif
  2209. static void
  2210. imap_open_store_namespace( imap_store_t *ctx )
  2211. {
  2212. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2213. ctx->state = SST_HALF;
  2214. ctx->prefix = cfg->gen.path;
  2215. ctx->delimiter[0] = cfg->delimiter;
  2216. if (((!ctx->prefix && cfg->use_namespace) || !cfg->delimiter) && CAP(NAMESPACE)) {
  2217. /* get NAMESPACE info */
  2218. if (!ctx->got_namespace)
  2219. imap_exec( ctx, NULL, imap_open_store_namespace_p2, "NAMESPACE" );
  2220. else
  2221. imap_open_store_namespace2( ctx );
  2222. return;
  2223. }
  2224. imap_open_store_finalize( ctx );
  2225. }
  2226. static void
  2227. imap_open_store_namespace_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2228. {
  2229. if (response == RESP_NO) {
  2230. imap_open_store_bail( ctx, FAIL_FINAL );
  2231. } else if (response == RESP_OK) {
  2232. ctx->got_namespace = 1;
  2233. imap_open_store_namespace2( ctx );
  2234. }
  2235. }
  2236. static void
  2237. imap_open_store_namespace2( imap_store_t *ctx )
  2238. {
  2239. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2240. if (!ctx->prefix && cfg->use_namespace)
  2241. ctx->prefix = ctx->ns_prefix;
  2242. if (!ctx->delimiter[0])
  2243. ctx->delimiter[0] = ctx->ns_delimiter;
  2244. imap_open_store_finalize( ctx );
  2245. }
  2246. static void
  2247. imap_open_store_finalize( imap_store_t *ctx )
  2248. {
  2249. ctx->state = SST_GOOD;
  2250. if (!ctx->prefix)
  2251. ctx->prefix = "";
  2252. ctx->trashnc = TrashUnknown;
  2253. ctx->callbacks.imap_open( DRV_OK, ctx->callback_aux );
  2254. }
  2255. #ifdef HAVE_LIBSSL
  2256. static void
  2257. imap_open_store_ssl_bail( imap_store_t *ctx )
  2258. {
  2259. /* This avoids that we try to send LOGOUT to an unusable socket. */
  2260. socket_close( &ctx->conn );
  2261. imap_open_store_bail( ctx, FAIL_FINAL );
  2262. }
  2263. #endif
  2264. static void
  2265. imap_open_store_bail( imap_store_t *ctx, int failed )
  2266. {
  2267. ((imap_store_conf_t *)ctx->gen.conf)->server->failed = (char)failed;
  2268. ctx->callbacks.imap_open( DRV_STORE_BAD, ctx->callback_aux );
  2269. }
  2270. /******************* imap_open_box *******************/
  2271. static int
  2272. imap_select_box( store_t *gctx, const char *name )
  2273. {
  2274. imap_store_t *ctx = (imap_store_t *)gctx;
  2275. assert( !ctx->pending && !ctx->in_progress && !ctx->wait_check );
  2276. free_generic_messages( ctx->msgs );
  2277. ctx->msgs = NULL;
  2278. ctx->msgapp = &ctx->msgs;
  2279. ctx->name = name;
  2280. return DRV_OK;
  2281. }
  2282. static const char *
  2283. imap_get_box_path( store_t *gctx ATTR_UNUSED )
  2284. {
  2285. return NULL;
  2286. }
  2287. typedef struct {
  2288. imap_cmd_t gen;
  2289. void (*callback)( int sts, uint uidvalidity, void *aux );
  2290. void *callback_aux;
  2291. } imap_cmd_open_box_t;
  2292. static void imap_open_box_p2( imap_store_t *, imap_cmd_t *, int );
  2293. static void imap_open_box_p3( imap_store_t *, imap_cmd_t *, int );
  2294. static void imap_open_box_p4( imap_store_t *, imap_cmd_open_box_t *, int );
  2295. static void
  2296. imap_open_box( store_t *gctx,
  2297. void (*cb)( int sts, uint uidvalidity, void *aux ), void *aux )
  2298. {
  2299. imap_store_t *ctx = (imap_store_t *)gctx;
  2300. imap_cmd_open_box_t *cmd;
  2301. char *buf;
  2302. if (prepare_box( &buf, ctx ) < 0) {
  2303. cb( DRV_BOX_BAD, UIDVAL_BAD, aux );
  2304. return;
  2305. }
  2306. ctx->uidvalidity = UIDVAL_BAD;
  2307. ctx->uidnext = 0;
  2308. INIT_IMAP_CMD(imap_cmd_open_box_t, cmd, cb, aux)
  2309. cmd->gen.param.failok = 1;
  2310. imap_exec( ctx, &cmd->gen, imap_open_box_p2,
  2311. "SELECT \"%\\s\"", buf );
  2312. free( buf );
  2313. }
  2314. static void
  2315. imap_open_box_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2316. {
  2317. imap_cmd_open_box_t *cmdp = (imap_cmd_open_box_t *)gcmd;
  2318. imap_cmd_open_box_t *cmd;
  2319. if (response != RESP_OK || ctx->uidnext) {
  2320. imap_open_box_p4( ctx, cmdp, response );
  2321. return;
  2322. }
  2323. INIT_IMAP_CMD(imap_cmd_open_box_t, cmd, cmdp->callback, cmdp->callback_aux)
  2324. cmd->gen.param.lastuid = 1;
  2325. imap_exec( ctx, &cmd->gen, imap_open_box_p3,
  2326. "UID FETCH * (UID)" );
  2327. }
  2328. static void
  2329. imap_open_box_p3( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2330. {
  2331. imap_cmd_open_box_t *cmdp = (imap_cmd_open_box_t *)gcmd;
  2332. if (!ctx->uidnext) {
  2333. if (ctx->total_msgs) {
  2334. error( "IMAP error: querying server for highest UID failed\n" );
  2335. imap_open_box_p4( ctx, cmdp, RESP_NO );
  2336. return;
  2337. }
  2338. // This is ok, the box is simply empty.
  2339. ctx->uidnext = 1;
  2340. }
  2341. imap_open_box_p4( ctx, cmdp, response );
  2342. }
  2343. static void
  2344. imap_open_box_p4( imap_store_t *ctx, imap_cmd_open_box_t *cmdp, int response )
  2345. {
  2346. transform_box_response( &response );
  2347. cmdp->callback( response, ctx->uidvalidity, cmdp->callback_aux );
  2348. }
  2349. static uint
  2350. imap_get_uidnext( store_t *gctx )
  2351. {
  2352. imap_store_t *ctx = (imap_store_t *)gctx;
  2353. return ctx->uidnext;
  2354. }
  2355. static xint
  2356. imap_get_supported_flags( store_t *gctx )
  2357. {
  2358. imap_store_t *ctx = (imap_store_t *)gctx;
  2359. return ctx->has_forwarded ? 255 : (255 & ~F_FORWARDED);
  2360. }
  2361. /******************* imap_create_box *******************/
  2362. static void
  2363. imap_create_box( store_t *gctx,
  2364. void (*cb)( int sts, void *aux ), void *aux )
  2365. {
  2366. imap_store_t *ctx = (imap_store_t *)gctx;
  2367. imap_cmd_simple_t *cmd;
  2368. char *buf;
  2369. if (prepare_box( &buf, ctx ) < 0) {
  2370. cb( DRV_BOX_BAD, aux );
  2371. return;
  2372. }
  2373. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2374. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  2375. "CREATE \"%\\s\"", buf );
  2376. free( buf );
  2377. }
  2378. /******************* imap_delete_box *******************/
  2379. static int
  2380. imap_confirm_box_empty( store_t *gctx )
  2381. {
  2382. imap_store_t *ctx = (imap_store_t *)gctx;
  2383. return ctx->total_msgs ? DRV_BOX_BAD : DRV_OK;
  2384. }
  2385. static void imap_delete_box_p2( imap_store_t *, imap_cmd_t *, int );
  2386. static void
  2387. imap_delete_box( store_t *gctx,
  2388. void (*cb)( int sts, void *aux ), void *aux )
  2389. {
  2390. imap_store_t *ctx = (imap_store_t *)gctx;
  2391. imap_cmd_simple_t *cmd;
  2392. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2393. imap_exec( ctx, &cmd->gen, imap_delete_box_p2, "CLOSE" );
  2394. }
  2395. static void
  2396. imap_delete_box_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2397. {
  2398. imap_cmd_simple_t *cmdp = (imap_cmd_simple_t *)gcmd;
  2399. imap_cmd_simple_t *cmd;
  2400. char *buf;
  2401. if (response != RESP_OK) {
  2402. imap_done_simple_box( ctx, &cmdp->gen, response );
  2403. return;
  2404. }
  2405. if (prepare_box( &buf, ctx ) < 0) {
  2406. imap_done_simple_box( ctx, &cmdp->gen, RESP_NO );
  2407. return;
  2408. }
  2409. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cmdp->callback, cmdp->callback_aux)
  2410. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  2411. "DELETE \"%\\s\"", buf );
  2412. free( buf );
  2413. }
  2414. static int
  2415. imap_finish_delete_box( store_t *gctx ATTR_UNUSED )
  2416. {
  2417. return DRV_OK;
  2418. }
  2419. /******************* imap_load_box *******************/
  2420. static uint
  2421. imap_prepare_load_box( store_t *gctx, uint opts )
  2422. {
  2423. imap_store_t *ctx = (imap_store_t *)gctx;
  2424. ctx->opts = opts;
  2425. return opts;
  2426. }
  2427. enum { WantSize = 1, WantTuids = 2, WantMsgids = 4 };
  2428. typedef struct {
  2429. uint first, last;
  2430. int flags;
  2431. } imap_range_t;
  2432. static void
  2433. imap_set_range( imap_range_t *ranges, uint *nranges, int low_flags, int high_flags, uint maxlow )
  2434. {
  2435. if (low_flags != high_flags) {
  2436. for (uint r = 0; r < *nranges; r++) {
  2437. if (ranges[r].first > maxlow)
  2438. break; /* Range starts above split point; so do all subsequent ranges. */
  2439. if (ranges[r].last < maxlow)
  2440. continue; /* Range ends below split point; try next one. */
  2441. if (ranges[r].last != maxlow) {
  2442. /* Range does not end exactly at split point; need to split. */
  2443. memmove( &ranges[r + 1], &ranges[r], ((*nranges)++ - r) * sizeof(*ranges) );
  2444. ranges[r].last = maxlow;
  2445. ranges[r + 1].first = maxlow + 1;
  2446. }
  2447. break;
  2448. }
  2449. }
  2450. for (uint r = 0; r < *nranges; r++)
  2451. ranges[r].flags |= (ranges[r].last <= maxlow) ? low_flags : high_flags;
  2452. }
  2453. typedef struct {
  2454. imap_cmd_refcounted_state_t gen;
  2455. void (*callback)( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux );
  2456. void *callback_aux;
  2457. } imap_load_box_state_t;
  2458. static void imap_submit_load( imap_store_t *, const char *, int, imap_load_box_state_t * );
  2459. static void imap_submit_load_p3( imap_store_t *ctx, imap_load_box_state_t * );
  2460. static void
  2461. imap_load_box( store_t *gctx, uint minuid, uint maxuid, uint finduid, uint pairuid, uint newuid, uint_array_t excs,
  2462. void (*cb)( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux ), void *aux )
  2463. {
  2464. imap_store_t *ctx = (imap_store_t *)gctx;
  2465. char buf[1000];
  2466. if (!ctx->total_msgs) {
  2467. free( excs.data );
  2468. cb( DRV_OK, NULL, 0, 0, aux );
  2469. } else {
  2470. INIT_REFCOUNTED_STATE(imap_load_box_state_t, sts, cb, aux)
  2471. for (uint i = 0; i < excs.size; ) {
  2472. for (int bl = 0; i < excs.size && bl < 960; i++) {
  2473. if (bl)
  2474. buf[bl++] = ',';
  2475. bl += sprintf( buf + bl, "%u", excs.data[i] );
  2476. uint j = i;
  2477. for (; i + 1 < excs.size && excs.data[i + 1] == excs.data[i] + 1; i++) {}
  2478. if (i != j)
  2479. bl += sprintf( buf + bl, ":%u", excs.data[i] );
  2480. }
  2481. imap_submit_load( ctx, buf, shifted_bit( ctx->opts, OPEN_OLD_IDS, WantMsgids ), sts );
  2482. }
  2483. if (maxuid == UINT_MAX)
  2484. maxuid = ctx->uidnext - 1;
  2485. if (maxuid >= minuid) {
  2486. imap_range_t ranges[3];
  2487. ranges[0].first = minuid;
  2488. ranges[0].last = maxuid;
  2489. ranges[0].flags = 0;
  2490. uint nranges = 1;
  2491. if (ctx->opts & OPEN_NEW_SIZE)
  2492. imap_set_range( ranges, &nranges, 0, WantSize, newuid );
  2493. if (ctx->opts & OPEN_FIND)
  2494. imap_set_range( ranges, &nranges, 0, WantTuids, finduid - 1 );
  2495. if (ctx->opts & OPEN_OLD_IDS)
  2496. imap_set_range( ranges, &nranges, WantMsgids, 0, pairuid );
  2497. for (uint r = 0; r < nranges; r++) {
  2498. sprintf( buf, "%u:%u", ranges[r].first, ranges[r].last );
  2499. imap_submit_load( ctx, buf, ranges[r].flags, sts );
  2500. }
  2501. }
  2502. free( excs.data );
  2503. imap_submit_load_p3( ctx, sts );
  2504. }
  2505. }
  2506. static int
  2507. imap_sort_msgs_comp( const void *a_, const void *b_ )
  2508. {
  2509. const message_t *a = *(const message_t * const *)a_;
  2510. const message_t *b = *(const message_t * const *)b_;
  2511. if (a->uid < b->uid)
  2512. return -1;
  2513. if (a->uid > b->uid)
  2514. return 1;
  2515. return 0;
  2516. }
  2517. static void
  2518. imap_sort_msgs( imap_store_t *ctx )
  2519. {
  2520. uint count = count_generic_messages( ctx->msgs );
  2521. if (count <= 1)
  2522. return;
  2523. message_t **t = nfmalloc( sizeof(*t) * count );
  2524. message_t *m = ctx->msgs;
  2525. for (uint i = 0; i < count; i++) {
  2526. t[i] = m;
  2527. m = m->next;
  2528. }
  2529. qsort( t, count, sizeof(*t), imap_sort_msgs_comp );
  2530. ctx->msgs = t[0];
  2531. uint j;
  2532. for (j = 0; j < count - 1; j++)
  2533. t[j]->next = t[j + 1];
  2534. ctx->msgapp = &t[j]->next;
  2535. *ctx->msgapp = NULL;
  2536. free( t );
  2537. }
  2538. static void imap_submit_load_p2( imap_store_t *, imap_cmd_t *, int );
  2539. static void
  2540. imap_submit_load( imap_store_t *ctx, const char *buf, int flags, imap_load_box_state_t *sts )
  2541. {
  2542. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_submit_load_p2,
  2543. "UID FETCH %s (UID%s%s%s%s%s%s%s)", buf,
  2544. (ctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  2545. (flags & WantSize) ? " RFC822.SIZE" : "",
  2546. (flags & (WantTuids | WantMsgids)) ? " BODY.PEEK[HEADER.FIELDS (" : "",
  2547. (flags & WantTuids) ? "X-TUID" : "",
  2548. !(~flags & (WantTuids | WantMsgids)) ? " " : "",
  2549. (flags & WantMsgids) ? "MESSAGE-ID" : "",
  2550. (flags & (WantTuids | WantMsgids)) ? ")]" : "");
  2551. }
  2552. static void
  2553. imap_submit_load_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  2554. {
  2555. imap_load_box_state_t *sts = (imap_load_box_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2556. transform_refcounted_box_response( &sts->gen, response );
  2557. imap_submit_load_p3( ctx, sts );
  2558. }
  2559. static void
  2560. imap_submit_load_p3( imap_store_t *ctx, imap_load_box_state_t *sts )
  2561. {
  2562. DONE_REFCOUNTED_STATE_ARGS(sts, {
  2563. if (sts->gen.ret_val == DRV_OK)
  2564. imap_sort_msgs( ctx );
  2565. }, ctx->msgs, ctx->total_msgs, ctx->recent_msgs)
  2566. }
  2567. /******************* imap_fetch_msg *******************/
  2568. static void imap_fetch_msg_p2( imap_store_t *, imap_cmd_t *, int );
  2569. static void
  2570. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data, int minimal,
  2571. void (*cb)( int sts, void *aux ), void *aux )
  2572. {
  2573. imap_cmd_fetch_msg_t *cmd;
  2574. INIT_IMAP_CMD_X(imap_cmd_fetch_msg_t, cmd, cb, aux)
  2575. cmd->gen.gen.param.uid = msg->uid;
  2576. cmd->msg_data = data;
  2577. data->data = NULL;
  2578. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_fetch_msg_p2,
  2579. "UID FETCH %u (%s%sBODY.PEEK[%s])", msg->uid,
  2580. !(msg->status & M_FLAGS) ? "FLAGS " : "",
  2581. (data->date== -1) ? "INTERNALDATE " : "",
  2582. minimal ? "HEADER" : "" );
  2583. }
  2584. static void
  2585. imap_fetch_msg_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2586. {
  2587. imap_cmd_fetch_msg_t *cmd = (imap_cmd_fetch_msg_t *)gcmd;
  2588. if (response == RESP_OK && !cmd->msg_data->data) {
  2589. /* The FETCH succeeded, but there is no message with this UID. */
  2590. response = RESP_NO;
  2591. }
  2592. imap_done_simple_msg( ctx, gcmd, response );
  2593. }
  2594. /******************* imap_set_msg_flags *******************/
  2595. static uint
  2596. imap_make_flags( int flags, char *buf )
  2597. {
  2598. const char *s;
  2599. uint i, d;
  2600. for (i = d = 0; i < as(Flags); i++)
  2601. if (flags & (1 << i)) {
  2602. buf[d++] = ' ';
  2603. for (s = Flags[i]; *s; s++)
  2604. buf[d++] = *s;
  2605. }
  2606. buf[0] = '(';
  2607. buf[d++] = ')';
  2608. return d;
  2609. }
  2610. typedef struct {
  2611. imap_cmd_refcounted_state_t gen;
  2612. void (*callback)( int sts, void *aux );
  2613. void *callback_aux;
  2614. } imap_set_msg_flags_state_t;
  2615. static void imap_set_flags_p2( imap_store_t *, imap_cmd_t *, int );
  2616. static void imap_set_flags_p3( imap_set_msg_flags_state_t * );
  2617. static void
  2618. imap_flags_helper( imap_store_t *ctx, uint uid, char what, int flags,
  2619. imap_set_msg_flags_state_t *sts )
  2620. {
  2621. char buf[256];
  2622. buf[imap_make_flags( flags, buf )] = 0;
  2623. imap_cmd_t *cmd = imap_refcounted_new_cmd( &sts->gen );
  2624. cmd->param.wait_check = 1;
  2625. imap_exec( ctx, cmd, imap_set_flags_p2,
  2626. "UID STORE %u %cFLAGS.SILENT %s", uid, what, buf );
  2627. }
  2628. static void
  2629. imap_set_msg_flags( store_t *gctx, message_t *msg, uint uid, int add, int del,
  2630. void (*cb)( int sts, void *aux ), void *aux )
  2631. {
  2632. imap_store_t *ctx = (imap_store_t *)gctx;
  2633. if (msg) {
  2634. uid = msg->uid;
  2635. add &= ~msg->flags;
  2636. del &= msg->flags;
  2637. msg->flags |= add;
  2638. msg->flags &= ~del;
  2639. }
  2640. if (add || del) {
  2641. INIT_REFCOUNTED_STATE(imap_set_msg_flags_state_t, sts, cb, aux)
  2642. if (add)
  2643. imap_flags_helper( ctx, uid, '+', add, sts );
  2644. if (del)
  2645. imap_flags_helper( ctx, uid, '-', del, sts );
  2646. imap_set_flags_p3( sts );
  2647. } else {
  2648. cb( DRV_OK, aux );
  2649. }
  2650. }
  2651. static void
  2652. imap_set_flags_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2653. {
  2654. imap_set_msg_flags_state_t *sts = (imap_set_msg_flags_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2655. transform_refcounted_msg_response( &sts->gen, response);
  2656. imap_set_flags_p3( sts );
  2657. }
  2658. static void
  2659. imap_set_flags_p3( imap_set_msg_flags_state_t *sts )
  2660. {
  2661. DONE_REFCOUNTED_STATE(sts)
  2662. }
  2663. /******************* imap_close_box *******************/
  2664. typedef struct {
  2665. imap_cmd_refcounted_state_t gen;
  2666. void (*callback)( int sts, void *aux );
  2667. void *callback_aux;
  2668. } imap_expunge_state_t;
  2669. static void imap_close_box_p2( imap_store_t *, imap_cmd_t *, int );
  2670. static void imap_close_box_p3( imap_expunge_state_t * );
  2671. static void
  2672. imap_close_box( store_t *gctx,
  2673. void (*cb)( int sts, void *aux ), void *aux )
  2674. {
  2675. imap_store_t *ctx = (imap_store_t *)gctx;
  2676. assert( !ctx->num_wait_check );
  2677. if (ctx->gen.conf->trash && CAP(UIDPLUS)) {
  2678. INIT_REFCOUNTED_STATE(imap_expunge_state_t, sts, cb, aux)
  2679. message_t *msg, *fmsg, *nmsg;
  2680. int bl;
  2681. char buf[1000];
  2682. for (msg = ctx->msgs; ; ) {
  2683. for (bl = 0; msg && bl < 960; msg = msg->next) {
  2684. if (!(msg->flags & F_DELETED))
  2685. continue;
  2686. if (bl)
  2687. buf[bl++] = ',';
  2688. bl += sprintf( buf + bl, "%u", msg->uid );
  2689. fmsg = msg;
  2690. for (; (nmsg = msg->next) && (nmsg->flags & F_DELETED); msg = nmsg) {}
  2691. if (msg != fmsg)
  2692. bl += sprintf( buf + bl, ":%u", msg->uid );
  2693. }
  2694. if (!bl)
  2695. break;
  2696. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_close_box_p2,
  2697. "UID EXPUNGE %s", buf );
  2698. }
  2699. imap_close_box_p3( sts );
  2700. } else {
  2701. /* This is inherently racy: it may cause messages which other clients
  2702. * marked as deleted to be expunged without being trashed. */
  2703. imap_cmd_simple_t *cmd;
  2704. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2705. imap_exec( ctx, &cmd->gen, imap_done_simple_box, "CLOSE" );
  2706. }
  2707. }
  2708. static void
  2709. imap_close_box_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2710. {
  2711. imap_expunge_state_t *sts = (imap_expunge_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2712. transform_refcounted_box_response( &sts->gen, response );
  2713. imap_close_box_p3( sts );
  2714. }
  2715. static void
  2716. imap_close_box_p3( imap_expunge_state_t *sts )
  2717. {
  2718. DONE_REFCOUNTED_STATE(sts)
  2719. }
  2720. /******************* imap_trash_msg *******************/
  2721. static void
  2722. imap_trash_msg( store_t *gctx, message_t *msg,
  2723. void (*cb)( int sts, void *aux ), void *aux )
  2724. {
  2725. imap_store_t *ctx = (imap_store_t *)gctx;
  2726. imap_cmd_simple_t *cmd;
  2727. char *buf;
  2728. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2729. cmd->gen.param.create = 1;
  2730. cmd->gen.param.to_trash = 1;
  2731. if (prepare_trash( &buf, ctx ) < 0) {
  2732. cb( DRV_BOX_BAD, aux );
  2733. return;
  2734. }
  2735. imap_exec( ctx, &cmd->gen, imap_done_simple_msg,
  2736. CAP(MOVE) ? "UID MOVE %u \"%\\s\"" : "UID COPY %u \"%\\s\"", msg->uid, buf );
  2737. free( buf );
  2738. }
  2739. /******************* imap_store_msg *******************/
  2740. static void imap_store_msg_p2( imap_store_t *, imap_cmd_t *, int );
  2741. static void
  2742. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  2743. void (*cb)( int sts, uint uid, void *aux ), void *aux )
  2744. {
  2745. imap_store_t *ctx = (imap_store_t *)gctx;
  2746. imap_cmd_out_uid_t *cmd;
  2747. char *buf;
  2748. uint d;
  2749. char flagstr[128], datestr[64];
  2750. d = 0;
  2751. if (data->flags) {
  2752. d = imap_make_flags( data->flags, flagstr );
  2753. flagstr[d++] = ' ';
  2754. }
  2755. flagstr[d] = 0;
  2756. INIT_IMAP_CMD(imap_cmd_out_uid_t, cmd, cb, aux)
  2757. ctx->buffer_mem += data->len;
  2758. cmd->gen.param.data_len = data->len;
  2759. cmd->gen.param.data = data->data;
  2760. cmd->out_uid = 0;
  2761. if (to_trash) {
  2762. cmd->gen.param.create = 1;
  2763. cmd->gen.param.to_trash = 1;
  2764. if (prepare_trash( &buf, ctx ) < 0) {
  2765. cb( DRV_BOX_BAD, 0, aux );
  2766. return;
  2767. }
  2768. } else {
  2769. if (prepare_box( &buf, ctx ) < 0) {
  2770. cb( DRV_BOX_BAD, 0, aux );
  2771. return;
  2772. }
  2773. }
  2774. if (data->date) {
  2775. /* configure ensures that %z actually works. */
  2776. DIAG_PUSH
  2777. DIAG_DISABLE("-Wformat")
  2778. strftime( datestr, sizeof(datestr), "%d-%b-%Y %H:%M:%S %z", localtime( &data->date ) );
  2779. DIAG_POP
  2780. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2781. "APPEND \"%\\s\" %s\"%\\s\" ", buf, flagstr, datestr );
  2782. } else {
  2783. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2784. "APPEND \"%\\s\" %s", buf, flagstr );
  2785. }
  2786. free( buf );
  2787. }
  2788. static void
  2789. imap_store_msg_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2790. {
  2791. imap_cmd_out_uid_t *cmdp = (imap_cmd_out_uid_t *)cmd;
  2792. transform_msg_response( &response );
  2793. cmdp->callback( response, cmdp->out_uid, cmdp->callback_aux );
  2794. }
  2795. /******************* imap_find_new_msgs *******************/
  2796. static void imap_find_new_msgs_p2( imap_store_t *, imap_cmd_t *, int );
  2797. static void imap_find_new_msgs_p3( imap_store_t *, imap_cmd_t *, int );
  2798. static void imap_find_new_msgs_p4( imap_store_t *, imap_cmd_t *, int );
  2799. static void
  2800. imap_find_new_msgs( store_t *gctx, uint newuid,
  2801. void (*cb)( int sts, message_t *msgs, void *aux ), void *aux )
  2802. {
  2803. imap_store_t *ctx = (imap_store_t *)gctx;
  2804. imap_cmd_find_new_t *cmd;
  2805. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cb, aux)
  2806. cmd->out_msgs = ctx->msgapp;
  2807. cmd->uid = newuid;
  2808. // Some servers fail to enumerate recently STOREd messages without syncing first.
  2809. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_find_new_msgs_p2, "CHECK" );
  2810. }
  2811. static void
  2812. imap_find_new_msgs_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2813. {
  2814. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2815. imap_cmd_find_new_t *cmd;
  2816. if (response != RESP_OK) {
  2817. imap_done_simple_box( ctx, gcmd, response );
  2818. return;
  2819. }
  2820. // We appended messages, so we need to re-query UIDNEXT.
  2821. ctx->uidnext = 0;
  2822. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cmdp->callback, cmdp->callback_aux)
  2823. cmd->out_msgs = cmdp->out_msgs;
  2824. cmd->uid = cmdp->uid;
  2825. cmd->gen.param.lastuid = 1;
  2826. imap_exec( ctx, &cmd->gen, imap_find_new_msgs_p3,
  2827. "UID FETCH * (UID)" );
  2828. }
  2829. static void
  2830. imap_find_new_msgs_p3( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2831. {
  2832. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2833. imap_cmd_find_new_t *cmd;
  2834. if (response != RESP_OK) {
  2835. imap_find_new_msgs_p4( ctx, gcmd, response );
  2836. return;
  2837. }
  2838. if (!ctx->uidnext) {
  2839. // We are assuming that the new messages were not in fact instantly deleted.
  2840. error( "IMAP error: re-querying server for highest UID failed\n" );
  2841. imap_find_new_msgs_p4( ctx, gcmd, RESP_NO );
  2842. return;
  2843. }
  2844. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cmdp->callback, cmdp->callback_aux)
  2845. cmd->out_msgs = cmdp->out_msgs;
  2846. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_find_new_msgs_p4,
  2847. "UID FETCH %u:%u (UID BODY.PEEK[HEADER.FIELDS (X-TUID)])", cmdp->uid, ctx->uidnext - 1 );
  2848. }
  2849. static void
  2850. imap_find_new_msgs_p4( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *gcmd, int response )
  2851. {
  2852. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2853. transform_box_response( &response );
  2854. cmdp->callback( response, *cmdp->out_msgs, cmdp->callback_aux );
  2855. }
  2856. /******************* imap_list_store *******************/
  2857. typedef struct {
  2858. imap_cmd_refcounted_state_t gen;
  2859. void (*callback)( int sts, string_list_t *, void *aux );
  2860. void *callback_aux;
  2861. } imap_list_store_state_t;
  2862. static void imap_list_store_p2( imap_store_t *, imap_cmd_t *, int );
  2863. static void imap_list_store_p3( imap_store_t *, imap_list_store_state_t * );
  2864. static void
  2865. imap_list_store( store_t *gctx, int flags,
  2866. void (*cb)( int sts, string_list_t *boxes, void *aux ), void *aux )
  2867. {
  2868. imap_store_t *ctx = (imap_store_t *)gctx;
  2869. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2870. INIT_REFCOUNTED_STATE(imap_list_store_state_t, sts, cb, aux)
  2871. // ctx->prefix may be empty, "INBOX.", or something else.
  2872. // 'flags' may be LIST_INBOX, LIST_PATH (or LIST_PATH_MAYBE), or both. 'listed'
  2873. // already containing a particular value effectively removes it from 'flags'.
  2874. // This matrix determines what to query, and what comes out as a side effect.
  2875. // The lowercase letters indicate unnecessary results; the queries are done
  2876. // this way to have non-overlapping result sets, so subsequent calls create
  2877. // no duplicates:
  2878. //
  2879. // qry \ pfx | empty | inbox | other
  2880. // ----------+-------+-------+-------
  2881. // inbox | p [I] | I [p] | I
  2882. // both | P [I] | I [P] | I + P
  2883. // path | P [i] | i [P] | P
  2884. //
  2885. int pfx_is_empty = !*ctx->prefix;
  2886. int pfx_is_inbox = !pfx_is_empty && is_inbox( ctx, ctx->prefix, -1 );
  2887. if (((flags & (LIST_PATH | LIST_PATH_MAYBE)) || pfx_is_empty) && !pfx_is_inbox && !(ctx->listed & LIST_PATH)) {
  2888. ctx->listed |= LIST_PATH;
  2889. if (pfx_is_empty)
  2890. ctx->listed |= LIST_INBOX;
  2891. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_list_store_p2,
  2892. "%s \"\" \"%\\s*\"", cfg->use_lsub ? "LSUB" : "LIST", ctx->prefix );
  2893. }
  2894. if (((flags & LIST_INBOX) || pfx_is_inbox) && !pfx_is_empty && !(ctx->listed & LIST_INBOX)) {
  2895. ctx->listed |= LIST_INBOX;
  2896. if (pfx_is_inbox)
  2897. ctx->listed |= LIST_PATH;
  2898. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_list_store_p2,
  2899. "%s \"\" INBOX*", cfg->use_lsub ? "LSUB" : "LIST" );
  2900. }
  2901. imap_list_store_p3( ctx, sts );
  2902. }
  2903. static void
  2904. imap_list_store_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  2905. {
  2906. imap_list_store_state_t *sts = (imap_list_store_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2907. transform_refcounted_box_response( &sts->gen, response );
  2908. imap_list_store_p3( ctx, sts );
  2909. }
  2910. static void
  2911. imap_list_store_p3( imap_store_t *ctx, imap_list_store_state_t *sts )
  2912. {
  2913. DONE_REFCOUNTED_STATE_ARGS(sts, , ctx->boxes)
  2914. }
  2915. /******************* imap_cancel_cmds *******************/
  2916. static void
  2917. imap_cancel_cmds( store_t *gctx,
  2918. void (*cb)( void *aux ), void *aux )
  2919. {
  2920. imap_store_t *ctx = (imap_store_t *)gctx;
  2921. finalize_checked_imap_cmds( ctx, RESP_CANCEL );
  2922. cancel_pending_imap_cmds( ctx );
  2923. if (ctx->in_progress) {
  2924. ctx->canceling = 1;
  2925. ctx->callbacks.imap_cancel = cb;
  2926. ctx->callback_aux = aux;
  2927. } else {
  2928. cb( aux );
  2929. }
  2930. }
  2931. /******************* imap_commit_cmds *******************/
  2932. static void imap_commit_cmds_p2( imap_store_t *, imap_cmd_t *, int );
  2933. static void
  2934. imap_commit_cmds( store_t *gctx )
  2935. {
  2936. imap_store_t *ctx = (imap_store_t *)gctx;
  2937. if (ctx->num_wait_check)
  2938. imap_exec( ctx, NULL, imap_commit_cmds_p2, "CHECK" );
  2939. }
  2940. static void
  2941. imap_commit_cmds_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2942. {
  2943. finalize_checked_imap_cmds( ctx, response );
  2944. }
  2945. /******************* imap_get_memory_usage *******************/
  2946. static uint
  2947. imap_get_memory_usage( store_t *gctx )
  2948. {
  2949. imap_store_t *ctx = (imap_store_t *)gctx;
  2950. return ctx->buffer_mem + ctx->conn.buffer_mem;
  2951. }
  2952. /******************* imap_get_fail_state *******************/
  2953. static int
  2954. imap_get_fail_state( store_conf_t *gconf )
  2955. {
  2956. return ((imap_store_conf_t *)gconf)->server->failed;
  2957. }
  2958. /******************* imap_parse_store *******************/
  2959. static imap_server_conf_t *servers, **serverapp = &servers;
  2960. static int
  2961. imap_parse_store( conffile_t *cfg, store_conf_t **storep )
  2962. {
  2963. imap_store_conf_t *store;
  2964. imap_server_conf_t *server, *srv, sserver;
  2965. const char *type, *name, *arg;
  2966. unsigned u;
  2967. int acc_opt = 0;
  2968. #ifdef HAVE_LIBSSL
  2969. /* Legacy SSL options */
  2970. int require_ssl = -1, use_imaps = -1;
  2971. int use_tlsv1 = -1, use_tlsv11 = -1, use_tlsv12 = -1, use_tlsv13 = -1;
  2972. #endif
  2973. /* Legacy SASL option */
  2974. int require_cram = -1;
  2975. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  2976. server = nfcalloc( sizeof(*server) );
  2977. server->name = nfstrdup( cfg->val );
  2978. *serverapp = server;
  2979. serverapp = &server->next;
  2980. store = NULL;
  2981. *storep = NULL;
  2982. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  2983. store = nfcalloc( sizeof(*store) );
  2984. store->gen.driver = &imap_driver;
  2985. store->gen.name = nfstrdup( cfg->val );
  2986. store->use_namespace = 1;
  2987. *storep = &store->gen;
  2988. memset( &sserver, 0, sizeof(sserver) );
  2989. server = &sserver;
  2990. } else
  2991. return 0;
  2992. server->sconf.timeout = 20;
  2993. #ifdef HAVE_LIBSSL
  2994. server->ssl_type = -1;
  2995. server->sconf.ssl_versions = -1;
  2996. server->sconf.system_certs = 1;
  2997. #endif
  2998. server->max_in_progress = INT_MAX;
  2999. while (getcline( cfg ) && cfg->cmd) {
  3000. if (!strcasecmp( "Host", cfg->cmd )) {
  3001. /* The imap[s]: syntax is just a backwards compat hack. */
  3002. arg = cfg->val;
  3003. #ifdef HAVE_LIBSSL
  3004. if (starts_with( arg, -1, "imaps:", 6 )) {
  3005. arg += 6;
  3006. server->ssl_type = SSL_IMAPS;
  3007. if (server->sconf.ssl_versions == -1)
  3008. server->sconf.ssl_versions = TLSv1 | TLSv1_1 | TLSv1_2 | TLSv1_3;
  3009. } else
  3010. #endif
  3011. if (starts_with( arg, -1, "imap:", 5 ))
  3012. arg += 5;
  3013. if (starts_with( arg, -1, "//", 2 ))
  3014. arg += 2;
  3015. if (arg != cfg->val)
  3016. warn( "%s:%d: Notice: URL notation is deprecated; use a plain host name and possibly 'SSLType IMAPS' instead\n", cfg->file, cfg->line );
  3017. server->sconf.host = nfstrdup( arg );
  3018. }
  3019. else if (!strcasecmp( "User", cfg->cmd ))
  3020. server->user = nfstrdup( cfg->val );
  3021. else if (!strcasecmp( "UserCmd", cfg->cmd ))
  3022. server->user_cmd = nfstrdup( cfg->val );
  3023. else if (!strcasecmp( "Pass", cfg->cmd ))
  3024. server->pass = nfstrdup( cfg->val );
  3025. else if (!strcasecmp( "PassCmd", cfg->cmd ))
  3026. server->pass_cmd = nfstrdup( cfg->val );
  3027. #ifdef HAVE_MACOS_KEYCHAIN
  3028. else if (!strcasecmp( "UseKeychain", cfg->cmd ))
  3029. server->use_keychain = parse_bool( cfg );
  3030. #endif
  3031. else if (!strcasecmp( "Port", cfg->cmd )) {
  3032. int port = parse_int( cfg );
  3033. if ((unsigned)port > 0xffff) {
  3034. error( "%s:%d: Invalid port number\n", cfg->file, cfg->line );
  3035. cfg->err = 1;
  3036. } else {
  3037. server->sconf.port = (ushort)port;
  3038. }
  3039. } else if (!strcasecmp( "Timeout", cfg->cmd ))
  3040. server->sconf.timeout = parse_int( cfg );
  3041. else if (!strcasecmp( "PipelineDepth", cfg->cmd )) {
  3042. if ((server->max_in_progress = parse_int( cfg )) < 1) {
  3043. error( "%s:%d: PipelineDepth must be at least 1\n", cfg->file, cfg->line );
  3044. cfg->err = 1;
  3045. }
  3046. } else if (!strcasecmp( "DisableExtension", cfg->cmd ) ||
  3047. !strcasecmp( "DisableExtensions", cfg->cmd )) {
  3048. arg = cfg->val;
  3049. do {
  3050. for (u = 0; u < as(cap_list); u++) {
  3051. if (!strcasecmp( cap_list[u], arg )) {
  3052. server->cap_mask |= 1 << u;
  3053. goto gotcap;
  3054. }
  3055. }
  3056. error( "%s:%d: Unrecognized IMAP extension '%s'\n", cfg->file, cfg->line, arg );
  3057. cfg->err = 1;
  3058. gotcap: ;
  3059. } while ((arg = get_arg( cfg, ARG_OPTIONAL, NULL )));
  3060. }
  3061. #ifdef HAVE_LIBSSL
  3062. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  3063. server->sconf.cert_file = expand_strdup( cfg->val );
  3064. if (access( server->sconf.cert_file, R_OK )) {
  3065. sys_error( "%s:%d: CertificateFile '%s'",
  3066. cfg->file, cfg->line, server->sconf.cert_file );
  3067. cfg->err = 1;
  3068. }
  3069. } else if (!strcasecmp( "SystemCertificates", cfg->cmd )) {
  3070. server->sconf.system_certs = parse_bool( cfg );
  3071. } else if (!strcasecmp( "ClientCertificate", cfg->cmd )) {
  3072. server->sconf.client_certfile = expand_strdup( cfg->val );
  3073. if (access( server->sconf.client_certfile, R_OK )) {
  3074. sys_error( "%s:%d: ClientCertificate '%s'",
  3075. cfg->file, cfg->line, server->sconf.client_certfile );
  3076. cfg->err = 1;
  3077. }
  3078. } else if (!strcasecmp( "ClientKey", cfg->cmd )) {
  3079. server->sconf.client_keyfile = expand_strdup( cfg->val );
  3080. if (access( server->sconf.client_keyfile, R_OK )) {
  3081. sys_error( "%s:%d: ClientKey '%s'",
  3082. cfg->file, cfg->line, server->sconf.client_keyfile );
  3083. cfg->err = 1;
  3084. }
  3085. } else if (!strcasecmp( "CipherString", cfg->cmd )) {
  3086. server->sconf.cipher_string = nfstrdup( cfg->val );
  3087. } else if (!strcasecmp( "SSLType", cfg->cmd )) {
  3088. if (!strcasecmp( "None", cfg->val )) {
  3089. server->ssl_type = SSL_None;
  3090. } else if (!strcasecmp( "STARTTLS", cfg->val )) {
  3091. server->ssl_type = SSL_STARTTLS;
  3092. } else if (!strcasecmp( "IMAPS", cfg->val )) {
  3093. server->ssl_type = SSL_IMAPS;
  3094. } else {
  3095. error( "%s:%d: Invalid SSL type\n", cfg->file, cfg->line );
  3096. cfg->err = 1;
  3097. }
  3098. } else if (!strcasecmp( "SSLVersion", cfg->cmd ) ||
  3099. !strcasecmp( "SSLVersions", cfg->cmd )) {
  3100. server->sconf.ssl_versions = 0;
  3101. arg = cfg->val;
  3102. do {
  3103. if (!strcasecmp( "SSLv2", arg )) {
  3104. warn( "Warning: SSLVersion SSLv2 is no longer supported\n" );
  3105. } else if (!strcasecmp( "SSLv3", arg )) {
  3106. warn( "Warning: SSLVersion SSLv3 is no longer supported\n" );
  3107. } else if (!strcasecmp( "TLSv1", arg )) {
  3108. server->sconf.ssl_versions |= TLSv1;
  3109. } else if (!strcasecmp( "TLSv1.1", arg )) {
  3110. server->sconf.ssl_versions |= TLSv1_1;
  3111. } else if (!strcasecmp( "TLSv1.2", arg )) {
  3112. server->sconf.ssl_versions |= TLSv1_2;
  3113. } else if (!strcasecmp( "TLSv1.3", arg )) {
  3114. server->sconf.ssl_versions |= TLSv1_3;
  3115. } else {
  3116. error( "%s:%d: Unrecognized SSL version\n", cfg->file, cfg->line );
  3117. cfg->err = 1;
  3118. }
  3119. } while ((arg = get_arg( cfg, ARG_OPTIONAL, NULL )));
  3120. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  3121. require_ssl = parse_bool( cfg );
  3122. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  3123. use_imaps = parse_bool( cfg );
  3124. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  3125. warn( "Warning: UseSSLv2 is no longer supported\n" );
  3126. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  3127. warn( "Warning: UseSSLv3 is no longer supported\n" );
  3128. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  3129. use_tlsv1 = parse_bool( cfg );
  3130. else if (!strcasecmp( "UseTLSv1.1", cfg->cmd ))
  3131. use_tlsv11 = parse_bool( cfg );
  3132. else if (!strcasecmp( "UseTLSv1.2", cfg->cmd ))
  3133. use_tlsv12 = parse_bool( cfg );
  3134. else if (!strcasecmp( "UseTLSv1.3", cfg->cmd ))
  3135. use_tlsv13 = parse_bool( cfg );
  3136. #endif
  3137. else if (!strcasecmp( "AuthMech", cfg->cmd ) ||
  3138. !strcasecmp( "AuthMechs", cfg->cmd )) {
  3139. arg = cfg->val;
  3140. do
  3141. add_string_list( &server->auth_mechs, arg );
  3142. while ((arg = get_arg( cfg, ARG_OPTIONAL, NULL )));
  3143. } else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  3144. require_cram = parse_bool( cfg );
  3145. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  3146. server->sconf.tunnel = nfstrdup( cfg->val );
  3147. else if (store) {
  3148. if (!strcasecmp( "Account", cfg->cmd )) {
  3149. for (srv = servers; srv; srv = srv->next)
  3150. if (srv->name && !strcmp( srv->name, cfg->val ))
  3151. goto gotsrv;
  3152. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  3153. cfg->err = 1;
  3154. continue;
  3155. gotsrv:
  3156. store->server = srv;
  3157. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  3158. store->use_namespace = parse_bool( cfg );
  3159. else if (!strcasecmp( "SubscribedOnly", cfg->cmd ))
  3160. store->use_lsub = parse_bool( cfg );
  3161. else if (!strcasecmp( "Path", cfg->cmd ))
  3162. store->gen.path = nfstrdup( cfg->val );
  3163. else if (!strcasecmp( "PathDelimiter", cfg->cmd )) {
  3164. if (strlen( cfg->val ) != 1) {
  3165. error( "%s:%d: Path delimiter must be exactly one character long\n", cfg->file, cfg->line );
  3166. cfg->err = 1;
  3167. continue;
  3168. }
  3169. store->delimiter = cfg->val[0];
  3170. } else
  3171. parse_generic_store( &store->gen, cfg );
  3172. continue;
  3173. } else {
  3174. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  3175. cfg->err = 1;
  3176. continue;
  3177. }
  3178. acc_opt = 1;
  3179. }
  3180. if (store)
  3181. type = "IMAP store", name = store->gen.name;
  3182. else
  3183. type = "IMAP account", name = server->name;
  3184. if (!store || !store->server) {
  3185. if (!server->sconf.tunnel && !server->sconf.host) {
  3186. error( "%s '%s' has neither Tunnel nor Host\n", type, name );
  3187. cfg->err = 1;
  3188. return 1;
  3189. }
  3190. if (server->user && server->user_cmd) {
  3191. error( "%s '%s' has both User and UserCmd\n", type, name );
  3192. cfg->err = 1;
  3193. return 1;
  3194. }
  3195. if (server->pass && server->pass_cmd) {
  3196. error( "%s '%s' has both Pass and PassCmd\n", type, name );
  3197. cfg->err = 1;
  3198. return 1;
  3199. }
  3200. #ifdef HAVE_MACOS_KEYCHAIN
  3201. if (server->use_keychain && (server->pass || server->pass_cmd)) {
  3202. error( "%s '%s' has UseKeychain enabled despite specifying Pass/PassCmd\n", type, name );
  3203. cfg->err = 1;
  3204. return 1;
  3205. }
  3206. #endif
  3207. #ifdef HAVE_LIBSSL
  3208. if ((use_tlsv1 & use_tlsv11 & use_tlsv12 & use_tlsv13) != -1 || use_imaps >= 0 || require_ssl >= 0) {
  3209. if (server->ssl_type >= 0 || server->sconf.ssl_versions >= 0) {
  3210. error( "%s '%s': The deprecated UseSSL*, UseTLS*, UseIMAPS, and RequireSSL options are mutually exclusive with SSLType and SSLVersions.\n", type, name );
  3211. cfg->err = 1;
  3212. return 1;
  3213. }
  3214. warn( "Notice: %s '%s': UseSSL*, UseTLS*, UseIMAPS, and RequireSSL are deprecated. Use SSLType and SSLVersions instead.\n", type, name );
  3215. server->sconf.ssl_versions =
  3216. (use_tlsv1 == 0 ? 0 : TLSv1) |
  3217. (use_tlsv11 != 1 ? 0 : TLSv1_1) |
  3218. (use_tlsv12 != 1 ? 0 : TLSv1_2) |
  3219. (use_tlsv13 != 1 ? 0 : TLSv1_3);
  3220. if (use_imaps == 1) {
  3221. server->ssl_type = SSL_IMAPS;
  3222. } else if (require_ssl) {
  3223. server->ssl_type = SSL_STARTTLS;
  3224. } else if (!server->sconf.ssl_versions) {
  3225. server->ssl_type = SSL_None;
  3226. } else {
  3227. warn( "Notice: %s '%s': 'RequireSSL no' is being ignored\n", type, name );
  3228. server->ssl_type = SSL_STARTTLS;
  3229. }
  3230. if (server->ssl_type != SSL_None && !server->sconf.ssl_versions) {
  3231. error( "%s '%s' requires SSL but no SSL versions enabled\n", type, name );
  3232. cfg->err = 1;
  3233. return 1;
  3234. }
  3235. } else {
  3236. if (server->sconf.ssl_versions < 0)
  3237. server->sconf.ssl_versions = TLSv1 | TLSv1_1 | TLSv1_2 | TLSv1_3;
  3238. if (server->ssl_type < 0)
  3239. server->ssl_type = server->sconf.tunnel ? SSL_None : SSL_STARTTLS;
  3240. }
  3241. #endif
  3242. if (require_cram >= 0) {
  3243. if (server->auth_mechs) {
  3244. error( "%s '%s': The deprecated RequireCRAM option is mutually exclusive with AuthMech.\n", type, name );
  3245. cfg->err = 1;
  3246. return 1;
  3247. }
  3248. warn( "Notice: %s '%s': RequireCRAM is deprecated. Use AuthMech instead.\n", type, name );
  3249. if (require_cram)
  3250. add_string_list(&server->auth_mechs, "CRAM-MD5");
  3251. }
  3252. if (!server->auth_mechs)
  3253. add_string_list( &server->auth_mechs, "*" );
  3254. if (!server->sconf.port)
  3255. server->sconf.port =
  3256. #ifdef HAVE_LIBSSL
  3257. server->ssl_type == SSL_IMAPS ? 993 :
  3258. #endif
  3259. 143;
  3260. }
  3261. if (store) {
  3262. if (!store->server) {
  3263. store->server = nfmalloc( sizeof(sserver) );
  3264. memcpy( store->server, &sserver, sizeof(sserver) );
  3265. store->server->name = store->gen.name;
  3266. } else if (acc_opt) {
  3267. error( "%s '%s' has both Account and account-specific options\n", type, name );
  3268. cfg->err = 1;
  3269. }
  3270. }
  3271. return 1;
  3272. }
  3273. static uint
  3274. imap_get_caps( store_t *gctx ATTR_UNUSED )
  3275. {
  3276. return DRV_CRLF | DRV_VERBOSE;
  3277. }
  3278. struct driver imap_driver = {
  3279. imap_get_caps,
  3280. imap_parse_store,
  3281. imap_cleanup,
  3282. imap_alloc_store,
  3283. imap_set_bad_callback,
  3284. imap_connect_store,
  3285. imap_free_store,
  3286. imap_cancel_store,
  3287. imap_list_store,
  3288. imap_select_box,
  3289. imap_get_box_path,
  3290. imap_create_box,
  3291. imap_open_box,
  3292. imap_get_uidnext,
  3293. imap_get_supported_flags,
  3294. imap_confirm_box_empty,
  3295. imap_delete_box,
  3296. imap_finish_delete_box,
  3297. imap_prepare_load_box,
  3298. imap_load_box,
  3299. imap_fetch_msg,
  3300. imap_store_msg,
  3301. imap_find_new_msgs,
  3302. imap_set_msg_flags,
  3303. imap_trash_msg,
  3304. imap_close_box,
  3305. imap_cancel_cmds,
  3306. imap_commit_cmds,
  3307. imap_get_memory_usage,
  3308. imap_get_fail_state,
  3309. };