drv_imap.c 94 KB

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