drv_imap.c 97 KB

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