drv_imap.c 99 KB

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