drv_imap.c 84 KB

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