drv_imap.c 97 KB

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