imap.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * RFC2195 CRAM-MD5 authentication
  22. * RFC2595 Using TLS with IMAP, POP3 and ACAP
  23. * RFC2831 DIGEST-MD5 authentication
  24. * RFC3501 IMAPv4 protocol
  25. * RFC4422 Simple Authentication and Security Layer (SASL)
  26. * RFC4616 PLAIN authentication
  27. * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
  28. * RFC4959 IMAP Extension for SASL Initial Client Response
  29. * RFC5092 IMAP URL Scheme
  30. * RFC6749 OAuth 2.0 Authorization Framework
  31. * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
  32. *
  33. ***************************************************************************/
  34. #include "curl_setup.h"
  35. #ifndef CURL_DISABLE_IMAP
  36. #ifdef HAVE_NETINET_IN_H
  37. #include <netinet/in.h>
  38. #endif
  39. #ifdef HAVE_ARPA_INET_H
  40. #include <arpa/inet.h>
  41. #endif
  42. #ifdef HAVE_UTSNAME_H
  43. #include <sys/utsname.h>
  44. #endif
  45. #ifdef HAVE_NETDB_H
  46. #include <netdb.h>
  47. #endif
  48. #ifdef __VMS
  49. #include <in.h>
  50. #include <inet.h>
  51. #endif
  52. #if (defined(NETWARE) && defined(__NOVELL_LIBC__))
  53. #undef in_addr_t
  54. #define in_addr_t unsigned long
  55. #endif
  56. #include <curl/curl.h>
  57. #include "urldata.h"
  58. #include "sendf.h"
  59. #include "if2ip.h"
  60. #include "hostip.h"
  61. #include "progress.h"
  62. #include "transfer.h"
  63. #include "escape.h"
  64. #include "http.h" /* for HTTP proxy tunnel stuff */
  65. #include "socks.h"
  66. #include "imap.h"
  67. #include "strtoofft.h"
  68. #include "strequal.h"
  69. #include "vtls/vtls.h"
  70. #include "connect.h"
  71. #include "strerror.h"
  72. #include "select.h"
  73. #include "multiif.h"
  74. #include "url.h"
  75. #include "rawstr.h"
  76. #include "curl_sasl.h"
  77. #include "warnless.h"
  78. #define _MPRINTF_REPLACE /* use our functions only */
  79. #include <curl/mprintf.h>
  80. #include "curl_memory.h"
  81. /* The last #include file should be: */
  82. #include "memdebug.h"
  83. /* Local API functions */
  84. static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
  85. static CURLcode imap_do(struct connectdata *conn, bool *done);
  86. static CURLcode imap_done(struct connectdata *conn, CURLcode status,
  87. bool premature);
  88. static CURLcode imap_connect(struct connectdata *conn, bool *done);
  89. static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
  90. static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
  91. static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
  92. int numsocks);
  93. static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done);
  94. static CURLcode imap_setup_connection(struct connectdata *conn);
  95. static char *imap_atom(const char *str);
  96. static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...);
  97. static CURLcode imap_parse_url_options(struct connectdata *conn);
  98. static CURLcode imap_parse_url_path(struct connectdata *conn);
  99. static CURLcode imap_parse_custom_request(struct connectdata *conn);
  100. static CURLcode imap_calc_sasl_details(struct connectdata *conn,
  101. const char **mech,
  102. char **initresp, size_t *len,
  103. imapstate *state1, imapstate *state2);
  104. /*
  105. * IMAP protocol handler.
  106. */
  107. const struct Curl_handler Curl_handler_imap = {
  108. "IMAP", /* scheme */
  109. imap_setup_connection, /* setup_connection */
  110. imap_do, /* do_it */
  111. imap_done, /* done */
  112. ZERO_NULL, /* do_more */
  113. imap_connect, /* connect_it */
  114. imap_multi_statemach, /* connecting */
  115. imap_doing, /* doing */
  116. imap_getsock, /* proto_getsock */
  117. imap_getsock, /* doing_getsock */
  118. ZERO_NULL, /* domore_getsock */
  119. ZERO_NULL, /* perform_getsock */
  120. imap_disconnect, /* disconnect */
  121. ZERO_NULL, /* readwrite */
  122. PORT_IMAP, /* defport */
  123. CURLPROTO_IMAP, /* protocol */
  124. PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD /* flags */
  125. };
  126. #ifdef USE_SSL
  127. /*
  128. * IMAPS protocol handler.
  129. */
  130. const struct Curl_handler Curl_handler_imaps = {
  131. "IMAPS", /* scheme */
  132. imap_setup_connection, /* setup_connection */
  133. imap_do, /* do_it */
  134. imap_done, /* done */
  135. ZERO_NULL, /* do_more */
  136. imap_connect, /* connect_it */
  137. imap_multi_statemach, /* connecting */
  138. imap_doing, /* doing */
  139. imap_getsock, /* proto_getsock */
  140. imap_getsock, /* doing_getsock */
  141. ZERO_NULL, /* domore_getsock */
  142. ZERO_NULL, /* perform_getsock */
  143. imap_disconnect, /* disconnect */
  144. ZERO_NULL, /* readwrite */
  145. PORT_IMAPS, /* defport */
  146. CURLPROTO_IMAPS, /* protocol */
  147. PROTOPT_CLOSEACTION | PROTOPT_SSL |
  148. PROTOPT_NEEDSPWD /* flags */
  149. };
  150. #endif
  151. #ifndef CURL_DISABLE_HTTP
  152. /*
  153. * HTTP-proxyed IMAP protocol handler.
  154. */
  155. static const struct Curl_handler Curl_handler_imap_proxy = {
  156. "IMAP", /* scheme */
  157. Curl_http_setup_conn, /* setup_connection */
  158. Curl_http, /* do_it */
  159. Curl_http_done, /* done */
  160. ZERO_NULL, /* do_more */
  161. ZERO_NULL, /* connect_it */
  162. ZERO_NULL, /* connecting */
  163. ZERO_NULL, /* doing */
  164. ZERO_NULL, /* proto_getsock */
  165. ZERO_NULL, /* doing_getsock */
  166. ZERO_NULL, /* domore_getsock */
  167. ZERO_NULL, /* perform_getsock */
  168. ZERO_NULL, /* disconnect */
  169. ZERO_NULL, /* readwrite */
  170. PORT_IMAP, /* defport */
  171. CURLPROTO_HTTP, /* protocol */
  172. PROTOPT_NONE /* flags */
  173. };
  174. #ifdef USE_SSL
  175. /*
  176. * HTTP-proxyed IMAPS protocol handler.
  177. */
  178. static const struct Curl_handler Curl_handler_imaps_proxy = {
  179. "IMAPS", /* scheme */
  180. Curl_http_setup_conn, /* setup_connection */
  181. Curl_http, /* do_it */
  182. Curl_http_done, /* done */
  183. ZERO_NULL, /* do_more */
  184. ZERO_NULL, /* connect_it */
  185. ZERO_NULL, /* connecting */
  186. ZERO_NULL, /* doing */
  187. ZERO_NULL, /* proto_getsock */
  188. ZERO_NULL, /* doing_getsock */
  189. ZERO_NULL, /* domore_getsock */
  190. ZERO_NULL, /* perform_getsock */
  191. ZERO_NULL, /* disconnect */
  192. ZERO_NULL, /* readwrite */
  193. PORT_IMAPS, /* defport */
  194. CURLPROTO_HTTP, /* protocol */
  195. PROTOPT_NONE /* flags */
  196. };
  197. #endif
  198. #endif
  199. #ifdef USE_SSL
  200. static void imap_to_imaps(struct connectdata *conn)
  201. {
  202. conn->handler = &Curl_handler_imaps;
  203. }
  204. #else
  205. #define imap_to_imaps(x) Curl_nop_stmt
  206. #endif
  207. /***********************************************************************
  208. *
  209. * imap_matchresp()
  210. *
  211. * Determines whether the untagged response is related to the specified
  212. * command by checking if it is in format "* <command-name> ..." or
  213. * "* <number> <command-name> ...".
  214. *
  215. * The "* " marker is assumed to have already been checked by the caller.
  216. */
  217. static bool imap_matchresp(const char *line, size_t len, const char *cmd)
  218. {
  219. const char *end = line + len;
  220. size_t cmd_len = strlen(cmd);
  221. /* Skip the untagged response marker */
  222. line += 2;
  223. /* Do we have a number after the marker? */
  224. if(line < end && ISDIGIT(*line)) {
  225. /* Skip the number */
  226. do
  227. line++;
  228. while(line < end && ISDIGIT(*line));
  229. /* Do we have the space character? */
  230. if(line == end || *line != ' ')
  231. return FALSE;
  232. line++;
  233. }
  234. /* Does the command name match and is it followed by a space character or at
  235. the end of line? */
  236. if(line + cmd_len <= end && Curl_raw_nequal(line, cmd, cmd_len) &&
  237. (line[cmd_len] == ' ' || line + cmd_len + 2 == end))
  238. return TRUE;
  239. return FALSE;
  240. }
  241. /***********************************************************************
  242. *
  243. * imap_endofresp()
  244. *
  245. * Checks whether the given string is a valid tagged, untagged or continuation
  246. * response which can be processed by the response handler.
  247. */
  248. static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
  249. int *resp)
  250. {
  251. struct IMAP *imap = conn->data->req.protop;
  252. struct imap_conn *imapc = &conn->proto.imapc;
  253. const char *id = imapc->resptag;
  254. size_t id_len = strlen(id);
  255. /* Do we have a tagged command response? */
  256. if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
  257. line += id_len + 1;
  258. len -= id_len + 1;
  259. if(len >= 2 && !memcmp(line, "OK", 2))
  260. *resp = 'O';
  261. else if(len >= 2 && !memcmp(line, "NO", 2))
  262. *resp = 'N';
  263. else if(len >= 3 && !memcmp(line, "BAD", 3))
  264. *resp = 'B';
  265. else {
  266. failf(conn->data, "Bad tagged response");
  267. *resp = -1;
  268. }
  269. return TRUE;
  270. }
  271. /* Do we have an untagged command response? */
  272. if(len >= 2 && !memcmp("* ", line, 2)) {
  273. switch(imapc->state) {
  274. /* States which are interested in untagged responses */
  275. case IMAP_CAPABILITY:
  276. if(!imap_matchresp(line, len, "CAPABILITY"))
  277. return FALSE;
  278. break;
  279. case IMAP_LIST:
  280. if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
  281. (imap->custom && !imap_matchresp(line, len, imap->custom) &&
  282. (strcmp(imap->custom, "STORE") ||
  283. !imap_matchresp(line, len, "FETCH")) &&
  284. strcmp(imap->custom, "SELECT") &&
  285. strcmp(imap->custom, "EXAMINE") &&
  286. strcmp(imap->custom, "SEARCH") &&
  287. strcmp(imap->custom, "EXPUNGE") &&
  288. strcmp(imap->custom, "LSUB") &&
  289. strcmp(imap->custom, "UID") &&
  290. strcmp(imap->custom, "NOOP")))
  291. return FALSE;
  292. break;
  293. case IMAP_SELECT:
  294. /* SELECT is special in that its untagged responses do not have a
  295. common prefix so accept anything! */
  296. break;
  297. case IMAP_FETCH:
  298. if(!imap_matchresp(line, len, "FETCH"))
  299. return FALSE;
  300. break;
  301. case IMAP_SEARCH:
  302. if(!imap_matchresp(line, len, "SEARCH"))
  303. return FALSE;
  304. break;
  305. /* Ignore other untagged responses */
  306. default:
  307. return FALSE;
  308. }
  309. *resp = '*';
  310. return TRUE;
  311. }
  312. /* Do we have a continuation response? This should be a + symbol followed by
  313. a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
  314. APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
  315. some e-mail servers ignore this and only send a single + instead. */
  316. if((len == 3 && !memcmp("+", line, 1)) ||
  317. (len >= 2 && !memcmp("+ ", line, 2))) {
  318. switch(imapc->state) {
  319. /* States which are interested in continuation responses */
  320. case IMAP_AUTHENTICATE_PLAIN:
  321. case IMAP_AUTHENTICATE_LOGIN:
  322. case IMAP_AUTHENTICATE_LOGIN_PASSWD:
  323. case IMAP_AUTHENTICATE_CRAMMD5:
  324. case IMAP_AUTHENTICATE_DIGESTMD5:
  325. case IMAP_AUTHENTICATE_DIGESTMD5_RESP:
  326. case IMAP_AUTHENTICATE_NTLM:
  327. case IMAP_AUTHENTICATE_NTLM_TYPE2MSG:
  328. case IMAP_AUTHENTICATE_XOAUTH2:
  329. case IMAP_AUTHENTICATE_FINAL:
  330. case IMAP_APPEND:
  331. *resp = '+';
  332. break;
  333. default:
  334. failf(conn->data, "Unexpected continuation response");
  335. *resp = -1;
  336. break;
  337. }
  338. return TRUE;
  339. }
  340. return FALSE; /* Nothing for us */
  341. }
  342. /***********************************************************************
  343. *
  344. * imap_get_message()
  345. *
  346. * Gets the authentication message from the response buffer.
  347. */
  348. static void imap_get_message(char *buffer, char** outptr)
  349. {
  350. size_t len = 0;
  351. char* message = NULL;
  352. /* Find the start of the message */
  353. for(message = buffer + 2; *message == ' ' || *message == '\t'; message++)
  354. ;
  355. /* Find the end of the message */
  356. for(len = strlen(message); len--;)
  357. if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
  358. message[len] != '\t')
  359. break;
  360. /* Terminate the message */
  361. if(++len) {
  362. message[len] = '\0';
  363. }
  364. *outptr = message;
  365. }
  366. /***********************************************************************
  367. *
  368. * state()
  369. *
  370. * This is the ONLY way to change IMAP state!
  371. */
  372. static void state(struct connectdata *conn, imapstate newstate)
  373. {
  374. struct imap_conn *imapc = &conn->proto.imapc;
  375. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  376. /* for debug purposes */
  377. static const char * const names[]={
  378. "STOP",
  379. "SERVERGREET",
  380. "CAPABILITY",
  381. "STARTTLS",
  382. "UPGRADETLS",
  383. "AUTHENTICATE_PLAIN",
  384. "AUTHENTICATE_LOGIN",
  385. "AUTHENTICATE_LOGIN_PASSWD",
  386. "AUTHENTICATE_CRAMMD5",
  387. "AUTHENTICATE_DIGESTMD5",
  388. "AUTHENTICATE_DIGESTMD5_RESP",
  389. "AUTHENTICATE_NTLM",
  390. "AUTHENTICATE_NTLM_TYPE2MSG",
  391. "AUTHENTICATE_GSSAPI",
  392. "AUTHENTICATE_GSSAPI_TOKEN",
  393. "AUTHENTICATE_GSSAPI_NO_DATA",
  394. "AUTHENTICATE_XOAUTH2",
  395. "AUTHENTICATE_CANCEL",
  396. "AUTHENTICATE_FINAL",
  397. "LOGIN",
  398. "LIST",
  399. "SELECT",
  400. "FETCH",
  401. "FETCH_FINAL",
  402. "APPEND",
  403. "APPEND_FINAL",
  404. "SEARCH",
  405. "LOGOUT",
  406. /* LAST */
  407. };
  408. if(imapc->state != newstate)
  409. infof(conn->data, "IMAP %p state change from %s to %s\n",
  410. (void *)imapc, names[imapc->state], names[newstate]);
  411. #endif
  412. imapc->state = newstate;
  413. }
  414. /***********************************************************************
  415. *
  416. * imap_perform_capability()
  417. *
  418. * Sends the CAPABILITY command in order to obtain a list of server side
  419. * supported capabilities.
  420. */
  421. static CURLcode imap_perform_capability(struct connectdata *conn)
  422. {
  423. CURLcode result = CURLE_OK;
  424. struct imap_conn *imapc = &conn->proto.imapc;
  425. imapc->authmechs = 0; /* No known authentication mechanisms yet */
  426. imapc->authused = 0; /* Clear the authentication mechanism used */
  427. imapc->tls_supported = FALSE; /* Clear the TLS capability */
  428. /* Send the CAPABILITY command */
  429. result = imap_sendf(conn, "CAPABILITY");
  430. if(!result)
  431. state(conn, IMAP_CAPABILITY);
  432. return result;
  433. }
  434. /***********************************************************************
  435. *
  436. * imap_perform_starttls()
  437. *
  438. * Sends the STARTTLS command to start the upgrade to TLS.
  439. */
  440. static CURLcode imap_perform_starttls(struct connectdata *conn)
  441. {
  442. CURLcode result = CURLE_OK;
  443. /* Send the STARTTLS command */
  444. result = imap_sendf(conn, "STARTTLS");
  445. if(!result)
  446. state(conn, IMAP_STARTTLS);
  447. return result;
  448. }
  449. /***********************************************************************
  450. *
  451. * imap_perform_upgrade_tls()
  452. *
  453. * Performs the upgrade to TLS.
  454. */
  455. static CURLcode imap_perform_upgrade_tls(struct connectdata *conn)
  456. {
  457. CURLcode result = CURLE_OK;
  458. struct imap_conn *imapc = &conn->proto.imapc;
  459. /* Start the SSL connection */
  460. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
  461. if(!result) {
  462. if(imapc->state != IMAP_UPGRADETLS)
  463. state(conn, IMAP_UPGRADETLS);
  464. if(imapc->ssldone) {
  465. imap_to_imaps(conn);
  466. result = imap_perform_capability(conn);
  467. }
  468. }
  469. return result;
  470. }
  471. /***********************************************************************
  472. *
  473. * imap_perform_login()
  474. *
  475. * Sends a clear text LOGIN command to authenticate with.
  476. */
  477. static CURLcode imap_perform_login(struct connectdata *conn)
  478. {
  479. CURLcode result = CURLE_OK;
  480. char *user;
  481. char *passwd;
  482. /* Check we have a username and password to authenticate with and end the
  483. connect phase if we don't */
  484. if(!conn->bits.user_passwd) {
  485. state(conn, IMAP_STOP);
  486. return result;
  487. }
  488. /* Make sure the username and password are in the correct atom format */
  489. user = imap_atom(conn->user);
  490. passwd = imap_atom(conn->passwd);
  491. /* Send the LOGIN command */
  492. result = imap_sendf(conn, "LOGIN %s %s", user ? user : "",
  493. passwd ? passwd : "");
  494. Curl_safefree(user);
  495. Curl_safefree(passwd);
  496. if(!result)
  497. state(conn, IMAP_LOGIN);
  498. return result;
  499. }
  500. /***********************************************************************
  501. *
  502. * imap_perform_authenticate()
  503. *
  504. * Sends an AUTHENTICATE command allowing the client to login with the given
  505. * SASL authentication mechanism.
  506. */
  507. static CURLcode imap_perform_authenticate(struct connectdata *conn,
  508. const char *mech,
  509. const char *initresp,
  510. imapstate state1, imapstate state2)
  511. {
  512. CURLcode result = CURLE_OK;
  513. if(initresp) {
  514. /* Send the AUTHENTICATE command with the initial response */
  515. result = imap_sendf(conn, "AUTHENTICATE %s %s", mech, initresp);
  516. if(!result)
  517. state(conn, state2);
  518. }
  519. else {
  520. /* Send the AUTHENTICATE command */
  521. result = imap_sendf(conn, "AUTHENTICATE %s", mech);
  522. if(!result)
  523. state(conn, state1);
  524. }
  525. return result;
  526. }
  527. /***********************************************************************
  528. *
  529. * imap_perform_authentication()
  530. *
  531. * Initiates the authentication sequence, with the appropriate SASL
  532. * authentication mechanism, falling back to clear text should a common
  533. * mechanism not be available between the client and server.
  534. */
  535. static CURLcode imap_perform_authentication(struct connectdata *conn)
  536. {
  537. CURLcode result = CURLE_OK;
  538. struct imap_conn *imapc = &conn->proto.imapc;
  539. const char *mech = NULL;
  540. char *initresp = NULL;
  541. size_t len = 0;
  542. imapstate state1 = IMAP_STOP;
  543. imapstate state2 = IMAP_STOP;
  544. /* Check we have a username and password to authenticate with and end the
  545. connect phase if we don't */
  546. if(!conn->bits.user_passwd) {
  547. state(conn, IMAP_STOP);
  548. return result;
  549. }
  550. /* Calculate the SASL login details */
  551. result = imap_calc_sasl_details(conn, &mech, &initresp, &len, &state1,
  552. &state2);
  553. if(!result) {
  554. if(mech && (imapc->preftype & IMAP_TYPE_SASL)) {
  555. /* Perform SASL based authentication */
  556. result = imap_perform_authenticate(conn, mech, initresp, state1, state2);
  557. }
  558. else if((!imapc->login_disabled) &&
  559. (imapc->preftype & IMAP_TYPE_CLEARTEXT))
  560. /* Perform clear text authentication */
  561. result = imap_perform_login(conn);
  562. else {
  563. /* Other mechanisms not supported */
  564. infof(conn->data, "No known authentication mechanisms supported!\n");
  565. result = CURLE_LOGIN_DENIED;
  566. }
  567. }
  568. Curl_safefree(initresp);
  569. return result;
  570. }
  571. /***********************************************************************
  572. *
  573. * imap_perform_list()
  574. *
  575. * Sends a LIST command or an alternative custom request.
  576. */
  577. static CURLcode imap_perform_list(struct connectdata *conn)
  578. {
  579. CURLcode result = CURLE_OK;
  580. struct SessionHandle *data = conn->data;
  581. struct IMAP *imap = data->req.protop;
  582. char *mailbox;
  583. if(imap->custom)
  584. /* Send the custom request */
  585. result = imap_sendf(conn, "%s%s", imap->custom,
  586. imap->custom_params ? imap->custom_params : "");
  587. else {
  588. /* Make sure the mailbox is in the correct atom format */
  589. mailbox = imap_atom(imap->mailbox ? imap->mailbox : "");
  590. if(!mailbox)
  591. return CURLE_OUT_OF_MEMORY;
  592. /* Send the LIST command */
  593. result = imap_sendf(conn, "LIST \"%s\" *", mailbox);
  594. Curl_safefree(mailbox);
  595. }
  596. if(!result)
  597. state(conn, IMAP_LIST);
  598. return result;
  599. }
  600. /***********************************************************************
  601. *
  602. * imap_perform_select()
  603. *
  604. * Sends a SELECT command to ask the server to change the selected mailbox.
  605. */
  606. static CURLcode imap_perform_select(struct connectdata *conn)
  607. {
  608. CURLcode result = CURLE_OK;
  609. struct SessionHandle *data = conn->data;
  610. struct IMAP *imap = data->req.protop;
  611. struct imap_conn *imapc = &conn->proto.imapc;
  612. char *mailbox;
  613. /* Invalidate old information as we are switching mailboxes */
  614. Curl_safefree(imapc->mailbox);
  615. Curl_safefree(imapc->mailbox_uidvalidity);
  616. /* Check we have a mailbox */
  617. if(!imap->mailbox) {
  618. failf(conn->data, "Cannot SELECT without a mailbox.");
  619. return CURLE_URL_MALFORMAT;
  620. }
  621. /* Make sure the mailbox is in the correct atom format */
  622. mailbox = imap_atom(imap->mailbox);
  623. if(!mailbox)
  624. return CURLE_OUT_OF_MEMORY;
  625. /* Send the SELECT command */
  626. result = imap_sendf(conn, "SELECT %s", mailbox);
  627. Curl_safefree(mailbox);
  628. if(!result)
  629. state(conn, IMAP_SELECT);
  630. return result;
  631. }
  632. /***********************************************************************
  633. *
  634. * imap_perform_fetch()
  635. *
  636. * Sends a FETCH command to initiate the download of a message.
  637. */
  638. static CURLcode imap_perform_fetch(struct connectdata *conn)
  639. {
  640. CURLcode result = CURLE_OK;
  641. struct IMAP *imap = conn->data->req.protop;
  642. /* Check we have a UID */
  643. if(!imap->uid) {
  644. failf(conn->data, "Cannot FETCH without a UID.");
  645. return CURLE_URL_MALFORMAT;
  646. }
  647. /* Send the FETCH command */
  648. if(imap->partial)
  649. result = imap_sendf(conn, "FETCH %s BODY[%s]<%s>",
  650. imap->uid,
  651. imap->section ? imap->section : "",
  652. imap->partial);
  653. else
  654. result = imap_sendf(conn, "FETCH %s BODY[%s]",
  655. imap->uid,
  656. imap->section ? imap->section : "");
  657. if(!result)
  658. state(conn, IMAP_FETCH);
  659. return result;
  660. }
  661. /***********************************************************************
  662. *
  663. * imap_perform_append()
  664. *
  665. * Sends an APPEND command to initiate the upload of a message.
  666. */
  667. static CURLcode imap_perform_append(struct connectdata *conn)
  668. {
  669. CURLcode result = CURLE_OK;
  670. struct IMAP *imap = conn->data->req.protop;
  671. char *mailbox;
  672. /* Check we have a mailbox */
  673. if(!imap->mailbox) {
  674. failf(conn->data, "Cannot APPEND without a mailbox.");
  675. return CURLE_URL_MALFORMAT;
  676. }
  677. /* Check we know the size of the upload */
  678. if(conn->data->state.infilesize < 0) {
  679. failf(conn->data, "Cannot APPEND with unknown input file size\n");
  680. return CURLE_UPLOAD_FAILED;
  681. }
  682. /* Make sure the mailbox is in the correct atom format */
  683. mailbox = imap_atom(imap->mailbox);
  684. if(!mailbox)
  685. return CURLE_OUT_OF_MEMORY;
  686. /* Send the APPEND command */
  687. result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}",
  688. mailbox, conn->data->state.infilesize);
  689. Curl_safefree(mailbox);
  690. if(!result)
  691. state(conn, IMAP_APPEND);
  692. return result;
  693. }
  694. /***********************************************************************
  695. *
  696. * imap_perform_search()
  697. *
  698. * Sends a SEARCH command.
  699. */
  700. static CURLcode imap_perform_search(struct connectdata *conn)
  701. {
  702. CURLcode result = CURLE_OK;
  703. struct IMAP *imap = conn->data->req.protop;
  704. /* Check we have a query string */
  705. if(!imap->query) {
  706. failf(conn->data, "Cannot SEARCH without a query string.");
  707. return CURLE_URL_MALFORMAT;
  708. }
  709. /* Send the SEARCH command */
  710. result = imap_sendf(conn, "SEARCH %s", imap->query);
  711. if(!result)
  712. state(conn, IMAP_SEARCH);
  713. return result;
  714. }
  715. /***********************************************************************
  716. *
  717. * imap_perform_logout()
  718. *
  719. * Performs the logout action prior to sclose() being called.
  720. */
  721. static CURLcode imap_perform_logout(struct connectdata *conn)
  722. {
  723. CURLcode result = CURLE_OK;
  724. /* Send the LOGOUT command */
  725. result = imap_sendf(conn, "LOGOUT");
  726. if(!result)
  727. state(conn, IMAP_LOGOUT);
  728. return result;
  729. }
  730. /* For the initial server greeting */
  731. static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
  732. int imapcode,
  733. imapstate instate)
  734. {
  735. CURLcode result = CURLE_OK;
  736. struct SessionHandle *data = conn->data;
  737. (void)instate; /* no use for this yet */
  738. if(imapcode != 'O') {
  739. failf(data, "Got unexpected imap-server response");
  740. result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
  741. }
  742. else
  743. result = imap_perform_capability(conn);
  744. return result;
  745. }
  746. /* For CAPABILITY responses */
  747. static CURLcode imap_state_capability_resp(struct connectdata *conn,
  748. int imapcode,
  749. imapstate instate)
  750. {
  751. CURLcode result = CURLE_OK;
  752. struct SessionHandle *data = conn->data;
  753. struct imap_conn *imapc = &conn->proto.imapc;
  754. const char *line = data->state.buffer;
  755. size_t wordlen;
  756. (void)instate; /* no use for this yet */
  757. /* Do we have a untagged response? */
  758. if(imapcode == '*') {
  759. line += 2;
  760. /* Loop through the data line */
  761. for(;;) {
  762. while(*line &&
  763. (*line == ' ' || *line == '\t' ||
  764. *line == '\r' || *line == '\n')) {
  765. line++;
  766. }
  767. if(!*line)
  768. break;
  769. /* Extract the word */
  770. for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' &&
  771. line[wordlen] != '\t' && line[wordlen] != '\r' &&
  772. line[wordlen] != '\n';)
  773. wordlen++;
  774. /* Does the server support the STARTTLS capability? */
  775. if(wordlen == 8 && !memcmp(line, "STARTTLS", 8))
  776. imapc->tls_supported = TRUE;
  777. /* Has the server explicitly disabled clear text authentication? */
  778. else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13))
  779. imapc->login_disabled = TRUE;
  780. /* Does the server support the SASL-IR capability? */
  781. else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7))
  782. imapc->ir_supported = TRUE;
  783. /* Do we have a SASL based authentication mechanism? */
  784. else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) {
  785. line += 5;
  786. wordlen -= 5;
  787. /* Test the word for a matching authentication mechanism */
  788. if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_LOGIN))
  789. imapc->authmechs |= SASL_MECH_LOGIN;
  790. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_PLAIN))
  791. imapc->authmechs |= SASL_MECH_PLAIN;
  792. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_CRAM_MD5))
  793. imapc->authmechs |= SASL_MECH_CRAM_MD5;
  794. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_DIGEST_MD5))
  795. imapc->authmechs |= SASL_MECH_DIGEST_MD5;
  796. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_GSSAPI))
  797. imapc->authmechs |= SASL_MECH_GSSAPI;
  798. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_EXTERNAL))
  799. imapc->authmechs |= SASL_MECH_EXTERNAL;
  800. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_NTLM))
  801. imapc->authmechs |= SASL_MECH_NTLM;
  802. else if(sasl_mech_equal(line, wordlen, SASL_MECH_STRING_XOAUTH2))
  803. imapc->authmechs |= SASL_MECH_XOAUTH2;
  804. }
  805. line += wordlen;
  806. }
  807. }
  808. else if(imapcode == 'O') {
  809. if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
  810. /* We don't have a SSL/TLS connection yet, but SSL is requested */
  811. if(imapc->tls_supported)
  812. /* Switch to TLS connection now */
  813. result = imap_perform_starttls(conn);
  814. else if(data->set.use_ssl == CURLUSESSL_TRY)
  815. /* Fallback and carry on with authentication */
  816. result = imap_perform_authentication(conn);
  817. else {
  818. failf(data, "STARTTLS not supported.");
  819. result = CURLE_USE_SSL_FAILED;
  820. }
  821. }
  822. else
  823. result = imap_perform_authentication(conn);
  824. }
  825. else
  826. result = imap_perform_authentication(conn);
  827. return result;
  828. }
  829. /* For STARTTLS responses */
  830. static CURLcode imap_state_starttls_resp(struct connectdata *conn,
  831. int imapcode,
  832. imapstate instate)
  833. {
  834. CURLcode result = CURLE_OK;
  835. struct SessionHandle *data = conn->data;
  836. (void)instate; /* no use for this yet */
  837. if(imapcode != 'O') {
  838. if(data->set.use_ssl != CURLUSESSL_TRY) {
  839. failf(data, "STARTTLS denied. %c", imapcode);
  840. result = CURLE_USE_SSL_FAILED;
  841. }
  842. else
  843. result = imap_perform_authentication(conn);
  844. }
  845. else
  846. result = imap_perform_upgrade_tls(conn);
  847. return result;
  848. }
  849. /* For AUTHENTICATE PLAIN (without initial response) responses */
  850. static CURLcode imap_state_auth_plain_resp(struct connectdata *conn,
  851. int imapcode,
  852. imapstate instate)
  853. {
  854. CURLcode result = CURLE_OK;
  855. struct SessionHandle *data = conn->data;
  856. size_t len = 0;
  857. char *plainauth = NULL;
  858. (void)instate; /* no use for this yet */
  859. if(imapcode != '+') {
  860. failf(data, "Access denied. %c", imapcode);
  861. result = CURLE_LOGIN_DENIED;
  862. }
  863. else {
  864. /* Create the authorisation message */
  865. result = Curl_sasl_create_plain_message(data, conn->user, conn->passwd,
  866. &plainauth, &len);
  867. if(!result && plainauth) {
  868. /* Send the message */
  869. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", plainauth);
  870. if(!result)
  871. state(conn, IMAP_AUTHENTICATE_FINAL);
  872. }
  873. }
  874. Curl_safefree(plainauth);
  875. return result;
  876. }
  877. /* For AUTHENTICATE LOGIN (without initial response) responses */
  878. static CURLcode imap_state_auth_login_resp(struct connectdata *conn,
  879. int imapcode,
  880. imapstate instate)
  881. {
  882. CURLcode result = CURLE_OK;
  883. struct SessionHandle *data = conn->data;
  884. size_t len = 0;
  885. char *authuser = NULL;
  886. (void)instate; /* no use for this yet */
  887. if(imapcode != '+') {
  888. failf(data, "Access denied: %d", imapcode);
  889. result = CURLE_LOGIN_DENIED;
  890. }
  891. else {
  892. /* Create the user message */
  893. result = Curl_sasl_create_login_message(data, conn->user,
  894. &authuser, &len);
  895. if(!result && authuser) {
  896. /* Send the user */
  897. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", authuser);
  898. if(!result)
  899. state(conn, IMAP_AUTHENTICATE_LOGIN_PASSWD);
  900. }
  901. }
  902. Curl_safefree(authuser);
  903. return result;
  904. }
  905. /* For AUTHENTICATE LOGIN user entry responses */
  906. static CURLcode imap_state_auth_login_password_resp(struct connectdata *conn,
  907. int imapcode,
  908. imapstate instate)
  909. {
  910. CURLcode result = CURLE_OK;
  911. struct SessionHandle *data = conn->data;
  912. size_t len = 0;
  913. char *authpasswd = NULL;
  914. (void)instate; /* no use for this yet */
  915. if(imapcode != '+') {
  916. failf(data, "Access denied: %d", imapcode);
  917. result = CURLE_LOGIN_DENIED;
  918. }
  919. else {
  920. /* Create the password message */
  921. result = Curl_sasl_create_login_message(data, conn->passwd,
  922. &authpasswd, &len);
  923. if(!result && authpasswd) {
  924. /* Send the password */
  925. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", authpasswd);
  926. if(!result)
  927. state(conn, IMAP_AUTHENTICATE_FINAL);
  928. }
  929. }
  930. Curl_safefree(authpasswd);
  931. return result;
  932. }
  933. #ifndef CURL_DISABLE_CRYPTO_AUTH
  934. /* For AUTHENTICATE CRAM-MD5 responses */
  935. static CURLcode imap_state_auth_cram_resp(struct connectdata *conn,
  936. int imapcode,
  937. imapstate instate)
  938. {
  939. CURLcode result = CURLE_OK;
  940. struct SessionHandle *data = conn->data;
  941. char *chlg = NULL;
  942. char *chlg64 = NULL;
  943. char *rplyb64 = NULL;
  944. size_t len = 0;
  945. (void)instate; /* no use for this yet */
  946. if(imapcode != '+') {
  947. failf(data, "Access denied: %d", imapcode);
  948. return CURLE_LOGIN_DENIED;
  949. }
  950. /* Get the challenge message */
  951. imap_get_message(data->state.buffer, &chlg64);
  952. /* Decode the challenge message */
  953. result = Curl_sasl_decode_cram_md5_message(chlg64, &chlg, &len);
  954. if(result) {
  955. /* Send the cancellation */
  956. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "*");
  957. if(!result)
  958. state(conn, IMAP_AUTHENTICATE_CANCEL);
  959. }
  960. else {
  961. /* Create the response message */
  962. result = Curl_sasl_create_cram_md5_message(data, chlg, conn->user,
  963. conn->passwd, &rplyb64, &len);
  964. if(!result && rplyb64) {
  965. /* Send the response */
  966. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", rplyb64);
  967. if(!result)
  968. state(conn, IMAP_AUTHENTICATE_FINAL);
  969. }
  970. }
  971. Curl_safefree(chlg);
  972. Curl_safefree(rplyb64);
  973. return result;
  974. }
  975. /* For AUTHENTICATE DIGEST-MD5 challenge responses */
  976. static CURLcode imap_state_auth_digest_resp(struct connectdata *conn,
  977. int imapcode,
  978. imapstate instate)
  979. {
  980. CURLcode result = CURLE_OK;
  981. struct SessionHandle *data = conn->data;
  982. char *chlg64 = NULL;
  983. char *rplyb64 = NULL;
  984. size_t len = 0;
  985. (void)instate; /* no use for this yet */
  986. if(imapcode != '+') {
  987. failf(data, "Access denied: %d", imapcode);
  988. return CURLE_LOGIN_DENIED;
  989. }
  990. /* Get the challenge message */
  991. imap_get_message(data->state.buffer, &chlg64);
  992. /* Create the response message */
  993. result = Curl_sasl_create_digest_md5_message(data, chlg64,
  994. conn->user, conn->passwd,
  995. "imap", &rplyb64, &len);
  996. if(result) {
  997. if(result == CURLE_BAD_CONTENT_ENCODING) {
  998. /* Send the cancellation */
  999. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "*");
  1000. if(!result)
  1001. state(conn, IMAP_AUTHENTICATE_CANCEL);
  1002. }
  1003. }
  1004. else {
  1005. /* Send the response */
  1006. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", rplyb64);
  1007. if(!result)
  1008. state(conn, IMAP_AUTHENTICATE_DIGESTMD5_RESP);
  1009. }
  1010. Curl_safefree(rplyb64);
  1011. return result;
  1012. }
  1013. /* For AUTHENTICATE DIGEST-MD5 challenge-response responses */
  1014. static CURLcode imap_state_auth_digest_resp_resp(struct connectdata *conn,
  1015. int imapcode,
  1016. imapstate instate)
  1017. {
  1018. CURLcode result = CURLE_OK;
  1019. struct SessionHandle *data = conn->data;
  1020. (void)instate; /* no use for this yet */
  1021. if(imapcode != '+') {
  1022. failf(data, "Authentication failed: %d", imapcode);
  1023. result = CURLE_LOGIN_DENIED;
  1024. }
  1025. else {
  1026. /* Send an empty response */
  1027. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
  1028. if(!result)
  1029. state(conn, IMAP_AUTHENTICATE_FINAL);
  1030. }
  1031. return result;
  1032. }
  1033. #endif
  1034. #ifdef USE_NTLM
  1035. /* For AUTHENTICATE NTLM (without initial response) responses */
  1036. static CURLcode imap_state_auth_ntlm_resp(struct connectdata *conn,
  1037. int imapcode,
  1038. imapstate instate)
  1039. {
  1040. CURLcode result = CURLE_OK;
  1041. struct SessionHandle *data = conn->data;
  1042. size_t len = 0;
  1043. char *type1msg = NULL;
  1044. (void)instate; /* no use for this yet */
  1045. if(imapcode != '+') {
  1046. failf(data, "Access denied: %d", imapcode);
  1047. result = CURLE_LOGIN_DENIED;
  1048. }
  1049. else {
  1050. /* Create the type-1 message */
  1051. result = Curl_sasl_create_ntlm_type1_message(conn->user, conn->passwd,
  1052. &conn->ntlm,
  1053. &type1msg, &len);
  1054. if(!result && type1msg) {
  1055. /* Send the message */
  1056. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", type1msg);
  1057. if(!result)
  1058. state(conn, IMAP_AUTHENTICATE_NTLM_TYPE2MSG);
  1059. }
  1060. }
  1061. Curl_safefree(type1msg);
  1062. return result;
  1063. }
  1064. /* For NTLM type-2 responses (sent in reponse to our type-1 message) */
  1065. static CURLcode imap_state_auth_ntlm_type2msg_resp(struct connectdata *conn,
  1066. int imapcode,
  1067. imapstate instate)
  1068. {
  1069. CURLcode result = CURLE_OK;
  1070. struct SessionHandle *data = conn->data;
  1071. char *type2msg = NULL;
  1072. char *type3msg = NULL;
  1073. size_t len = 0;
  1074. (void)instate; /* no use for this yet */
  1075. if(imapcode != '+') {
  1076. failf(data, "Access denied: %d", imapcode);
  1077. result = CURLE_LOGIN_DENIED;
  1078. }
  1079. else {
  1080. /* Get the challenge message */
  1081. imap_get_message(data->state.buffer, &type2msg);
  1082. /* Decode the type-2 message */
  1083. result = Curl_sasl_decode_ntlm_type2_message(data, type2msg, &conn->ntlm);
  1084. if(result) {
  1085. /* Send the cancellation */
  1086. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "*");
  1087. if(!result)
  1088. state(conn, IMAP_AUTHENTICATE_CANCEL);
  1089. }
  1090. else {
  1091. /* Create the type-3 message */
  1092. result = Curl_sasl_create_ntlm_type3_message(data, conn->user,
  1093. conn->passwd, &conn->ntlm,
  1094. &type3msg, &len);
  1095. if(!result && type3msg) {
  1096. /* Send the message */
  1097. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", type3msg);
  1098. if(!result)
  1099. state(conn, IMAP_AUTHENTICATE_FINAL);
  1100. }
  1101. }
  1102. }
  1103. Curl_safefree(type3msg);
  1104. return result;
  1105. }
  1106. #endif
  1107. #if defined(USE_KRB5)
  1108. /* For AUTHENTICATE GSSAPI (without initial response) responses */
  1109. static CURLcode imap_state_auth_gssapi_resp(struct connectdata *conn,
  1110. int imapcode,
  1111. imapstate instate)
  1112. {
  1113. CURLcode result = CURLE_OK;
  1114. struct SessionHandle *data = conn->data;
  1115. struct imap_conn *imapc = &conn->proto.imapc;
  1116. size_t len = 0;
  1117. char *respmsg = NULL;
  1118. (void)instate; /* no use for this yet */
  1119. if(imapcode != '+') {
  1120. failf(data, "Access denied: %d", imapcode);
  1121. result = CURLE_LOGIN_DENIED;
  1122. }
  1123. else {
  1124. /* Create the initial response message */
  1125. result = Curl_sasl_create_gssapi_user_message(data, conn->user,
  1126. conn->passwd, "imap",
  1127. imapc->mutual_auth,
  1128. NULL, &conn->krb5,
  1129. &respmsg, &len);
  1130. if(!result && respmsg) {
  1131. /* Send the message */
  1132. result = Curl_pp_sendf(&imapc->pp, "%s", respmsg);
  1133. if(!result)
  1134. state(conn, IMAP_AUTHENTICATE_GSSAPI_TOKEN);
  1135. }
  1136. }
  1137. Curl_safefree(respmsg);
  1138. return result;
  1139. }
  1140. /* For AUTHENTICATE GSSAPI user token responses */
  1141. static CURLcode imap_state_auth_gssapi_token_resp(struct connectdata *conn,
  1142. int imapcode,
  1143. imapstate instate)
  1144. {
  1145. CURLcode result = CURLE_OK;
  1146. struct SessionHandle *data = conn->data;
  1147. struct imap_conn *imapc = &conn->proto.imapc;
  1148. char *chlgmsg = NULL;
  1149. char *respmsg = NULL;
  1150. size_t len = 0;
  1151. (void)instate; /* no use for this yet */
  1152. if(imapcode != '+') {
  1153. failf(data, "Access denied: %d", imapcode);
  1154. result = CURLE_LOGIN_DENIED;
  1155. }
  1156. else {
  1157. /* Get the challenge message */
  1158. imap_get_message(data->state.buffer, &chlgmsg);
  1159. if(imapc->mutual_auth)
  1160. /* Decode the user token challenge and create the optional response
  1161. message */
  1162. result = Curl_sasl_create_gssapi_user_message(data, NULL, NULL, NULL,
  1163. imapc->mutual_auth,
  1164. chlgmsg, &conn->krb5,
  1165. &respmsg, &len);
  1166. else
  1167. /* Decode the security challenge and create the response message */
  1168. result = Curl_sasl_create_gssapi_security_message(data, chlgmsg,
  1169. &conn->krb5,
  1170. &respmsg, &len);
  1171. if(result) {
  1172. if(result == CURLE_BAD_CONTENT_ENCODING) {
  1173. /* Send the cancellation */
  1174. result = Curl_pp_sendf(&imapc->pp, "%s", "*");
  1175. if(!result)
  1176. state(conn, IMAP_AUTHENTICATE_CANCEL);
  1177. }
  1178. }
  1179. else {
  1180. /* Send the response */
  1181. if(respmsg)
  1182. result = Curl_pp_sendf(&imapc->pp, "%s", respmsg);
  1183. else
  1184. result = Curl_pp_sendf(&imapc->pp, "%s", "");
  1185. if(!result)
  1186. state(conn, (imapc->mutual_auth ? IMAP_AUTHENTICATE_GSSAPI_NO_DATA :
  1187. IMAP_AUTHENTICATE_FINAL));
  1188. }
  1189. }
  1190. Curl_safefree(respmsg);
  1191. return result;
  1192. }
  1193. /* For AUTHENTICATE GSSAPI no data responses */
  1194. static CURLcode imap_state_auth_gssapi_no_data_resp(struct connectdata *conn,
  1195. int imapcode,
  1196. imapstate instate)
  1197. {
  1198. CURLcode result = CURLE_OK;
  1199. struct SessionHandle *data = conn->data;
  1200. char *chlgmsg = NULL;
  1201. char *respmsg = NULL;
  1202. size_t len = 0;
  1203. (void)instate; /* no use for this yet */
  1204. if(imapcode != '+') {
  1205. failf(data, "Access denied: %d", imapcode);
  1206. result = CURLE_LOGIN_DENIED;
  1207. }
  1208. else {
  1209. /* Get the challenge message */
  1210. imap_get_message(data->state.buffer, &chlgmsg);
  1211. /* Decode the security challenge and create the response message */
  1212. result = Curl_sasl_create_gssapi_security_message(data, chlgmsg,
  1213. &conn->krb5,
  1214. &respmsg, &len);
  1215. if(result) {
  1216. if(result == CURLE_BAD_CONTENT_ENCODING) {
  1217. /* Send the cancellation */
  1218. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "*");
  1219. if(!result)
  1220. state(conn, IMAP_AUTHENTICATE_CANCEL);
  1221. }
  1222. }
  1223. else {
  1224. /* Send the response */
  1225. if(respmsg) {
  1226. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", respmsg);
  1227. if(!result)
  1228. state(conn, IMAP_AUTHENTICATE_FINAL);
  1229. }
  1230. }
  1231. }
  1232. Curl_safefree(respmsg);
  1233. return result;
  1234. }
  1235. #endif
  1236. /* For AUTHENTICATE XOAUTH2 (without initial response) responses */
  1237. static CURLcode imap_state_auth_xoauth2_resp(struct connectdata *conn,
  1238. int imapcode,
  1239. imapstate instate)
  1240. {
  1241. CURLcode result = CURLE_OK;
  1242. struct SessionHandle *data = conn->data;
  1243. size_t len = 0;
  1244. char *xoauth = NULL;
  1245. (void)instate; /* no use for this yet */
  1246. if(imapcode != '+') {
  1247. failf(data, "Access denied: %d", imapcode);
  1248. result = CURLE_LOGIN_DENIED;
  1249. }
  1250. else {
  1251. /* Create the authorisation message */
  1252. result = Curl_sasl_create_xoauth2_message(conn->data, conn->user,
  1253. conn->xoauth2_bearer,
  1254. &xoauth, &len);
  1255. if(!result && xoauth) {
  1256. /* Send the message */
  1257. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", xoauth);
  1258. if(!result)
  1259. state(conn, IMAP_AUTHENTICATE_FINAL);
  1260. }
  1261. }
  1262. Curl_safefree(xoauth);
  1263. return result;
  1264. }
  1265. /* For AUTHENTICATE cancellation responses */
  1266. static CURLcode imap_state_auth_cancel_resp(struct connectdata *conn,
  1267. int imapcode,
  1268. imapstate instate)
  1269. {
  1270. CURLcode result = CURLE_OK;
  1271. struct SessionHandle *data = conn->data;
  1272. struct imap_conn *imapc = &conn->proto.imapc;
  1273. const char *mech = NULL;
  1274. char *initresp = NULL;
  1275. size_t len = 0;
  1276. imapstate state1 = IMAP_STOP;
  1277. imapstate state2 = IMAP_STOP;
  1278. (void)imapcode;
  1279. (void)instate; /* no use for this yet */
  1280. /* Remove the offending mechanism from the supported list */
  1281. imapc->authmechs ^= imapc->authused;
  1282. /* Calculate alternative SASL login details */
  1283. result = imap_calc_sasl_details(conn, &mech, &initresp, &len, &state1,
  1284. &state2);
  1285. if(!result) {
  1286. /* Do we have any mechanisms left or can we fallback to clear text? */
  1287. if(mech) {
  1288. /* Retry SASL based authentication */
  1289. result = imap_perform_authenticate(conn, mech, initresp, state1, state2);
  1290. Curl_safefree(initresp);
  1291. }
  1292. else if((!imapc->login_disabled) &&
  1293. (imapc->preftype & IMAP_TYPE_CLEARTEXT))
  1294. /* Perform clear text authentication */
  1295. result = imap_perform_login(conn);
  1296. else {
  1297. failf(data, "Authentication cancelled");
  1298. result = CURLE_LOGIN_DENIED;
  1299. }
  1300. }
  1301. return result;
  1302. }
  1303. /* For final responses in the AUTHENTICATE sequence */
  1304. static CURLcode imap_state_auth_final_resp(struct connectdata *conn,
  1305. int imapcode,
  1306. imapstate instate)
  1307. {
  1308. CURLcode result = CURLE_OK;
  1309. struct SessionHandle *data = conn->data;
  1310. (void)instate; /* no use for this yet */
  1311. if(imapcode != 'O') {
  1312. failf(data, "Authentication failed: %d", imapcode);
  1313. result = CURLE_LOGIN_DENIED;
  1314. }
  1315. else
  1316. /* End of connect phase */
  1317. state(conn, IMAP_STOP);
  1318. return result;
  1319. }
  1320. /* For LOGIN responses */
  1321. static CURLcode imap_state_login_resp(struct connectdata *conn,
  1322. int imapcode,
  1323. imapstate instate)
  1324. {
  1325. CURLcode result = CURLE_OK;
  1326. struct SessionHandle *data = conn->data;
  1327. (void)instate; /* no use for this yet */
  1328. if(imapcode != 'O') {
  1329. failf(data, "Access denied. %c", imapcode);
  1330. result = CURLE_LOGIN_DENIED;
  1331. }
  1332. else
  1333. /* End of connect phase */
  1334. state(conn, IMAP_STOP);
  1335. return result;
  1336. }
  1337. /* For LIST responses */
  1338. static CURLcode imap_state_list_resp(struct connectdata *conn, int imapcode,
  1339. imapstate instate)
  1340. {
  1341. CURLcode result = CURLE_OK;
  1342. char *line = conn->data->state.buffer;
  1343. size_t len = strlen(line);
  1344. (void)instate; /* No use for this yet */
  1345. if(imapcode == '*') {
  1346. /* Temporarily add the LF character back and send as body to the client */
  1347. line[len] = '\n';
  1348. result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
  1349. line[len] = '\0';
  1350. }
  1351. else if(imapcode != 'O')
  1352. result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */
  1353. else
  1354. /* End of DO phase */
  1355. state(conn, IMAP_STOP);
  1356. return result;
  1357. }
  1358. /* For SELECT responses */
  1359. static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
  1360. imapstate instate)
  1361. {
  1362. CURLcode result = CURLE_OK;
  1363. struct SessionHandle *data = conn->data;
  1364. struct IMAP *imap = conn->data->req.protop;
  1365. struct imap_conn *imapc = &conn->proto.imapc;
  1366. const char *line = data->state.buffer;
  1367. char tmp[20];
  1368. (void)instate; /* no use for this yet */
  1369. if(imapcode == '*') {
  1370. /* See if this is an UIDVALIDITY response */
  1371. if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) {
  1372. Curl_safefree(imapc->mailbox_uidvalidity);
  1373. imapc->mailbox_uidvalidity = strdup(tmp);
  1374. }
  1375. }
  1376. else if(imapcode == 'O') {
  1377. /* Check if the UIDVALIDITY has been specified and matches */
  1378. if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
  1379. strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)) {
  1380. failf(conn->data, "Mailbox UIDVALIDITY has changed");
  1381. result = CURLE_REMOTE_FILE_NOT_FOUND;
  1382. }
  1383. else {
  1384. /* Note the currently opened mailbox on this connection */
  1385. imapc->mailbox = strdup(imap->mailbox);
  1386. if(imap->custom)
  1387. result = imap_perform_list(conn);
  1388. else if(imap->query)
  1389. result = imap_perform_search(conn);
  1390. else
  1391. result = imap_perform_fetch(conn);
  1392. }
  1393. }
  1394. else {
  1395. failf(data, "Select failed");
  1396. result = CURLE_LOGIN_DENIED;
  1397. }
  1398. return result;
  1399. }
  1400. /* For the (first line of the) FETCH responses */
  1401. static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
  1402. imapstate instate)
  1403. {
  1404. CURLcode result = CURLE_OK;
  1405. struct SessionHandle *data = conn->data;
  1406. struct imap_conn *imapc = &conn->proto.imapc;
  1407. struct pingpong *pp = &imapc->pp;
  1408. const char *ptr = data->state.buffer;
  1409. bool parsed = FALSE;
  1410. curl_off_t size;
  1411. (void)instate; /* no use for this yet */
  1412. if(imapcode != '*') {
  1413. Curl_pgrsSetDownloadSize(data, -1);
  1414. state(conn, IMAP_STOP);
  1415. return CURLE_REMOTE_FILE_NOT_FOUND; /* TODO: Fix error code */
  1416. }
  1417. /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
  1418. the continuation data contained within the curly brackets */
  1419. while(*ptr && (*ptr != '{'))
  1420. ptr++;
  1421. if(*ptr == '{') {
  1422. char *endptr;
  1423. size = curlx_strtoofft(ptr + 1, &endptr, 10);
  1424. if(endptr - ptr > 1 && endptr[0] == '}' &&
  1425. endptr[1] == '\r' && endptr[2] == '\0')
  1426. parsed = TRUE;
  1427. }
  1428. if(parsed) {
  1429. infof(data, "Found %" CURL_FORMAT_CURL_OFF_TU " bytes to download\n",
  1430. size);
  1431. Curl_pgrsSetDownloadSize(data, size);
  1432. if(pp->cache) {
  1433. /* At this point there is a bunch of data in the header "cache" that is
  1434. actually body content, send it as body and then skip it. Do note
  1435. that there may even be additional "headers" after the body. */
  1436. size_t chunk = pp->cache_size;
  1437. if(chunk > (size_t)size)
  1438. /* The conversion from curl_off_t to size_t is always fine here */
  1439. chunk = (size_t)size;
  1440. result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
  1441. if(result)
  1442. return result;
  1443. data->req.bytecount += chunk;
  1444. infof(data, "Written %" CURL_FORMAT_CURL_OFF_TU
  1445. " bytes, %" CURL_FORMAT_CURL_OFF_TU
  1446. " bytes are left for transfer\n", (curl_off_t)chunk,
  1447. size - chunk);
  1448. /* Have we used the entire cache or just part of it?*/
  1449. if(pp->cache_size > chunk) {
  1450. /* Only part of it so shrink the cache to fit the trailing data */
  1451. memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
  1452. pp->cache_size -= chunk;
  1453. }
  1454. else {
  1455. /* Free the cache */
  1456. Curl_safefree(pp->cache);
  1457. /* Reset the cache size */
  1458. pp->cache_size = 0;
  1459. }
  1460. }
  1461. if(data->req.bytecount == size)
  1462. /* The entire data is already transferred! */
  1463. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1464. else {
  1465. /* IMAP download */
  1466. data->req.maxdownload = size;
  1467. Curl_setup_transfer(conn, FIRSTSOCKET, size, FALSE, NULL, -1, NULL);
  1468. }
  1469. }
  1470. else {
  1471. /* We don't know how to parse this line */
  1472. failf(pp->conn->data, "Failed to parse FETCH response.");
  1473. result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
  1474. }
  1475. /* End of DO phase */
  1476. state(conn, IMAP_STOP);
  1477. return result;
  1478. }
  1479. /* For final FETCH responses performed after the download */
  1480. static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
  1481. int imapcode,
  1482. imapstate instate)
  1483. {
  1484. CURLcode result = CURLE_OK;
  1485. (void)instate; /* No use for this yet */
  1486. if(imapcode != 'O')
  1487. result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: Fix error code */
  1488. else
  1489. /* End of DONE phase */
  1490. state(conn, IMAP_STOP);
  1491. return result;
  1492. }
  1493. /* For APPEND responses */
  1494. static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode,
  1495. imapstate instate)
  1496. {
  1497. CURLcode result = CURLE_OK;
  1498. struct SessionHandle *data = conn->data;
  1499. (void)instate; /* No use for this yet */
  1500. if(imapcode != '+') {
  1501. result = CURLE_UPLOAD_FAILED;
  1502. }
  1503. else {
  1504. /* Set the progress upload size */
  1505. Curl_pgrsSetUploadSize(data, data->state.infilesize);
  1506. /* IMAP upload */
  1507. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
  1508. /* End of DO phase */
  1509. state(conn, IMAP_STOP);
  1510. }
  1511. return result;
  1512. }
  1513. /* For final APPEND responses performed after the upload */
  1514. static CURLcode imap_state_append_final_resp(struct connectdata *conn,
  1515. int imapcode,
  1516. imapstate instate)
  1517. {
  1518. CURLcode result = CURLE_OK;
  1519. (void)instate; /* No use for this yet */
  1520. if(imapcode != 'O')
  1521. result = CURLE_UPLOAD_FAILED;
  1522. else
  1523. /* End of DONE phase */
  1524. state(conn, IMAP_STOP);
  1525. return result;
  1526. }
  1527. /* For SEARCH responses */
  1528. static CURLcode imap_state_search_resp(struct connectdata *conn, int imapcode,
  1529. imapstate instate)
  1530. {
  1531. CURLcode result = CURLE_OK;
  1532. char *line = conn->data->state.buffer;
  1533. size_t len = strlen(line);
  1534. (void)instate; /* No use for this yet */
  1535. if(imapcode == '*') {
  1536. /* Temporarily add the LF character back and send as body to the client */
  1537. line[len] = '\n';
  1538. result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
  1539. line[len] = '\0';
  1540. }
  1541. else if(imapcode != 'O')
  1542. result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */
  1543. else
  1544. /* End of DO phase */
  1545. state(conn, IMAP_STOP);
  1546. return result;
  1547. }
  1548. static CURLcode imap_statemach_act(struct connectdata *conn)
  1549. {
  1550. CURLcode result = CURLE_OK;
  1551. curl_socket_t sock = conn->sock[FIRSTSOCKET];
  1552. int imapcode;
  1553. struct imap_conn *imapc = &conn->proto.imapc;
  1554. struct pingpong *pp = &imapc->pp;
  1555. size_t nread = 0;
  1556. /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
  1557. if(imapc->state == IMAP_UPGRADETLS)
  1558. return imap_perform_upgrade_tls(conn);
  1559. /* Flush any data that needs to be sent */
  1560. if(pp->sendleft)
  1561. return Curl_pp_flushsend(pp);
  1562. do {
  1563. /* Read the response from the server */
  1564. result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
  1565. if(result)
  1566. return result;
  1567. /* Was there an error parsing the response line? */
  1568. if(imapcode == -1)
  1569. return CURLE_FTP_WEIRD_SERVER_REPLY;
  1570. if(!imapcode)
  1571. break;
  1572. /* We have now received a full IMAP server response */
  1573. switch(imapc->state) {
  1574. case IMAP_SERVERGREET:
  1575. result = imap_state_servergreet_resp(conn, imapcode, imapc->state);
  1576. break;
  1577. case IMAP_CAPABILITY:
  1578. result = imap_state_capability_resp(conn, imapcode, imapc->state);
  1579. break;
  1580. case IMAP_STARTTLS:
  1581. result = imap_state_starttls_resp(conn, imapcode, imapc->state);
  1582. break;
  1583. case IMAP_AUTHENTICATE_PLAIN:
  1584. result = imap_state_auth_plain_resp(conn, imapcode, imapc->state);
  1585. break;
  1586. case IMAP_AUTHENTICATE_LOGIN:
  1587. result = imap_state_auth_login_resp(conn, imapcode, imapc->state);
  1588. break;
  1589. case IMAP_AUTHENTICATE_LOGIN_PASSWD:
  1590. result = imap_state_auth_login_password_resp(conn, imapcode,
  1591. imapc->state);
  1592. break;
  1593. #ifndef CURL_DISABLE_CRYPTO_AUTH
  1594. case IMAP_AUTHENTICATE_CRAMMD5:
  1595. result = imap_state_auth_cram_resp(conn, imapcode, imapc->state);
  1596. break;
  1597. case IMAP_AUTHENTICATE_DIGESTMD5:
  1598. result = imap_state_auth_digest_resp(conn, imapcode, imapc->state);
  1599. break;
  1600. case IMAP_AUTHENTICATE_DIGESTMD5_RESP:
  1601. result = imap_state_auth_digest_resp_resp(conn, imapcode, imapc->state);
  1602. break;
  1603. #endif
  1604. #ifdef USE_NTLM
  1605. case IMAP_AUTHENTICATE_NTLM:
  1606. result = imap_state_auth_ntlm_resp(conn, imapcode, imapc->state);
  1607. break;
  1608. case IMAP_AUTHENTICATE_NTLM_TYPE2MSG:
  1609. result = imap_state_auth_ntlm_type2msg_resp(conn, imapcode,
  1610. imapc->state);
  1611. break;
  1612. #endif
  1613. #if defined(USE_KRB5)
  1614. case IMAP_AUTHENTICATE_GSSAPI:
  1615. result = imap_state_auth_gssapi_resp(conn, imapcode, imapc->state);
  1616. break;
  1617. case IMAP_AUTHENTICATE_GSSAPI_TOKEN:
  1618. result = imap_state_auth_gssapi_token_resp(conn, imapcode, imapc->state);
  1619. break;
  1620. case IMAP_AUTHENTICATE_GSSAPI_NO_DATA:
  1621. result = imap_state_auth_gssapi_no_data_resp(conn, imapcode,
  1622. imapc->state);
  1623. break;
  1624. #endif
  1625. case IMAP_AUTHENTICATE_XOAUTH2:
  1626. result = imap_state_auth_xoauth2_resp(conn, imapcode, imapc->state);
  1627. break;
  1628. case IMAP_AUTHENTICATE_CANCEL:
  1629. result = imap_state_auth_cancel_resp(conn, imapcode, imapc->state);
  1630. break;
  1631. case IMAP_AUTHENTICATE_FINAL:
  1632. result = imap_state_auth_final_resp(conn, imapcode, imapc->state);
  1633. break;
  1634. case IMAP_LOGIN:
  1635. result = imap_state_login_resp(conn, imapcode, imapc->state);
  1636. break;
  1637. case IMAP_LIST:
  1638. result = imap_state_list_resp(conn, imapcode, imapc->state);
  1639. break;
  1640. case IMAP_SELECT:
  1641. result = imap_state_select_resp(conn, imapcode, imapc->state);
  1642. break;
  1643. case IMAP_FETCH:
  1644. result = imap_state_fetch_resp(conn, imapcode, imapc->state);
  1645. break;
  1646. case IMAP_FETCH_FINAL:
  1647. result = imap_state_fetch_final_resp(conn, imapcode, imapc->state);
  1648. break;
  1649. case IMAP_APPEND:
  1650. result = imap_state_append_resp(conn, imapcode, imapc->state);
  1651. break;
  1652. case IMAP_APPEND_FINAL:
  1653. result = imap_state_append_final_resp(conn, imapcode, imapc->state);
  1654. break;
  1655. case IMAP_SEARCH:
  1656. result = imap_state_search_resp(conn, imapcode, imapc->state);
  1657. break;
  1658. case IMAP_LOGOUT:
  1659. /* fallthrough, just stop! */
  1660. default:
  1661. /* internal error */
  1662. state(conn, IMAP_STOP);
  1663. break;
  1664. }
  1665. } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
  1666. return result;
  1667. }
  1668. /* Called repeatedly until done from multi.c */
  1669. static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done)
  1670. {
  1671. CURLcode result = CURLE_OK;
  1672. struct imap_conn *imapc = &conn->proto.imapc;
  1673. if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) {
  1674. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
  1675. if(result || !imapc->ssldone)
  1676. return result;
  1677. }
  1678. result = Curl_pp_statemach(&imapc->pp, FALSE);
  1679. *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
  1680. return result;
  1681. }
  1682. static CURLcode imap_block_statemach(struct connectdata *conn)
  1683. {
  1684. CURLcode result = CURLE_OK;
  1685. struct imap_conn *imapc = &conn->proto.imapc;
  1686. while(imapc->state != IMAP_STOP && !result)
  1687. result = Curl_pp_statemach(&imapc->pp, TRUE);
  1688. return result;
  1689. }
  1690. /* Allocate and initialize the struct IMAP for the current SessionHandle if
  1691. required */
  1692. static CURLcode imap_init(struct connectdata *conn)
  1693. {
  1694. CURLcode result = CURLE_OK;
  1695. struct SessionHandle *data = conn->data;
  1696. struct IMAP *imap;
  1697. imap = data->req.protop = calloc(sizeof(struct IMAP), 1);
  1698. if(!imap)
  1699. result = CURLE_OUT_OF_MEMORY;
  1700. return result;
  1701. }
  1702. /* For the IMAP "protocol connect" and "doing" phases only */
  1703. static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
  1704. int numsocks)
  1705. {
  1706. return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks);
  1707. }
  1708. /***********************************************************************
  1709. *
  1710. * imap_connect()
  1711. *
  1712. * This function should do everything that is to be considered a part of the
  1713. * connection phase.
  1714. *
  1715. * The variable 'done' points to will be TRUE if the protocol-layer connect
  1716. * phase is done when this function returns, or FALSE if not.
  1717. */
  1718. static CURLcode imap_connect(struct connectdata *conn, bool *done)
  1719. {
  1720. CURLcode result = CURLE_OK;
  1721. struct imap_conn *imapc = &conn->proto.imapc;
  1722. struct pingpong *pp = &imapc->pp;
  1723. *done = FALSE; /* default to not done yet */
  1724. /* We always support persistent connections in IMAP */
  1725. connkeep(conn, "IMAP default");
  1726. /* Set the default response time-out */
  1727. pp->response_time = RESP_TIMEOUT;
  1728. pp->statemach_act = imap_statemach_act;
  1729. pp->endofresp = imap_endofresp;
  1730. pp->conn = conn;
  1731. /* Set the default preferred authentication type and mechanism */
  1732. imapc->preftype = IMAP_TYPE_ANY;
  1733. imapc->prefmech = SASL_AUTH_ANY;
  1734. /* Initialise the pingpong layer */
  1735. Curl_pp_init(pp);
  1736. /* Parse the URL options */
  1737. result = imap_parse_url_options(conn);
  1738. if(result)
  1739. return result;
  1740. /* Start off waiting for the server greeting response */
  1741. state(conn, IMAP_SERVERGREET);
  1742. /* Start off with an response id of '*' */
  1743. strcpy(imapc->resptag, "*");
  1744. result = imap_multi_statemach(conn, done);
  1745. return result;
  1746. }
  1747. /***********************************************************************
  1748. *
  1749. * imap_done()
  1750. *
  1751. * The DONE function. This does what needs to be done after a single DO has
  1752. * performed.
  1753. *
  1754. * Input argument is already checked for validity.
  1755. */
  1756. static CURLcode imap_done(struct connectdata *conn, CURLcode status,
  1757. bool premature)
  1758. {
  1759. CURLcode result = CURLE_OK;
  1760. struct SessionHandle *data = conn->data;
  1761. struct IMAP *imap = data->req.protop;
  1762. (void)premature;
  1763. if(!imap)
  1764. /* When the easy handle is removed from the multi interface while libcurl
  1765. is still trying to resolve the host name, the IMAP struct is not yet
  1766. initialized. However, the removal action calls Curl_done() which in
  1767. turn calls this function, so we simply return success. */
  1768. return CURLE_OK;
  1769. if(status) {
  1770. connclose(conn, "IMAP done with bad status"); /* marked for closure */
  1771. result = status; /* use the already set error code */
  1772. }
  1773. else if(!data->set.connect_only && !imap->custom &&
  1774. (imap->uid || data->set.upload)) {
  1775. /* Handle responses after FETCH or APPEND transfer has finished */
  1776. if(!data->set.upload)
  1777. state(conn, IMAP_FETCH_FINAL);
  1778. else {
  1779. /* End the APPEND command first by sending an empty line */
  1780. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
  1781. if(!result)
  1782. state(conn, IMAP_APPEND_FINAL);
  1783. }
  1784. /* Run the state-machine
  1785. TODO: when the multi interface is used, this _really_ should be using
  1786. the imap_multi_statemach function but we have no general support for
  1787. non-blocking DONE operations, not in the multi state machine and with
  1788. Curl_done() invokes on several places in the code!
  1789. */
  1790. if(!result)
  1791. result = imap_block_statemach(conn);
  1792. }
  1793. /* Cleanup our per-request based variables */
  1794. Curl_safefree(imap->mailbox);
  1795. Curl_safefree(imap->uidvalidity);
  1796. Curl_safefree(imap->uid);
  1797. Curl_safefree(imap->section);
  1798. Curl_safefree(imap->partial);
  1799. Curl_safefree(imap->query);
  1800. Curl_safefree(imap->custom);
  1801. Curl_safefree(imap->custom_params);
  1802. /* Clear the transfer mode for the next request */
  1803. imap->transfer = FTPTRANSFER_BODY;
  1804. return result;
  1805. }
  1806. /***********************************************************************
  1807. *
  1808. * imap_perform()
  1809. *
  1810. * This is the actual DO function for IMAP. Fetch or append a message, or do
  1811. * other things according to the options previously setup.
  1812. */
  1813. static CURLcode imap_perform(struct connectdata *conn, bool *connected,
  1814. bool *dophase_done)
  1815. {
  1816. /* This is IMAP and no proxy */
  1817. CURLcode result = CURLE_OK;
  1818. struct SessionHandle *data = conn->data;
  1819. struct IMAP *imap = data->req.protop;
  1820. struct imap_conn *imapc = &conn->proto.imapc;
  1821. bool selected = FALSE;
  1822. DEBUGF(infof(conn->data, "DO phase starts\n"));
  1823. if(conn->data->set.opt_no_body) {
  1824. /* Requested no body means no transfer */
  1825. imap->transfer = FTPTRANSFER_INFO;
  1826. }
  1827. *dophase_done = FALSE; /* not done yet */
  1828. /* Determine if the requested mailbox (with the same UIDVALIDITY if set)
  1829. has already been selected on this connection */
  1830. if(imap->mailbox && imapc->mailbox &&
  1831. !strcmp(imap->mailbox, imapc->mailbox) &&
  1832. (!imap->uidvalidity || !imapc->mailbox_uidvalidity ||
  1833. !strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)))
  1834. selected = TRUE;
  1835. /* Start the first command in the DO phase */
  1836. if(conn->data->set.upload)
  1837. /* APPEND can be executed directly */
  1838. result = imap_perform_append(conn);
  1839. else if(imap->custom && (selected || !imap->mailbox))
  1840. /* Custom command using the same mailbox or no mailbox */
  1841. result = imap_perform_list(conn);
  1842. else if(!imap->custom && selected && imap->uid)
  1843. /* FETCH from the same mailbox */
  1844. result = imap_perform_fetch(conn);
  1845. else if(!imap->custom && selected && imap->query)
  1846. /* SEARCH the current mailbox */
  1847. result = imap_perform_search(conn);
  1848. else if(imap->mailbox && !selected &&
  1849. (imap->custom || imap->uid || imap->query))
  1850. /* SELECT the mailbox */
  1851. result = imap_perform_select(conn);
  1852. else
  1853. /* LIST */
  1854. result = imap_perform_list(conn);
  1855. if(result)
  1856. return result;
  1857. /* Run the state-machine */
  1858. result = imap_multi_statemach(conn, dophase_done);
  1859. *connected = conn->bits.tcpconnect[FIRSTSOCKET];
  1860. if(*dophase_done)
  1861. DEBUGF(infof(conn->data, "DO phase is complete\n"));
  1862. return result;
  1863. }
  1864. /***********************************************************************
  1865. *
  1866. * imap_do()
  1867. *
  1868. * This function is registered as 'curl_do' function. It decodes the path
  1869. * parts etc as a wrapper to the actual DO function (imap_perform).
  1870. *
  1871. * The input argument is already checked for validity.
  1872. */
  1873. static CURLcode imap_do(struct connectdata *conn, bool *done)
  1874. {
  1875. CURLcode result = CURLE_OK;
  1876. *done = FALSE; /* default to false */
  1877. /* Parse the URL path */
  1878. result = imap_parse_url_path(conn);
  1879. if(result)
  1880. return result;
  1881. /* Parse the custom request */
  1882. result = imap_parse_custom_request(conn);
  1883. if(result)
  1884. return result;
  1885. result = imap_regular_transfer(conn, done);
  1886. return result;
  1887. }
  1888. /***********************************************************************
  1889. *
  1890. * imap_disconnect()
  1891. *
  1892. * Disconnect from an IMAP server. Cleanup protocol-specific per-connection
  1893. * resources. BLOCKING.
  1894. */
  1895. static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
  1896. {
  1897. struct imap_conn *imapc = &conn->proto.imapc;
  1898. /* We cannot send quit unconditionally. If this connection is stale or
  1899. bad in any way, sending quit and waiting around here will make the
  1900. disconnect wait in vain and cause more problems than we need to. */
  1901. /* The IMAP session may or may not have been allocated/setup at this
  1902. point! */
  1903. if(!dead_connection && imapc->pp.conn && imapc->pp.conn->bits.protoconnstart)
  1904. if(!imap_perform_logout(conn))
  1905. (void)imap_block_statemach(conn); /* ignore errors on LOGOUT */
  1906. /* Disconnect from the server */
  1907. Curl_pp_disconnect(&imapc->pp);
  1908. /* Cleanup the SASL module */
  1909. Curl_sasl_cleanup(conn, imapc->authused);
  1910. /* Cleanup our connection based variables */
  1911. Curl_safefree(imapc->mailbox);
  1912. Curl_safefree(imapc->mailbox_uidvalidity);
  1913. return CURLE_OK;
  1914. }
  1915. /* Call this when the DO phase has completed */
  1916. static CURLcode imap_dophase_done(struct connectdata *conn, bool connected)
  1917. {
  1918. struct IMAP *imap = conn->data->req.protop;
  1919. (void)connected;
  1920. if(imap->transfer != FTPTRANSFER_BODY)
  1921. /* no data to transfer */
  1922. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1923. return CURLE_OK;
  1924. }
  1925. /* Called from multi.c while DOing */
  1926. static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done)
  1927. {
  1928. CURLcode result = imap_multi_statemach(conn, dophase_done);
  1929. if(result)
  1930. DEBUGF(infof(conn->data, "DO phase failed\n"));
  1931. else if(*dophase_done) {
  1932. result = imap_dophase_done(conn, FALSE /* not connected */);
  1933. DEBUGF(infof(conn->data, "DO phase is complete\n"));
  1934. }
  1935. return result;
  1936. }
  1937. /***********************************************************************
  1938. *
  1939. * imap_regular_transfer()
  1940. *
  1941. * The input argument is already checked for validity.
  1942. *
  1943. * Performs all commands done before a regular transfer between a local and a
  1944. * remote host.
  1945. */
  1946. static CURLcode imap_regular_transfer(struct connectdata *conn,
  1947. bool *dophase_done)
  1948. {
  1949. CURLcode result = CURLE_OK;
  1950. bool connected = FALSE;
  1951. struct SessionHandle *data = conn->data;
  1952. /* Make sure size is unknown at this point */
  1953. data->req.size = -1;
  1954. /* Set the progress data */
  1955. Curl_pgrsSetUploadCounter(data, 0);
  1956. Curl_pgrsSetDownloadCounter(data, 0);
  1957. Curl_pgrsSetUploadSize(data, -1);
  1958. Curl_pgrsSetDownloadSize(data, -1);
  1959. /* Carry out the perform */
  1960. result = imap_perform(conn, &connected, dophase_done);
  1961. /* Perform post DO phase operations if necessary */
  1962. if(!result && *dophase_done)
  1963. result = imap_dophase_done(conn, connected);
  1964. return result;
  1965. }
  1966. static CURLcode imap_setup_connection(struct connectdata *conn)
  1967. {
  1968. struct SessionHandle *data = conn->data;
  1969. /* Initialise the IMAP layer */
  1970. CURLcode result = imap_init(conn);
  1971. if(result)
  1972. return result;
  1973. if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
  1974. /* Unless we have asked to tunnel IMAP operations through the proxy, we
  1975. switch and use HTTP operations only */
  1976. #ifndef CURL_DISABLE_HTTP
  1977. if(conn->handler == &Curl_handler_imap)
  1978. conn->handler = &Curl_handler_imap_proxy;
  1979. else {
  1980. #ifdef USE_SSL
  1981. conn->handler = &Curl_handler_imaps_proxy;
  1982. #else
  1983. failf(data, "IMAPS not supported!");
  1984. return CURLE_UNSUPPORTED_PROTOCOL;
  1985. #endif
  1986. }
  1987. /* set it up as an HTTP connection instead */
  1988. return conn->handler->setup_connection(conn);
  1989. #else
  1990. failf(data, "IMAP over http proxy requires HTTP support built-in!");
  1991. return CURLE_UNSUPPORTED_PROTOCOL;
  1992. #endif
  1993. }
  1994. data->state.path++; /* don't include the initial slash */
  1995. return CURLE_OK;
  1996. }
  1997. /***********************************************************************
  1998. *
  1999. * imap_sendf()
  2000. *
  2001. * Sends the formated string as an IMAP command to the server.
  2002. *
  2003. * Designed to never block.
  2004. */
  2005. static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
  2006. {
  2007. CURLcode result = CURLE_OK;
  2008. struct imap_conn *imapc = &conn->proto.imapc;
  2009. char *taggedfmt;
  2010. va_list ap;
  2011. DEBUGASSERT(fmt);
  2012. /* Calculate the next command ID wrapping at 3 digits */
  2013. imapc->cmdid = (imapc->cmdid + 1) % 1000;
  2014. /* Calculate the tag based on the connection ID and command ID */
  2015. snprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d",
  2016. 'A' + curlx_sltosi(conn->connection_id % 26), imapc->cmdid);
  2017. /* Prefix the format with the tag */
  2018. taggedfmt = aprintf("%s %s", imapc->resptag, fmt);
  2019. if(!taggedfmt)
  2020. return CURLE_OUT_OF_MEMORY;
  2021. /* Send the data with the tag */
  2022. va_start(ap, fmt);
  2023. result = Curl_pp_vsendf(&imapc->pp, taggedfmt, ap);
  2024. va_end(ap);
  2025. Curl_safefree(taggedfmt);
  2026. return result;
  2027. }
  2028. /***********************************************************************
  2029. *
  2030. * imap_atom()
  2031. *
  2032. * Checks the input string for characters that need escaping and returns an
  2033. * atom ready for sending to the server.
  2034. *
  2035. * The returned string needs to be freed.
  2036. *
  2037. */
  2038. static char *imap_atom(const char *str)
  2039. {
  2040. const char *p1;
  2041. char *p2;
  2042. size_t backsp_count = 0;
  2043. size_t quote_count = 0;
  2044. bool space_exists = FALSE;
  2045. size_t newlen = 0;
  2046. char *newstr = NULL;
  2047. if(!str)
  2048. return NULL;
  2049. /* Count any unescapped characters */
  2050. p1 = str;
  2051. while(*p1) {
  2052. if(*p1 == '\\')
  2053. backsp_count++;
  2054. else if(*p1 == '"')
  2055. quote_count++;
  2056. else if(*p1 == ' ')
  2057. space_exists = TRUE;
  2058. p1++;
  2059. }
  2060. /* Does the input contain any unescapped characters? */
  2061. if(!backsp_count && !quote_count && !space_exists)
  2062. return strdup(str);
  2063. /* Calculate the new string length */
  2064. newlen = strlen(str) + backsp_count + quote_count + (space_exists ? 2 : 0);
  2065. /* Allocate the new string */
  2066. newstr = (char *) malloc((newlen + 1) * sizeof(char));
  2067. if(!newstr)
  2068. return NULL;
  2069. /* Surround the string in quotes if necessary */
  2070. p2 = newstr;
  2071. if(space_exists) {
  2072. newstr[0] = '"';
  2073. newstr[newlen - 1] = '"';
  2074. p2++;
  2075. }
  2076. /* Copy the string, escaping backslash and quote characters along the way */
  2077. p1 = str;
  2078. while(*p1) {
  2079. if(*p1 == '\\' || *p1 == '"') {
  2080. *p2 = '\\';
  2081. p2++;
  2082. }
  2083. *p2 = *p1;
  2084. p1++;
  2085. p2++;
  2086. }
  2087. /* Terminate the string */
  2088. newstr[newlen] = '\0';
  2089. return newstr;
  2090. }
  2091. /***********************************************************************
  2092. *
  2093. * imap_is_bchar()
  2094. *
  2095. * Portable test of whether the specified char is a "bchar" as defined in the
  2096. * grammar of RFC-5092.
  2097. */
  2098. static bool imap_is_bchar(char ch)
  2099. {
  2100. switch(ch) {
  2101. /* bchar */
  2102. case ':': case '@': case '/':
  2103. /* bchar -> achar */
  2104. case '&': case '=':
  2105. /* bchar -> achar -> uchar -> unreserved */
  2106. case '0': case '1': case '2': case '3': case '4': case '5': case '6':
  2107. case '7': case '8': case '9':
  2108. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
  2109. case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
  2110. case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
  2111. case 'V': case 'W': case 'X': case 'Y': case 'Z':
  2112. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
  2113. case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
  2114. case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
  2115. case 'v': case 'w': case 'x': case 'y': case 'z':
  2116. case '-': case '.': case '_': case '~':
  2117. /* bchar -> achar -> uchar -> sub-delims-sh */
  2118. case '!': case '$': case '\'': case '(': case ')': case '*':
  2119. case '+': case ',':
  2120. /* bchar -> achar -> uchar -> pct-encoded */
  2121. case '%': /* HEXDIG chars are already included above */
  2122. return true;
  2123. default:
  2124. return false;
  2125. }
  2126. }
  2127. /***********************************************************************
  2128. *
  2129. * imap_parse_url_options()
  2130. *
  2131. * Parse the URL login options.
  2132. */
  2133. static CURLcode imap_parse_url_options(struct connectdata *conn)
  2134. {
  2135. CURLcode result = CURLE_OK;
  2136. struct imap_conn *imapc = &conn->proto.imapc;
  2137. const char *options = conn->options;
  2138. const char *ptr = options;
  2139. bool reset = TRUE;
  2140. while(ptr && *ptr) {
  2141. const char *key = ptr;
  2142. while(*ptr && *ptr != '=')
  2143. ptr++;
  2144. if(strnequal(key, "AUTH", 4)) {
  2145. size_t len = 0;
  2146. const char *value = ++ptr;
  2147. if(reset) {
  2148. reset = FALSE;
  2149. imapc->preftype = IMAP_TYPE_NONE;
  2150. imapc->prefmech = SASL_AUTH_NONE;
  2151. }
  2152. while(*ptr && *ptr != ';') {
  2153. ptr++;
  2154. len++;
  2155. }
  2156. if(strnequal(value, "*", len)) {
  2157. imapc->preftype = IMAP_TYPE_ANY;
  2158. imapc->prefmech = SASL_AUTH_ANY;
  2159. }
  2160. else if(strnequal(value, SASL_MECH_STRING_LOGIN, len)) {
  2161. imapc->preftype = IMAP_TYPE_SASL;
  2162. imapc->prefmech |= SASL_MECH_LOGIN;
  2163. }
  2164. else if(strnequal(value, SASL_MECH_STRING_PLAIN, len)) {
  2165. imapc->preftype = IMAP_TYPE_SASL;
  2166. imapc->prefmech |= SASL_MECH_PLAIN;
  2167. }
  2168. else if(strnequal(value, SASL_MECH_STRING_CRAM_MD5, len)) {
  2169. imapc->preftype = IMAP_TYPE_SASL;
  2170. imapc->prefmech |= SASL_MECH_CRAM_MD5;
  2171. }
  2172. else if(strnequal(value, SASL_MECH_STRING_DIGEST_MD5, len)) {
  2173. imapc->preftype = IMAP_TYPE_SASL;
  2174. imapc->prefmech |= SASL_MECH_DIGEST_MD5;
  2175. }
  2176. else if(strnequal(value, SASL_MECH_STRING_GSSAPI, len)) {
  2177. imapc->preftype = IMAP_TYPE_SASL;
  2178. imapc->prefmech |= SASL_MECH_GSSAPI;
  2179. }
  2180. else if(strnequal(value, SASL_MECH_STRING_NTLM, len)) {
  2181. imapc->preftype = IMAP_TYPE_SASL;
  2182. imapc->prefmech |= SASL_MECH_NTLM;
  2183. }
  2184. else if(strnequal(value, SASL_MECH_STRING_XOAUTH2, len)) {
  2185. imapc->preftype = IMAP_TYPE_SASL;
  2186. imapc->prefmech |= SASL_MECH_XOAUTH2;
  2187. }
  2188. if(*ptr == ';')
  2189. ptr++;
  2190. }
  2191. else
  2192. result = CURLE_URL_MALFORMAT;
  2193. }
  2194. return result;
  2195. }
  2196. /***********************************************************************
  2197. *
  2198. * imap_parse_url_path()
  2199. *
  2200. * Parse the URL path into separate path components.
  2201. *
  2202. */
  2203. static CURLcode imap_parse_url_path(struct connectdata *conn)
  2204. {
  2205. /* The imap struct is already initialised in imap_connect() */
  2206. CURLcode result = CURLE_OK;
  2207. struct SessionHandle *data = conn->data;
  2208. struct IMAP *imap = data->req.protop;
  2209. const char *begin = data->state.path;
  2210. const char *ptr = begin;
  2211. /* See how much of the URL is a valid path and decode it */
  2212. while(imap_is_bchar(*ptr))
  2213. ptr++;
  2214. if(ptr != begin) {
  2215. /* Remove the trailing slash if present */
  2216. const char *end = ptr;
  2217. if(end > begin && end[-1] == '/')
  2218. end--;
  2219. result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL,
  2220. TRUE);
  2221. if(result)
  2222. return result;
  2223. }
  2224. else
  2225. imap->mailbox = NULL;
  2226. /* There can be any number of parameters in the form ";NAME=VALUE" */
  2227. while(*ptr == ';') {
  2228. char *name;
  2229. char *value;
  2230. size_t valuelen;
  2231. /* Find the length of the name parameter */
  2232. begin = ++ptr;
  2233. while(*ptr && *ptr != '=')
  2234. ptr++;
  2235. if(!*ptr)
  2236. return CURLE_URL_MALFORMAT;
  2237. /* Decode the name parameter */
  2238. result = Curl_urldecode(data, begin, ptr - begin, &name, NULL, TRUE);
  2239. if(result)
  2240. return result;
  2241. /* Find the length of the value parameter */
  2242. begin = ++ptr;
  2243. while(imap_is_bchar(*ptr))
  2244. ptr++;
  2245. /* Decode the value parameter */
  2246. result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen, TRUE);
  2247. if(result) {
  2248. Curl_safefree(name);
  2249. return result;
  2250. }
  2251. DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value));
  2252. /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and
  2253. PARTIAL) stripping of the trailing slash character if it is present.
  2254. Note: Unknown parameters trigger a URL_MALFORMAT error. */
  2255. if(Curl_raw_equal(name, "UIDVALIDITY") && !imap->uidvalidity) {
  2256. if(valuelen > 0 && value[valuelen - 1] == '/')
  2257. value[valuelen - 1] = '\0';
  2258. imap->uidvalidity = value;
  2259. value = NULL;
  2260. }
  2261. else if(Curl_raw_equal(name, "UID") && !imap->uid) {
  2262. if(valuelen > 0 && value[valuelen - 1] == '/')
  2263. value[valuelen - 1] = '\0';
  2264. imap->uid = value;
  2265. value = NULL;
  2266. }
  2267. else if(Curl_raw_equal(name, "SECTION") && !imap->section) {
  2268. if(valuelen > 0 && value[valuelen - 1] == '/')
  2269. value[valuelen - 1] = '\0';
  2270. imap->section = value;
  2271. value = NULL;
  2272. }
  2273. else if(Curl_raw_equal(name, "PARTIAL") && !imap->partial) {
  2274. if(valuelen > 0 && value[valuelen - 1] == '/')
  2275. value[valuelen - 1] = '\0';
  2276. imap->partial = value;
  2277. value = NULL;
  2278. }
  2279. else {
  2280. Curl_safefree(name);
  2281. Curl_safefree(value);
  2282. return CURLE_URL_MALFORMAT;
  2283. }
  2284. Curl_safefree(name);
  2285. Curl_safefree(value);
  2286. }
  2287. /* Does the URL contain a query parameter? Only valid when we have a mailbox
  2288. and no UID as per RFC-5092 */
  2289. if(imap->mailbox && !imap->uid && *ptr == '?') {
  2290. /* Find the length of the query parameter */
  2291. begin = ++ptr;
  2292. while(imap_is_bchar(*ptr))
  2293. ptr++;
  2294. /* Decode the query parameter */
  2295. result = Curl_urldecode(data, begin, ptr - begin, &imap->query, NULL,
  2296. TRUE);
  2297. if(result)
  2298. return result;
  2299. }
  2300. /* Any extra stuff at the end of the URL is an error */
  2301. if(*ptr)
  2302. return CURLE_URL_MALFORMAT;
  2303. return CURLE_OK;
  2304. }
  2305. /***********************************************************************
  2306. *
  2307. * imap_parse_custom_request()
  2308. *
  2309. * Parse the custom request.
  2310. */
  2311. static CURLcode imap_parse_custom_request(struct connectdata *conn)
  2312. {
  2313. CURLcode result = CURLE_OK;
  2314. struct SessionHandle *data = conn->data;
  2315. struct IMAP *imap = data->req.protop;
  2316. const char *custom = data->set.str[STRING_CUSTOMREQUEST];
  2317. if(custom) {
  2318. /* URL decode the custom request */
  2319. result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, TRUE);
  2320. /* Extract the parameters if specified */
  2321. if(!result) {
  2322. const char *params = imap->custom;
  2323. while(*params && *params != ' ')
  2324. params++;
  2325. if(*params) {
  2326. imap->custom_params = strdup(params);
  2327. imap->custom[params - imap->custom] = '\0';
  2328. if(!imap->custom_params)
  2329. result = CURLE_OUT_OF_MEMORY;
  2330. }
  2331. }
  2332. }
  2333. return result;
  2334. }
  2335. /***********************************************************************
  2336. *
  2337. * imap_calc_sasl_details()
  2338. *
  2339. * Calculate the required login details for SASL authentication.
  2340. */
  2341. static CURLcode imap_calc_sasl_details(struct connectdata *conn,
  2342. const char **mech,
  2343. char **initresp, size_t *len,
  2344. imapstate *state1, imapstate *state2)
  2345. {
  2346. CURLcode result = CURLE_OK;
  2347. struct SessionHandle *data = conn->data;
  2348. struct imap_conn *imapc = &conn->proto.imapc;
  2349. /* Calculate the supported authentication mechanism, by decreasing order of
  2350. security, as well as the initial response where appropriate */
  2351. #if defined(USE_KRB5)
  2352. if((imapc->authmechs & SASL_MECH_GSSAPI) &&
  2353. (imapc->prefmech & SASL_MECH_GSSAPI)) {
  2354. imapc->mutual_auth = FALSE; /* TODO: Calculate mutual authentication */
  2355. *mech = SASL_MECH_STRING_GSSAPI;
  2356. *state1 = IMAP_AUTHENTICATE_GSSAPI;
  2357. *state2 = IMAP_AUTHENTICATE_GSSAPI_TOKEN;
  2358. imapc->authused = SASL_MECH_GSSAPI;
  2359. if(imapc->ir_supported || data->set.sasl_ir)
  2360. result = Curl_sasl_create_gssapi_user_message(data, conn->user,
  2361. conn->passwd, "imap",
  2362. imapc->mutual_auth,
  2363. NULL, &conn->krb5,
  2364. initresp, len);
  2365. }
  2366. else
  2367. #endif
  2368. #ifndef CURL_DISABLE_CRYPTO_AUTH
  2369. if((imapc->authmechs & SASL_MECH_DIGEST_MD5) &&
  2370. (imapc->prefmech & SASL_MECH_DIGEST_MD5)) {
  2371. *mech = SASL_MECH_STRING_DIGEST_MD5;
  2372. *state1 = IMAP_AUTHENTICATE_DIGESTMD5;
  2373. imapc->authused = SASL_MECH_DIGEST_MD5;
  2374. }
  2375. else if((imapc->authmechs & SASL_MECH_CRAM_MD5) &&
  2376. (imapc->prefmech & SASL_MECH_CRAM_MD5)) {
  2377. *mech = SASL_MECH_STRING_CRAM_MD5;
  2378. *state1 = IMAP_AUTHENTICATE_CRAMMD5;
  2379. imapc->authused = SASL_MECH_CRAM_MD5;
  2380. }
  2381. else
  2382. #endif
  2383. #ifdef USE_NTLM
  2384. if((imapc->authmechs & SASL_MECH_NTLM) &&
  2385. (imapc->prefmech & SASL_MECH_NTLM)) {
  2386. *mech = SASL_MECH_STRING_NTLM;
  2387. *state1 = IMAP_AUTHENTICATE_NTLM;
  2388. *state2 = IMAP_AUTHENTICATE_NTLM_TYPE2MSG;
  2389. imapc->authused = SASL_MECH_NTLM;
  2390. if(imapc->ir_supported || data->set.sasl_ir)
  2391. result = Curl_sasl_create_ntlm_type1_message(conn->user, conn->passwd,
  2392. &conn->ntlm,
  2393. initresp, len);
  2394. }
  2395. else
  2396. #endif
  2397. if(((imapc->authmechs & SASL_MECH_XOAUTH2) &&
  2398. (imapc->prefmech & SASL_MECH_XOAUTH2) &&
  2399. (imapc->prefmech != SASL_AUTH_ANY)) || conn->xoauth2_bearer) {
  2400. *mech = SASL_MECH_STRING_XOAUTH2;
  2401. *state1 = IMAP_AUTHENTICATE_XOAUTH2;
  2402. *state2 = IMAP_AUTHENTICATE_FINAL;
  2403. imapc->authused = SASL_MECH_XOAUTH2;
  2404. if(imapc->ir_supported || data->set.sasl_ir)
  2405. result = Curl_sasl_create_xoauth2_message(data, conn->user,
  2406. conn->xoauth2_bearer,
  2407. initresp, len);
  2408. }
  2409. else if((imapc->authmechs & SASL_MECH_LOGIN) &&
  2410. (imapc->prefmech & SASL_MECH_LOGIN)) {
  2411. *mech = SASL_MECH_STRING_LOGIN;
  2412. *state1 = IMAP_AUTHENTICATE_LOGIN;
  2413. *state2 = IMAP_AUTHENTICATE_LOGIN_PASSWD;
  2414. imapc->authused = SASL_MECH_LOGIN;
  2415. if(imapc->ir_supported || data->set.sasl_ir)
  2416. result = Curl_sasl_create_login_message(data, conn->user, initresp, len);
  2417. }
  2418. else if((imapc->authmechs & SASL_MECH_PLAIN) &&
  2419. (imapc->prefmech & SASL_MECH_PLAIN)) {
  2420. *mech = SASL_MECH_STRING_PLAIN;
  2421. *state1 = IMAP_AUTHENTICATE_PLAIN;
  2422. *state2 = IMAP_AUTHENTICATE_FINAL;
  2423. imapc->authused = SASL_MECH_PLAIN;
  2424. if(imapc->ir_supported || data->set.sasl_ir)
  2425. result = Curl_sasl_create_plain_message(data, conn->user, conn->passwd,
  2426. initresp, len);
  2427. }
  2428. return result;
  2429. }
  2430. #endif /* CURL_DISABLE_IMAP */