drv_imap.c 93 KB

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