drv_imap.c 89 KB

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