imap.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, 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 https://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 "hostip.h"
  60. #include "progress.h"
  61. #include "transfer.h"
  62. #include "escape.h"
  63. #include "http.h" /* for HTTP proxy tunnel stuff */
  64. #include "socks.h"
  65. #include "imap.h"
  66. #include "strtoofft.h"
  67. #include "strcase.h"
  68. #include "vtls/vtls.h"
  69. #include "connect.h"
  70. #include "strerror.h"
  71. #include "select.h"
  72. #include "multiif.h"
  73. #include "url.h"
  74. #include "strcase.h"
  75. #include "curl_sasl.h"
  76. #include "warnless.h"
  77. /* The last 3 #include files should be in this order */
  78. #include "curl_printf.h"
  79. #include "curl_memory.h"
  80. #include "memdebug.h"
  81. /* Local API functions */
  82. static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
  83. static CURLcode imap_do(struct connectdata *conn, bool *done);
  84. static CURLcode imap_done(struct connectdata *conn, CURLcode status,
  85. bool premature);
  86. static CURLcode imap_connect(struct connectdata *conn, bool *done);
  87. static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
  88. static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
  89. static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
  90. int numsocks);
  91. static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done);
  92. static CURLcode imap_setup_connection(struct connectdata *conn);
  93. static char *imap_atom(const char *str, bool escape_only);
  94. static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...);
  95. static CURLcode imap_parse_url_options(struct connectdata *conn);
  96. static CURLcode imap_parse_url_path(struct connectdata *conn);
  97. static CURLcode imap_parse_custom_request(struct connectdata *conn);
  98. static CURLcode imap_perform_authenticate(struct connectdata *conn,
  99. const char *mech,
  100. const char *initresp);
  101. static CURLcode imap_continue_authenticate(struct connectdata *conn,
  102. const char *resp);
  103. static void imap_get_message(char *buffer, char **outptr);
  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| /* flags */
  125. PROTOPT_URLOPTIONS
  126. };
  127. #ifdef USE_SSL
  128. /*
  129. * IMAPS protocol handler.
  130. */
  131. const struct Curl_handler Curl_handler_imaps = {
  132. "IMAPS", /* scheme */
  133. imap_setup_connection, /* setup_connection */
  134. imap_do, /* do_it */
  135. imap_done, /* done */
  136. ZERO_NULL, /* do_more */
  137. imap_connect, /* connect_it */
  138. imap_multi_statemach, /* connecting */
  139. imap_doing, /* doing */
  140. imap_getsock, /* proto_getsock */
  141. imap_getsock, /* doing_getsock */
  142. ZERO_NULL, /* domore_getsock */
  143. ZERO_NULL, /* perform_getsock */
  144. imap_disconnect, /* disconnect */
  145. ZERO_NULL, /* readwrite */
  146. PORT_IMAPS, /* defport */
  147. CURLPROTO_IMAPS, /* protocol */
  148. PROTOPT_CLOSEACTION | PROTOPT_SSL /* 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. /* SASL parameters for the imap protocol */
  200. static const struct SASLproto saslimap = {
  201. "imap", /* The service name */
  202. '+', /* Code received when continuation is expected */
  203. 'O', /* Code to receive upon authentication success */
  204. 0, /* Maximum initial response length (no max) */
  205. imap_perform_authenticate, /* Send authentication command */
  206. imap_continue_authenticate, /* Send authentication continuation */
  207. imap_get_message /* Get SASL response message */
  208. };
  209. #ifdef USE_SSL
  210. static void imap_to_imaps(struct connectdata *conn)
  211. {
  212. /* Change the connection handler */
  213. conn->handler = &Curl_handler_imaps;
  214. /* Set the connection's upgraded to TLS flag */
  215. conn->tls_upgraded = TRUE;
  216. }
  217. #else
  218. #define imap_to_imaps(x) Curl_nop_stmt
  219. #endif
  220. /***********************************************************************
  221. *
  222. * imap_matchresp()
  223. *
  224. * Determines whether the untagged response is related to the specified
  225. * command by checking if it is in format "* <command-name> ..." or
  226. * "* <number> <command-name> ...".
  227. *
  228. * The "* " marker is assumed to have already been checked by the caller.
  229. */
  230. static bool imap_matchresp(const char *line, size_t len, const char *cmd)
  231. {
  232. const char *end = line + len;
  233. size_t cmd_len = strlen(cmd);
  234. /* Skip the untagged response marker */
  235. line += 2;
  236. /* Do we have a number after the marker? */
  237. if(line < end && ISDIGIT(*line)) {
  238. /* Skip the number */
  239. do
  240. line++;
  241. while(line < end && ISDIGIT(*line));
  242. /* Do we have the space character? */
  243. if(line == end || *line != ' ')
  244. return FALSE;
  245. line++;
  246. }
  247. /* Does the command name match and is it followed by a space character or at
  248. the end of line? */
  249. if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) &&
  250. (line[cmd_len] == ' ' || line + cmd_len + 2 == end))
  251. return TRUE;
  252. return FALSE;
  253. }
  254. /***********************************************************************
  255. *
  256. * imap_endofresp()
  257. *
  258. * Checks whether the given string is a valid tagged, untagged or continuation
  259. * response which can be processed by the response handler.
  260. */
  261. static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
  262. int *resp)
  263. {
  264. struct IMAP *imap = conn->data->req.protop;
  265. struct imap_conn *imapc = &conn->proto.imapc;
  266. const char *id = imapc->resptag;
  267. size_t id_len = strlen(id);
  268. /* Do we have a tagged command response? */
  269. if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
  270. line += id_len + 1;
  271. len -= id_len + 1;
  272. if(len >= 2 && !memcmp(line, "OK", 2))
  273. *resp = 'O';
  274. else if(len >= 2 && !memcmp(line, "NO", 2))
  275. *resp = 'N';
  276. else if(len >= 3 && !memcmp(line, "BAD", 3))
  277. *resp = 'B';
  278. else {
  279. failf(conn->data, "Bad tagged response");
  280. *resp = -1;
  281. }
  282. return TRUE;
  283. }
  284. /* Do we have an untagged command response? */
  285. if(len >= 2 && !memcmp("* ", line, 2)) {
  286. switch(imapc->state) {
  287. /* States which are interested in untagged responses */
  288. case IMAP_CAPABILITY:
  289. if(!imap_matchresp(line, len, "CAPABILITY"))
  290. return FALSE;
  291. break;
  292. case IMAP_LIST:
  293. if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
  294. (imap->custom && !imap_matchresp(line, len, imap->custom) &&
  295. (strcmp(imap->custom, "STORE") ||
  296. !imap_matchresp(line, len, "FETCH")) &&
  297. strcmp(imap->custom, "SELECT") &&
  298. strcmp(imap->custom, "EXAMINE") &&
  299. strcmp(imap->custom, "SEARCH") &&
  300. strcmp(imap->custom, "EXPUNGE") &&
  301. strcmp(imap->custom, "LSUB") &&
  302. strcmp(imap->custom, "UID") &&
  303. strcmp(imap->custom, "NOOP")))
  304. return FALSE;
  305. break;
  306. case IMAP_SELECT:
  307. /* SELECT is special in that its untagged responses do not have a
  308. common prefix so accept anything! */
  309. break;
  310. case IMAP_FETCH:
  311. if(!imap_matchresp(line, len, "FETCH"))
  312. return FALSE;
  313. break;
  314. case IMAP_SEARCH:
  315. if(!imap_matchresp(line, len, "SEARCH"))
  316. return FALSE;
  317. break;
  318. /* Ignore other untagged responses */
  319. default:
  320. return FALSE;
  321. }
  322. *resp = '*';
  323. return TRUE;
  324. }
  325. /* Do we have a continuation response? This should be a + symbol followed by
  326. a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
  327. APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
  328. some e-mail servers ignore this and only send a single + instead. */
  329. if(imap && !imap->custom && ((len == 3 && !memcmp("+", line, 1)) ||
  330. (len >= 2 && !memcmp("+ ", line, 2)))) {
  331. switch(imapc->state) {
  332. /* States which are interested in continuation responses */
  333. case IMAP_AUTHENTICATE:
  334. case IMAP_APPEND:
  335. *resp = '+';
  336. break;
  337. default:
  338. failf(conn->data, "Unexpected continuation response");
  339. *resp = -1;
  340. break;
  341. }
  342. return TRUE;
  343. }
  344. return FALSE; /* Nothing for us */
  345. }
  346. /***********************************************************************
  347. *
  348. * imap_get_message()
  349. *
  350. * Gets the authentication message from the response buffer.
  351. */
  352. static void imap_get_message(char *buffer, char **outptr)
  353. {
  354. size_t len = 0;
  355. char *message = NULL;
  356. /* Find the start of the message */
  357. for(message = buffer + 2; *message == ' ' || *message == '\t'; message++)
  358. ;
  359. /* Find the end of the message */
  360. for(len = strlen(message); len--;)
  361. if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
  362. message[len] != '\t')
  363. break;
  364. /* Terminate the message */
  365. if(++len) {
  366. message[len] = '\0';
  367. }
  368. *outptr = message;
  369. }
  370. /***********************************************************************
  371. *
  372. * state()
  373. *
  374. * This is the ONLY way to change IMAP state!
  375. */
  376. static void state(struct connectdata *conn, imapstate newstate)
  377. {
  378. struct imap_conn *imapc = &conn->proto.imapc;
  379. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  380. /* for debug purposes */
  381. static const char * const names[]={
  382. "STOP",
  383. "SERVERGREET",
  384. "CAPABILITY",
  385. "STARTTLS",
  386. "UPGRADETLS",
  387. "AUTHENTICATE",
  388. "LOGIN",
  389. "LIST",
  390. "SELECT",
  391. "FETCH",
  392. "FETCH_FINAL",
  393. "APPEND",
  394. "APPEND_FINAL",
  395. "SEARCH",
  396. "LOGOUT",
  397. /* LAST */
  398. };
  399. if(imapc->state != newstate)
  400. infof(conn->data, "IMAP %p state change from %s to %s\n",
  401. (void *)imapc, names[imapc->state], names[newstate]);
  402. #endif
  403. imapc->state = newstate;
  404. }
  405. /***********************************************************************
  406. *
  407. * imap_perform_capability()
  408. *
  409. * Sends the CAPABILITY command in order to obtain a list of server side
  410. * supported capabilities.
  411. */
  412. static CURLcode imap_perform_capability(struct connectdata *conn)
  413. {
  414. CURLcode result = CURLE_OK;
  415. struct imap_conn *imapc = &conn->proto.imapc;
  416. imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
  417. imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */
  418. imapc->tls_supported = FALSE; /* Clear the TLS capability */
  419. /* Send the CAPABILITY command */
  420. result = imap_sendf(conn, "CAPABILITY");
  421. if(!result)
  422. state(conn, IMAP_CAPABILITY);
  423. return result;
  424. }
  425. /***********************************************************************
  426. *
  427. * imap_perform_starttls()
  428. *
  429. * Sends the STARTTLS command to start the upgrade to TLS.
  430. */
  431. static CURLcode imap_perform_starttls(struct connectdata *conn)
  432. {
  433. CURLcode result = CURLE_OK;
  434. /* Send the STARTTLS command */
  435. result = imap_sendf(conn, "STARTTLS");
  436. if(!result)
  437. state(conn, IMAP_STARTTLS);
  438. return result;
  439. }
  440. /***********************************************************************
  441. *
  442. * imap_perform_upgrade_tls()
  443. *
  444. * Performs the upgrade to TLS.
  445. */
  446. static CURLcode imap_perform_upgrade_tls(struct connectdata *conn)
  447. {
  448. CURLcode result = CURLE_OK;
  449. struct imap_conn *imapc = &conn->proto.imapc;
  450. /* Start the SSL connection */
  451. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
  452. if(!result) {
  453. if(imapc->state != IMAP_UPGRADETLS)
  454. state(conn, IMAP_UPGRADETLS);
  455. if(imapc->ssldone) {
  456. imap_to_imaps(conn);
  457. result = imap_perform_capability(conn);
  458. }
  459. }
  460. return result;
  461. }
  462. /***********************************************************************
  463. *
  464. * imap_perform_login()
  465. *
  466. * Sends a clear text LOGIN command to authenticate with.
  467. */
  468. static CURLcode imap_perform_login(struct connectdata *conn)
  469. {
  470. CURLcode result = CURLE_OK;
  471. char *user;
  472. char *passwd;
  473. /* Check we have a username and password to authenticate with and end the
  474. connect phase if we don't */
  475. if(!conn->bits.user_passwd) {
  476. state(conn, IMAP_STOP);
  477. return result;
  478. }
  479. /* Make sure the username and password are in the correct atom format */
  480. user = imap_atom(conn->user, false);
  481. passwd = imap_atom(conn->passwd, false);
  482. /* Send the LOGIN command */
  483. result = imap_sendf(conn, "LOGIN %s %s", user ? user : "",
  484. passwd ? passwd : "");
  485. free(user);
  486. free(passwd);
  487. if(!result)
  488. state(conn, IMAP_LOGIN);
  489. return result;
  490. }
  491. /***********************************************************************
  492. *
  493. * imap_perform_authenticate()
  494. *
  495. * Sends an AUTHENTICATE command allowing the client to login with the given
  496. * SASL authentication mechanism.
  497. */
  498. static CURLcode imap_perform_authenticate(struct connectdata *conn,
  499. const char *mech,
  500. const char *initresp)
  501. {
  502. CURLcode result = CURLE_OK;
  503. if(initresp) {
  504. /* Send the AUTHENTICATE command with the initial response */
  505. result = imap_sendf(conn, "AUTHENTICATE %s %s", mech, initresp);
  506. }
  507. else {
  508. /* Send the AUTHENTICATE command */
  509. result = imap_sendf(conn, "AUTHENTICATE %s", mech);
  510. }
  511. return result;
  512. }
  513. /***********************************************************************
  514. *
  515. * imap_continue_authenticate()
  516. *
  517. * Sends SASL continuation data or cancellation.
  518. */
  519. static CURLcode imap_continue_authenticate(struct connectdata *conn,
  520. const char *resp)
  521. {
  522. struct imap_conn *imapc = &conn->proto.imapc;
  523. return Curl_pp_sendf(&imapc->pp, "%s", resp);
  524. }
  525. /***********************************************************************
  526. *
  527. * imap_perform_authentication()
  528. *
  529. * Initiates the authentication sequence, with the appropriate SASL
  530. * authentication mechanism, falling back to clear text should a common
  531. * mechanism not be available between the client and server.
  532. */
  533. static CURLcode imap_perform_authentication(struct connectdata *conn)
  534. {
  535. CURLcode result = CURLE_OK;
  536. struct imap_conn *imapc = &conn->proto.imapc;
  537. saslprogress progress;
  538. /* Check we have enough data to authenticate with and end the
  539. connect phase if we don't */
  540. if(!Curl_sasl_can_authenticate(&imapc->sasl, conn)) {
  541. state(conn, IMAP_STOP);
  542. return result;
  543. }
  544. /* Calculate the SASL login details */
  545. result = Curl_sasl_start(&imapc->sasl, conn, imapc->ir_supported, &progress);
  546. if(!result) {
  547. if(progress == SASL_INPROGRESS)
  548. state(conn, IMAP_AUTHENTICATE);
  549. else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
  550. /* Perform clear text authentication */
  551. result = imap_perform_login(conn);
  552. else {
  553. /* Other mechanisms not supported */
  554. infof(conn->data, "No known authentication mechanisms supported!\n");
  555. result = CURLE_LOGIN_DENIED;
  556. }
  557. }
  558. return result;
  559. }
  560. /***********************************************************************
  561. *
  562. * imap_perform_list()
  563. *
  564. * Sends a LIST command or an alternative custom request.
  565. */
  566. static CURLcode imap_perform_list(struct connectdata *conn)
  567. {
  568. CURLcode result = CURLE_OK;
  569. struct Curl_easy *data = conn->data;
  570. struct IMAP *imap = data->req.protop;
  571. char *mailbox;
  572. if(imap->custom)
  573. /* Send the custom request */
  574. result = imap_sendf(conn, "%s%s", imap->custom,
  575. imap->custom_params ? imap->custom_params : "");
  576. else {
  577. /* Make sure the mailbox is in the correct atom format if necessary */
  578. mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) : strdup("");
  579. if(!mailbox)
  580. return CURLE_OUT_OF_MEMORY;
  581. /* Send the LIST command */
  582. result = imap_sendf(conn, "LIST \"%s\" *", mailbox);
  583. free(mailbox);
  584. }
  585. if(!result)
  586. state(conn, IMAP_LIST);
  587. return result;
  588. }
  589. /***********************************************************************
  590. *
  591. * imap_perform_select()
  592. *
  593. * Sends a SELECT command to ask the server to change the selected mailbox.
  594. */
  595. static CURLcode imap_perform_select(struct connectdata *conn)
  596. {
  597. CURLcode result = CURLE_OK;
  598. struct Curl_easy *data = conn->data;
  599. struct IMAP *imap = data->req.protop;
  600. struct imap_conn *imapc = &conn->proto.imapc;
  601. char *mailbox;
  602. /* Invalidate old information as we are switching mailboxes */
  603. Curl_safefree(imapc->mailbox);
  604. Curl_safefree(imapc->mailbox_uidvalidity);
  605. /* Check we have a mailbox */
  606. if(!imap->mailbox) {
  607. failf(conn->data, "Cannot SELECT without a mailbox.");
  608. return CURLE_URL_MALFORMAT;
  609. }
  610. /* Make sure the mailbox is in the correct atom format */
  611. mailbox = imap_atom(imap->mailbox, false);
  612. if(!mailbox)
  613. return CURLE_OUT_OF_MEMORY;
  614. /* Send the SELECT command */
  615. result = imap_sendf(conn, "SELECT %s", mailbox);
  616. free(mailbox);
  617. if(!result)
  618. state(conn, IMAP_SELECT);
  619. return result;
  620. }
  621. /***********************************************************************
  622. *
  623. * imap_perform_fetch()
  624. *
  625. * Sends a FETCH command to initiate the download of a message.
  626. */
  627. static CURLcode imap_perform_fetch(struct connectdata *conn)
  628. {
  629. CURLcode result = CURLE_OK;
  630. struct IMAP *imap = conn->data->req.protop;
  631. /* Check we have a UID */
  632. if(!imap->uid) {
  633. failf(conn->data, "Cannot FETCH without a UID.");
  634. return CURLE_URL_MALFORMAT;
  635. }
  636. /* Send the FETCH command */
  637. if(imap->partial)
  638. result = imap_sendf(conn, "FETCH %s BODY[%s]<%s>",
  639. imap->uid,
  640. imap->section ? imap->section : "",
  641. imap->partial);
  642. else
  643. result = imap_sendf(conn, "FETCH %s BODY[%s]",
  644. imap->uid,
  645. imap->section ? imap->section : "");
  646. if(!result)
  647. state(conn, IMAP_FETCH);
  648. return result;
  649. }
  650. /***********************************************************************
  651. *
  652. * imap_perform_append()
  653. *
  654. * Sends an APPEND command to initiate the upload of a message.
  655. */
  656. static CURLcode imap_perform_append(struct connectdata *conn)
  657. {
  658. CURLcode result = CURLE_OK;
  659. struct IMAP *imap = conn->data->req.protop;
  660. char *mailbox;
  661. /* Check we have a mailbox */
  662. if(!imap->mailbox) {
  663. failf(conn->data, "Cannot APPEND without a mailbox.");
  664. return CURLE_URL_MALFORMAT;
  665. }
  666. /* Check we know the size of the upload */
  667. if(conn->data->state.infilesize < 0) {
  668. failf(conn->data, "Cannot APPEND with unknown input file size\n");
  669. return CURLE_UPLOAD_FAILED;
  670. }
  671. /* Make sure the mailbox is in the correct atom format */
  672. mailbox = imap_atom(imap->mailbox, false);
  673. if(!mailbox)
  674. return CURLE_OUT_OF_MEMORY;
  675. /* Send the APPEND command */
  676. result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}",
  677. mailbox, conn->data->state.infilesize);
  678. free(mailbox);
  679. if(!result)
  680. state(conn, IMAP_APPEND);
  681. return result;
  682. }
  683. /***********************************************************************
  684. *
  685. * imap_perform_search()
  686. *
  687. * Sends a SEARCH command.
  688. */
  689. static CURLcode imap_perform_search(struct connectdata *conn)
  690. {
  691. CURLcode result = CURLE_OK;
  692. struct IMAP *imap = conn->data->req.protop;
  693. /* Check we have a query string */
  694. if(!imap->query) {
  695. failf(conn->data, "Cannot SEARCH without a query string.");
  696. return CURLE_URL_MALFORMAT;
  697. }
  698. /* Send the SEARCH command */
  699. result = imap_sendf(conn, "SEARCH %s", imap->query);
  700. if(!result)
  701. state(conn, IMAP_SEARCH);
  702. return result;
  703. }
  704. /***********************************************************************
  705. *
  706. * imap_perform_logout()
  707. *
  708. * Performs the logout action prior to sclose() being called.
  709. */
  710. static CURLcode imap_perform_logout(struct connectdata *conn)
  711. {
  712. CURLcode result = CURLE_OK;
  713. /* Send the LOGOUT command */
  714. result = imap_sendf(conn, "LOGOUT");
  715. if(!result)
  716. state(conn, IMAP_LOGOUT);
  717. return result;
  718. }
  719. /* For the initial server greeting */
  720. static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
  721. int imapcode,
  722. imapstate instate)
  723. {
  724. CURLcode result = CURLE_OK;
  725. struct Curl_easy *data = conn->data;
  726. (void)instate; /* no use for this yet */
  727. if(imapcode != 'O') {
  728. failf(data, "Got unexpected imap-server response");
  729. result = CURLE_WEIRD_SERVER_REPLY;
  730. }
  731. else
  732. result = imap_perform_capability(conn);
  733. return result;
  734. }
  735. /* For CAPABILITY responses */
  736. static CURLcode imap_state_capability_resp(struct connectdata *conn,
  737. int imapcode,
  738. imapstate instate)
  739. {
  740. CURLcode result = CURLE_OK;
  741. struct Curl_easy *data = conn->data;
  742. struct imap_conn *imapc = &conn->proto.imapc;
  743. const char *line = data->state.buffer;
  744. size_t wordlen;
  745. (void)instate; /* no use for this yet */
  746. /* Do we have a untagged response? */
  747. if(imapcode == '*') {
  748. line += 2;
  749. /* Loop through the data line */
  750. for(;;) {
  751. while(*line &&
  752. (*line == ' ' || *line == '\t' ||
  753. *line == '\r' || *line == '\n')) {
  754. line++;
  755. }
  756. if(!*line)
  757. break;
  758. /* Extract the word */
  759. for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' &&
  760. line[wordlen] != '\t' && line[wordlen] != '\r' &&
  761. line[wordlen] != '\n';)
  762. wordlen++;
  763. /* Does the server support the STARTTLS capability? */
  764. if(wordlen == 8 && !memcmp(line, "STARTTLS", 8))
  765. imapc->tls_supported = TRUE;
  766. /* Has the server explicitly disabled clear text authentication? */
  767. else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13))
  768. imapc->login_disabled = TRUE;
  769. /* Does the server support the SASL-IR capability? */
  770. else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7))
  771. imapc->ir_supported = TRUE;
  772. /* Do we have a SASL based authentication mechanism? */
  773. else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) {
  774. size_t llen;
  775. unsigned int mechbit;
  776. line += 5;
  777. wordlen -= 5;
  778. /* Test the word for a matching authentication mechanism */
  779. mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
  780. if(mechbit && llen == wordlen)
  781. imapc->sasl.authmechs |= mechbit;
  782. }
  783. line += wordlen;
  784. }
  785. }
  786. else if(imapcode == 'O') {
  787. if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
  788. /* We don't have a SSL/TLS connection yet, but SSL is requested */
  789. if(imapc->tls_supported)
  790. /* Switch to TLS connection now */
  791. result = imap_perform_starttls(conn);
  792. else if(data->set.use_ssl == CURLUSESSL_TRY)
  793. /* Fallback and carry on with authentication */
  794. result = imap_perform_authentication(conn);
  795. else {
  796. failf(data, "STARTTLS not supported.");
  797. result = CURLE_USE_SSL_FAILED;
  798. }
  799. }
  800. else
  801. result = imap_perform_authentication(conn);
  802. }
  803. else
  804. result = imap_perform_authentication(conn);
  805. return result;
  806. }
  807. /* For STARTTLS responses */
  808. static CURLcode imap_state_starttls_resp(struct connectdata *conn,
  809. int imapcode,
  810. imapstate instate)
  811. {
  812. CURLcode result = CURLE_OK;
  813. struct Curl_easy *data = conn->data;
  814. (void)instate; /* no use for this yet */
  815. if(imapcode != 'O') {
  816. if(data->set.use_ssl != CURLUSESSL_TRY) {
  817. failf(data, "STARTTLS denied");
  818. result = CURLE_USE_SSL_FAILED;
  819. }
  820. else
  821. result = imap_perform_authentication(conn);
  822. }
  823. else
  824. result = imap_perform_upgrade_tls(conn);
  825. return result;
  826. }
  827. /* For SASL authentication responses */
  828. static CURLcode imap_state_auth_resp(struct connectdata *conn,
  829. int imapcode,
  830. imapstate instate)
  831. {
  832. CURLcode result = CURLE_OK;
  833. struct Curl_easy *data = conn->data;
  834. struct imap_conn *imapc = &conn->proto.imapc;
  835. saslprogress progress;
  836. (void)instate; /* no use for this yet */
  837. result = Curl_sasl_continue(&imapc->sasl, conn, imapcode, &progress);
  838. if(!result)
  839. switch(progress) {
  840. case SASL_DONE:
  841. state(conn, IMAP_STOP); /* Authenticated */
  842. break;
  843. case SASL_IDLE: /* No mechanism left after cancellation */
  844. if((!imapc->login_disabled) && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
  845. /* Perform clear text authentication */
  846. result = imap_perform_login(conn);
  847. else {
  848. failf(data, "Authentication cancelled");
  849. result = CURLE_LOGIN_DENIED;
  850. }
  851. break;
  852. default:
  853. break;
  854. }
  855. return result;
  856. }
  857. /* For LOGIN responses */
  858. static CURLcode imap_state_login_resp(struct connectdata *conn,
  859. int imapcode,
  860. imapstate instate)
  861. {
  862. CURLcode result = CURLE_OK;
  863. struct Curl_easy *data = conn->data;
  864. (void)instate; /* no use for this yet */
  865. if(imapcode != 'O') {
  866. failf(data, "Access denied. %c", imapcode);
  867. result = CURLE_LOGIN_DENIED;
  868. }
  869. else
  870. /* End of connect phase */
  871. state(conn, IMAP_STOP);
  872. return result;
  873. }
  874. /* For LIST and SEARCH responses */
  875. static CURLcode imap_state_listsearch_resp(struct connectdata *conn,
  876. int imapcode,
  877. imapstate instate)
  878. {
  879. CURLcode result = CURLE_OK;
  880. char *line = conn->data->state.buffer;
  881. size_t len = strlen(line);
  882. (void)instate; /* No use for this yet */
  883. if(imapcode == '*') {
  884. /* Temporarily add the LF character back and send as body to the client */
  885. line[len] = '\n';
  886. result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
  887. line[len] = '\0';
  888. }
  889. else if(imapcode != 'O')
  890. result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */
  891. else
  892. /* End of DO phase */
  893. state(conn, IMAP_STOP);
  894. return result;
  895. }
  896. /* For SELECT responses */
  897. static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
  898. imapstate instate)
  899. {
  900. CURLcode result = CURLE_OK;
  901. struct Curl_easy *data = conn->data;
  902. struct IMAP *imap = conn->data->req.protop;
  903. struct imap_conn *imapc = &conn->proto.imapc;
  904. const char *line = data->state.buffer;
  905. char tmp[20];
  906. (void)instate; /* no use for this yet */
  907. if(imapcode == '*') {
  908. /* See if this is an UIDVALIDITY response */
  909. if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) {
  910. Curl_safefree(imapc->mailbox_uidvalidity);
  911. imapc->mailbox_uidvalidity = strdup(tmp);
  912. }
  913. }
  914. else if(imapcode == 'O') {
  915. /* Check if the UIDVALIDITY has been specified and matches */
  916. if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
  917. strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)) {
  918. failf(conn->data, "Mailbox UIDVALIDITY has changed");
  919. result = CURLE_REMOTE_FILE_NOT_FOUND;
  920. }
  921. else {
  922. /* Note the currently opened mailbox on this connection */
  923. imapc->mailbox = strdup(imap->mailbox);
  924. if(imap->custom)
  925. result = imap_perform_list(conn);
  926. else if(imap->query)
  927. result = imap_perform_search(conn);
  928. else
  929. result = imap_perform_fetch(conn);
  930. }
  931. }
  932. else {
  933. failf(data, "Select failed");
  934. result = CURLE_LOGIN_DENIED;
  935. }
  936. return result;
  937. }
  938. /* For the (first line of the) FETCH responses */
  939. static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
  940. imapstate instate)
  941. {
  942. CURLcode result = CURLE_OK;
  943. struct Curl_easy *data = conn->data;
  944. struct imap_conn *imapc = &conn->proto.imapc;
  945. struct pingpong *pp = &imapc->pp;
  946. const char *ptr = data->state.buffer;
  947. bool parsed = FALSE;
  948. curl_off_t size = 0;
  949. (void)instate; /* no use for this yet */
  950. if(imapcode != '*') {
  951. Curl_pgrsSetDownloadSize(data, -1);
  952. state(conn, IMAP_STOP);
  953. return CURLE_REMOTE_FILE_NOT_FOUND; /* TODO: Fix error code */
  954. }
  955. /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
  956. the continuation data contained within the curly brackets */
  957. while(*ptr && (*ptr != '{'))
  958. ptr++;
  959. if(*ptr == '{') {
  960. char *endptr;
  961. size = curlx_strtoofft(ptr + 1, &endptr, 10);
  962. if(endptr - ptr > 1 && endptr[0] == '}' &&
  963. endptr[1] == '\r' && endptr[2] == '\0')
  964. parsed = TRUE;
  965. }
  966. if(parsed) {
  967. infof(data, "Found %" CURL_FORMAT_CURL_OFF_TU " bytes to download\n",
  968. size);
  969. Curl_pgrsSetDownloadSize(data, size);
  970. if(pp->cache) {
  971. /* At this point there is a bunch of data in the header "cache" that is
  972. actually body content, send it as body and then skip it. Do note
  973. that there may even be additional "headers" after the body. */
  974. size_t chunk = pp->cache_size;
  975. if(chunk > (size_t)size)
  976. /* The conversion from curl_off_t to size_t is always fine here */
  977. chunk = (size_t)size;
  978. result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
  979. if(result)
  980. return result;
  981. data->req.bytecount += chunk;
  982. infof(data, "Written %" CURL_FORMAT_CURL_OFF_TU
  983. " bytes, %" CURL_FORMAT_CURL_OFF_TU
  984. " bytes are left for transfer\n", (curl_off_t)chunk,
  985. size - chunk);
  986. /* Have we used the entire cache or just part of it?*/
  987. if(pp->cache_size > chunk) {
  988. /* Only part of it so shrink the cache to fit the trailing data */
  989. memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
  990. pp->cache_size -= chunk;
  991. }
  992. else {
  993. /* Free the cache */
  994. Curl_safefree(pp->cache);
  995. /* Reset the cache size */
  996. pp->cache_size = 0;
  997. }
  998. }
  999. if(data->req.bytecount == size)
  1000. /* The entire data is already transferred! */
  1001. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1002. else {
  1003. /* IMAP download */
  1004. data->req.maxdownload = size;
  1005. Curl_setup_transfer(conn, FIRSTSOCKET, size, FALSE, NULL, -1, NULL);
  1006. }
  1007. }
  1008. else {
  1009. /* We don't know how to parse this line */
  1010. failf(pp->conn->data, "Failed to parse FETCH response.");
  1011. result = CURLE_WEIRD_SERVER_REPLY;
  1012. }
  1013. /* End of DO phase */
  1014. state(conn, IMAP_STOP);
  1015. return result;
  1016. }
  1017. /* For final FETCH responses performed after the download */
  1018. static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
  1019. int imapcode,
  1020. imapstate instate)
  1021. {
  1022. CURLcode result = CURLE_OK;
  1023. (void)instate; /* No use for this yet */
  1024. if(imapcode != 'O')
  1025. result = CURLE_WEIRD_SERVER_REPLY;
  1026. else
  1027. /* End of DONE phase */
  1028. state(conn, IMAP_STOP);
  1029. return result;
  1030. }
  1031. /* For APPEND responses */
  1032. static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode,
  1033. imapstate instate)
  1034. {
  1035. CURLcode result = CURLE_OK;
  1036. struct Curl_easy *data = conn->data;
  1037. (void)instate; /* No use for this yet */
  1038. if(imapcode != '+') {
  1039. result = CURLE_UPLOAD_FAILED;
  1040. }
  1041. else {
  1042. /* Set the progress upload size */
  1043. Curl_pgrsSetUploadSize(data, data->state.infilesize);
  1044. /* IMAP upload */
  1045. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
  1046. /* End of DO phase */
  1047. state(conn, IMAP_STOP);
  1048. }
  1049. return result;
  1050. }
  1051. /* For final APPEND responses performed after the upload */
  1052. static CURLcode imap_state_append_final_resp(struct connectdata *conn,
  1053. int imapcode,
  1054. imapstate instate)
  1055. {
  1056. CURLcode result = CURLE_OK;
  1057. (void)instate; /* No use for this yet */
  1058. if(imapcode != 'O')
  1059. result = CURLE_UPLOAD_FAILED;
  1060. else
  1061. /* End of DONE phase */
  1062. state(conn, IMAP_STOP);
  1063. return result;
  1064. }
  1065. static CURLcode imap_statemach_act(struct connectdata *conn)
  1066. {
  1067. CURLcode result = CURLE_OK;
  1068. curl_socket_t sock = conn->sock[FIRSTSOCKET];
  1069. int imapcode;
  1070. struct imap_conn *imapc = &conn->proto.imapc;
  1071. struct pingpong *pp = &imapc->pp;
  1072. size_t nread = 0;
  1073. /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
  1074. if(imapc->state == IMAP_UPGRADETLS)
  1075. return imap_perform_upgrade_tls(conn);
  1076. /* Flush any data that needs to be sent */
  1077. if(pp->sendleft)
  1078. return Curl_pp_flushsend(pp);
  1079. do {
  1080. /* Read the response from the server */
  1081. result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
  1082. if(result)
  1083. return result;
  1084. /* Was there an error parsing the response line? */
  1085. if(imapcode == -1)
  1086. return CURLE_WEIRD_SERVER_REPLY;
  1087. if(!imapcode)
  1088. break;
  1089. /* We have now received a full IMAP server response */
  1090. switch(imapc->state) {
  1091. case IMAP_SERVERGREET:
  1092. result = imap_state_servergreet_resp(conn, imapcode, imapc->state);
  1093. break;
  1094. case IMAP_CAPABILITY:
  1095. result = imap_state_capability_resp(conn, imapcode, imapc->state);
  1096. break;
  1097. case IMAP_STARTTLS:
  1098. result = imap_state_starttls_resp(conn, imapcode, imapc->state);
  1099. break;
  1100. case IMAP_AUTHENTICATE:
  1101. result = imap_state_auth_resp(conn, imapcode, imapc->state);
  1102. break;
  1103. case IMAP_LOGIN:
  1104. result = imap_state_login_resp(conn, imapcode, imapc->state);
  1105. break;
  1106. case IMAP_LIST:
  1107. result = imap_state_listsearch_resp(conn, imapcode, imapc->state);
  1108. break;
  1109. case IMAP_SELECT:
  1110. result = imap_state_select_resp(conn, imapcode, imapc->state);
  1111. break;
  1112. case IMAP_FETCH:
  1113. result = imap_state_fetch_resp(conn, imapcode, imapc->state);
  1114. break;
  1115. case IMAP_FETCH_FINAL:
  1116. result = imap_state_fetch_final_resp(conn, imapcode, imapc->state);
  1117. break;
  1118. case IMAP_APPEND:
  1119. result = imap_state_append_resp(conn, imapcode, imapc->state);
  1120. break;
  1121. case IMAP_APPEND_FINAL:
  1122. result = imap_state_append_final_resp(conn, imapcode, imapc->state);
  1123. break;
  1124. case IMAP_SEARCH:
  1125. result = imap_state_listsearch_resp(conn, imapcode, imapc->state);
  1126. break;
  1127. case IMAP_LOGOUT:
  1128. /* fallthrough, just stop! */
  1129. default:
  1130. /* internal error */
  1131. state(conn, IMAP_STOP);
  1132. break;
  1133. }
  1134. } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
  1135. return result;
  1136. }
  1137. /* Called repeatedly until done from multi.c */
  1138. static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done)
  1139. {
  1140. CURLcode result = CURLE_OK;
  1141. struct imap_conn *imapc = &conn->proto.imapc;
  1142. if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) {
  1143. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
  1144. if(result || !imapc->ssldone)
  1145. return result;
  1146. }
  1147. result = Curl_pp_statemach(&imapc->pp, FALSE);
  1148. *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
  1149. return result;
  1150. }
  1151. static CURLcode imap_block_statemach(struct connectdata *conn)
  1152. {
  1153. CURLcode result = CURLE_OK;
  1154. struct imap_conn *imapc = &conn->proto.imapc;
  1155. while(imapc->state != IMAP_STOP && !result)
  1156. result = Curl_pp_statemach(&imapc->pp, TRUE);
  1157. return result;
  1158. }
  1159. /* Allocate and initialize the struct IMAP for the current Curl_easy if
  1160. required */
  1161. static CURLcode imap_init(struct connectdata *conn)
  1162. {
  1163. CURLcode result = CURLE_OK;
  1164. struct Curl_easy *data = conn->data;
  1165. struct IMAP *imap;
  1166. imap = data->req.protop = calloc(sizeof(struct IMAP), 1);
  1167. if(!imap)
  1168. result = CURLE_OUT_OF_MEMORY;
  1169. return result;
  1170. }
  1171. /* For the IMAP "protocol connect" and "doing" phases only */
  1172. static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
  1173. int numsocks)
  1174. {
  1175. return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks);
  1176. }
  1177. /***********************************************************************
  1178. *
  1179. * imap_connect()
  1180. *
  1181. * This function should do everything that is to be considered a part of the
  1182. * connection phase.
  1183. *
  1184. * The variable 'done' points to will be TRUE if the protocol-layer connect
  1185. * phase is done when this function returns, or FALSE if not.
  1186. */
  1187. static CURLcode imap_connect(struct connectdata *conn, bool *done)
  1188. {
  1189. CURLcode result = CURLE_OK;
  1190. struct imap_conn *imapc = &conn->proto.imapc;
  1191. struct pingpong *pp = &imapc->pp;
  1192. *done = FALSE; /* default to not done yet */
  1193. /* We always support persistent connections in IMAP */
  1194. connkeep(conn, "IMAP default");
  1195. /* Set the default response time-out */
  1196. pp->response_time = RESP_TIMEOUT;
  1197. pp->statemach_act = imap_statemach_act;
  1198. pp->endofresp = imap_endofresp;
  1199. pp->conn = conn;
  1200. /* Set the default preferred authentication type and mechanism */
  1201. imapc->preftype = IMAP_TYPE_ANY;
  1202. Curl_sasl_init(&imapc->sasl, &saslimap);
  1203. /* Initialise the pingpong layer */
  1204. Curl_pp_init(pp);
  1205. /* Parse the URL options */
  1206. result = imap_parse_url_options(conn);
  1207. if(result)
  1208. return result;
  1209. /* Start off waiting for the server greeting response */
  1210. state(conn, IMAP_SERVERGREET);
  1211. /* Start off with an response id of '*' */
  1212. strcpy(imapc->resptag, "*");
  1213. result = imap_multi_statemach(conn, done);
  1214. return result;
  1215. }
  1216. /***********************************************************************
  1217. *
  1218. * imap_done()
  1219. *
  1220. * The DONE function. This does what needs to be done after a single DO has
  1221. * performed.
  1222. *
  1223. * Input argument is already checked for validity.
  1224. */
  1225. static CURLcode imap_done(struct connectdata *conn, CURLcode status,
  1226. bool premature)
  1227. {
  1228. CURLcode result = CURLE_OK;
  1229. struct Curl_easy *data = conn->data;
  1230. struct IMAP *imap = data->req.protop;
  1231. (void)premature;
  1232. if(!imap)
  1233. return CURLE_OK;
  1234. if(status) {
  1235. connclose(conn, "IMAP done with bad status"); /* marked for closure */
  1236. result = status; /* use the already set error code */
  1237. }
  1238. else if(!data->set.connect_only && !imap->custom &&
  1239. (imap->uid || data->set.upload)) {
  1240. /* Handle responses after FETCH or APPEND transfer has finished */
  1241. if(!data->set.upload)
  1242. state(conn, IMAP_FETCH_FINAL);
  1243. else {
  1244. /* End the APPEND command first by sending an empty line */
  1245. result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
  1246. if(!result)
  1247. state(conn, IMAP_APPEND_FINAL);
  1248. }
  1249. /* Run the state-machine
  1250. TODO: when the multi interface is used, this _really_ should be using
  1251. the imap_multi_statemach function but we have no general support for
  1252. non-blocking DONE operations!
  1253. */
  1254. if(!result)
  1255. result = imap_block_statemach(conn);
  1256. }
  1257. /* Cleanup our per-request based variables */
  1258. Curl_safefree(imap->mailbox);
  1259. Curl_safefree(imap->uidvalidity);
  1260. Curl_safefree(imap->uid);
  1261. Curl_safefree(imap->section);
  1262. Curl_safefree(imap->partial);
  1263. Curl_safefree(imap->query);
  1264. Curl_safefree(imap->custom);
  1265. Curl_safefree(imap->custom_params);
  1266. /* Clear the transfer mode for the next request */
  1267. imap->transfer = FTPTRANSFER_BODY;
  1268. return result;
  1269. }
  1270. /***********************************************************************
  1271. *
  1272. * imap_perform()
  1273. *
  1274. * This is the actual DO function for IMAP. Fetch or append a message, or do
  1275. * other things according to the options previously setup.
  1276. */
  1277. static CURLcode imap_perform(struct connectdata *conn, bool *connected,
  1278. bool *dophase_done)
  1279. {
  1280. /* This is IMAP and no proxy */
  1281. CURLcode result = CURLE_OK;
  1282. struct Curl_easy *data = conn->data;
  1283. struct IMAP *imap = data->req.protop;
  1284. struct imap_conn *imapc = &conn->proto.imapc;
  1285. bool selected = FALSE;
  1286. DEBUGF(infof(conn->data, "DO phase starts\n"));
  1287. if(conn->data->set.opt_no_body) {
  1288. /* Requested no body means no transfer */
  1289. imap->transfer = FTPTRANSFER_INFO;
  1290. }
  1291. *dophase_done = FALSE; /* not done yet */
  1292. /* Determine if the requested mailbox (with the same UIDVALIDITY if set)
  1293. has already been selected on this connection */
  1294. if(imap->mailbox && imapc->mailbox &&
  1295. !strcmp(imap->mailbox, imapc->mailbox) &&
  1296. (!imap->uidvalidity || !imapc->mailbox_uidvalidity ||
  1297. !strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)))
  1298. selected = TRUE;
  1299. /* Start the first command in the DO phase */
  1300. if(conn->data->set.upload)
  1301. /* APPEND can be executed directly */
  1302. result = imap_perform_append(conn);
  1303. else if(imap->custom && (selected || !imap->mailbox))
  1304. /* Custom command using the same mailbox or no mailbox */
  1305. result = imap_perform_list(conn);
  1306. else if(!imap->custom && selected && imap->uid)
  1307. /* FETCH from the same mailbox */
  1308. result = imap_perform_fetch(conn);
  1309. else if(!imap->custom && selected && imap->query)
  1310. /* SEARCH the current mailbox */
  1311. result = imap_perform_search(conn);
  1312. else if(imap->mailbox && !selected &&
  1313. (imap->custom || imap->uid || imap->query))
  1314. /* SELECT the mailbox */
  1315. result = imap_perform_select(conn);
  1316. else
  1317. /* LIST */
  1318. result = imap_perform_list(conn);
  1319. if(result)
  1320. return result;
  1321. /* Run the state-machine */
  1322. result = imap_multi_statemach(conn, dophase_done);
  1323. *connected = conn->bits.tcpconnect[FIRSTSOCKET];
  1324. if(*dophase_done)
  1325. DEBUGF(infof(conn->data, "DO phase is complete\n"));
  1326. return result;
  1327. }
  1328. /***********************************************************************
  1329. *
  1330. * imap_do()
  1331. *
  1332. * This function is registered as 'curl_do' function. It decodes the path
  1333. * parts etc as a wrapper to the actual DO function (imap_perform).
  1334. *
  1335. * The input argument is already checked for validity.
  1336. */
  1337. static CURLcode imap_do(struct connectdata *conn, bool *done)
  1338. {
  1339. CURLcode result = CURLE_OK;
  1340. *done = FALSE; /* default to false */
  1341. /* Parse the URL path */
  1342. result = imap_parse_url_path(conn);
  1343. if(result)
  1344. return result;
  1345. /* Parse the custom request */
  1346. result = imap_parse_custom_request(conn);
  1347. if(result)
  1348. return result;
  1349. result = imap_regular_transfer(conn, done);
  1350. return result;
  1351. }
  1352. /***********************************************************************
  1353. *
  1354. * imap_disconnect()
  1355. *
  1356. * Disconnect from an IMAP server. Cleanup protocol-specific per-connection
  1357. * resources. BLOCKING.
  1358. */
  1359. static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
  1360. {
  1361. struct imap_conn *imapc = &conn->proto.imapc;
  1362. /* We cannot send quit unconditionally. If this connection is stale or
  1363. bad in any way, sending quit and waiting around here will make the
  1364. disconnect wait in vain and cause more problems than we need to. */
  1365. /* The IMAP session may or may not have been allocated/setup at this
  1366. point! */
  1367. if(!dead_connection && imapc->pp.conn && imapc->pp.conn->bits.protoconnstart)
  1368. if(!imap_perform_logout(conn))
  1369. (void)imap_block_statemach(conn); /* ignore errors on LOGOUT */
  1370. /* Disconnect from the server */
  1371. Curl_pp_disconnect(&imapc->pp);
  1372. /* Cleanup the SASL module */
  1373. Curl_sasl_cleanup(conn, imapc->sasl.authused);
  1374. /* Cleanup our connection based variables */
  1375. Curl_safefree(imapc->mailbox);
  1376. Curl_safefree(imapc->mailbox_uidvalidity);
  1377. return CURLE_OK;
  1378. }
  1379. /* Call this when the DO phase has completed */
  1380. static CURLcode imap_dophase_done(struct connectdata *conn, bool connected)
  1381. {
  1382. struct IMAP *imap = conn->data->req.protop;
  1383. (void)connected;
  1384. if(imap->transfer != FTPTRANSFER_BODY)
  1385. /* no data to transfer */
  1386. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1387. return CURLE_OK;
  1388. }
  1389. /* Called from multi.c while DOing */
  1390. static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done)
  1391. {
  1392. CURLcode result = imap_multi_statemach(conn, dophase_done);
  1393. if(result)
  1394. DEBUGF(infof(conn->data, "DO phase failed\n"));
  1395. else if(*dophase_done) {
  1396. result = imap_dophase_done(conn, FALSE /* not connected */);
  1397. DEBUGF(infof(conn->data, "DO phase is complete\n"));
  1398. }
  1399. return result;
  1400. }
  1401. /***********************************************************************
  1402. *
  1403. * imap_regular_transfer()
  1404. *
  1405. * The input argument is already checked for validity.
  1406. *
  1407. * Performs all commands done before a regular transfer between a local and a
  1408. * remote host.
  1409. */
  1410. static CURLcode imap_regular_transfer(struct connectdata *conn,
  1411. bool *dophase_done)
  1412. {
  1413. CURLcode result = CURLE_OK;
  1414. bool connected = FALSE;
  1415. struct Curl_easy *data = conn->data;
  1416. /* Make sure size is unknown at this point */
  1417. data->req.size = -1;
  1418. /* Set the progress data */
  1419. Curl_pgrsSetUploadCounter(data, 0);
  1420. Curl_pgrsSetDownloadCounter(data, 0);
  1421. Curl_pgrsSetUploadSize(data, -1);
  1422. Curl_pgrsSetDownloadSize(data, -1);
  1423. /* Carry out the perform */
  1424. result = imap_perform(conn, &connected, dophase_done);
  1425. /* Perform post DO phase operations if necessary */
  1426. if(!result && *dophase_done)
  1427. result = imap_dophase_done(conn, connected);
  1428. return result;
  1429. }
  1430. static CURLcode imap_setup_connection(struct connectdata *conn)
  1431. {
  1432. struct Curl_easy *data = conn->data;
  1433. /* Initialise the IMAP layer */
  1434. CURLcode result = imap_init(conn);
  1435. if(result)
  1436. return result;
  1437. /* Clear the TLS upgraded flag */
  1438. conn->tls_upgraded = FALSE;
  1439. /* Set up the proxy if necessary */
  1440. if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
  1441. /* Unless we have asked to tunnel IMAP operations through the proxy, we
  1442. switch and use HTTP operations only */
  1443. #ifndef CURL_DISABLE_HTTP
  1444. if(conn->handler == &Curl_handler_imap)
  1445. conn->handler = &Curl_handler_imap_proxy;
  1446. else {
  1447. #ifdef USE_SSL
  1448. conn->handler = &Curl_handler_imaps_proxy;
  1449. #else
  1450. failf(data, "IMAPS not supported!");
  1451. return CURLE_UNSUPPORTED_PROTOCOL;
  1452. #endif
  1453. }
  1454. /* set it up as an HTTP connection instead */
  1455. return conn->handler->setup_connection(conn);
  1456. #else
  1457. failf(data, "IMAP over http proxy requires HTTP support built-in!");
  1458. return CURLE_UNSUPPORTED_PROTOCOL;
  1459. #endif
  1460. }
  1461. data->state.path++; /* don't include the initial slash */
  1462. return CURLE_OK;
  1463. }
  1464. /***********************************************************************
  1465. *
  1466. * imap_sendf()
  1467. *
  1468. * Sends the formated string as an IMAP command to the server.
  1469. *
  1470. * Designed to never block.
  1471. */
  1472. static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
  1473. {
  1474. CURLcode result = CURLE_OK;
  1475. struct imap_conn *imapc = &conn->proto.imapc;
  1476. char *taggedfmt;
  1477. va_list ap;
  1478. DEBUGASSERT(fmt);
  1479. /* Calculate the next command ID wrapping at 3 digits */
  1480. imapc->cmdid = (imapc->cmdid + 1) % 1000;
  1481. /* Calculate the tag based on the connection ID and command ID */
  1482. snprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d",
  1483. 'A' + curlx_sltosi(conn->connection_id % 26), imapc->cmdid);
  1484. /* Prefix the format with the tag */
  1485. taggedfmt = aprintf("%s %s", imapc->resptag, fmt);
  1486. if(!taggedfmt)
  1487. return CURLE_OUT_OF_MEMORY;
  1488. /* Send the data with the tag */
  1489. va_start(ap, fmt);
  1490. result = Curl_pp_vsendf(&imapc->pp, taggedfmt, ap);
  1491. va_end(ap);
  1492. free(taggedfmt);
  1493. return result;
  1494. }
  1495. /***********************************************************************
  1496. *
  1497. * imap_atom()
  1498. *
  1499. * Checks the input string for characters that need escaping and returns an
  1500. * atom ready for sending to the server.
  1501. *
  1502. * The returned string needs to be freed.
  1503. *
  1504. */
  1505. static char *imap_atom(const char *str, bool escape_only)
  1506. {
  1507. /* !checksrc! disable PARENBRACE 1 */
  1508. const char atom_specials[] = "(){ %*]";
  1509. const char *p1;
  1510. char *p2;
  1511. size_t backsp_count = 0;
  1512. size_t quote_count = 0;
  1513. bool others_exists = FALSE;
  1514. size_t newlen = 0;
  1515. char *newstr = NULL;
  1516. if(!str)
  1517. return NULL;
  1518. /* Look for "atom-specials", counting the backslash and quote characters as
  1519. these will need escapping */
  1520. p1 = str;
  1521. while(*p1) {
  1522. if(*p1 == '\\')
  1523. backsp_count++;
  1524. else if(*p1 == '"')
  1525. quote_count++;
  1526. else if(!escape_only) {
  1527. const char *p3 = atom_specials;
  1528. while(*p3 && !others_exists) {
  1529. if(*p1 == *p3)
  1530. others_exists = TRUE;
  1531. p3++;
  1532. }
  1533. }
  1534. p1++;
  1535. }
  1536. /* Does the input contain any "atom-special" characters? */
  1537. if(!backsp_count && !quote_count && !others_exists)
  1538. return strdup(str);
  1539. /* Calculate the new string length */
  1540. newlen = strlen(str) + backsp_count + quote_count + (others_exists ? 2 : 0);
  1541. /* Allocate the new string */
  1542. newstr = (char *) malloc((newlen + 1) * sizeof(char));
  1543. if(!newstr)
  1544. return NULL;
  1545. /* Surround the string in quotes if necessary */
  1546. p2 = newstr;
  1547. if(others_exists) {
  1548. newstr[0] = '"';
  1549. newstr[newlen - 1] = '"';
  1550. p2++;
  1551. }
  1552. /* Copy the string, escaping backslash and quote characters along the way */
  1553. p1 = str;
  1554. while(*p1) {
  1555. if(*p1 == '\\' || *p1 == '"') {
  1556. *p2 = '\\';
  1557. p2++;
  1558. }
  1559. *p2 = *p1;
  1560. p1++;
  1561. p2++;
  1562. }
  1563. /* Terminate the string */
  1564. newstr[newlen] = '\0';
  1565. return newstr;
  1566. }
  1567. /***********************************************************************
  1568. *
  1569. * imap_is_bchar()
  1570. *
  1571. * Portable test of whether the specified char is a "bchar" as defined in the
  1572. * grammar of RFC-5092.
  1573. */
  1574. static bool imap_is_bchar(char ch)
  1575. {
  1576. switch(ch) {
  1577. /* bchar */
  1578. case ':': case '@': case '/':
  1579. /* bchar -> achar */
  1580. case '&': case '=':
  1581. /* bchar -> achar -> uchar -> unreserved */
  1582. case '0': case '1': case '2': case '3': case '4': case '5': case '6':
  1583. case '7': case '8': case '9':
  1584. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
  1585. case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
  1586. case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
  1587. case 'V': case 'W': case 'X': case 'Y': case 'Z':
  1588. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
  1589. case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
  1590. case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
  1591. case 'v': case 'w': case 'x': case 'y': case 'z':
  1592. case '-': case '.': case '_': case '~':
  1593. /* bchar -> achar -> uchar -> sub-delims-sh */
  1594. case '!': case '$': case '\'': case '(': case ')': case '*':
  1595. case '+': case ',':
  1596. /* bchar -> achar -> uchar -> pct-encoded */
  1597. case '%': /* HEXDIG chars are already included above */
  1598. return true;
  1599. default:
  1600. return false;
  1601. }
  1602. }
  1603. /***********************************************************************
  1604. *
  1605. * imap_parse_url_options()
  1606. *
  1607. * Parse the URL login options.
  1608. */
  1609. static CURLcode imap_parse_url_options(struct connectdata *conn)
  1610. {
  1611. CURLcode result = CURLE_OK;
  1612. struct imap_conn *imapc = &conn->proto.imapc;
  1613. const char *ptr = conn->options;
  1614. imapc->sasl.resetprefs = TRUE;
  1615. while(!result && ptr && *ptr) {
  1616. const char *key = ptr;
  1617. const char *value;
  1618. while(*ptr && *ptr != '=')
  1619. ptr++;
  1620. value = ptr + 1;
  1621. while(*ptr && *ptr != ';')
  1622. ptr++;
  1623. if(strncasecompare(key, "AUTH=", 5))
  1624. result = Curl_sasl_parse_url_auth_option(&imapc->sasl,
  1625. value, ptr - value);
  1626. else
  1627. result = CURLE_URL_MALFORMAT;
  1628. if(*ptr == ';')
  1629. ptr++;
  1630. }
  1631. switch(imapc->sasl.prefmech) {
  1632. case SASL_AUTH_NONE:
  1633. imapc->preftype = IMAP_TYPE_NONE;
  1634. break;
  1635. case SASL_AUTH_DEFAULT:
  1636. imapc->preftype = IMAP_TYPE_ANY;
  1637. break;
  1638. default:
  1639. imapc->preftype = IMAP_TYPE_SASL;
  1640. break;
  1641. }
  1642. return result;
  1643. }
  1644. /***********************************************************************
  1645. *
  1646. * imap_parse_url_path()
  1647. *
  1648. * Parse the URL path into separate path components.
  1649. *
  1650. */
  1651. static CURLcode imap_parse_url_path(struct connectdata *conn)
  1652. {
  1653. /* The imap struct is already initialised in imap_connect() */
  1654. CURLcode result = CURLE_OK;
  1655. struct Curl_easy *data = conn->data;
  1656. struct IMAP *imap = data->req.protop;
  1657. const char *begin = data->state.path;
  1658. const char *ptr = begin;
  1659. /* See how much of the URL is a valid path and decode it */
  1660. while(imap_is_bchar(*ptr))
  1661. ptr++;
  1662. if(ptr != begin) {
  1663. /* Remove the trailing slash if present */
  1664. const char *end = ptr;
  1665. if(end > begin && end[-1] == '/')
  1666. end--;
  1667. result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL,
  1668. TRUE);
  1669. if(result)
  1670. return result;
  1671. }
  1672. else
  1673. imap->mailbox = NULL;
  1674. /* There can be any number of parameters in the form ";NAME=VALUE" */
  1675. while(*ptr == ';') {
  1676. char *name;
  1677. char *value;
  1678. size_t valuelen;
  1679. /* Find the length of the name parameter */
  1680. begin = ++ptr;
  1681. while(*ptr && *ptr != '=')
  1682. ptr++;
  1683. if(!*ptr)
  1684. return CURLE_URL_MALFORMAT;
  1685. /* Decode the name parameter */
  1686. result = Curl_urldecode(data, begin, ptr - begin, &name, NULL, TRUE);
  1687. if(result)
  1688. return result;
  1689. /* Find the length of the value parameter */
  1690. begin = ++ptr;
  1691. while(imap_is_bchar(*ptr))
  1692. ptr++;
  1693. /* Decode the value parameter */
  1694. result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen, TRUE);
  1695. if(result) {
  1696. free(name);
  1697. return result;
  1698. }
  1699. DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value));
  1700. /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and
  1701. PARTIAL) stripping of the trailing slash character if it is present.
  1702. Note: Unknown parameters trigger a URL_MALFORMAT error. */
  1703. if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) {
  1704. if(valuelen > 0 && value[valuelen - 1] == '/')
  1705. value[valuelen - 1] = '\0';
  1706. imap->uidvalidity = value;
  1707. value = NULL;
  1708. }
  1709. else if(strcasecompare(name, "UID") && !imap->uid) {
  1710. if(valuelen > 0 && value[valuelen - 1] == '/')
  1711. value[valuelen - 1] = '\0';
  1712. imap->uid = value;
  1713. value = NULL;
  1714. }
  1715. else if(strcasecompare(name, "SECTION") && !imap->section) {
  1716. if(valuelen > 0 && value[valuelen - 1] == '/')
  1717. value[valuelen - 1] = '\0';
  1718. imap->section = value;
  1719. value = NULL;
  1720. }
  1721. else if(strcasecompare(name, "PARTIAL") && !imap->partial) {
  1722. if(valuelen > 0 && value[valuelen - 1] == '/')
  1723. value[valuelen - 1] = '\0';
  1724. imap->partial = value;
  1725. value = NULL;
  1726. }
  1727. else {
  1728. free(name);
  1729. free(value);
  1730. return CURLE_URL_MALFORMAT;
  1731. }
  1732. free(name);
  1733. free(value);
  1734. }
  1735. /* Does the URL contain a query parameter? Only valid when we have a mailbox
  1736. and no UID as per RFC-5092 */
  1737. if(imap->mailbox && !imap->uid && *ptr == '?') {
  1738. /* Find the length of the query parameter */
  1739. begin = ++ptr;
  1740. while(imap_is_bchar(*ptr))
  1741. ptr++;
  1742. /* Decode the query parameter */
  1743. result = Curl_urldecode(data, begin, ptr - begin, &imap->query, NULL,
  1744. TRUE);
  1745. if(result)
  1746. return result;
  1747. }
  1748. /* Any extra stuff at the end of the URL is an error */
  1749. if(*ptr)
  1750. return CURLE_URL_MALFORMAT;
  1751. return CURLE_OK;
  1752. }
  1753. /***********************************************************************
  1754. *
  1755. * imap_parse_custom_request()
  1756. *
  1757. * Parse the custom request.
  1758. */
  1759. static CURLcode imap_parse_custom_request(struct connectdata *conn)
  1760. {
  1761. CURLcode result = CURLE_OK;
  1762. struct Curl_easy *data = conn->data;
  1763. struct IMAP *imap = data->req.protop;
  1764. const char *custom = data->set.str[STRING_CUSTOMREQUEST];
  1765. if(custom) {
  1766. /* URL decode the custom request */
  1767. result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, TRUE);
  1768. /* Extract the parameters if specified */
  1769. if(!result) {
  1770. const char *params = imap->custom;
  1771. while(*params && *params != ' ')
  1772. params++;
  1773. if(*params) {
  1774. imap->custom_params = strdup(params);
  1775. imap->custom[params - imap->custom] = '\0';
  1776. if(!imap->custom_params)
  1777. result = CURLE_OUT_OF_MEMORY;
  1778. }
  1779. }
  1780. }
  1781. return result;
  1782. }
  1783. #endif /* CURL_DISABLE_IMAP */