drv_imap.c 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509
  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. // Use this to check whether a full path refers to the actual IMAP INBOX.
  1128. static int
  1129. is_inbox( imap_store_t *ctx, const char *arg, int argl )
  1130. {
  1131. if (!starts_with_upper( arg, argl, "INBOX", 5 ))
  1132. return 0;
  1133. if (arg[5] && arg[5] != ctx->delimiter[0])
  1134. return 0;
  1135. return 1;
  1136. }
  1137. // Use this to check whether a path fragment collides with the canonical INBOX.
  1138. static int
  1139. is_INBOX( imap_store_t *ctx, const char *arg, int argl )
  1140. {
  1141. if (!starts_with( arg, argl, "INBOX", 5 ))
  1142. return 0;
  1143. if (arg[5] && arg[5] != ctx->delimiter[0])
  1144. return 0;
  1145. return 1;
  1146. }
  1147. static int
  1148. parse_list_rsp_p2( imap_store_t *ctx, list_t *list, char *cmd ATTR_UNUSED )
  1149. {
  1150. string_list_t *narg;
  1151. char *arg, c;
  1152. int argl, l;
  1153. if (!is_atom( list )) {
  1154. error( "IMAP error: malformed LIST response\n" );
  1155. listbad:
  1156. free_list( list );
  1157. return LIST_BAD;
  1158. }
  1159. arg = list->val;
  1160. argl = list->len;
  1161. if ((l = strlen( ctx->prefix ))) {
  1162. if (!starts_with( arg, argl, ctx->prefix, l )) {
  1163. if (is_inbox( ctx, arg, argl )) {
  1164. // INBOX and its subfolders bypass the namespace.
  1165. goto inbox;
  1166. }
  1167. goto skip;
  1168. }
  1169. arg += l;
  1170. argl -= l;
  1171. // A folder named "INBOX" would be indistinguishable from the
  1172. // actual INBOX after prefix stripping, so drop it. This applies
  1173. // only to the fully uppercased spelling, as our canonical box
  1174. // names are case-sensitive (unlike IMAP's INBOX).
  1175. if (is_INBOX( ctx, arg, argl )) {
  1176. if (!arg[5]) // No need to complain about subfolders as well.
  1177. warn( "IMAP warning: ignoring INBOX in %s\n", ctx->prefix );
  1178. goto skip;
  1179. }
  1180. } else if (is_inbox( ctx, arg, argl )) {
  1181. inbox:
  1182. // The server might be weird and have a non-uppercase INBOX. It
  1183. // may legitimately do so, but we need the canonical spelling.
  1184. // Note that we do that only after prefix matching, under the
  1185. // assumption that the NAMESPACE (or Path) matches the
  1186. // capitalization of LIST.
  1187. memcpy( arg, "INBOX", 5 );
  1188. }
  1189. if (argl >= 5 && !memcmp( arg + argl - 5, ".lock", 5 )) /* workaround broken servers */
  1190. goto skip;
  1191. if (map_name( arg, (char **)&narg, offsetof(string_list_t, string), ctx->delimiter, "/") < 0) {
  1192. warn( "IMAP warning: ignoring mailbox %s (reserved character '/' in name)\n", arg );
  1193. goto skip;
  1194. }
  1195. // Validate the normalized name. Technically speaking, we could tolerate
  1196. // '//' and '/./', and '/../' being forbidden is a limitation of the Maildir
  1197. // driver, but there isn't really a legitimate reason for these being present.
  1198. for (const char *p = narg->string, *sp = p;;) {
  1199. if (!(c = *p) || c == '/') {
  1200. uint pcl = (uint)(p - sp);
  1201. if (!pcl) {
  1202. error( "IMAP warning: ignoring mailbox '%s' due to empty name component\n", narg->string );
  1203. free( narg );
  1204. goto skip;
  1205. }
  1206. if (pcl == 1 && sp[0] == '.') {
  1207. error( "IMAP warning: ignoring mailbox '%s' due to '.' component\n", narg->string );
  1208. free( narg );
  1209. goto skip;
  1210. }
  1211. if (pcl == 2 && sp[0] == '.' && sp[1] == '.') {
  1212. error( "IMAP error: LIST'd mailbox name '%s' contains '..' component - THIS MIGHT BE AN ATTEMPT TO HACK YOU!\n", narg->string );
  1213. free( narg );
  1214. goto listbad;
  1215. }
  1216. if (!c)
  1217. break;
  1218. sp = ++p;
  1219. } else {
  1220. ++p;
  1221. }
  1222. }
  1223. narg->next = ctx->boxes;
  1224. ctx->boxes = narg;
  1225. skip:
  1226. free_list( list );
  1227. return LIST_OK;
  1228. }
  1229. static int
  1230. prepare_name( char **buf, const imap_store_t *ctx, const char *prefix, const char *name )
  1231. {
  1232. int pl = strlen( prefix );
  1233. switch (map_name( name, buf, pl, "/", ctx->delimiter )) {
  1234. case -1:
  1235. error( "IMAP error: mailbox name %s contains server's hierarchy delimiter\n", name );
  1236. return -1;
  1237. case -2:
  1238. error( "IMAP error: server's hierarchy delimiter not known\n" );
  1239. return -1;
  1240. default:
  1241. memcpy( *buf, prefix, pl );
  1242. return 0;
  1243. }
  1244. }
  1245. static int
  1246. prepare_box( char **buf, const imap_store_t *ctx )
  1247. {
  1248. const char *name = ctx->name;
  1249. return prepare_name( buf, ctx,
  1250. (starts_with( name, -1, "INBOX", 5 ) && (!name[5] || name[5] == '/')) ? "" : ctx->prefix, name );
  1251. }
  1252. static int
  1253. prepare_trash( char **buf, const imap_store_t *ctx )
  1254. {
  1255. return prepare_name( buf, ctx, ctx->prefix, ctx->gen.conf->trash );
  1256. }
  1257. typedef struct {
  1258. imap_cmd_t gen;
  1259. imap_cmd_t *orig_cmd;
  1260. } imap_cmd_trycreate_t;
  1261. static void imap_open_store_greeted( imap_store_t * );
  1262. static void get_cmd_result_p2( imap_store_t *, imap_cmd_t *, int );
  1263. static void
  1264. imap_socket_read( void *aux )
  1265. {
  1266. imap_store_t *ctx = (imap_store_t *)aux;
  1267. imap_cmd_t *cmdp, **pcmdp;
  1268. char *cmd, *arg, *arg1, *p;
  1269. int resp, resp2, tag;
  1270. conn_iovec_t iov[2];
  1271. for (;;) {
  1272. if (ctx->parse_list_sts.level) {
  1273. resp = parse_list_continue( ctx, 0 );
  1274. listret:
  1275. if (resp == LIST_PARTIAL)
  1276. return;
  1277. if (resp == LIST_BAD)
  1278. break;
  1279. continue;
  1280. }
  1281. if (!(cmd = socket_read_line( &ctx->conn )))
  1282. return;
  1283. if (cmd == (void *)~0) {
  1284. if (!ctx->expectEOF)
  1285. error( "IMAP error: unexpected EOF from %s\n", ctx->conn.name );
  1286. /* A clean shutdown sequence ends with bad_callback as well (see imap_cleanup()). */
  1287. break;
  1288. }
  1289. if (DFlags & DEBUG_NET) {
  1290. printf( "%s%s\n", ctx->label, cmd );
  1291. fflush( stdout );
  1292. }
  1293. arg = next_arg( &cmd );
  1294. if (!arg) {
  1295. error( "IMAP error: empty response\n" );
  1296. break;
  1297. }
  1298. if (*arg == '*') {
  1299. arg = next_arg( &cmd );
  1300. if (!arg) {
  1301. error( "IMAP error: malformed untagged response\n" );
  1302. break;
  1303. }
  1304. if (ctx->greeting == GreetingPending && !strcmp( "PREAUTH", arg )) {
  1305. parse_response_code( ctx, 0, cmd );
  1306. ctx->greeting = GreetingPreauth;
  1307. dogreet:
  1308. imap_ref( ctx );
  1309. imap_open_store_greeted( ctx );
  1310. if (imap_deref( ctx ))
  1311. return;
  1312. } else if (!strcmp( "OK", arg )) {
  1313. parse_response_code( ctx, 0, cmd );
  1314. if (ctx->greeting == GreetingPending) {
  1315. ctx->greeting = GreetingOk;
  1316. goto dogreet;
  1317. }
  1318. } else if (!strcmp( "BYE", arg )) {
  1319. if (!ctx->expectBYE) {
  1320. ctx->greeting = GreetingBad;
  1321. error( "IMAP error: unexpected BYE response: %s\n", cmd );
  1322. /* We just wait for the server to close the connection now. */
  1323. ctx->expectEOF = 1;
  1324. } else {
  1325. /* We still need to wait for the LOGOUT's tagged OK. */
  1326. }
  1327. } else if (ctx->greeting == GreetingPending) {
  1328. error( "IMAP error: bogus greeting response %s\n", arg );
  1329. break;
  1330. } else if (!strcmp( "NO", arg )) {
  1331. warn( "Warning from IMAP server: %s\n", cmd );
  1332. } else if (!strcmp( "BAD", arg )) {
  1333. error( "Error from IMAP server: %s\n", cmd );
  1334. } else if (!strcmp( "CAPABILITY", arg )) {
  1335. parse_capability( ctx, cmd );
  1336. } else if (!strcmp( "LIST", arg )) {
  1337. resp = parse_list( ctx, cmd, parse_list_rsp );
  1338. goto listret;
  1339. } else if (!strcmp( "NAMESPACE", arg )) {
  1340. resp = parse_list( ctx, cmd, parse_namespace_rsp );
  1341. goto listret;
  1342. } else if ((arg1 = next_arg( &cmd ))) {
  1343. if (!strcmp( "EXISTS", arg1 ))
  1344. ctx->total_msgs = atoi( arg );
  1345. else if (!strcmp( "RECENT", arg1 ))
  1346. ctx->recent_msgs = atoi( arg );
  1347. else if(!strcmp ( "FETCH", arg1 )) {
  1348. resp = parse_list( ctx, cmd, parse_fetch_rsp );
  1349. goto listret;
  1350. }
  1351. } else {
  1352. error( "IMAP error: unrecognized untagged response '%s'\n", arg );
  1353. break; /* this may mean anything, so prefer not to spam the log */
  1354. }
  1355. continue;
  1356. } else if (!ctx->in_progress) {
  1357. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  1358. break; /* this may mean anything, so prefer not to spam the log */
  1359. } else if (*arg == '+') {
  1360. socket_expect_read( &ctx->conn, 0 );
  1361. /* There can be any number of commands in flight, but only the last
  1362. * one can require a continuation, as it enforces a round-trip. */
  1363. cmdp = (imap_cmd_t *)((char *)ctx->in_progress_append -
  1364. offsetof(imap_cmd_t, next));
  1365. if (cmdp->param.data) {
  1366. if (cmdp->param.to_trash)
  1367. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1368. if (DFlags & DEBUG_NET_ALL) {
  1369. printf( "%s>>>>>>>>>\n", ctx->label );
  1370. fwrite( cmdp->param.data, cmdp->param.data_len, 1, stdout );
  1371. printf( "%s>>>>>>>>>\n", ctx->label );
  1372. fflush( stdout );
  1373. }
  1374. iov[0].buf = cmdp->param.data;
  1375. iov[0].len = cmdp->param.data_len;
  1376. iov[0].takeOwn = GiveOwn;
  1377. cmdp->param.data = 0;
  1378. ctx->buffer_mem -= cmdp->param.data_len;
  1379. iov[1].buf = "\r\n";
  1380. iov[1].len = 2;
  1381. iov[1].takeOwn = KeepOwn;
  1382. socket_write( &ctx->conn, iov, 2 );
  1383. } else if (cmdp->param.cont) {
  1384. if (cmdp->param.cont( ctx, cmdp, cmd ))
  1385. return;
  1386. } else {
  1387. error( "IMAP error: unexpected command continuation request\n" );
  1388. break;
  1389. }
  1390. socket_expect_read( &ctx->conn, 1 );
  1391. } else {
  1392. tag = atoi( arg );
  1393. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  1394. if (cmdp->tag == tag)
  1395. goto gottag;
  1396. error( "IMAP error: unexpected tag %s\n", arg );
  1397. break;
  1398. gottag:
  1399. if (!(*pcmdp = cmdp->next))
  1400. ctx->in_progress_append = pcmdp;
  1401. if (!--ctx->num_in_progress)
  1402. socket_expect_read( &ctx->conn, 0 );
  1403. arg = next_arg( &cmd );
  1404. if (!arg) {
  1405. error( "IMAP error: malformed tagged response\n" );
  1406. break;
  1407. }
  1408. if (!strcmp( "OK", arg )) {
  1409. if (cmdp->param.to_trash)
  1410. ctx->trashnc = TrashKnown; /* Can't get NO [TRYCREATE] any more. */
  1411. resp = RESP_OK;
  1412. } else {
  1413. if (!strcmp( "NO", arg )) {
  1414. if (cmdp->param.create && cmd && starts_with( cmd, -1, "[TRYCREATE]", 11 )) { /* APPEND or UID COPY */
  1415. imap_cmd_trycreate_t *cmd2 =
  1416. (imap_cmd_trycreate_t *)new_imap_cmd( sizeof(*cmd2) );
  1417. cmd2->orig_cmd = cmdp;
  1418. cmd2->gen.param.high_prio = 1;
  1419. p = strchr( cmdp->cmd, '"' );
  1420. imap_exec( ctx, &cmd2->gen, get_cmd_result_p2,
  1421. "CREATE %.*s", imap_strchr( p + 1, '"' ) - p + 1, p );
  1422. continue;
  1423. }
  1424. resp = RESP_NO;
  1425. if (cmdp->param.failok)
  1426. goto doresp;
  1427. } else /*if (!strcmp( "BAD", arg ))*/
  1428. resp = RESP_CANCEL;
  1429. error( "IMAP command '%s' returned an error: %s %s\n",
  1430. starts_with( cmdp->cmd, -1, "LOGIN", 5 ) ?
  1431. "LOGIN <user> <pass>" :
  1432. starts_with( cmdp->cmd, -1, "AUTHENTICATE PLAIN", 18 ) ?
  1433. "AUTHENTICATE PLAIN <authdata>" :
  1434. cmdp->cmd,
  1435. arg, cmd ? cmd : "" );
  1436. }
  1437. doresp:
  1438. if ((resp2 = parse_response_code( ctx, cmdp, cmd )) > resp)
  1439. resp = resp2;
  1440. imap_ref( ctx );
  1441. if (resp == RESP_CANCEL)
  1442. imap_invoke_bad_callback( ctx );
  1443. done_imap_cmd( ctx, cmdp, resp );
  1444. if (imap_deref( ctx ))
  1445. return;
  1446. if (ctx->canceling && !ctx->in_progress) {
  1447. ctx->canceling = 0;
  1448. ctx->callbacks.imap_cancel( ctx->callback_aux );
  1449. return;
  1450. }
  1451. }
  1452. flush_imap_cmds( ctx );
  1453. }
  1454. imap_invoke_bad_callback( ctx );
  1455. }
  1456. static void
  1457. get_cmd_result_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  1458. {
  1459. imap_cmd_trycreate_t *cmdp = (imap_cmd_trycreate_t *)cmd;
  1460. imap_cmd_t *ocmd = cmdp->orig_cmd;
  1461. if (response != RESP_OK) {
  1462. done_imap_cmd( ctx, ocmd, response );
  1463. } else {
  1464. ctx->uidnext = 1;
  1465. if (ocmd->param.to_trash)
  1466. ctx->trashnc = TrashKnown;
  1467. ocmd->param.create = 0;
  1468. ocmd->param.high_prio = 1;
  1469. submit_imap_cmd( ctx, ocmd );
  1470. }
  1471. }
  1472. /******************* imap_cancel_store *******************/
  1473. static void
  1474. imap_cancel_store( store_t *gctx )
  1475. {
  1476. imap_store_t *ctx = (imap_store_t *)gctx;
  1477. #ifdef HAVE_LIBSASL
  1478. sasl_dispose( &ctx->sasl );
  1479. #endif
  1480. socket_close( &ctx->conn );
  1481. cancel_sent_imap_cmds( ctx );
  1482. cancel_pending_imap_cmds( ctx );
  1483. free_list( ctx->ns_personal );
  1484. free_list( ctx->ns_other );
  1485. free_list( ctx->ns_shared );
  1486. free_string_list( ctx->auth_mechs );
  1487. free_generic_messages( ctx->msgs );
  1488. free_string_list( ctx->boxes );
  1489. imap_deref( ctx );
  1490. }
  1491. static int
  1492. imap_deref( imap_store_t *ctx )
  1493. {
  1494. if (!--ctx->ref_count) {
  1495. free( ctx );
  1496. return -1;
  1497. }
  1498. return 0;
  1499. }
  1500. static void
  1501. imap_set_bad_callback( store_t *gctx, void (*cb)( void *aux ), void *aux )
  1502. {
  1503. imap_store_t *ctx = (imap_store_t *)gctx;
  1504. ctx->bad_callback = cb;
  1505. ctx->bad_callback_aux = aux;
  1506. }
  1507. static void
  1508. imap_invoke_bad_callback( imap_store_t *ctx )
  1509. {
  1510. ctx->bad_callback( ctx->bad_callback_aux );
  1511. }
  1512. /******************* imap_free_store *******************/
  1513. static store_t *unowned;
  1514. static void
  1515. imap_cancel_unowned( void *gctx )
  1516. {
  1517. store_t *store, **storep;
  1518. for (storep = &unowned; (store = *storep); storep = &store->next)
  1519. if (store == gctx) {
  1520. *storep = store->next;
  1521. break;
  1522. }
  1523. imap_cancel_store( gctx );
  1524. }
  1525. static void
  1526. imap_free_store( store_t *gctx )
  1527. {
  1528. imap_store_t *ctx = (imap_store_t *)gctx;
  1529. free_generic_messages( ctx->msgs );
  1530. ctx->msgs = 0;
  1531. imap_set_bad_callback( gctx, imap_cancel_unowned, gctx );
  1532. gctx->next = unowned;
  1533. unowned = gctx;
  1534. }
  1535. /******************* imap_cleanup *******************/
  1536. static void imap_cleanup_p2( imap_store_t *, imap_cmd_t *, int );
  1537. static void
  1538. imap_cleanup( void )
  1539. {
  1540. store_t *ctx, *nctx;
  1541. for (ctx = unowned; ctx; ctx = nctx) {
  1542. nctx = ctx->next;
  1543. imap_set_bad_callback( ctx, (void (*)(void *))imap_cancel_store, ctx );
  1544. if (((imap_store_t *)ctx)->state != SST_BAD) {
  1545. ((imap_store_t *)ctx)->expectBYE = 1;
  1546. imap_exec( (imap_store_t *)ctx, 0, imap_cleanup_p2, "LOGOUT" );
  1547. } else {
  1548. imap_cancel_store( ctx );
  1549. }
  1550. }
  1551. }
  1552. static void
  1553. imap_cleanup_p2( imap_store_t *ctx,
  1554. imap_cmd_t *cmd ATTR_UNUSED, int response )
  1555. {
  1556. if (response == RESP_NO)
  1557. imap_cancel_store( &ctx->gen );
  1558. else if (response == RESP_OK)
  1559. ctx->expectEOF = 1;
  1560. }
  1561. /******************* imap_open_store *******************/
  1562. static void imap_open_store_connected( int, void * );
  1563. #ifdef HAVE_LIBSSL
  1564. static void imap_open_store_tlsstarted1( int, void * );
  1565. #endif
  1566. static void imap_open_store_p2( imap_store_t *, imap_cmd_t *, int );
  1567. static void imap_open_store_authenticate( imap_store_t * );
  1568. #ifdef HAVE_LIBSSL
  1569. static void imap_open_store_authenticate_p2( imap_store_t *, imap_cmd_t *, int );
  1570. static void imap_open_store_tlsstarted2( int, void * );
  1571. static void imap_open_store_authenticate_p3( imap_store_t *, imap_cmd_t *, int );
  1572. #endif
  1573. static void imap_open_store_authenticate2( imap_store_t * );
  1574. static void imap_open_store_authenticate2_p2( imap_store_t *, imap_cmd_t *, int );
  1575. static void imap_open_store_compress( imap_store_t * );
  1576. #ifdef HAVE_LIBZ
  1577. static void imap_open_store_compress_p2( imap_store_t *, imap_cmd_t *, int );
  1578. #endif
  1579. static void imap_open_store_namespace( imap_store_t * );
  1580. static void imap_open_store_namespace_p2( imap_store_t *, imap_cmd_t *, int );
  1581. static void imap_open_store_namespace2( imap_store_t * );
  1582. static void imap_open_store_finalize( imap_store_t * );
  1583. #ifdef HAVE_LIBSSL
  1584. static void imap_open_store_ssl_bail( imap_store_t * );
  1585. #endif
  1586. static void imap_open_store_bail( imap_store_t *, int );
  1587. static store_t *
  1588. imap_alloc_store( store_conf_t *conf, const char *label )
  1589. {
  1590. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1591. imap_server_conf_t *srvc = cfg->server;
  1592. imap_store_t *ctx;
  1593. store_t **ctxp;
  1594. /* First try to recycle a whole store. */
  1595. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1596. if (ctx->state == SST_GOOD && ctx->gen.conf == conf) {
  1597. *ctxp = ctx->gen.next;
  1598. ctx->label = label;
  1599. return &ctx->gen;
  1600. }
  1601. /* Then try to recycle a server connection. */
  1602. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1603. if (ctx->state != SST_BAD && ((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1604. *ctxp = ctx->gen.next;
  1605. free_string_list( ctx->boxes );
  1606. ctx->boxes = NULL;
  1607. ctx->listed = 0;
  1608. /* One could ping the server here, but given that the idle timeout
  1609. * is at least 30 minutes, this sounds pretty pointless. */
  1610. ctx->state = SST_HALF;
  1611. goto gotsrv;
  1612. }
  1613. /* Finally, schedule opening a new server connection. */
  1614. ctx = nfcalloc( sizeof(*ctx) );
  1615. socket_init( &ctx->conn, &srvc->sconf,
  1616. (void (*)( void * ))imap_invoke_bad_callback,
  1617. imap_socket_read, (void (*)(void *))flush_imap_cmds, ctx );
  1618. ctx->in_progress_append = &ctx->in_progress;
  1619. ctx->pending_append = &ctx->pending;
  1620. gotsrv:
  1621. ctx->gen.driver = &imap_driver;
  1622. ctx->gen.conf = conf;
  1623. ctx->label = label;
  1624. ctx->ref_count = 1;
  1625. return &ctx->gen;
  1626. }
  1627. static void
  1628. imap_connect_store( store_t *gctx,
  1629. void (*cb)( int sts, void *aux ), void *aux )
  1630. {
  1631. imap_store_t *ctx = (imap_store_t *)gctx;
  1632. if (ctx->state == SST_GOOD) {
  1633. cb( DRV_OK, aux );
  1634. } else {
  1635. ctx->callbacks.imap_open = cb;
  1636. ctx->callback_aux = aux;
  1637. if (ctx->state == SST_HALF)
  1638. imap_open_store_namespace( ctx );
  1639. else
  1640. socket_connect( &ctx->conn, imap_open_store_connected );
  1641. }
  1642. }
  1643. static void
  1644. imap_open_store_connected( int ok, void *aux )
  1645. {
  1646. imap_store_t *ctx = (imap_store_t *)aux;
  1647. #ifdef HAVE_LIBSSL
  1648. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1649. imap_server_conf_t *srvc = cfg->server;
  1650. #endif
  1651. if (!ok)
  1652. imap_open_store_bail( ctx, FAIL_WAIT );
  1653. #ifdef HAVE_LIBSSL
  1654. else if (srvc->ssl_type == SSL_IMAPS)
  1655. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted1 );
  1656. #endif
  1657. else
  1658. socket_expect_read( &ctx->conn, 1 );
  1659. }
  1660. #ifdef HAVE_LIBSSL
  1661. static void
  1662. imap_open_store_tlsstarted1( int ok, void *aux )
  1663. {
  1664. imap_store_t *ctx = (imap_store_t *)aux;
  1665. if (!ok)
  1666. imap_open_store_ssl_bail( ctx );
  1667. else
  1668. socket_expect_read( &ctx->conn, 1 );
  1669. }
  1670. #endif
  1671. static void
  1672. imap_open_store_greeted( imap_store_t *ctx )
  1673. {
  1674. socket_expect_read( &ctx->conn, 0 );
  1675. if (!ctx->caps)
  1676. imap_exec( ctx, 0, imap_open_store_p2, "CAPABILITY" );
  1677. else
  1678. imap_open_store_authenticate( ctx );
  1679. }
  1680. static void
  1681. imap_open_store_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1682. {
  1683. if (response == RESP_NO)
  1684. imap_open_store_bail( ctx, FAIL_FINAL );
  1685. else if (response == RESP_OK)
  1686. imap_open_store_authenticate( ctx );
  1687. }
  1688. static void
  1689. imap_open_store_authenticate( imap_store_t *ctx )
  1690. {
  1691. #ifdef HAVE_LIBSSL
  1692. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1693. imap_server_conf_t *srvc = cfg->server;
  1694. #endif
  1695. if (ctx->greeting != GreetingPreauth) {
  1696. #ifdef HAVE_LIBSSL
  1697. if (srvc->ssl_type == SSL_STARTTLS) {
  1698. if (CAP(STARTTLS)) {
  1699. imap_exec( ctx, 0, imap_open_store_authenticate_p2, "STARTTLS" );
  1700. return;
  1701. } else {
  1702. error( "IMAP error: SSL support not available\n" );
  1703. imap_open_store_bail( ctx, FAIL_FINAL );
  1704. return;
  1705. }
  1706. }
  1707. #endif
  1708. imap_open_store_authenticate2( ctx );
  1709. } else {
  1710. #ifdef HAVE_LIBSSL
  1711. if (srvc->ssl_type == SSL_STARTTLS) {
  1712. error( "IMAP error: SSL support not available\n" );
  1713. imap_open_store_bail( ctx, FAIL_FINAL );
  1714. return;
  1715. }
  1716. #endif
  1717. imap_open_store_compress( ctx );
  1718. }
  1719. }
  1720. #ifdef HAVE_LIBSSL
  1721. static void
  1722. imap_open_store_authenticate_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1723. {
  1724. if (response == RESP_NO)
  1725. imap_open_store_bail( ctx, FAIL_FINAL );
  1726. else if (response == RESP_OK)
  1727. socket_start_tls( &ctx->conn, imap_open_store_tlsstarted2 );
  1728. }
  1729. static void
  1730. imap_open_store_tlsstarted2( int ok, void *aux )
  1731. {
  1732. imap_store_t *ctx = (imap_store_t *)aux;
  1733. if (!ok)
  1734. imap_open_store_ssl_bail( ctx );
  1735. else
  1736. imap_exec( ctx, 0, imap_open_store_authenticate_p3, "CAPABILITY" );
  1737. }
  1738. static void
  1739. imap_open_store_authenticate_p3( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1740. {
  1741. if (response == RESP_NO)
  1742. imap_open_store_bail( ctx, FAIL_FINAL );
  1743. else if (response == RESP_OK)
  1744. imap_open_store_authenticate2( ctx );
  1745. }
  1746. #endif
  1747. static const char *
  1748. ensure_user( imap_server_conf_t *srvc )
  1749. {
  1750. if (!srvc->user) {
  1751. error( "Skipping account %s, no user\n", srvc->name );
  1752. return 0;
  1753. }
  1754. return srvc->user;
  1755. }
  1756. static const char *
  1757. ensure_password( imap_server_conf_t *srvc )
  1758. {
  1759. char *cmd = srvc->pass_cmd;
  1760. if (cmd) {
  1761. FILE *fp;
  1762. int ret;
  1763. char buffer[8192]; // Hopefully more than enough room for XOAUTH2, etc. tokens
  1764. if (*cmd == '+') {
  1765. flushn();
  1766. cmd++;
  1767. }
  1768. if (!(fp = popen( cmd, "r" ))) {
  1769. pipeerr:
  1770. sys_error( "Skipping account %s, password command failed", srvc->name );
  1771. return 0;
  1772. }
  1773. if (!fgets( buffer, sizeof(buffer), fp ))
  1774. buffer[0] = 0;
  1775. if ((ret = pclose( fp )) < 0)
  1776. goto pipeerr;
  1777. if (ret) {
  1778. if (WIFSIGNALED( ret ))
  1779. error( "Skipping account %s, password command crashed\n", srvc->name );
  1780. else
  1781. error( "Skipping account %s, password command exited with status %d\n", srvc->name, WEXITSTATUS( ret ) );
  1782. return 0;
  1783. }
  1784. if (!buffer[0]) {
  1785. error( "Skipping account %s, password command produced no output\n", srvc->name );
  1786. return 0;
  1787. }
  1788. buffer[strcspn( buffer, "\n" )] = 0; /* Strip trailing newline */
  1789. free( srvc->pass ); /* From previous runs */
  1790. srvc->pass = nfstrdup( buffer );
  1791. } else if (!srvc->pass) {
  1792. char *pass, prompt[80];
  1793. flushn();
  1794. sprintf( prompt, "Password (%s): ", srvc->name );
  1795. pass = getpass( prompt );
  1796. if (!pass) {
  1797. perror( "getpass" );
  1798. exit( 1 );
  1799. }
  1800. if (!*pass) {
  1801. error( "Skipping account %s, no password\n", srvc->name );
  1802. return 0;
  1803. }
  1804. /* getpass() returns a pointer to a static buffer. Make a copy for long term storage. */
  1805. srvc->pass = nfstrdup( pass );
  1806. }
  1807. return srvc->pass;
  1808. }
  1809. #ifdef HAVE_LIBSASL
  1810. static sasl_callback_t sasl_callbacks[] = {
  1811. { SASL_CB_USER, NULL, NULL },
  1812. { SASL_CB_AUTHNAME, NULL, NULL },
  1813. { SASL_CB_PASS, NULL, NULL },
  1814. { SASL_CB_LIST_END, NULL, NULL }
  1815. };
  1816. static int
  1817. process_sasl_interact( sasl_interact_t *interact, imap_server_conf_t *srvc )
  1818. {
  1819. const char *val;
  1820. for (;; ++interact) {
  1821. switch (interact->id) {
  1822. case SASL_CB_LIST_END:
  1823. return 0;
  1824. case SASL_CB_USER:
  1825. case SASL_CB_AUTHNAME:
  1826. val = ensure_user( srvc );
  1827. break;
  1828. case SASL_CB_PASS:
  1829. val = ensure_password( srvc );
  1830. break;
  1831. default:
  1832. error( "Error: Unknown SASL interaction ID\n" );
  1833. return -1;
  1834. }
  1835. if (!val)
  1836. return -1;
  1837. interact->result = val;
  1838. interact->len = strlen( val );
  1839. }
  1840. }
  1841. static int
  1842. process_sasl_step( imap_store_t *ctx, int rc, const char *in, uint in_len,
  1843. sasl_interact_t *interact, const char **out, uint *out_len )
  1844. {
  1845. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1846. while (rc == SASL_INTERACT) {
  1847. if (process_sasl_interact( interact, srvc ) < 0)
  1848. return -1;
  1849. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, out, out_len );
  1850. }
  1851. if (rc == SASL_CONTINUE) {
  1852. ctx->sasl_cont = 1;
  1853. } else if (rc == SASL_OK) {
  1854. ctx->sasl_cont = 0;
  1855. } else {
  1856. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  1857. return -1;
  1858. }
  1859. return 0;
  1860. }
  1861. static int
  1862. decode_sasl_data( const char *prompt, char **in, uint *in_len )
  1863. {
  1864. if (prompt) {
  1865. int rc;
  1866. uint prompt_len = strlen( prompt );
  1867. /* We're decoding, the output will be shorter than prompt_len. */
  1868. *in = nfmalloc( prompt_len );
  1869. rc = sasl_decode64( prompt, prompt_len, *in, prompt_len, in_len );
  1870. if (rc != SASL_OK) {
  1871. free( *in );
  1872. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1873. return -1;
  1874. }
  1875. } else {
  1876. *in = NULL;
  1877. *in_len = 0;
  1878. }
  1879. return 0;
  1880. }
  1881. static int
  1882. encode_sasl_data( const char *out, uint out_len, char **enc, uint *enc_len )
  1883. {
  1884. int rc;
  1885. uint enc_len_max = ((out_len + 2) / 3) * 4 + 1;
  1886. *enc = nfmalloc( enc_len_max );
  1887. rc = sasl_encode64( out, out_len, *enc, enc_len_max, enc_len );
  1888. if (rc != SASL_OK) {
  1889. free( *enc );
  1890. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  1891. return -1;
  1892. }
  1893. return 0;
  1894. }
  1895. static int
  1896. do_sasl_auth( imap_store_t *ctx, imap_cmd_t *cmdp ATTR_UNUSED, const char *prompt )
  1897. {
  1898. int rc, ret, iovcnt = 0;
  1899. uint in_len, out_len, enc_len;
  1900. const char *out;
  1901. char *in, *enc;
  1902. sasl_interact_t *interact = NULL;
  1903. conn_iovec_t iov[2];
  1904. if (!ctx->sasl_cont) {
  1905. error( "Error: IMAP wants more steps despite successful SASL authentication.\n" );
  1906. goto bail;
  1907. }
  1908. if (decode_sasl_data( prompt, &in, &in_len ) < 0)
  1909. goto bail;
  1910. rc = sasl_client_step( ctx->sasl, in, in_len, &interact, &out, &out_len );
  1911. ret = process_sasl_step( ctx, rc, in, in_len, interact, &out, &out_len );
  1912. free( in );
  1913. if (ret < 0)
  1914. goto bail;
  1915. if (out) {
  1916. if (encode_sasl_data( out, out_len, &enc, &enc_len ) < 0)
  1917. goto bail;
  1918. iov[0].buf = enc;
  1919. iov[0].len = enc_len;
  1920. iov[0].takeOwn = GiveOwn;
  1921. iovcnt = 1;
  1922. if (DFlags & DEBUG_NET) {
  1923. printf( "%s>+> %s\n", ctx->label, enc );
  1924. fflush( stdout );
  1925. }
  1926. } else {
  1927. if (DFlags & DEBUG_NET) {
  1928. printf( "%s>+>\n", ctx->label );
  1929. fflush( stdout );
  1930. }
  1931. }
  1932. iov[iovcnt].buf = "\r\n";
  1933. iov[iovcnt].len = 2;
  1934. iov[iovcnt].takeOwn = KeepOwn;
  1935. iovcnt++;
  1936. socket_write( &ctx->conn, iov, iovcnt );
  1937. return 0;
  1938. bail:
  1939. imap_open_store_bail( ctx, FAIL_FINAL );
  1940. return -1;
  1941. }
  1942. static void
  1943. done_sasl_auth( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  1944. {
  1945. if (response == RESP_OK && ctx->sasl_cont) {
  1946. sasl_interact_t *interact = NULL;
  1947. const char *out;
  1948. uint out_len;
  1949. int rc = sasl_client_step( ctx->sasl, NULL, 0, &interact, &out, &out_len );
  1950. if (process_sasl_step( ctx, rc, NULL, 0, interact, &out, &out_len ) < 0)
  1951. warn( "Warning: SASL reported failure despite successful IMAP authentication. Ignoring...\n" );
  1952. else if (out_len > 0)
  1953. warn( "Warning: SASL wants more steps despite successful IMAP authentication. Ignoring...\n" );
  1954. }
  1955. imap_open_store_authenticate2_p2( ctx, NULL, response );
  1956. }
  1957. #endif
  1958. static void
  1959. imap_open_store_authenticate2( imap_store_t *ctx )
  1960. {
  1961. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1962. imap_server_conf_t *srvc = cfg->server;
  1963. string_list_t *mech, *cmech;
  1964. int auth_login = 0;
  1965. int skipped_login = 0;
  1966. #ifdef HAVE_LIBSASL
  1967. const char *saslavail;
  1968. char saslmechs[1024], *saslend = saslmechs;
  1969. #endif
  1970. info( "Logging in...\n" );
  1971. for (mech = srvc->auth_mechs; mech; mech = mech->next) {
  1972. int any = !strcmp( mech->string, "*" );
  1973. for (cmech = ctx->auth_mechs; cmech; cmech = cmech->next) {
  1974. if (any || !strcasecmp( mech->string, cmech->string )) {
  1975. if (!strcasecmp( cmech->string, "LOGIN" )) {
  1976. #ifdef HAVE_LIBSSL
  1977. if (ctx->conn.ssl || !any)
  1978. #else
  1979. if (!any)
  1980. #endif
  1981. auth_login = 1;
  1982. else
  1983. skipped_login = 1;
  1984. #ifdef HAVE_LIBSASL
  1985. } else {
  1986. int len = strlen( cmech->string );
  1987. if (saslend + len + 2 > saslmechs + sizeof(saslmechs))
  1988. oob();
  1989. *saslend++ = ' ';
  1990. memcpy( saslend, cmech->string, len + 1 );
  1991. saslend += len;
  1992. #endif
  1993. }
  1994. }
  1995. }
  1996. }
  1997. #ifdef HAVE_LIBSASL
  1998. if (saslend != saslmechs) {
  1999. int rc;
  2000. uint out_len = 0;
  2001. char *enc = NULL;
  2002. const char *gotmech = NULL, *out = NULL;
  2003. sasl_interact_t *interact = NULL;
  2004. imap_cmd_t *cmd;
  2005. static int sasl_inited;
  2006. if (!sasl_inited) {
  2007. rc = sasl_client_init( sasl_callbacks );
  2008. if (rc != SASL_OK) {
  2009. saslbail:
  2010. error( "Error: SASL(%d): %s\n", rc, sasl_errstring( rc, NULL, NULL ) );
  2011. goto bail;
  2012. }
  2013. sasl_inited = 1;
  2014. }
  2015. rc = sasl_client_new( "imap", srvc->sconf.host, NULL, NULL, NULL, 0, &ctx->sasl );
  2016. if (rc != SASL_OK) {
  2017. if (rc == SASL_NOMECH)
  2018. goto notsasl;
  2019. if (!ctx->sasl)
  2020. goto saslbail;
  2021. error( "Error: %s\n", sasl_errdetail( ctx->sasl ) );
  2022. goto bail;
  2023. }
  2024. rc = sasl_client_start( ctx->sasl, saslmechs + 1, &interact, CAP(SASLIR) ? &out : NULL, &out_len, &gotmech );
  2025. if (rc == SASL_NOMECH)
  2026. goto notsasl;
  2027. if (gotmech)
  2028. info( "Authenticating with SASL mechanism %s...\n", gotmech );
  2029. /* Technically, we are supposed to loop over sasl_client_start(),
  2030. * but it just calls sasl_client_step() anyway. */
  2031. if (process_sasl_step( ctx, rc, NULL, 0, interact, CAP(SASLIR) ? &out : NULL, &out_len ) < 0)
  2032. goto bail;
  2033. if (out) {
  2034. if (!out_len)
  2035. enc = nfstrdup( "=" ); /* A zero-length initial response is encoded as padding. */
  2036. else if (encode_sasl_data( out, out_len, &enc, NULL ) < 0)
  2037. goto bail;
  2038. }
  2039. cmd = new_imap_cmd( sizeof(*cmd) );
  2040. cmd->param.cont = do_sasl_auth;
  2041. imap_exec( ctx, cmd, done_sasl_auth, enc ? "AUTHENTICATE %s %s" : "AUTHENTICATE %s", gotmech, enc );
  2042. free( enc );
  2043. return;
  2044. notsasl:
  2045. if (!ctx->sasl || sasl_listmech( ctx->sasl, NULL, "", " ", "", &saslavail, NULL, NULL ) != SASL_OK)
  2046. saslavail = "(none)"; /* EXTERNAL is always there anyway. */
  2047. if (!auth_login) {
  2048. error( "IMAP error: selected SASL mechanism(s) not available;\n"
  2049. " selected:%s\n available: %s\n", saslmechs, saslavail );
  2050. goto skipnote;
  2051. }
  2052. info( "NOT using available SASL mechanism(s): %s\n", saslavail );
  2053. sasl_dispose( &ctx->sasl );
  2054. }
  2055. #endif
  2056. if (auth_login) {
  2057. if (!ensure_user( srvc ) || !ensure_password( srvc ))
  2058. goto bail;
  2059. #ifdef HAVE_LIBSSL
  2060. if (!ctx->conn.ssl)
  2061. #endif
  2062. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  2063. imap_exec( ctx, 0, imap_open_store_authenticate2_p2,
  2064. "LOGIN \"%\\s\" \"%\\s\"", srvc->user, srvc->pass );
  2065. return;
  2066. }
  2067. error( "IMAP error: server supports no acceptable authentication mechanism\n" );
  2068. #ifdef HAVE_LIBSASL
  2069. skipnote:
  2070. #endif
  2071. if (skipped_login)
  2072. error( "Note: not using LOGIN because connection is not encrypted;\n"
  2073. " use 'AuthMechs LOGIN' explicitly to force it.\n" );
  2074. bail:
  2075. imap_open_store_bail( ctx, FAIL_FINAL );
  2076. }
  2077. static void
  2078. imap_open_store_authenticate2_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2079. {
  2080. if (response == RESP_NO)
  2081. imap_open_store_bail( ctx, FAIL_FINAL );
  2082. else if (response == RESP_OK)
  2083. imap_open_store_compress( ctx );
  2084. }
  2085. static void
  2086. imap_open_store_compress( imap_store_t *ctx )
  2087. {
  2088. #ifdef HAVE_LIBZ
  2089. if (CAP(COMPRESS_DEFLATE)) {
  2090. imap_exec( ctx, 0, imap_open_store_compress_p2, "COMPRESS DEFLATE" );
  2091. return;
  2092. }
  2093. #endif
  2094. imap_open_store_namespace( ctx );
  2095. }
  2096. #ifdef HAVE_LIBZ
  2097. static void
  2098. imap_open_store_compress_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2099. {
  2100. if (response == RESP_NO) {
  2101. /* We already reported an error, but it's not fatal to us. */
  2102. imap_open_store_namespace( ctx );
  2103. } else if (response == RESP_OK) {
  2104. socket_start_deflate( &ctx->conn );
  2105. imap_open_store_namespace( ctx );
  2106. }
  2107. }
  2108. #endif
  2109. static void
  2110. imap_open_store_namespace( imap_store_t *ctx )
  2111. {
  2112. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2113. ctx->state = SST_HALF;
  2114. ctx->prefix = cfg->gen.path;
  2115. ctx->delimiter[0] = cfg->delimiter;
  2116. if (((!ctx->prefix && cfg->use_namespace) || !cfg->delimiter) && CAP(NAMESPACE)) {
  2117. /* get NAMESPACE info */
  2118. if (!ctx->got_namespace)
  2119. imap_exec( ctx, 0, imap_open_store_namespace_p2, "NAMESPACE" );
  2120. else
  2121. imap_open_store_namespace2( ctx );
  2122. return;
  2123. }
  2124. imap_open_store_finalize( ctx );
  2125. }
  2126. static void
  2127. imap_open_store_namespace_p2( imap_store_t *ctx, imap_cmd_t *cmd ATTR_UNUSED, int response )
  2128. {
  2129. if (response == RESP_NO) {
  2130. imap_open_store_bail( ctx, FAIL_FINAL );
  2131. } else if (response == RESP_OK) {
  2132. ctx->got_namespace = 1;
  2133. imap_open_store_namespace2( ctx );
  2134. }
  2135. }
  2136. static void
  2137. imap_open_store_namespace2( imap_store_t *ctx )
  2138. {
  2139. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  2140. list_t *nsp, *nsp_1st;
  2141. /* XXX for now assume 1st personal namespace */
  2142. if (is_list( (nsp = ctx->ns_personal) ) &&
  2143. is_list( (nsp_1st = nsp->child) ))
  2144. {
  2145. list_t *nsp_1st_ns = nsp_1st->child;
  2146. list_t *nsp_1st_dl = nsp_1st_ns->next;
  2147. if (!ctx->prefix && cfg->use_namespace)
  2148. ctx->prefix = nsp_1st_ns->val;
  2149. if (!ctx->delimiter[0] && is_atom( nsp_1st_dl ))
  2150. ctx->delimiter[0] = nsp_1st_dl->val[0];
  2151. }
  2152. imap_open_store_finalize( ctx );
  2153. }
  2154. static void
  2155. imap_open_store_finalize( imap_store_t *ctx )
  2156. {
  2157. ctx->state = SST_GOOD;
  2158. if (!ctx->prefix)
  2159. ctx->prefix = "";
  2160. ctx->trashnc = TrashUnknown;
  2161. ctx->callbacks.imap_open( DRV_OK, ctx->callback_aux );
  2162. }
  2163. #ifdef HAVE_LIBSSL
  2164. static void
  2165. imap_open_store_ssl_bail( imap_store_t *ctx )
  2166. {
  2167. /* This avoids that we try to send LOGOUT to an unusable socket. */
  2168. socket_close( &ctx->conn );
  2169. imap_open_store_bail( ctx, FAIL_FINAL );
  2170. }
  2171. #endif
  2172. static void
  2173. imap_open_store_bail( imap_store_t *ctx, int failed )
  2174. {
  2175. ((imap_store_conf_t *)ctx->gen.conf)->server->failed = failed;
  2176. ctx->callbacks.imap_open( DRV_STORE_BAD, ctx->callback_aux );
  2177. }
  2178. /******************* imap_open_box *******************/
  2179. static int
  2180. imap_select_box( store_t *gctx, const char *name )
  2181. {
  2182. imap_store_t *ctx = (imap_store_t *)gctx;
  2183. free_generic_messages( ctx->msgs );
  2184. ctx->msgs = 0;
  2185. ctx->msgapp = &ctx->msgs;
  2186. ctx->name = name;
  2187. return DRV_OK;
  2188. }
  2189. static const char *
  2190. imap_get_box_path( store_t *gctx ATTR_UNUSED )
  2191. {
  2192. return 0;
  2193. }
  2194. typedef struct {
  2195. imap_cmd_t gen;
  2196. void (*callback)( int sts, int uidvalidity, void *aux );
  2197. void *callback_aux;
  2198. } imap_cmd_open_box_t;
  2199. static void imap_open_box_p2( imap_store_t *, imap_cmd_t *, int );
  2200. static void imap_open_box_p3( imap_store_t *, imap_cmd_t *, int );
  2201. static void imap_open_box_p4( imap_store_t *, imap_cmd_open_box_t *, int );
  2202. static void
  2203. imap_open_box( store_t *gctx,
  2204. void (*cb)( int sts, int uidvalidity, void *aux ), void *aux )
  2205. {
  2206. imap_store_t *ctx = (imap_store_t *)gctx;
  2207. imap_cmd_open_box_t *cmd;
  2208. char *buf;
  2209. if (prepare_box( &buf, ctx ) < 0) {
  2210. cb( DRV_BOX_BAD, UIDVAL_BAD, aux );
  2211. return;
  2212. }
  2213. ctx->uidvalidity = UIDVAL_BAD;
  2214. ctx->uidnext = 0;
  2215. INIT_IMAP_CMD(imap_cmd_open_box_t, cmd, cb, aux)
  2216. cmd->gen.param.failok = 1;
  2217. imap_exec( ctx, &cmd->gen, imap_open_box_p2,
  2218. "SELECT \"%\\s\"", buf );
  2219. free( buf );
  2220. }
  2221. static void
  2222. imap_open_box_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2223. {
  2224. imap_cmd_open_box_t *cmdp = (imap_cmd_open_box_t *)gcmd;
  2225. imap_cmd_open_box_t *cmd;
  2226. if (response != RESP_OK || ctx->uidnext) {
  2227. imap_open_box_p4( ctx, cmdp, response );
  2228. return;
  2229. }
  2230. INIT_IMAP_CMD(imap_cmd_open_box_t, cmd, cmdp->callback, cmdp->callback_aux)
  2231. cmd->gen.param.lastuid = 1;
  2232. imap_exec( ctx, &cmd->gen, imap_open_box_p3,
  2233. "UID FETCH * (UID)" );
  2234. }
  2235. static void
  2236. imap_open_box_p3( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2237. {
  2238. imap_cmd_open_box_t *cmdp = (imap_cmd_open_box_t *)gcmd;
  2239. if (!ctx->uidnext) {
  2240. if (ctx->total_msgs) {
  2241. error( "IMAP error: querying server for highest UID failed\n" );
  2242. imap_open_box_p4( ctx, cmdp, RESP_NO );
  2243. return;
  2244. }
  2245. // This is ok, the box is simply empty.
  2246. ctx->uidnext = 1;
  2247. }
  2248. imap_open_box_p4( ctx, cmdp, response );
  2249. }
  2250. static void
  2251. imap_open_box_p4( imap_store_t *ctx, imap_cmd_open_box_t *cmdp, int response )
  2252. {
  2253. transform_box_response( &response );
  2254. cmdp->callback( response, ctx->uidvalidity, cmdp->callback_aux );
  2255. }
  2256. static int
  2257. imap_get_uidnext( store_t *gctx )
  2258. {
  2259. imap_store_t *ctx = (imap_store_t *)gctx;
  2260. return ctx->uidnext;
  2261. }
  2262. /******************* imap_create_box *******************/
  2263. static void
  2264. imap_create_box( store_t *gctx,
  2265. void (*cb)( int sts, void *aux ), void *aux )
  2266. {
  2267. imap_store_t *ctx = (imap_store_t *)gctx;
  2268. imap_cmd_simple_t *cmd;
  2269. char *buf;
  2270. if (prepare_box( &buf, ctx ) < 0) {
  2271. cb( DRV_BOX_BAD, aux );
  2272. return;
  2273. }
  2274. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2275. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  2276. "CREATE \"%\\s\"", buf );
  2277. free( buf );
  2278. }
  2279. /******************* imap_delete_box *******************/
  2280. static int
  2281. imap_confirm_box_empty( store_t *gctx )
  2282. {
  2283. imap_store_t *ctx = (imap_store_t *)gctx;
  2284. return ctx->total_msgs ? DRV_BOX_BAD : DRV_OK;
  2285. }
  2286. static void imap_delete_box_p2( imap_store_t *, imap_cmd_t *, int );
  2287. static void
  2288. imap_delete_box( store_t *gctx,
  2289. void (*cb)( int sts, void *aux ), void *aux )
  2290. {
  2291. imap_store_t *ctx = (imap_store_t *)gctx;
  2292. imap_cmd_simple_t *cmd;
  2293. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2294. imap_exec( ctx, &cmd->gen, imap_delete_box_p2, "CLOSE" );
  2295. }
  2296. static void
  2297. imap_delete_box_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2298. {
  2299. imap_cmd_simple_t *cmdp = (imap_cmd_simple_t *)gcmd;
  2300. imap_cmd_simple_t *cmd;
  2301. char *buf;
  2302. if (response != RESP_OK) {
  2303. imap_done_simple_box( ctx, &cmdp->gen, response );
  2304. return;
  2305. }
  2306. if (prepare_box( &buf, ctx ) < 0) {
  2307. imap_done_simple_box( ctx, &cmdp->gen, RESP_NO );
  2308. return;
  2309. }
  2310. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cmdp->callback, cmdp->callback_aux)
  2311. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  2312. "DELETE \"%\\s\"", buf );
  2313. free( buf );
  2314. }
  2315. static int
  2316. imap_finish_delete_box( store_t *gctx ATTR_UNUSED )
  2317. {
  2318. return DRV_OK;
  2319. }
  2320. /******************* imap_load_box *******************/
  2321. static int
  2322. imap_prepare_load_box( store_t *gctx, int opts )
  2323. {
  2324. imap_store_t *ctx = (imap_store_t *)gctx;
  2325. ctx->opts = opts;
  2326. return opts;
  2327. }
  2328. enum { WantSize = 1, WantTuids = 2, WantMsgids = 4 };
  2329. typedef struct {
  2330. int first, last, flags;
  2331. } imap_range_t;
  2332. static void
  2333. imap_set_range( imap_range_t *ranges, int *nranges, int low_flags, int high_flags, int maxlow )
  2334. {
  2335. if (low_flags != high_flags) {
  2336. for (int r = 0; r < *nranges; r++) {
  2337. if (ranges[r].first > maxlow)
  2338. break; /* Range starts above split point; so do all subsequent ranges. */
  2339. if (ranges[r].last < maxlow)
  2340. continue; /* Range ends below split point; try next one. */
  2341. if (ranges[r].last != maxlow) {
  2342. /* Range does not end exactly at split point; need to split. */
  2343. memmove( &ranges[r + 1], &ranges[r], ((*nranges)++ - r) * sizeof(*ranges) );
  2344. ranges[r].last = maxlow;
  2345. ranges[r + 1].first = maxlow + 1;
  2346. }
  2347. break;
  2348. }
  2349. }
  2350. for (int r = 0; r < *nranges; r++)
  2351. ranges[r].flags |= (ranges[r].last <= maxlow) ? low_flags : high_flags;
  2352. }
  2353. typedef struct {
  2354. imap_cmd_refcounted_state_t gen;
  2355. void (*callback)( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux );
  2356. void *callback_aux;
  2357. } imap_load_box_state_t;
  2358. static void imap_submit_load( imap_store_t *, const char *, int, imap_load_box_state_t * );
  2359. static void imap_submit_load_p3( imap_store_t *ctx, imap_load_box_state_t * );
  2360. static void
  2361. imap_load_box( store_t *gctx, uint minuid, uint maxuid, uint newuid, uint seenuid, uint_array_t excs,
  2362. void (*cb)( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux ), void *aux )
  2363. {
  2364. imap_store_t *ctx = (imap_store_t *)gctx;
  2365. int i, j, bl;
  2366. char buf[1000];
  2367. if (!ctx->total_msgs) {
  2368. free( excs.data );
  2369. cb( DRV_OK, 0, 0, 0, aux );
  2370. } else {
  2371. INIT_REFCOUNTED_STATE(imap_load_box_state_t, sts, cb, aux)
  2372. for (i = 0; i < excs.size; ) {
  2373. for (bl = 0; i < excs.size && bl < 960; i++) {
  2374. if (bl)
  2375. buf[bl++] = ',';
  2376. bl += sprintf( buf + bl, "%u", excs.data[i] );
  2377. j = i;
  2378. for (; i + 1 < excs.size && excs.data[i + 1] == excs.data[i] + 1; i++) {}
  2379. if (i != j)
  2380. bl += sprintf( buf + bl, ":%u", excs.data[i] );
  2381. }
  2382. imap_submit_load( ctx, buf, shifted_bit( ctx->opts, OPEN_OLD_IDS, WantMsgids ), sts );
  2383. }
  2384. if (maxuid == UINT_MAX)
  2385. maxuid = ctx->uidnext - 1;
  2386. if (maxuid >= minuid) {
  2387. imap_range_t ranges[3];
  2388. ranges[0].first = minuid;
  2389. ranges[0].last = maxuid;
  2390. ranges[0].flags = 0;
  2391. int nranges = 1;
  2392. if (ctx->opts & (OPEN_OLD_SIZE | OPEN_NEW_SIZE))
  2393. imap_set_range( ranges, &nranges, shifted_bit( ctx->opts, OPEN_OLD_SIZE, WantSize),
  2394. shifted_bit( ctx->opts, OPEN_NEW_SIZE, WantSize), seenuid );
  2395. if (ctx->opts & OPEN_FIND)
  2396. imap_set_range( ranges, &nranges, 0, WantTuids, newuid - 1 );
  2397. if (ctx->opts & OPEN_OLD_IDS)
  2398. imap_set_range( ranges, &nranges, WantMsgids, 0, seenuid );
  2399. for (int r = 0; r < nranges; r++) {
  2400. sprintf( buf, "%u:%u", ranges[r].first, ranges[r].last );
  2401. imap_submit_load( ctx, buf, ranges[r].flags, sts );
  2402. }
  2403. }
  2404. free( excs.data );
  2405. imap_submit_load_p3( ctx, sts );
  2406. }
  2407. }
  2408. static int
  2409. imap_sort_msgs_comp( const void *a_, const void *b_ )
  2410. {
  2411. const message_t *a = *(const message_t * const *)a_;
  2412. const message_t *b = *(const message_t * const *)b_;
  2413. if (a->uid < b->uid)
  2414. return -1;
  2415. if (a->uid > b->uid)
  2416. return 1;
  2417. return 0;
  2418. }
  2419. static void
  2420. imap_sort_msgs( imap_store_t *ctx )
  2421. {
  2422. int count = count_generic_messages( ctx->msgs );
  2423. if (count <= 1)
  2424. return;
  2425. message_t **t = nfmalloc( sizeof(*t) * count );
  2426. message_t *m = ctx->msgs;
  2427. for (int i = 0; i < count; i++) {
  2428. t[i] = m;
  2429. m = m->next;
  2430. }
  2431. qsort( t, count, sizeof(*t), imap_sort_msgs_comp );
  2432. ctx->msgs = t[0];
  2433. int j;
  2434. for (j = 0; j < count - 1; j++)
  2435. t[j]->next = t[j + 1];
  2436. ctx->msgapp = &t[j]->next;
  2437. *ctx->msgapp = NULL;
  2438. free( t );
  2439. }
  2440. static void imap_submit_load_p2( imap_store_t *, imap_cmd_t *, int );
  2441. static void
  2442. imap_submit_load( imap_store_t *ctx, const char *buf, int flags, imap_load_box_state_t *sts )
  2443. {
  2444. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_submit_load_p2,
  2445. "UID FETCH %s (UID%s%s%s%s%s%s%s)", buf,
  2446. (ctx->opts & OPEN_FLAGS) ? " FLAGS" : "",
  2447. (flags & WantSize) ? " RFC822.SIZE" : "",
  2448. (flags & (WantTuids | WantMsgids)) ? " BODY.PEEK[HEADER.FIELDS (" : "",
  2449. (flags & WantTuids) ? "X-TUID" : "",
  2450. !(~flags & (WantTuids | WantMsgids)) ? " " : "",
  2451. (flags & WantMsgids) ? "MESSAGE-ID" : "",
  2452. (flags & (WantTuids | WantMsgids)) ? ")]" : "");
  2453. }
  2454. static void
  2455. imap_submit_load_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  2456. {
  2457. imap_load_box_state_t *sts = (imap_load_box_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2458. transform_refcounted_box_response( &sts->gen, response );
  2459. imap_submit_load_p3( ctx, sts );
  2460. }
  2461. static void
  2462. imap_submit_load_p3( imap_store_t *ctx, imap_load_box_state_t *sts )
  2463. {
  2464. DONE_REFCOUNTED_STATE_ARGS(sts, {
  2465. if (sts->gen.ret_val == DRV_OK)
  2466. imap_sort_msgs( ctx );
  2467. }, ctx->msgs, ctx->total_msgs, ctx->recent_msgs)
  2468. }
  2469. /******************* imap_fetch_msg *******************/
  2470. static void imap_fetch_msg_p2( imap_store_t *, imap_cmd_t *, int );
  2471. static void
  2472. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data,
  2473. void (*cb)( int sts, void *aux ), void *aux )
  2474. {
  2475. imap_cmd_fetch_msg_t *cmd;
  2476. INIT_IMAP_CMD_X(imap_cmd_fetch_msg_t, cmd, cb, aux)
  2477. cmd->gen.gen.param.uid = msg->uid;
  2478. cmd->msg_data = data;
  2479. data->data = 0;
  2480. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_fetch_msg_p2,
  2481. "UID FETCH %u (%s%sBODY.PEEK[])", msg->uid,
  2482. !(msg->status & M_FLAGS) ? "FLAGS " : "",
  2483. (data->date== -1) ? "INTERNALDATE " : "" );
  2484. }
  2485. static void
  2486. imap_fetch_msg_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2487. {
  2488. imap_cmd_fetch_msg_t *cmd = (imap_cmd_fetch_msg_t *)gcmd;
  2489. if (response == RESP_OK && !cmd->msg_data->data) {
  2490. /* The FETCH succeeded, but there is no message with this UID. */
  2491. response = RESP_NO;
  2492. }
  2493. imap_done_simple_msg( ctx, gcmd, response );
  2494. }
  2495. /******************* imap_set_msg_flags *******************/
  2496. static int
  2497. imap_make_flags( int flags, char *buf )
  2498. {
  2499. const char *s;
  2500. uint i, d;
  2501. for (i = d = 0; i < as(Flags); i++)
  2502. if (flags & (1 << i)) {
  2503. buf[d++] = ' ';
  2504. buf[d++] = '\\';
  2505. for (s = Flags[i]; *s; s++)
  2506. buf[d++] = *s;
  2507. }
  2508. buf[0] = '(';
  2509. buf[d++] = ')';
  2510. return d;
  2511. }
  2512. typedef struct {
  2513. imap_cmd_refcounted_state_t gen;
  2514. void (*callback)( int sts, void *aux );
  2515. void *callback_aux;
  2516. } imap_set_msg_flags_state_t;
  2517. static void imap_set_flags_p2( imap_store_t *, imap_cmd_t *, int );
  2518. static void imap_set_flags_p3( imap_set_msg_flags_state_t * );
  2519. static void
  2520. imap_flags_helper( imap_store_t *ctx, uint uid, char what, int flags,
  2521. imap_set_msg_flags_state_t *sts )
  2522. {
  2523. char buf[256];
  2524. buf[imap_make_flags( flags, buf )] = 0;
  2525. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_set_flags_p2,
  2526. "UID STORE %u %cFLAGS.SILENT %s", uid, what, buf );
  2527. }
  2528. static void
  2529. imap_set_msg_flags( store_t *gctx, message_t *msg, uint uid, int add, int del,
  2530. void (*cb)( int sts, void *aux ), void *aux )
  2531. {
  2532. imap_store_t *ctx = (imap_store_t *)gctx;
  2533. if (msg) {
  2534. uid = msg->uid;
  2535. add &= ~msg->flags;
  2536. del &= msg->flags;
  2537. msg->flags |= add;
  2538. msg->flags &= ~del;
  2539. }
  2540. if (add || del) {
  2541. INIT_REFCOUNTED_STATE(imap_set_msg_flags_state_t, sts, cb, aux)
  2542. if (add)
  2543. imap_flags_helper( ctx, uid, '+', add, sts );
  2544. if (del)
  2545. imap_flags_helper( ctx, uid, '-', del, sts );
  2546. imap_set_flags_p3( sts );
  2547. } else {
  2548. cb( DRV_OK, aux );
  2549. }
  2550. }
  2551. static void
  2552. imap_set_flags_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2553. {
  2554. imap_set_msg_flags_state_t *sts = (imap_set_msg_flags_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2555. transform_refcounted_msg_response( &sts->gen, response);
  2556. imap_set_flags_p3( sts );
  2557. }
  2558. static void
  2559. imap_set_flags_p3( imap_set_msg_flags_state_t *sts )
  2560. {
  2561. DONE_REFCOUNTED_STATE(sts)
  2562. }
  2563. /******************* imap_close_box *******************/
  2564. typedef struct {
  2565. imap_cmd_refcounted_state_t gen;
  2566. void (*callback)( int sts, void *aux );
  2567. void *callback_aux;
  2568. } imap_expunge_state_t;
  2569. static void imap_close_box_p2( imap_store_t *, imap_cmd_t *, int );
  2570. static void imap_close_box_p3( imap_expunge_state_t * );
  2571. static void
  2572. imap_close_box( store_t *gctx,
  2573. void (*cb)( int sts, void *aux ), void *aux )
  2574. {
  2575. imap_store_t *ctx = (imap_store_t *)gctx;
  2576. if (ctx->gen.conf->trash && CAP(UIDPLUS)) {
  2577. INIT_REFCOUNTED_STATE(imap_expunge_state_t, sts, cb, aux)
  2578. message_t *msg, *fmsg, *nmsg;
  2579. int bl;
  2580. char buf[1000];
  2581. for (msg = ctx->msgs; ; ) {
  2582. for (bl = 0; msg && bl < 960; msg = msg->next) {
  2583. if (!(msg->flags & F_DELETED))
  2584. continue;
  2585. if (bl)
  2586. buf[bl++] = ',';
  2587. bl += sprintf( buf + bl, "%u", msg->uid );
  2588. fmsg = msg;
  2589. for (; (nmsg = msg->next) && (nmsg->flags & F_DELETED); msg = nmsg) {}
  2590. if (msg != fmsg)
  2591. bl += sprintf( buf + bl, ":%u", msg->uid );
  2592. }
  2593. if (!bl)
  2594. break;
  2595. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_close_box_p2,
  2596. "UID EXPUNGE %s", buf );
  2597. }
  2598. imap_close_box_p3( sts );
  2599. } else {
  2600. /* This is inherently racy: it may cause messages which other clients
  2601. * marked as deleted to be expunged without being trashed. */
  2602. imap_cmd_simple_t *cmd;
  2603. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2604. imap_exec( ctx, &cmd->gen, imap_done_simple_box, "CLOSE" );
  2605. }
  2606. }
  2607. static void
  2608. imap_close_box_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2609. {
  2610. imap_expunge_state_t *sts = (imap_expunge_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2611. transform_refcounted_box_response( &sts->gen, response );
  2612. imap_close_box_p3( sts );
  2613. }
  2614. static void
  2615. imap_close_box_p3( imap_expunge_state_t *sts )
  2616. {
  2617. DONE_REFCOUNTED_STATE(sts)
  2618. }
  2619. /******************* imap_trash_msg *******************/
  2620. static void
  2621. imap_trash_msg( store_t *gctx, message_t *msg,
  2622. void (*cb)( int sts, void *aux ), void *aux )
  2623. {
  2624. imap_store_t *ctx = (imap_store_t *)gctx;
  2625. imap_cmd_simple_t *cmd;
  2626. char *buf;
  2627. INIT_IMAP_CMD(imap_cmd_simple_t, cmd, cb, aux)
  2628. cmd->gen.param.create = 1;
  2629. cmd->gen.param.to_trash = 1;
  2630. if (prepare_trash( &buf, ctx ) < 0) {
  2631. cb( DRV_BOX_BAD, aux );
  2632. return;
  2633. }
  2634. imap_exec( ctx, &cmd->gen, imap_done_simple_msg,
  2635. CAP(MOVE) ? "UID MOVE %u \"%\\s\"" : "UID COPY %u \"%\\s\"", msg->uid, buf );
  2636. free( buf );
  2637. }
  2638. /******************* imap_store_msg *******************/
  2639. static void imap_store_msg_p2( imap_store_t *, imap_cmd_t *, int );
  2640. static size_t
  2641. my_strftime( char *s, size_t max, const char *fmt, const struct tm *tm )
  2642. {
  2643. return strftime( s, max, fmt, tm );
  2644. }
  2645. static void
  2646. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  2647. void (*cb)( int sts, uint uid, void *aux ), void *aux )
  2648. {
  2649. imap_store_t *ctx = (imap_store_t *)gctx;
  2650. imap_cmd_out_uid_t *cmd;
  2651. char *buf;
  2652. int d;
  2653. char flagstr[128], datestr[64];
  2654. d = 0;
  2655. if (data->flags) {
  2656. d = imap_make_flags( data->flags, flagstr );
  2657. flagstr[d++] = ' ';
  2658. }
  2659. flagstr[d] = 0;
  2660. INIT_IMAP_CMD(imap_cmd_out_uid_t, cmd, cb, aux)
  2661. ctx->buffer_mem += data->len;
  2662. cmd->gen.param.data_len = data->len;
  2663. cmd->gen.param.data = data->data;
  2664. cmd->out_uid = 0;
  2665. if (to_trash) {
  2666. cmd->gen.param.create = 1;
  2667. cmd->gen.param.to_trash = 1;
  2668. if (prepare_trash( &buf, ctx ) < 0) {
  2669. cb( DRV_BOX_BAD, -1, aux );
  2670. return;
  2671. }
  2672. } else {
  2673. if (prepare_box( &buf, ctx ) < 0) {
  2674. cb( DRV_BOX_BAD, -1, aux );
  2675. return;
  2676. }
  2677. }
  2678. if (data->date) {
  2679. /* configure ensures that %z actually works. */
  2680. my_strftime( datestr, sizeof(datestr), "%d-%b-%Y %H:%M:%S %z", localtime( &data->date ) );
  2681. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2682. "APPEND \"%\\s\" %s\"%\\s\" ", buf, flagstr, datestr );
  2683. } else {
  2684. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  2685. "APPEND \"%\\s\" %s", buf, flagstr );
  2686. }
  2687. free( buf );
  2688. }
  2689. static void
  2690. imap_store_msg_p2( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *cmd, int response )
  2691. {
  2692. imap_cmd_out_uid_t *cmdp = (imap_cmd_out_uid_t *)cmd;
  2693. transform_msg_response( &response );
  2694. cmdp->callback( response, cmdp->out_uid, cmdp->callback_aux );
  2695. }
  2696. /******************* imap_find_new_msgs *******************/
  2697. static void imap_find_new_msgs_p2( imap_store_t *, imap_cmd_t *, int );
  2698. static void imap_find_new_msgs_p3( imap_store_t *, imap_cmd_t *, int );
  2699. static void imap_find_new_msgs_p4( imap_store_t *, imap_cmd_t *, int );
  2700. static void
  2701. imap_find_new_msgs( store_t *gctx, uint newuid,
  2702. void (*cb)( int sts, message_t *msgs, void *aux ), void *aux )
  2703. {
  2704. imap_store_t *ctx = (imap_store_t *)gctx;
  2705. imap_cmd_find_new_t *cmd;
  2706. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cb, aux)
  2707. cmd->out_msgs = ctx->msgapp;
  2708. cmd->uid = newuid;
  2709. // Some servers fail to enumerate recently STOREd messages without syncing first.
  2710. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_find_new_msgs_p2, "CHECK" );
  2711. }
  2712. static void
  2713. imap_find_new_msgs_p2( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2714. {
  2715. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2716. imap_cmd_find_new_t *cmd;
  2717. if (response != RESP_OK) {
  2718. imap_done_simple_box( ctx, gcmd, response );
  2719. return;
  2720. }
  2721. ctx->uidnext = 0;
  2722. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cmdp->callback, cmdp->callback_aux)
  2723. cmd->out_msgs = cmdp->out_msgs;
  2724. cmd->uid = cmdp->uid;
  2725. cmd->gen.param.lastuid = 1;
  2726. imap_exec( ctx, &cmd->gen, imap_find_new_msgs_p3,
  2727. "UID FETCH * (UID)" );
  2728. }
  2729. static void
  2730. imap_find_new_msgs_p3( imap_store_t *ctx, imap_cmd_t *gcmd, int response )
  2731. {
  2732. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2733. imap_cmd_find_new_t *cmd;
  2734. if (response != RESP_OK) {
  2735. imap_find_new_msgs_p4( ctx, gcmd, response );
  2736. return;
  2737. }
  2738. if (!ctx->uidnext) {
  2739. // We are assuming that the new messages were not in fact instantly deleted.
  2740. error( "IMAP error: re-querying server for highest UID failed\n" );
  2741. imap_find_new_msgs_p4( ctx, gcmd, RESP_NO );
  2742. return;
  2743. }
  2744. INIT_IMAP_CMD(imap_cmd_find_new_t, cmd, cmdp->callback, cmdp->callback_aux)
  2745. cmd->out_msgs = cmdp->out_msgs;
  2746. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_find_new_msgs_p4,
  2747. "UID FETCH %u:%u (UID BODY.PEEK[HEADER.FIELDS (X-TUID)])", cmdp->uid, ctx->uidnext - 1 );
  2748. }
  2749. static void
  2750. imap_find_new_msgs_p4( imap_store_t *ctx ATTR_UNUSED, imap_cmd_t *gcmd, int response )
  2751. {
  2752. imap_cmd_find_new_t *cmdp = (imap_cmd_find_new_t *)gcmd;
  2753. transform_box_response( &response );
  2754. cmdp->callback( response, *cmdp->out_msgs, cmdp->callback_aux );
  2755. }
  2756. /******************* imap_list_store *******************/
  2757. typedef struct {
  2758. imap_cmd_refcounted_state_t gen;
  2759. void (*callback)( int sts, string_list_t *, void *aux );
  2760. void *callback_aux;
  2761. } imap_list_store_state_t;
  2762. static void imap_list_store_p2( imap_store_t *, imap_cmd_t *, int );
  2763. static void imap_list_store_p3( imap_store_t *, imap_list_store_state_t * );
  2764. static void
  2765. imap_list_store( store_t *gctx, int flags,
  2766. void (*cb)( int sts, string_list_t *boxes, void *aux ), void *aux )
  2767. {
  2768. imap_store_t *ctx = (imap_store_t *)gctx;
  2769. INIT_REFCOUNTED_STATE(imap_list_store_state_t, sts, cb, aux)
  2770. // ctx->prefix may be empty, "INBOX.", or something else.
  2771. // 'flags' may be LIST_INBOX, LIST_PATH (or LIST_PATH_MAYBE), or both. 'listed'
  2772. // already containing a particular value effectively removes it from 'flags'.
  2773. // This matrix determines what to query, and what comes out as a side effect.
  2774. // The lowercase letters indicate unnecessary results; the queries are done
  2775. // this way to have non-overlapping result sets, so subsequent calls create
  2776. // no duplicates:
  2777. //
  2778. // qry \ pfx | empty | inbox | other
  2779. // ----------+-------+-------+-------
  2780. // inbox | p [I] | I [p] | I
  2781. // both | P [I] | I [P] | I + P
  2782. // path | P [i] | i [P] | P
  2783. //
  2784. int pfx_is_empty = !*ctx->prefix;
  2785. int pfx_is_inbox = !pfx_is_empty && is_inbox( ctx, ctx->prefix, -1 );
  2786. if (((flags & (LIST_PATH | LIST_PATH_MAYBE)) || pfx_is_empty) && !pfx_is_inbox && !(ctx->listed & LIST_PATH)) {
  2787. ctx->listed |= LIST_PATH;
  2788. if (pfx_is_empty)
  2789. ctx->listed |= LIST_INBOX;
  2790. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_list_store_p2,
  2791. "LIST \"\" \"%\\s*\"", ctx->prefix );
  2792. }
  2793. if (((flags & LIST_INBOX) || pfx_is_inbox) && !pfx_is_empty && !(ctx->listed & LIST_INBOX)) {
  2794. ctx->listed |= LIST_INBOX;
  2795. if (pfx_is_inbox)
  2796. ctx->listed |= LIST_PATH;
  2797. imap_exec( ctx, imap_refcounted_new_cmd( &sts->gen ), imap_list_store_p2,
  2798. "LIST \"\" INBOX*" );
  2799. }
  2800. imap_list_store_p3( ctx, sts );
  2801. }
  2802. static void
  2803. imap_list_store_p2( imap_store_t *ctx, imap_cmd_t *cmd, int response )
  2804. {
  2805. imap_list_store_state_t *sts = (imap_list_store_state_t *)((imap_cmd_refcounted_t *)cmd)->state;
  2806. transform_refcounted_box_response( &sts->gen, response );
  2807. imap_list_store_p3( ctx, sts );
  2808. }
  2809. static void
  2810. imap_list_store_p3( imap_store_t *ctx, imap_list_store_state_t *sts )
  2811. {
  2812. DONE_REFCOUNTED_STATE_ARGS(sts, , ctx->boxes)
  2813. }
  2814. /******************* imap_cancel_cmds *******************/
  2815. static void
  2816. imap_cancel_cmds( store_t *gctx,
  2817. void (*cb)( void *aux ), void *aux )
  2818. {
  2819. imap_store_t *ctx = (imap_store_t *)gctx;
  2820. cancel_pending_imap_cmds( ctx );
  2821. if (ctx->in_progress) {
  2822. ctx->canceling = 1;
  2823. ctx->callbacks.imap_cancel = cb;
  2824. ctx->callback_aux = aux;
  2825. } else {
  2826. cb( aux );
  2827. }
  2828. }
  2829. /******************* imap_commit_cmds *******************/
  2830. static void
  2831. imap_commit_cmds( store_t *gctx )
  2832. {
  2833. (void)gctx;
  2834. }
  2835. /******************* imap_get_memory_usage *******************/
  2836. static int
  2837. imap_get_memory_usage( store_t *gctx )
  2838. {
  2839. imap_store_t *ctx = (imap_store_t *)gctx;
  2840. return ctx->buffer_mem + ctx->conn.buffer_mem;
  2841. }
  2842. /******************* imap_get_fail_state *******************/
  2843. static int
  2844. imap_get_fail_state( store_conf_t *gconf )
  2845. {
  2846. return ((imap_store_conf_t *)gconf)->server->failed;
  2847. }
  2848. /******************* imap_parse_store *******************/
  2849. imap_server_conf_t *servers, **serverapp = &servers;
  2850. static int
  2851. imap_parse_store( conffile_t *cfg, store_conf_t **storep )
  2852. {
  2853. imap_store_conf_t *store;
  2854. imap_server_conf_t *server, *srv, sserver;
  2855. const char *type, *name, *arg;
  2856. unsigned u;
  2857. int acc_opt = 0;
  2858. #ifdef HAVE_LIBSSL
  2859. /* Legacy SSL options */
  2860. int require_ssl = -1, use_imaps = -1;
  2861. int use_sslv3 = -1, use_tlsv1 = -1, use_tlsv11 = -1, use_tlsv12 = -1;
  2862. #endif
  2863. /* Legacy SASL option */
  2864. int require_cram = -1;
  2865. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  2866. server = nfcalloc( sizeof(*server) );
  2867. server->name = nfstrdup( cfg->val );
  2868. *serverapp = server;
  2869. serverapp = &server->next;
  2870. store = 0;
  2871. *storep = 0;
  2872. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  2873. store = nfcalloc( sizeof(*store) );
  2874. store->gen.driver = &imap_driver;
  2875. store->gen.name = nfstrdup( cfg->val );
  2876. store->use_namespace = 1;
  2877. *storep = &store->gen;
  2878. memset( &sserver, 0, sizeof(sserver) );
  2879. server = &sserver;
  2880. } else
  2881. return 0;
  2882. server->sconf.timeout = 20;
  2883. #ifdef HAVE_LIBSSL
  2884. server->ssl_type = -1;
  2885. server->sconf.ssl_versions = -1;
  2886. server->sconf.system_certs = 1;
  2887. #endif
  2888. server->max_in_progress = INT_MAX;
  2889. while (getcline( cfg ) && cfg->cmd) {
  2890. if (!strcasecmp( "Host", cfg->cmd )) {
  2891. /* The imap[s]: syntax is just a backwards compat hack. */
  2892. arg = cfg->val;
  2893. #ifdef HAVE_LIBSSL
  2894. if (starts_with( arg, -1, "imaps:", 6 )) {
  2895. arg += 6;
  2896. server->ssl_type = SSL_IMAPS;
  2897. if (server->sconf.ssl_versions == -1)
  2898. server->sconf.ssl_versions = SSLv3 | TLSv1 | TLSv1_1 | TLSv1_2;
  2899. } else
  2900. #endif
  2901. if (starts_with( arg, -1, "imap:", 5 ))
  2902. arg += 5;
  2903. if (starts_with( arg, -1, "//", 2 ))
  2904. arg += 2;
  2905. if (arg != cfg->val)
  2906. warn( "%s:%d: Notice: URL notation is deprecated; use a plain host name and possibly 'SSLType IMAPS' instead\n", cfg->file, cfg->line );
  2907. server->sconf.host = nfstrdup( arg );
  2908. }
  2909. else if (!strcasecmp( "User", cfg->cmd ))
  2910. server->user = nfstrdup( cfg->val );
  2911. else if (!strcasecmp( "Pass", cfg->cmd ))
  2912. server->pass = nfstrdup( cfg->val );
  2913. else if (!strcasecmp( "PassCmd", cfg->cmd ))
  2914. server->pass_cmd = nfstrdup( cfg->val );
  2915. else if (!strcasecmp( "Port", cfg->cmd )) {
  2916. int port = parse_int( cfg );
  2917. if ((unsigned)port > 0xffff) {
  2918. error( "%s:%d: Invalid port number\n", cfg->file, cfg->line );
  2919. cfg->err = 1;
  2920. } else {
  2921. server->sconf.port = (ushort)port;
  2922. }
  2923. } else if (!strcasecmp( "Timeout", cfg->cmd ))
  2924. server->sconf.timeout = parse_int( cfg );
  2925. else if (!strcasecmp( "PipelineDepth", cfg->cmd )) {
  2926. if ((server->max_in_progress = parse_int( cfg )) < 1) {
  2927. error( "%s:%d: PipelineDepth must be at least 1\n", cfg->file, cfg->line );
  2928. cfg->err = 1;
  2929. }
  2930. } else if (!strcasecmp( "DisableExtension", cfg->cmd ) ||
  2931. !strcasecmp( "DisableExtensions", cfg->cmd )) {
  2932. arg = cfg->val;
  2933. do {
  2934. for (u = 0; u < as(cap_list); u++) {
  2935. if (!strcasecmp( cap_list[u], arg )) {
  2936. server->cap_mask |= 1 << u;
  2937. goto gotcap;
  2938. }
  2939. }
  2940. error( "%s:%d: Unrecognized IMAP extension '%s'\n", cfg->file, cfg->line, arg );
  2941. cfg->err = 1;
  2942. gotcap: ;
  2943. } while ((arg = get_arg( cfg, ARG_OPTIONAL, 0 )));
  2944. }
  2945. #ifdef HAVE_LIBSSL
  2946. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  2947. server->sconf.cert_file = expand_strdup( cfg->val );
  2948. if (access( server->sconf.cert_file, R_OK )) {
  2949. sys_error( "%s:%d: CertificateFile '%s'",
  2950. cfg->file, cfg->line, server->sconf.cert_file );
  2951. cfg->err = 1;
  2952. }
  2953. } else if (!strcasecmp( "SystemCertificates", cfg->cmd )) {
  2954. server->sconf.system_certs = parse_bool( cfg );
  2955. } else if (!strcasecmp( "ClientCertificate", cfg->cmd )) {
  2956. server->sconf.client_certfile = expand_strdup( cfg->val );
  2957. if (access( server->sconf.client_certfile, R_OK )) {
  2958. sys_error( "%s:%d: ClientCertificate '%s'",
  2959. cfg->file, cfg->line, server->sconf.client_certfile );
  2960. cfg->err = 1;
  2961. }
  2962. } else if (!strcasecmp( "ClientKey", cfg->cmd )) {
  2963. server->sconf.client_keyfile = expand_strdup( cfg->val );
  2964. if (access( server->sconf.client_keyfile, R_OK )) {
  2965. sys_error( "%s:%d: ClientKey '%s'",
  2966. cfg->file, cfg->line, server->sconf.client_keyfile );
  2967. cfg->err = 1;
  2968. }
  2969. } else if (!strcasecmp( "SSLType", cfg->cmd )) {
  2970. if (!strcasecmp( "None", cfg->val )) {
  2971. server->ssl_type = SSL_None;
  2972. } else if (!strcasecmp( "STARTTLS", cfg->val )) {
  2973. server->ssl_type = SSL_STARTTLS;
  2974. } else if (!strcasecmp( "IMAPS", cfg->val )) {
  2975. server->ssl_type = SSL_IMAPS;
  2976. } else {
  2977. error( "%s:%d: Invalid SSL type\n", cfg->file, cfg->line );
  2978. cfg->err = 1;
  2979. }
  2980. } else if (!strcasecmp( "SSLVersion", cfg->cmd ) ||
  2981. !strcasecmp( "SSLVersions", cfg->cmd )) {
  2982. server->sconf.ssl_versions = 0;
  2983. arg = cfg->val;
  2984. do {
  2985. if (!strcasecmp( "SSLv2", arg )) {
  2986. warn( "Warning: SSLVersion SSLv2 is no longer supported\n" );
  2987. } else if (!strcasecmp( "SSLv3", arg )) {
  2988. server->sconf.ssl_versions |= SSLv3;
  2989. } else if (!strcasecmp( "TLSv1", arg )) {
  2990. server->sconf.ssl_versions |= TLSv1;
  2991. } else if (!strcasecmp( "TLSv1.1", arg )) {
  2992. server->sconf.ssl_versions |= TLSv1_1;
  2993. } else if (!strcasecmp( "TLSv1.2", arg )) {
  2994. server->sconf.ssl_versions |= TLSv1_2;
  2995. } else {
  2996. error( "%s:%d: Unrecognized SSL version\n", cfg->file, cfg->line );
  2997. cfg->err = 1;
  2998. }
  2999. } while ((arg = get_arg( cfg, ARG_OPTIONAL, 0 )));
  3000. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  3001. require_ssl = parse_bool( cfg );
  3002. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  3003. use_imaps = parse_bool( cfg );
  3004. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  3005. warn( "Warning: UseSSLv2 is no longer supported\n" );
  3006. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  3007. use_sslv3 = parse_bool( cfg );
  3008. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  3009. use_tlsv1 = parse_bool( cfg );
  3010. else if (!strcasecmp( "UseTLSv1.1", cfg->cmd ))
  3011. use_tlsv11 = parse_bool( cfg );
  3012. else if (!strcasecmp( "UseTLSv1.2", cfg->cmd ))
  3013. use_tlsv12 = parse_bool( cfg );
  3014. #endif
  3015. else if (!strcasecmp( "AuthMech", cfg->cmd ) ||
  3016. !strcasecmp( "AuthMechs", cfg->cmd )) {
  3017. arg = cfg->val;
  3018. do
  3019. add_string_list( &server->auth_mechs, arg );
  3020. while ((arg = get_arg( cfg, ARG_OPTIONAL, 0 )));
  3021. } else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  3022. require_cram = parse_bool( cfg );
  3023. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  3024. server->sconf.tunnel = nfstrdup( cfg->val );
  3025. else if (store) {
  3026. if (!strcasecmp( "Account", cfg->cmd )) {
  3027. for (srv = servers; srv; srv = srv->next)
  3028. if (srv->name && !strcmp( srv->name, cfg->val ))
  3029. goto gotsrv;
  3030. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  3031. cfg->err = 1;
  3032. continue;
  3033. gotsrv:
  3034. store->server = srv;
  3035. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  3036. store->use_namespace = parse_bool( cfg );
  3037. else if (!strcasecmp( "Path", cfg->cmd ))
  3038. store->gen.path = nfstrdup( cfg->val );
  3039. else if (!strcasecmp( "PathDelimiter", cfg->cmd )) {
  3040. if (strlen( cfg->val ) != 1) {
  3041. error( "%s:%d: Path delimiter must be exactly one character long\n", cfg->file, cfg->line );
  3042. cfg->err = 1;
  3043. continue;
  3044. }
  3045. store->delimiter = cfg->val[0];
  3046. } else
  3047. parse_generic_store( &store->gen, cfg );
  3048. continue;
  3049. } else {
  3050. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  3051. cfg->err = 1;
  3052. continue;
  3053. }
  3054. acc_opt = 1;
  3055. }
  3056. if (store)
  3057. type = "IMAP store", name = store->gen.name;
  3058. else
  3059. type = "IMAP account", name = server->name;
  3060. if (!store || !store->server) {
  3061. if (!server->sconf.tunnel && !server->sconf.host) {
  3062. error( "%s '%s' has neither Tunnel nor Host\n", type, name );
  3063. cfg->err = 1;
  3064. return 1;
  3065. }
  3066. if (server->pass && server->pass_cmd) {
  3067. error( "%s '%s' has both Pass and PassCmd\n", type, name );
  3068. cfg->err = 1;
  3069. return 1;
  3070. }
  3071. #ifdef HAVE_LIBSSL
  3072. if ((use_sslv3 & use_tlsv1 & use_tlsv11 & use_tlsv12) != -1 || use_imaps >= 0 || require_ssl >= 0) {
  3073. if (server->ssl_type >= 0 || server->sconf.ssl_versions >= 0) {
  3074. error( "%s '%s': The deprecated UseSSL*, UseTLS*, UseIMAPS, and RequireSSL options are mutually exclusive with SSLType and SSLVersions.\n", type, name );
  3075. cfg->err = 1;
  3076. return 1;
  3077. }
  3078. warn( "Notice: %s '%s': UseSSL*, UseTLS*, UseIMAPS, and RequireSSL are deprecated. Use SSLType and SSLVersions instead.\n", type, name );
  3079. server->sconf.ssl_versions =
  3080. (use_sslv3 != 1 ? 0 : SSLv3) |
  3081. (use_tlsv1 == 0 ? 0 : TLSv1) |
  3082. (use_tlsv11 != 1 ? 0 : TLSv1_1) |
  3083. (use_tlsv12 != 1 ? 0 : TLSv1_2);
  3084. if (use_imaps == 1) {
  3085. server->ssl_type = SSL_IMAPS;
  3086. } else if (require_ssl) {
  3087. server->ssl_type = SSL_STARTTLS;
  3088. } else if (!server->sconf.ssl_versions) {
  3089. server->ssl_type = SSL_None;
  3090. } else {
  3091. warn( "Notice: %s '%s': 'RequireSSL no' is being ignored\n", type, name );
  3092. server->ssl_type = SSL_STARTTLS;
  3093. }
  3094. if (server->ssl_type != SSL_None && !server->sconf.ssl_versions) {
  3095. error( "%s '%s' requires SSL but no SSL versions enabled\n", type, name );
  3096. cfg->err = 1;
  3097. return 1;
  3098. }
  3099. } else {
  3100. if (server->sconf.ssl_versions < 0)
  3101. server->sconf.ssl_versions = TLSv1 | TLSv1_1 | TLSv1_2;
  3102. if (server->ssl_type < 0)
  3103. server->ssl_type = server->sconf.tunnel ? SSL_None : SSL_STARTTLS;
  3104. }
  3105. #endif
  3106. if (require_cram >= 0) {
  3107. if (server->auth_mechs) {
  3108. error( "%s '%s': The deprecated RequireCRAM option is mutually exclusive with AuthMech.\n", type, name );
  3109. cfg->err = 1;
  3110. return 1;
  3111. }
  3112. warn( "Notice: %s '%s': RequireCRAM is deprecated. Use AuthMech instead.\n", type, name );
  3113. if (require_cram)
  3114. add_string_list(&server->auth_mechs, "CRAM-MD5");
  3115. }
  3116. if (!server->auth_mechs)
  3117. add_string_list( &server->auth_mechs, "*" );
  3118. if (!server->sconf.port)
  3119. server->sconf.port =
  3120. #ifdef HAVE_LIBSSL
  3121. server->ssl_type == SSL_IMAPS ? 993 :
  3122. #endif
  3123. 143;
  3124. }
  3125. if (store) {
  3126. if (!store->server) {
  3127. store->server = nfmalloc( sizeof(sserver) );
  3128. memcpy( store->server, &sserver, sizeof(sserver) );
  3129. store->server->name = store->gen.name;
  3130. } else if (acc_opt) {
  3131. error( "%s '%s' has both Account and account-specific options\n", type, name );
  3132. cfg->err = 1;
  3133. }
  3134. }
  3135. return 1;
  3136. }
  3137. static int
  3138. imap_get_caps( store_t *gctx ATTR_UNUSED )
  3139. {
  3140. return DRV_CRLF | DRV_VERBOSE;
  3141. }
  3142. struct driver imap_driver = {
  3143. imap_get_caps,
  3144. imap_parse_store,
  3145. imap_cleanup,
  3146. imap_alloc_store,
  3147. imap_set_bad_callback,
  3148. imap_connect_store,
  3149. imap_free_store,
  3150. imap_cancel_store,
  3151. imap_list_store,
  3152. imap_select_box,
  3153. imap_get_box_path,
  3154. imap_create_box,
  3155. imap_open_box,
  3156. imap_get_uidnext,
  3157. imap_confirm_box_empty,
  3158. imap_delete_box,
  3159. imap_finish_delete_box,
  3160. imap_prepare_load_box,
  3161. imap_load_box,
  3162. imap_fetch_msg,
  3163. imap_store_msg,
  3164. imap_find_new_msgs,
  3165. imap_set_msg_flags,
  3166. imap_trash_msg,
  3167. imap_close_box,
  3168. imap_cancel_cmds,
  3169. imap_commit_cmds,
  3170. imap_get_memory_usage,
  3171. imap_get_fail_state,
  3172. };