drv_imap.c 84 KB

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