drv_imap.c 90 KB

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