drv_imap.c 97 KB

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