drv_imap.c 95 KB

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