imap.c 59 KB

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