Artifactspublic-v0

curl

master
ply4 git calls187 ms305 KiB2 cachedprotocol v2
2332 lines68 KiBRaw
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 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.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 * SPDX-License-Identifier: curl
22 *
23 * RFC2195 CRAM-MD5 authentication
24 * RFC2595 Using TLS with IMAP, POP3 and ACAP
25 * RFC2831 DIGEST-MD5 authentication
26 * RFC3501 IMAPv4 protocol
27 * RFC4422 Simple Authentication and Security Layer (SASL)
28 * RFC4616 PLAIN authentication
29 * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
30 * RFC4959 IMAP Extension for SASL Initial Client Response
31 * RFC5092 IMAP URL Scheme
32 * RFC6749 OAuth 2.0 Authorization Framework
33 * RFC8314 Use of TLS for Email Submission and Access
34 * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
35 *
36 ***************************************************************************/
37#include "curl_setup.h"
38#include "urldata.h"
39#include "imap.h"
41#ifndef CURL_DISABLE_IMAP
43#ifdef HAVE_NETINET_IN_H
44#include <netinet/in.h>
45#endif
46#ifdef HAVE_ARPA_INET_H
47#include <arpa/inet.h>
48#endif
49#ifdef HAVE_NETDB_H
50#include <netdb.h>
51#endif
52#ifdef __VMS
53#include <in.h>
54#include <inet.h>
55#endif
57#include "curlx/dynbuf.h"
58#include "sendf.h"
59#include "curl_trc.h"
60#include "progress.h"
61#include "transfer.h"
62#include "escape.h"
63#include "pingpong.h"
64#include "mime.h"
65#include "curlx/strparse.h"
66#include "strcase.h"
67#include "vtls/vtls.h"
68#include "cfilters.h"
69#include "connect.h"
70#include "select.h"
71#include "url.h"
72#include "bufref.h"
73#include "curl_sasl.h"
74#include "curlx/strcopy.h"
76/* meta key for storing protocol meta at easy handle */
77#define CURL_META_IMAP_EASY "meta:proto:imap:easy"
78/* meta key for storing protocol meta at connection */
79#define CURL_META_IMAP_CONN "meta:proto:imap:conn"
81typedef enum {
82 IMAP_STOP, /* do nothing state, stops the state machine */
83 IMAP_SERVERGREET, /* waiting for the initial greeting immediately after
84 a connect */
85 IMAP_CAPABILITY,
86 IMAP_STARTTLS,
87 IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
88 (multi mode only) */
89 IMAP_AUTHENTICATE,
90 IMAP_LOGIN,
91 IMAP_LIST,
92 IMAP_SELECT,
93 IMAP_FETCH,
94 IMAP_FETCH_FINAL,
95 IMAP_APPEND,
96 IMAP_APPEND_FINAL,
97 IMAP_SEARCH,
98 IMAP_LOGOUT,
99 IMAP_LAST /* never used */
100} imapstate;
102/* imap_conn is used for struct connection-oriented data */
103struct imap_conn {
104 struct pingpong pp;
105 struct SASL sasl; /* SASL-related parameters */
106 char *mailbox; /* The last selected mailbox */
107 imapstate state; /* Always use imap.c:state() to change state! */
108 unsigned int mb_uidvalidity; /* UIDVALIDITY parsed from select response */
109 char resptag[5]; /* Response tag to wait for */
110 unsigned char preftype; /* Preferred authentication type */
111 unsigned char cmdid; /* Last used command ID */
112 BIT(ssldone); /* Is connect() over SSL done? */
113 BIT(preauth); /* Is this connection PREAUTH? */
114 BIT(tls_supported); /* StartTLS capability supported by server */
115 BIT(login_disabled); /* LOGIN command disabled by server */
116 BIT(ir_supported); /* Initial response supported by server */
117 BIT(mb_uidvalidity_set);
118};
120/* This IMAP struct is used in the Curl_easy. All IMAP data that is
121 connection-oriented must be in imap_conn to properly deal with the fact that
122 perhaps the Curl_easy is changed between the times the connection is
123 used. */
124struct IMAP {
125 curl_pp_transfer transfer;
126 char *mailbox; /* Mailbox to select */
127 char *uid; /* Message UID to fetch */
128 char *mindex; /* Index in mail box of mail to fetch */
129 char *section; /* Message SECTION to fetch */
130 char *partial; /* Message PARTIAL to fetch */
131 char *query; /* Query to search for */
132 char *custom; /* Custom request */
133 char *custom_params; /* Parameters for the custom request */
134 unsigned int uidvalidity; /* UIDVALIDITY to check in select */
135 BIT(uidvalidity_set);
136};
138#define IMAP_RESP_OK 1
139#define IMAP_RESP_NOT_OK 2
140#define IMAP_RESP_PREAUTH 3
142struct ulbits {
143 int bit;
144 const char *flag;
145};
147/***********************************************************************
148 *
149 * imap_sendf()
150 *
151 * Sends the formatted string as an IMAP command to the server.
152 *
153 * Designed to never block.
154 */
155static CURLcode imap_sendf(struct Curl_easy *data,
156 struct imap_conn *imapc,
157 const char *fmt, ...) CURL_PRINTF(3, 4);
158static CURLcode imap_sendf(struct Curl_easy *data,
159 struct imap_conn *imapc,
160 const char *fmt, ...)
162 CURLcode result = CURLE_OK;
163 va_list ap;
165 DEBUGASSERT(fmt);
167 /* Calculate the tag based on the connection ID and command ID */
168 curl_msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d",
169 'A' + curlx_sltosi((long)(data->conn->connection_id % 26)),
170 ++imapc->cmdid);
172 va_start(ap, fmt);
173 result = Curl_pp_vsendf(data, &imapc->pp, imapc->resptag, fmt, ap);
174 va_end(ap);
175 return result;
178/***********************************************************************
179 *
180 * imap_atom()
181 *
182 * Checks the input string for characters that need escaping and returns an
183 * atom ready for sending to the server.
184 *
185 * The returned string needs to be freed.
186 *
187 */
188static char *imap_atom(const char *str, bool escape_only)
190 struct dynbuf line;
191 size_t nclean;
192 size_t len;
194 if(!str)
195 return NULL;
197 len = strlen(str);
198 nclean = strcspn(str, "() {%*]\\\"");
199 if(len == nclean)
200 /* nothing to escape, return a strdup */
201 return curlx_strdup(str);
203 curlx_dyn_init(&line, 2000);
205 if(!escape_only && curlx_dyn_addn(&line, "\"", 1))
206 return NULL;
208 while(*str) {
209 if((*str == '\\' || *str == '"') &&
210 curlx_dyn_addn(&line, "\\", 1))
211 return NULL;
212 if(curlx_dyn_addn(&line, str, 1))
213 return NULL;
214 str++;
215 }
217 if(!escape_only && curlx_dyn_addn(&line, "\"", 1))
218 return NULL;
220 return curlx_dyn_ptr(&line);
223/*
224 * Finds the start of a literal '{size}' in line, skipping over quoted strings.
225 */
226static const char *imap_find_literal(const char *line, size_t len)
228 const char *end = line + len;
229 bool in_quote = FALSE;
231 while(line < end) {
232 if(in_quote) {
233 if(*line == '\\' && (line + 1) < end) {
234 line += 2;
235 continue;
236 }
237 if(*line == '"')
238 in_quote = FALSE;
239 }
240 else {
241 if(*line == '"')
242 in_quote = TRUE;
243 else if(*line == '{')
244 return line;
245 }
246 line++;
247 }
248 return NULL;
251/***********************************************************************
252 *
253 * imap_matchresp()
254 *
255 * Determines whether the untagged response is related to the specified
256 * command by checking if it is in format "* <command-name> ..." or
257 * "* <number> <command-name> ...".
258 *
259 * The "* " marker is assumed to have already been checked by the caller.
260 */
261static bool imap_matchresp(const char *line, size_t len, const char *cmd)
263 const char *end = line + len;
264 size_t cmd_len = strlen(cmd);
266 /* Skip the untagged response marker */
267 line += 2;
269 /* Do we have a number after the marker? */
270 if(line < end && ISDIGIT(*line)) {
271 /* Skip the number */
272 do
273 line++;
274 while(line < end && ISDIGIT(*line));
276 /* Do we have the space character? */
277 if(line == end || *line != ' ')
278 return FALSE;
280 line++;
281 }
283 /* Does the command name match and is it followed by a space character or at
284 the end of line? */
285 if(line + cmd_len <= end && curl_strnequal(line, cmd, cmd_len) &&
286 (line[cmd_len] == ' ' || line + cmd_len + 2 == end))
287 return TRUE;
289 return FALSE;
292/***********************************************************************
293 *
294 * imap_endofresp()
295 *
296 * Checks whether the given string is a valid tagged, untagged or continuation
297 * response which can be processed by the response handler.
298 */
299static bool imap_endofresp(struct Curl_easy *data, struct connectdata *conn,
300 const char *line, size_t len, int *resp)
302 struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN);
303 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
304 const char *id;
305 size_t id_len;
307 DEBUGASSERT(imapc);
308 DEBUGASSERT(imap);
309 if(!imapc || !imap)
310 return FALSE;
312 /* Do we have a tagged command response? */
313 id = imapc->resptag;
314 id_len = strlen(id);
315 if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
316 line += id_len + 1;
317 len -= id_len + 1;
319 if(len >= 2 && !memcmp(line, "OK", 2))
320 *resp = IMAP_RESP_OK;
321 else if(len >= 7 && !memcmp(line, "PREAUTH", 7))
322 *resp = IMAP_RESP_PREAUTH;
323 else
324 *resp = IMAP_RESP_NOT_OK;
326 return TRUE;
327 }
329 /* Do we have an untagged command response? */
330 if(len >= 2 && !memcmp("* ", line, 2)) {
331 switch(imapc->state) {
332 /* States which are interested in untagged responses */
333 case IMAP_CAPABILITY:
334 if(!imap_matchresp(line, len, "CAPABILITY"))
335 return FALSE;
336 break;
338 case IMAP_LIST:
339 if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
340 (imap->custom && !imap_matchresp(line, len, imap->custom) &&
341 (!curl_strequal(imap->custom, "STORE") ||
342 !imap_matchresp(line, len, "FETCH")) &&
343 !curl_strequal(imap->custom, "SELECT") &&
344 !curl_strequal(imap->custom, "EXAMINE") &&
345 !curl_strequal(imap->custom, "SEARCH") &&
346 !curl_strequal(imap->custom, "EXPUNGE") &&
347 !curl_strequal(imap->custom, "LSUB") &&
348 !curl_strequal(imap->custom, "UID") &&
349 !curl_strequal(imap->custom, "GETQUOTAROOT") &&
350 !curl_strequal(imap->custom, "NOOP")))
351 return FALSE;
352 break;
354 case IMAP_SELECT:
355 /* SELECT is special in that its untagged responses do not have a
356 common prefix so accept anything! */
357 break;
359 case IMAP_FETCH:
360 if(!imap_matchresp(line, len, "FETCH"))
361 return FALSE;
362 break;
364 case IMAP_SEARCH:
365 if(!imap_matchresp(line, len, "SEARCH"))
366 return FALSE;
367 break;
369 /* Ignore other untagged responses */
370 default:
371 return FALSE;
372 }
374 *resp = '*';
375 return TRUE;
376 }
378 /* Do we have a continuation response? This should be a + symbol followed by
379 a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
380 APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
381 some email servers ignore this and only send a single + instead. */
382 if(!imap->custom && ((len == 3 && line[0] == '+') ||
383 (len >= 2 && !memcmp("+ ", line, 2)))) {
384 switch(imapc->state) {
385 /* States which are interested in continuation responses */
386 case IMAP_AUTHENTICATE:
387 case IMAP_APPEND:
388 *resp = '+';
389 break;
391 default:
392 failf(data, "Unexpected continuation response");
393 *resp = -1;
394 break;
395 }
397 return TRUE;
398 }
400 if(imapc->state == IMAP_FETCH_FINAL && imap_find_literal(line, len)) {
401 /* FETCH_FINAL only waits for the tagged completion of the command. A
402 literal marker here means the server sent more response data (e.g.
403 another literal of a multi-section FETCH) than the transfer consumed.
404 Fail visibly instead of silently dropping the rest. */
405 failf(data, "Multiple literals in FETCH response, "
406 "only the first can be downloaded");
407 *resp = -1;
408 return TRUE;
409 }
411 return FALSE; /* Nothing for us */
414/***********************************************************************
415 *
416 * imap_get_message()
417 *
418 * Gets the authentication message from the response buffer.
419 */
420static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out)
422 struct imap_conn *imapc =
423 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
424 char *message;
425 size_t len;
427 if(!imapc)
428 return CURLE_FAILED_INIT;
430 message = curlx_dyn_ptr(&imapc->pp.recvbuf);
431 len = imapc->pp.nfinal;
432 if(len > 2) {
433 /* Find the start of the message */
434 len -= 2;
435 for(message += 2; ISBLANK(*message); message++, len--)
436 ;
438 /* Find the end of the message */
439 while(len--)
440 if(!ISNEWLINE(message[len]) && !ISBLANK(message[len]))
441 break;
443 /* Terminate the message */
444 message[++len] = '\0';
445 Curl_bufref_set(out, message, len, NULL);
446 }
447 else
448 /* junk input => zero length output */
449 Curl_bufref_set(out, "", 0, NULL);
451 return CURLE_OK;
454/***********************************************************************
455 *
456 * imap_state()
457 *
458 * This is the ONLY way to change IMAP state!
459 */
460static void imap_state(struct Curl_easy *data,
461 struct imap_conn *imapc,
462 imapstate newstate)
464#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
465 /* for debug purposes */
466 static const char * const names[] = {
467 "STOP",
468 "SERVERGREET",
469 "CAPABILITY",
470 "STARTTLS",
471 "UPGRADETLS",
472 "AUTHENTICATE",
473 "LOGIN",
474 "LIST",
475 "SELECT",
476 "FETCH",
477 "FETCH_FINAL",
478 "APPEND",
479 "APPEND_FINAL",
480 "SEARCH",
481 "LOGOUT",
482 /* LAST */
483 };
485 if(imapc->state != newstate)
486 infof(data, "IMAP %p state change from %s to %s",
487 (void *)imapc, names[imapc->state], names[newstate]);
488#else
489 (void)data;
490#endif
491 imapc->state = newstate;
494/***********************************************************************
495 *
496 * imap_perform_capability()
497 *
498 * Sends the CAPABILITY command in order to obtain a list of server side
499 * supported capabilities.
500 */
501static CURLcode imap_perform_capability(struct Curl_easy *data,
502 struct imap_conn *imapc)
504 CURLcode result = CURLE_OK;
506 imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
507 imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */
508 imapc->tls_supported = FALSE; /* Clear the TLS capability */
510 /* Send the CAPABILITY command */
511 result = imap_sendf(data, imapc, "CAPABILITY");
513 if(!result)
514 imap_state(data, imapc, IMAP_CAPABILITY);
516 return result;
519/***********************************************************************
520 *
521 * imap_perform_starttls()
522 *
523 * Sends the STARTTLS command to start the upgrade to TLS.
524 */
525static CURLcode imap_perform_starttls(struct Curl_easy *data,
526 struct imap_conn *imapc)
528 /* Send the STARTTLS command */
529 CURLcode result = imap_sendf(data, imapc, "STARTTLS");
531 if(!result)
532 imap_state(data, imapc, IMAP_STARTTLS);
534 return result;
537/***********************************************************************
538 *
539 * imap_perform_upgrade_tls()
540 *
541 * Performs the upgrade to TLS.
542 */
543static CURLcode imap_perform_upgrade_tls(struct Curl_easy *data,
544 struct imap_conn *imapc,
545 struct connectdata *conn)
547#ifdef USE_SSL
548 /* Start the SSL connection */
549 CURLcode result;
550 bool ssldone = FALSE;
552 if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) {
553 result = Curl_ssl_cfilter_add(
554 data, Curl_conn_get_origin(conn, FIRSTSOCKET), conn, FIRSTSOCKET);
555 if(result)
556 goto out;
557 /* Change the connection handler */
558 conn->scheme = &Curl_scheme_imaps;
559 }
561 DEBUGASSERT(!imapc->ssldone);
562 result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone);
563 DEBUGF(infof(data, "imap_perform_upgrade_tls, connect -> %d, %d",
564 (int)result, ssldone));
565 if(!result && ssldone) {
566 imapc->ssldone = ssldone;
567 /* perform CAPA now, changes imapc->state out of IMAP_UPGRADETLS */
568 result = imap_perform_capability(data, imapc);
569 }
570out:
571 return result;
572#else
573 (void)data;
574 (void)imapc;
575 (void)conn;
576 return CURLE_NOT_BUILT_IN;
577#endif
580/***********************************************************************
581 *
582 * imap_perform_login()
583 *
584 * Sends a clear text LOGIN command to authenticate with.
585 */
586static CURLcode imap_perform_login(struct Curl_easy *data,
587 struct imap_conn *imapc,
588 struct connectdata *conn)
590 CURLcode result = CURLE_OK;
591 char *user;
592 char *passwd;
594 /* Check we have a username and password to authenticate with and end the
595 connect phase if we do not */
596 if(!conn->creds) {
597 imap_state(data, imapc, IMAP_STOP);
599 return result;
600 }
602 /* Make sure the username and password are in the correct atom format */
603 user = imap_atom(Curl_creds_user(conn->creds), FALSE);
604 passwd = imap_atom(Curl_creds_passwd(conn->creds), FALSE);
606 /* Send the LOGIN command */
607 result = imap_sendf(data, imapc, "LOGIN %s %s", user ? user : "",
608 passwd ? passwd : "");
610 curlx_free(user);
611 curlx_strzero(passwd);
612 curlx_free(passwd);
614 if(!result)
615 imap_state(data, imapc, IMAP_LOGIN);
617 return result;
620/***********************************************************************
621 *
622 * imap_perform_authenticate()
623 *
624 * Sends an AUTHENTICATE command allowing the client to login with the given
625 * SASL authentication mechanism.
626 */
627static CURLcode imap_perform_authenticate(struct Curl_easy *data,
628 const char *mech,
629 const struct bufref *initresp)
631 struct imap_conn *imapc =
632 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
633 CURLcode result = CURLE_OK;
634 const char *ir = Curl_bufref_ptr(initresp);
636 if(!imapc)
637 return CURLE_FAILED_INIT;
638 if(ir) {
639 /* Send the AUTHENTICATE command with the initial response */
640 result = imap_sendf(data, imapc, "AUTHENTICATE %s %s",
641 mech, *ir ? ir : "=");
642 }
643 else {
644 /* Send the AUTHENTICATE command */
645 result = imap_sendf(data, imapc, "AUTHENTICATE %s", mech);
646 }
648 return result;
651/***********************************************************************
652 *
653 * imap_continue_authenticate()
654 *
655 * Sends SASL continuation data.
656 */
657static CURLcode imap_continue_authenticate(struct Curl_easy *data,
658 const char *mech,
659 const struct bufref *resp)
661 struct imap_conn *imapc =
662 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
664 (void)mech;
665 if(!imapc)
666 return CURLE_FAILED_INIT;
667 return Curl_pp_sendf(data, &imapc->pp, "%s", Curl_bufref_ptr(resp));
670/***********************************************************************
671 *
672 * imap_cancel_authenticate()
673 *
674 * Sends SASL cancellation.
675 */
676static CURLcode imap_cancel_authenticate(struct Curl_easy *data,
677 const char *mech)
679 struct imap_conn *imapc =
680 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
682 (void)mech;
683 if(!imapc)
684 return CURLE_FAILED_INIT;
685 return Curl_pp_sendf(data, &imapc->pp, "*");
688/***********************************************************************
689 *
690 * imap_perform_authentication()
691 *
692 * Initiates the authentication sequence, with the appropriate SASL
693 * authentication mechanism, falling back to clear text should a common
694 * mechanism not be available between the client and server.
695 */
696static CURLcode imap_perform_authentication(struct Curl_easy *data,
697 struct imap_conn *imapc)
699 CURLcode result = CURLE_OK;
700 saslprogress progress;
702 /* Check if already authenticated OR if there is enough data to authenticate
703 with and end the connect phase if we do not */
704 if(imapc->preauth ||
705 !Curl_sasl_can_authenticate(&imapc->sasl, data)) {
706 imap_state(data, imapc, IMAP_STOP);
707 return result;
708 }
710 /* Calculate the SASL login details */
711 result = Curl_sasl_start(&imapc->sasl, data, (bool)imapc->ir_supported,
712 &progress);
713 if(!result) {
714 if(progress == SASL_INPROGRESS)
715 imap_state(data, imapc, IMAP_AUTHENTICATE);
716 else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
717 /* Perform clear text authentication */
718 result = imap_perform_login(data, imapc, data->conn);
719 else
720 result = Curl_sasl_is_blocked(&imapc->sasl, data);
721 }
723 return result;
726/***********************************************************************
727 *
728 * imap_perform_list()
729 *
730 * Sends a LIST command or an alternative custom request.
731 */
732static CURLcode imap_perform_list(struct Curl_easy *data,
733 struct imap_conn *imapc,
734 struct IMAP *imap)
736 CURLcode result = CURLE_OK;
738 if(imap->custom)
739 /* Send the custom request */
740 result = imap_sendf(data, imapc, "%s%s", imap->custom,
741 imap->custom_params ? imap->custom_params : "");
742 else {
743 /* Make sure the mailbox is in the correct atom format if necessary */
744 char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, TRUE)
745 : curlx_strdup("");
746 if(!mailbox)
747 return CURLE_OUT_OF_MEMORY;
749 /* Send the LIST command */
750 result = imap_sendf(data, imapc, "LIST \"%s\" *", mailbox);
752 curlx_free(mailbox);
753 }
755 if(!result)
756 imap_state(data, imapc, IMAP_LIST);
758 return result;
761/***********************************************************************
762 *
763 * imap_perform_select()
764 *
765 * Sends a SELECT command to ask the server to change the selected mailbox.
766 */
767static CURLcode imap_perform_select(struct Curl_easy *data,
768 struct imap_conn *imapc,
769 struct IMAP *imap)
771 CURLcode result = CURLE_OK;
772 char *mailbox;
774 /* Invalidate old information as we are switching mailboxes */
775 curlx_safefree(imapc->mailbox);
776 imapc->mb_uidvalidity_set = FALSE;
778 /* Check we have a mailbox */
779 if(!imap->mailbox) {
780 failf(data, "Cannot SELECT without a mailbox.");
781 return CURLE_URL_MALFORMAT;
782 }
784 /* Make sure the mailbox is in the correct atom format */
785 mailbox = imap_atom(imap->mailbox, FALSE);
786 if(!mailbox)
787 return CURLE_OUT_OF_MEMORY;
789 /* Send the SELECT command */
790 result = imap_sendf(data, imapc, "SELECT %s", mailbox);
792 curlx_free(mailbox);
794 if(!result)
795 imap_state(data, imapc, IMAP_SELECT);
797 return result;
800/***********************************************************************
801 *
802 * imap_perform_fetch()
803 *
804 * Sends a FETCH command to initiate the download of a message.
805 */
806static CURLcode imap_perform_fetch(struct Curl_easy *data,
807 struct imap_conn *imapc,
808 struct IMAP *imap)
810 CURLcode result = CURLE_OK;
811 /* Check we have a UID */
812 if(imap->uid) {
814 /* Send the FETCH command */
815 if(imap->partial)
816 result = imap_sendf(data, imapc, "UID FETCH %s BODY[%s]<%s>",
817 imap->uid, imap->section ? imap->section : "",
818 imap->partial);
819 else
820 result = imap_sendf(data, imapc, "UID FETCH %s BODY[%s]",
821 imap->uid, imap->section ? imap->section : "");
822 }
823 else if(imap->mindex) {
824 /* Send the FETCH command */
825 if(imap->partial)
826 result = imap_sendf(data, imapc, "FETCH %s BODY[%s]<%s>",
827 imap->mindex, imap->section ? imap->section : "",
828 imap->partial);
829 else
830 result = imap_sendf(data, imapc, "FETCH %s BODY[%s]",
831 imap->mindex, imap->section ? imap->section : "");
832 }
833 else {
834 failf(data, "Cannot FETCH without a UID.");
835 return CURLE_URL_MALFORMAT;
836 }
837 if(!result)
838 imap_state(data, imapc, IMAP_FETCH);
840 return result;
843/***********************************************************************
844 *
845 * imap_perform_append()
846 *
847 * Sends an APPEND command to initiate the upload of a message.
848 */
849static CURLcode imap_perform_append(struct Curl_easy *data,
850 struct imap_conn *imapc,
851 struct IMAP *imap)
853 CURLcode result = CURLE_OK;
854 char *mailbox;
855 struct dynbuf flags;
857 /* Check we have a mailbox */
858 if(!imap->mailbox) {
859 failf(data, "Cannot APPEND without a mailbox.");
860 return CURLE_URL_MALFORMAT;
861 }
863#ifndef CURL_DISABLE_MIME
864 /* Prepare the mime data if some. */
865 if(IS_MIME_POST(data)) {
866 curl_mimepart *postp = data->set.mimepostp;
868 /* Use the whole structure as data. */
869 postp->flags &= ~(unsigned int)MIME_BODY_ONLY;
871 /* Add external headers and mime version. */
872 curl_mime_headers(postp, data->set.headers, 0);
873 result = Curl_mime_prepare_headers(data, postp, NULL,
874 NULL, MIMESTRATEGY_MAIL);
876 if(!result && !Curl_checkheaders(data, STRCONST("Mime-Version")))
877 result = Curl_mime_add_header(&postp->curlheaders, "Mime-Version: 1.0");
878 if(!result)
879 result = Curl_creader_set_mime(data, postp);
880 if(result)
881 return result;
882 }
883 else
884#endif
885 {
886 result = Curl_creader_set_fread(data, data->state.infilesize);
887 if(result)
888 return result;
889 }
891 /* Check we know the size of the upload. This takes all readers
892 * into account. Especially crlf conversions which make the size
893 * unpredictable, e.g. -1. */
894 data->state.infilesize = Curl_creader_total_length(data);
895 if(data->state.infilesize < 0) {
896 if(data->set.crlf)
897 failf(data, "Cannot APPEND with CRLF conversion making size unknown");
898 else
899 failf(data, "Cannot APPEND with unknown input file size");
900 return CURLE_UPLOAD_FAILED;
901 }
903 /* Make sure the mailbox is in the correct atom format */
904 mailbox = imap_atom(imap->mailbox, FALSE);
905 if(!mailbox)
906 return CURLE_OUT_OF_MEMORY;
908 /* Generate flags string and send the APPEND command */
909 curlx_dyn_init(&flags, 100);
910 if(data->set.upload_flags) {
911 int i;
912 struct ulbits ulflag[] = {
913 { CURLULFLAG_ANSWERED, "Answered" },
914 { CURLULFLAG_DELETED, "Deleted" },
915 { CURLULFLAG_DRAFT, "Draft" },
916 { CURLULFLAG_FLAGGED, "Flagged" },
917 { CURLULFLAG_SEEN, "Seen" },
918 { 0, NULL }
919 };
921 result = CURLE_OUT_OF_MEMORY;
922 if(curlx_dyn_add(&flags, " (")) {
923 goto cleanup;
924 }
926 for(i = 0; ulflag[i].bit; i++) {
927 if(data->set.upload_flags & ulflag[i].bit &&
928 ((curlx_dyn_len(&flags) > 2 && curlx_dyn_add(&flags, " ")) ||
929 curlx_dyn_add(&flags, "\\") ||
930 curlx_dyn_add(&flags, ulflag[i].flag)))
931 goto cleanup;
932 }
934 if(curlx_dyn_add(&flags, ")"))
935 goto cleanup;
936 }
937 else if(curlx_dyn_add(&flags, ""))
938 goto cleanup;
940 result = imap_sendf(data, imapc, "APPEND %s%s {%" FMT_OFF_T "}",
941 mailbox, curlx_dyn_ptr(&flags), data->state.infilesize);
943cleanup:
944 curlx_dyn_free(&flags);
945 curlx_free(mailbox);
947 if(!result)
948 imap_state(data, imapc, IMAP_APPEND);
950 return result;
953/***********************************************************************
954 *
955 * imap_perform_search()
956 *
957 * Sends a SEARCH command.
958 */
959static CURLcode imap_perform_search(struct Curl_easy *data,
960 struct imap_conn *imapc,
961 struct IMAP *imap)
963 CURLcode result = CURLE_OK;
965 /* Check we have a query string */
966 if(!imap->query) {
967 failf(data, "Cannot SEARCH without a query string.");
968 return CURLE_URL_MALFORMAT;
969 }
971 /* Send the SEARCH command */
972 result = imap_sendf(data, imapc, "SEARCH %s", imap->query);
974 if(!result)
975 imap_state(data, imapc, IMAP_SEARCH);
977 return result;
980/***********************************************************************
981 *
982 * imap_perform_logout()
983 *
984 * Performs the logout action prior to sclose() being called.
985 */
986static CURLcode imap_perform_logout(struct Curl_easy *data,
987 struct imap_conn *imapc)
989 /* Send the LOGOUT command */
990 CURLcode result = imap_sendf(data, imapc, "LOGOUT");
992 if(!result)
993 imap_state(data, imapc, IMAP_LOGOUT);
995 return result;
998/* For the initial server greeting */
999static CURLcode imap_state_servergreet_resp(struct Curl_easy *data,
1000 struct imap_conn *imapc,
1001 int imapcode,
1002 imapstate instate)
1004 (void)instate;
1006 if(imapcode == IMAP_RESP_PREAUTH) {
1007 /* PREAUTH */
1008 imapc->preauth = TRUE;
1009 infof(data, "PREAUTH connection, already authenticated");
1011 else if(imapcode != IMAP_RESP_OK) {
1012 failf(data, "Got unexpected imap-server response");
1013 return CURLE_WEIRD_SERVER_REPLY;
1016 return imap_perform_capability(data, imapc);
1019/* For CAPABILITY responses */
1020static CURLcode imap_state_capability_resp(struct Curl_easy *data,
1021 struct imap_conn *imapc,
1022 int imapcode,
1023 imapstate instate)
1025 CURLcode result = CURLE_OK;
1026 const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf);
1028 (void)instate;
1030 /* Do we have an untagged response? */
1031 if(imapcode == '*') {
1032 line += 2;
1034 /* Loop through the data line */
1035 for(;;) {
1036 size_t wordlen;
1037 while(*line && (ISBLANK(*line) || ISNEWLINE(*line)))
1038 line++;
1040 if(!*line)
1041 break;
1043 /* Extract the word */
1044 for(wordlen = 0; line[wordlen] && !ISBLANK(line[wordlen]) &&
1045 !ISNEWLINE(line[wordlen]);)
1046 wordlen++;
1048 /* Does the server support the STARTTLS capability? */
1049 if(wordlen == 8 && curl_strnequal(line, "STARTTLS", 8))
1050 imapc->tls_supported = TRUE;
1052 /* Has the server explicitly disabled clear text authentication? */
1053 else if(wordlen == 13 && curl_strnequal(line, "LOGINDISABLED", 13))
1054 imapc->login_disabled = TRUE;
1056 /* Does the server support the SASL-IR capability? */
1057 else if(wordlen == 7 && curl_strnequal(line, "SASL-IR", 7))
1058 imapc->ir_supported = TRUE;
1060 /* Do we have a SASL based authentication mechanism? */
1061 else if(wordlen > 5 && curl_strnequal(line, "AUTH=", 5)) {
1062 size_t llen;
1063 unsigned short mechbit;
1065 line += 5;
1066 wordlen -= 5;
1068 /* Test the word for a matching authentication mechanism */
1069 mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
1070 if(mechbit && llen == wordlen)
1071 imapc->sasl.authmechs |= mechbit;
1074 line += wordlen;
1077 else if(data->set.use_ssl && !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) {
1078 /* PREAUTH is not compatible with STARTTLS. */
1079 if(imapcode == IMAP_RESP_OK && imapc->tls_supported && !imapc->preauth) {
1080 /* Switch to TLS connection now */
1081 result = imap_perform_starttls(data, imapc);
1083 else if(data->set.use_ssl <= CURLUSESSL_TRY)
1084 result = imap_perform_authentication(data, imapc);
1085 else {
1086 failf(data, "STARTTLS not available.");
1087 result = CURLE_USE_SSL_FAILED;
1090 else
1091 result = imap_perform_authentication(data, imapc);
1093 return result;
1096/* For STARTTLS responses */
1097static CURLcode imap_state_starttls_resp(struct Curl_easy *data,
1098 struct imap_conn *imapc,
1099 int imapcode,
1100 imapstate instate)
1102 CURLcode result = CURLE_OK;
1104 (void)instate;
1106 /* Pipelining in response is forbidden. */
1107 if(imapc->pp.overflow)
1108 return CURLE_WEIRD_SERVER_REPLY;
1110 if(imapcode != IMAP_RESP_OK) {
1111 if(data->set.use_ssl != CURLUSESSL_TRY) {
1112 failf(data, "STARTTLS denied");
1113 result = CURLE_USE_SSL_FAILED;
1115 else
1116 result = imap_perform_authentication(data, imapc);
1118 else
1119 imap_state(data, imapc, IMAP_UPGRADETLS);
1121 return result;
1124/* For SASL authentication responses */
1125static CURLcode imap_state_auth_resp(struct Curl_easy *data,
1126 struct imap_conn *imapc,
1127 int imapcode,
1128 imapstate instate)
1130 CURLcode result = CURLE_OK;
1131 saslprogress progress;
1133 (void)instate;
1135 result = Curl_sasl_continue(&imapc->sasl, data, imapcode, &progress);
1136 if(!result)
1137 switch(progress) {
1138 case SASL_DONE:
1139 imap_state(data, imapc, IMAP_STOP); /* Authenticated */
1140 break;
1141 case SASL_IDLE: /* No mechanism left after cancellation */
1142 if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
1143 /* Perform clear text authentication */
1144 result = imap_perform_login(data, imapc, data->conn);
1145 else {
1146 failf(data, "Authentication cancelled");
1147 result = CURLE_LOGIN_DENIED;
1149 break;
1150 default:
1151 break;
1154 return result;
1157/* For LOGIN responses */
1158static CURLcode imap_state_login_resp(struct Curl_easy *data,
1159 struct imap_conn *imapc,
1160 int imapcode,
1161 imapstate instate)
1163 CURLcode result = CURLE_OK;
1164 (void)instate;
1166 if(imapcode != IMAP_RESP_OK) {
1167 failf(data, "Access denied. %c", imapcode);
1168 result = CURLE_LOGIN_DENIED;
1170 else
1171 /* End of connect phase */
1172 imap_state(data, imapc, IMAP_STOP);
1174 return result;
1177/* Detect IMAP listings vs. downloading a single email */
1178static bool is_custom_fetch_listing_match(const char *params)
1180 /* match " 1:* (FLAGS ..." or " 1,2,3 (FLAGS ..." */
1181 if(*params++ != ' ')
1182 return FALSE;
1184 while(ISDIGIT(*params)) {
1185 params++;
1186 if(*params == 0)
1187 return FALSE;
1189 if(*params == ':')
1190 return TRUE;
1191 if(*params == ',')
1192 return TRUE;
1193 return FALSE;
1196static bool is_custom_fetch_listing(struct IMAP *imap)
1198 /* filter out "UID FETCH 1:* (FLAGS ..." queries to list emails */
1199 if(!imap->custom)
1200 return FALSE;
1201 else if(curl_strequal(imap->custom, "FETCH") && imap->custom_params) {
1202 const char *p = imap->custom_params;
1203 return is_custom_fetch_listing_match(p);
1205 else if(curl_strequal(imap->custom, "UID") && imap->custom_params &&
1206 curl_strnequal(imap->custom_params, " FETCH ", 7)) {
1207 const char *p = imap->custom_params + 6;
1208 return is_custom_fetch_listing_match(p);
1210 return FALSE;
1213/* For LIST and SEARCH responses */
1214static CURLcode imap_state_listsearch_resp(struct Curl_easy *data,
1215 struct imap_conn *imapc,
1216 int imapcode,
1217 imapstate instate)
1219 CURLcode result = CURLE_OK;
1220 const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf);
1221 size_t len = imapc->pp.nfinal;
1222 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
1224 DEBUGASSERT(imap);
1225 if(!imap)
1226 return CURLE_FAILED_INIT;
1227 (void)instate;
1229 if(imapcode == '*' && is_custom_fetch_listing(imap)) {
1230 /* custom FETCH or UID FETCH for listing is not handled here */
1232 else if(imapcode == '*') {
1233 /* Check if this response contains a literal (e.g. FETCH responses with
1234 body data). Literal syntax is {size}\r\n */
1235 const char *cr = memchr(line, '\r', len);
1236 size_t line_len = cr ? (size_t)(cr - line) : len;
1237 const char *ptr = imap_find_literal(line, line_len);
1238 if(ptr) {
1239 curl_off_t size = 0;
1240 bool parsed = FALSE;
1241 ptr++;
1242 if(!curlx_str_number(&ptr, &size, CURL_OFF_T_MAX) &&
1243 !curlx_str_single(&ptr, '}'))
1244 parsed = TRUE;
1246 if(parsed) {
1247 struct pingpong *pp = &imapc->pp;
1248 size_t buffer_len = curlx_dyn_len(&pp->recvbuf);
1249 size_t after_header = buffer_len - pp->nfinal;
1251 /* This is a literal response, setup to receive the body data */
1252 infof(data, "Found %" FMT_OFF_T " bytes to download", size);
1254 /* First write the header line */
1255 result = Curl_client_write(data, CLIENTWRITE_BODY, line, len);
1256 if(result)
1257 return result;
1259 /* Handle data already in buffer after the header line */
1260 if(after_header > 0) {
1261 /* There is already data in the buffer that is part of the literal
1262 body or subsequent responses */
1263 size_t chunk = after_header;
1265 /* Keep only the data after the header line */
1266 curlx_dyn_tail(&pp->recvbuf, chunk);
1267 pp->nfinal = 0; /* done */
1269 /* Limit chunk to the literal size */
1270 if((curl_off_t)chunk > size)
1271 chunk = (size_t)size;
1273 if(chunk) {
1274 /* Write the literal body data */
1275 result = Curl_client_write(data, CLIENTWRITE_BODY,
1276 curlx_dyn_ptr(&pp->recvbuf), chunk);
1277 if(result)
1278 return result;
1281 /* Handle remaining data in buffer (either more literal data or
1282 subsequent responses) */
1283 if(after_header > chunk) {
1284 /* Keep the data after the literal body */
1285 pp->overflow = after_header - chunk;
1286 curlx_dyn_tail(&pp->recvbuf, pp->overflow);
1288 if(imap_find_literal(curlx_dyn_ptr(&pp->recvbuf), pp->overflow)) {
1289 /* The buffered remainder contains another literal, meaning
1290 this FETCH response carries more body sections than the
1291 single transfer set up above can deliver. Fail visibly
1292 instead of silently dropping the rest. */
1293 failf(data, "Multiple literals in FETCH response, "
1294 "only the first can be downloaded");
1295 return CURLE_WEIRD_SERVER_REPLY;
1298 else {
1299 pp->overflow = 0;
1300 curlx_dyn_reset(&pp->recvbuf);
1303 else {
1304 /* No data in buffer yet, reset overflow */
1305 pp->overflow = 0;
1308 if((CURL_OFF_T_MAX - size) < (curl_off_t)len)
1309 /* unlikely to actually be a transfer this big, but avoid integer
1310 overflow */
1311 size = CURL_OFF_T_MAX;
1312 else
1313 size += len;
1315 /* Progress size includes both header line and literal body */
1316 Curl_pgrsSetDownloadSize(data, size);
1318 if(data->req.bytecount == size)
1319 /* All data already transferred (header + literal body) */
1320 Curl_xfer_setup_nop(data);
1321 else {
1322 /* Setup to receive the literal body data.
1323 maxdownload and transfer size include both header line and
1324 literal body */
1325 data->req.maxdownload = size;
1326 Curl_xfer_setup_recv(data, FIRSTSOCKET, size);
1328 /* End of DO phase */
1329 imap_state(data, imapc, IMAP_STOP);
1331 else {
1332 /* Failed to parse literal, write the line */
1333 result = Curl_client_write(data, CLIENTWRITE_BODY, line, len);
1336 else {
1337 /* No literal, write the line as-is */
1338 result = Curl_client_write(data, CLIENTWRITE_BODY, line, len);
1341 else if(imapcode != IMAP_RESP_OK)
1342 result = CURLE_QUOTE_ERROR;
1343 else
1344 /* End of DO phase */
1345 imap_state(data, imapc, IMAP_STOP);
1347 return result;
1350/* For SELECT responses */
1351static CURLcode imap_state_select_resp(struct Curl_easy *data,
1352 struct imap_conn *imapc,
1353 struct IMAP *imap,
1354 int imapcode,
1355 imapstate instate)
1357 CURLcode result = CURLE_OK;
1358 (void)instate;
1360 if(imapcode == '*') {
1361 /* See if this is an UIDVALIDITY response */
1362 const char *line = curlx_dyn_ptr(&imapc->pp.recvbuf);
1363 size_t len = curlx_dyn_len(&imapc->pp.recvbuf);
1364 if((len >= 18) && checkprefix("OK [UIDVALIDITY ", &line[2])) {
1365 curl_off_t value;
1366 const char *p = &line[2] + CURL_CSTRLEN("OK [UIDVALIDITY ");
1367 if(!curlx_str_number(&p, &value, UINT_MAX)) {
1368 imapc->mb_uidvalidity = (unsigned int)value;
1369 imapc->mb_uidvalidity_set = TRUE;
1373 else if(imapcode == IMAP_RESP_OK) {
1374 /* Check if the UIDVALIDITY has been specified and matches */
1375 if(imap->uidvalidity_set && imapc->mb_uidvalidity_set &&
1376 (imap->uidvalidity != imapc->mb_uidvalidity)) {
1377 failf(data, "Mailbox UIDVALIDITY has changed");
1378 result = CURLE_REMOTE_FILE_NOT_FOUND;
1380 else {
1381 /* Note the currently opened mailbox on this connection */
1382 DEBUGASSERT(!imapc->mailbox);
1383 imapc->mailbox = curlx_strdup(imap->mailbox);
1384 if(!imapc->mailbox)
1385 return CURLE_OUT_OF_MEMORY;
1387 if(imap->custom)
1388 result = imap_perform_list(data, imapc, imap);
1389 else if(imap->query)
1390 result = imap_perform_search(data, imapc, imap);
1391 else
1392 result = imap_perform_fetch(data, imapc, imap);
1395 else {
1396 failf(data, "Select failed");
1397 result = CURLE_LOGIN_DENIED;
1400 return result;
1403/* For the (first line of the) FETCH responses */
1404static CURLcode imap_state_fetch_resp(struct Curl_easy *data,
1405 struct imap_conn *imapc,
1406 int imapcode,
1407 imapstate instate)
1409 CURLcode result = CURLE_OK;
1410 struct pingpong *pp = &imapc->pp;
1411 const char *ptr = curlx_dyn_ptr(&imapc->pp.recvbuf);
1412 size_t len = imapc->pp.nfinal;
1413 bool parsed = FALSE;
1414 curl_off_t size = 0;
1416 (void)instate;
1418 if(imapcode != '*') {
1419 Curl_pgrsSetDownloadSize(data, -1);
1420 imap_state(data, imapc, IMAP_STOP);
1421 return CURLE_REMOTE_FILE_NOT_FOUND;
1424 /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
1425 the continuation data contained within the curly brackets */
1426 ptr = imap_find_literal(ptr, len);
1427 if(ptr) {
1428 ptr++;
1429 if(!curlx_str_number(&ptr, &size, CURL_OFF_T_MAX) &&
1430 !curlx_str_single(&ptr, '}'))
1431 parsed = TRUE;
1434 if(parsed) {
1435 infof(data, "Found %" FMT_OFF_T " bytes to download", size);
1436 Curl_pgrsSetDownloadSize(data, size);
1438 if(pp->overflow) {
1439 /* At this point there is a data in the receive buffer that is body
1440 content, send it as body and then skip it. Do note that there may
1441 even be additional "headers" after the body. */
1442 size_t chunk = pp->overflow;
1444 /* keep only the overflow */
1445 curlx_dyn_tail(&pp->recvbuf, chunk);
1446 pp->nfinal = 0; /* done */
1448 if((curl_off_t)chunk > size)
1449 /* The conversion from curl_off_t to size_t is always fine here */
1450 chunk = (size_t)size;
1452 if(!chunk) {
1453 /* no size, we are done with the data */
1454 imap_state(data, imapc, IMAP_STOP);
1455 return CURLE_OK;
1457 result = Curl_client_write(data, CLIENTWRITE_BODY,
1458 curlx_dyn_ptr(&pp->recvbuf), chunk);
1459 if(result)
1460 return result;
1462 infof(data, "Written %zu bytes, %" FMT_OFF_T
1463 " bytes are left for transfer", chunk, (curl_off_t)(size - chunk));
1465 /* Have we used the entire overflow or part of it?*/
1466 if(pp->overflow > chunk) {
1467 /* remember the remaining trailing overflow data */
1468 pp->overflow -= chunk;
1469 curlx_dyn_tail(&pp->recvbuf, pp->overflow);
1471 else {
1472 pp->overflow = 0; /* handled */
1473 /* Free the cache */
1474 curlx_dyn_reset(&pp->recvbuf);
1478 if(data->req.bytecount == size)
1479 /* The entire data is already transferred! */
1480 Curl_xfer_setup_nop(data);
1481 else {
1482 /* IMAP download */
1483 data->req.maxdownload = size;
1484 Curl_xfer_setup_recv(data, FIRSTSOCKET, size);
1487 else {
1488 /* We do not know how to parse this line */
1489 failf(data, "Failed to parse FETCH response.");
1490 result = CURLE_WEIRD_SERVER_REPLY;
1493 /* End of DO phase */
1494 imap_state(data, imapc, IMAP_STOP);
1496 return result;
1499/* For final FETCH responses performed after the download */
1500static CURLcode imap_state_fetch_final_resp(struct Curl_easy *data,
1501 struct imap_conn *imapc,
1502 int imapcode,
1503 imapstate instate)
1505 CURLcode result = CURLE_OK;
1507 (void)instate;
1509 if(imapcode != IMAP_RESP_OK)
1510 result = CURLE_WEIRD_SERVER_REPLY;
1511 else
1512 /* End of DONE phase */
1513 imap_state(data, imapc, IMAP_STOP);
1515 return result;
1518/* For APPEND responses */
1519static CURLcode imap_state_append_resp(struct Curl_easy *data,
1520 struct imap_conn *imapc,
1521 int imapcode,
1522 imapstate instate)
1524 CURLcode result = CURLE_OK;
1525 (void)instate;
1527 if(imapcode != '+') {
1528 result = CURLE_UPLOAD_FAILED;
1530 else {
1531 /* Set the progress upload size */
1532 Curl_pgrsSetUploadSize(data, data->state.infilesize);
1534 /* IMAP upload */
1535 Curl_xfer_setup_send(data, FIRSTSOCKET);
1537 /* End of DO phase */
1538 imap_state(data, imapc, IMAP_STOP);
1541 return result;
1544/* For final APPEND responses performed after the upload */
1545static CURLcode imap_state_append_final_resp(struct Curl_easy *data,
1546 struct imap_conn *imapc,
1547 int imapcode,
1548 imapstate instate)
1550 CURLcode result = CURLE_OK;
1552 (void)instate;
1554 if(imapcode != IMAP_RESP_OK)
1555 result = CURLE_UPLOAD_FAILED;
1556 else
1557 /* End of DONE phase */
1558 imap_state(data, imapc, IMAP_STOP);
1560 return result;
1563static CURLcode imap_pp_statemachine(struct Curl_easy *data,
1564 struct connectdata *conn)
1566 CURLcode result = CURLE_OK;
1567 int imapcode;
1568 struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN);
1569 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
1570 struct pingpong *pp;
1571 size_t nread = 0;
1573 if(!imapc || !imap)
1574 return CURLE_FAILED_INIT;
1575 pp = &imapc->pp;
1576 /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
1577upgrade_tls:
1578 if(imapc->state == IMAP_UPGRADETLS) {
1579 result = imap_perform_upgrade_tls(data, imapc, conn);
1580 if(result || (imapc->state == IMAP_UPGRADETLS))
1581 return result;
1584 /* Flush any data that needs to be sent */
1585 if(pp->sendleft)
1586 return Curl_pp_flushsend(data, pp);
1588 do {
1589 /* Read the response from the server */
1590 result = Curl_pp_readresp(data, FIRSTSOCKET, pp, &imapcode, &nread);
1591 if(result)
1592 return result;
1594 /* Was there an error parsing the response line? */
1595 if(imapcode == -1)
1596 return CURLE_WEIRD_SERVER_REPLY;
1598 if(!imapcode)
1599 break;
1601 /* We have now received a full IMAP server response */
1602 switch(imapc->state) {
1603 case IMAP_SERVERGREET:
1604 result = imap_state_servergreet_resp(data, imapc,
1605 imapcode, imapc->state);
1606 break;
1608 case IMAP_CAPABILITY:
1609 result = imap_state_capability_resp(data, imapc, imapcode, imapc->state);
1610 break;
1612 case IMAP_STARTTLS:
1613 result = imap_state_starttls_resp(data, imapc, imapcode, imapc->state);
1614 /* During UPGRADETLS, leave the read loop as we need to connect
1615 * (e.g. TLS handshake) before we continue sending/receiving. */
1616 if(!result && (imapc->state == IMAP_UPGRADETLS))
1617 goto upgrade_tls;
1618 break;
1620 case IMAP_AUTHENTICATE:
1621 result = imap_state_auth_resp(data, imapc, imapcode, imapc->state);
1622 break;
1624 case IMAP_LOGIN:
1625 result = imap_state_login_resp(data, imapc, imapcode, imapc->state);
1626 break;
1628 case IMAP_LIST:
1629 case IMAP_SEARCH:
1630 result = imap_state_listsearch_resp(data, imapc, imapcode, imapc->state);
1631 break;
1633 case IMAP_SELECT:
1634 result = imap_state_select_resp(data, imapc, imap,
1635 imapcode, imapc->state);
1636 break;
1638 case IMAP_FETCH:
1639 result = imap_state_fetch_resp(data, imapc, imapcode, imapc->state);
1640 break;
1642 case IMAP_FETCH_FINAL:
1643 result = imap_state_fetch_final_resp(data, imapc,
1644 imapcode, imapc->state);
1645 break;
1647 case IMAP_APPEND:
1648 result = imap_state_append_resp(data, imapc, imapcode, imapc->state);
1649 break;
1651 case IMAP_APPEND_FINAL:
1652 result = imap_state_append_final_resp(data, imapc,
1653 imapcode, imapc->state);
1654 break;
1656 case IMAP_LOGOUT:
1657 default:
1658 /* internal error */
1659 imap_state(data, imapc, IMAP_STOP);
1660 break;
1662 } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
1664 return result;
1667/* Called repeatedly until done from multi.c */
1668static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done)
1670 CURLcode result = CURLE_OK;
1671 struct imap_conn *imapc =
1672 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
1674 *done = FALSE;
1675 if(!imapc)
1676 return CURLE_FAILED_INIT;
1677 result = Curl_pp_statemach(data, &imapc->pp, FALSE, FALSE);
1678 *done = (imapc->state == IMAP_STOP);
1680 return result;
1683static CURLcode imap_block_statemach(struct Curl_easy *data,
1684 struct imap_conn *imapc,
1685 bool disconnecting)
1687 CURLcode result = CURLE_OK;
1689 while(imapc->state != IMAP_STOP && !result)
1690 result = Curl_pp_statemach(data, &imapc->pp, TRUE, disconnecting);
1692 return result;
1695/* For the IMAP "protocol connect" and "doing" phases only */
1696static CURLcode imap_pollset(struct Curl_easy *data,
1697 struct easy_pollset *ps)
1699 struct imap_conn *imapc =
1700 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
1701 return imapc ? Curl_pp_pollset(data, &imapc->pp, ps) : CURLE_OK;
1704static void imap_easy_reset(struct IMAP *imap)
1706 curlx_safefree(imap->mailbox);
1707 curlx_safefree(imap->uid);
1708 curlx_safefree(imap->mindex);
1709 curlx_safefree(imap->section);
1710 curlx_safefree(imap->partial);
1711 curlx_safefree(imap->query);
1712 curlx_safefree(imap->custom);
1713 curlx_safefree(imap->custom_params);
1714 imap->uidvalidity_set = FALSE;
1715 /* Clear the transfer mode for the next request */
1716 imap->transfer = PPTRANSFER_BODY;
1719/***********************************************************************
1721 * imap_is_bchar()
1723 * Portable test of whether the specified char is a "bchar" as defined in the
1724 * grammar of RFC-5092.
1725 */
1726static bool imap_is_bchar(char ch)
1728 /* Performing the alnum check first with macro is faster because of ASCII
1729 arithmetic */
1730 return ch && (ISALNUM(ch) || strchr(":@/&=-._~!$\'()*+,%", ch));
1733/***********************************************************************
1735 * imap_parse_url_options()
1737 * Parse the URL login options.
1738 */
1739static CURLcode imap_parse_url_options(struct connectdata *conn,
1740 struct imap_conn *imapc)
1742 CURLcode result = CURLE_OK;
1743 const char *ptr = conn->options;
1744 bool prefer_login = FALSE;
1746 while(!result && ptr && *ptr) {
1747 const char *key = ptr;
1748 const char *value;
1750 while(*ptr && *ptr != '=')
1751 ptr++;
1753 value = ptr + 1;
1755 while(*ptr && *ptr != ';')
1756 ptr++;
1758 if(curl_strnequal(key, "AUTH=+LOGIN", 11)) {
1759 /* User prefers plaintext LOGIN over any SASL, including SASL LOGIN */
1760 prefer_login = TRUE;
1761 imapc->sasl.prefmech = SASL_AUTH_NONE;
1763 else if(curl_strnequal(key, "AUTH=", 5)) {
1764 prefer_login = FALSE;
1765 result = Curl_sasl_parse_url_auth_option(&imapc->sasl,
1766 value, ptr - value);
1768 else {
1769 prefer_login = FALSE;
1770 result = CURLE_URL_MALFORMAT;
1773 if(*ptr == ';')
1774 ptr++;
1777 if(prefer_login)
1778 imapc->preftype = IMAP_TYPE_CLEARTEXT;
1779 else {
1780 switch(imapc->sasl.prefmech) {
1781 case SASL_AUTH_NONE:
1782 imapc->preftype = IMAP_TYPE_NONE;
1783 break;
1784 case SASL_AUTH_DEFAULT:
1785 imapc->preftype = IMAP_TYPE_ANY;
1786 break;
1787 default:
1788 imapc->preftype = IMAP_TYPE_SASL;
1789 break;
1793 return result;
1796/***********************************************************************
1798 * imap_parse_url_path()
1800 * Parse the URL path into separate path components.
1802 */
1803static CURLcode imap_parse_url_path(struct Curl_easy *data,
1804 struct IMAP *imap)
1806 /* The imap struct is already initialized in imap_connect() */
1807 CURLcode result = CURLE_OK;
1808 const char *begin = &data->state.up.path[1]; /* skip leading slash */
1809 const char *ptr = begin;
1811 /* See how much of the URL is a valid path and decode it */
1812 while(imap_is_bchar(*ptr))
1813 ptr++;
1815 if(ptr != begin) {
1816 /* Remove the trailing slash if present */
1817 const char *end = ptr;
1818 if(end > begin && end[-1] == '/')
1819 end--;
1821 result = Curl_urldecode(begin, end - begin, &imap->mailbox, NULL,
1822 REJECT_CTRL);
1823 if(result)
1824 return result;
1826 else
1827 imap->mailbox = NULL;
1829 /* There can be any number of parameters in the form ";NAME=VALUE" */
1830 while(*ptr == ';') {
1831 char *name;
1832 char *value;
1833 size_t valuelen;
1835 /* Find the length of the name parameter */
1836 begin = ++ptr;
1837 while(*ptr && *ptr != '=')
1838 ptr++;
1840 if(!*ptr)
1841 return CURLE_URL_MALFORMAT;
1843 /* Decode the name parameter */
1844 result = Curl_urldecode(begin, ptr - begin, &name, NULL,
1845 REJECT_CTRL);
1846 if(result)
1847 return result;
1849 /* Find the length of the value parameter */
1850 begin = ++ptr;
1851 while(imap_is_bchar(*ptr))
1852 ptr++;
1854 /* Decode the value parameter */
1855 result = Curl_urldecode(begin, ptr - begin, &value, &valuelen,
1856 REJECT_CTRL);
1857 if(result) {
1858 curlx_free(name);
1859 return result;
1862 DEBUGF(infof(data, "IMAP URL parameter '%s' = '%s'", name, value));
1864 /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION
1865 and PARTIAL) stripping of the trailing slash character if it is
1866 present.
1868 Note: Unknown parameters trigger a URL_MALFORMAT error. */
1869 if(valuelen > 0 && value[valuelen - 1] == '/')
1870 value[valuelen - 1] = '\0';
1871 if(valuelen) {
1872 if(curl_strequal(name, "UIDVALIDITY") && !imap->uidvalidity_set) {
1873 curl_off_t num;
1874 const char *p = (const char *)value;
1875 if(!curlx_str_number(&p, &num, UINT_MAX)) {
1876 imap->uidvalidity = (unsigned int)num;
1877 imap->uidvalidity_set = TRUE;
1879 curlx_free(value);
1881 else if(curl_strequal(name, "UID") && !imap->uid) {
1882 imap->uid = value;
1884 else if(curl_strequal(name, "MAILINDEX") && !imap->mindex) {
1885 imap->mindex = value;
1887 else if(curl_strequal(name, "SECTION") && !imap->section) {
1888 imap->section = value;
1890 else if(curl_strequal(name, "PARTIAL") && !imap->partial) {
1891 imap->partial = value;
1893 else {
1894 curlx_free(name);
1895 curlx_free(value);
1896 return CURLE_URL_MALFORMAT;
1899 else
1900 /* blank? */
1901 curlx_free(value);
1902 curlx_free(name);
1905 /* Does the URL contain a query parameter? Only valid when we have a mailbox
1906 and no UID as per RFC-5092 */
1907 if(imap->mailbox && !imap->uid && !imap->mindex) {
1908 /* Get the query parameter, URL decoded */
1909 CURLUcode uc = curl_url_get(data->state.uh, CURLUPART_QUERY, &imap->query,
1910 CURLU_URLDECODE);
1911 if(uc == CURLUE_OUT_OF_MEMORY)
1912 return CURLE_OUT_OF_MEMORY;
1915 /* Any extra stuff at the end of the URL is an error */
1916 if(*ptr)
1917 return CURLE_URL_MALFORMAT;
1919 return CURLE_OK;
1922/***********************************************************************
1924 * imap_parse_custom_request()
1926 * Parse the custom request.
1927 */
1928static CURLcode imap_parse_custom_request(struct Curl_easy *data,
1929 struct IMAP *imap)
1931 CURLcode result = CURLE_OK;
1932 const char *custom = CURL_EASY_STR(data, STRING_CUSTOMREQUEST);
1934 if(custom) {
1935 /* URL decode the custom request */
1936 result = Curl_urldecode(custom, 0, &imap->custom, NULL, REJECT_CTRL);
1938 /* Extract the parameters if specified */
1939 if(!result) {
1940 const char *params = imap->custom;
1942 while(*params && *params != ' ')
1943 params++;
1945 if(*params) {
1946 imap->custom_params = curlx_strdup(params);
1947 imap->custom[params - imap->custom] = '\0';
1949 if(!imap->custom_params)
1950 result = CURLE_OUT_OF_MEMORY;
1955 return result;
1958/***********************************************************************
1960 * imap_connect()
1962 * This function should do everything that is to be considered a part of the
1963 * connection phase.
1965 * The variable 'done' points to will be TRUE if the protocol-layer connect
1966 * phase is done when this function returns, or FALSE if not.
1967 */
1968static CURLcode imap_connect(struct Curl_easy *data, bool *done)
1970 struct imap_conn *imapc =
1971 Curl_conn_meta_get(data->conn, CURL_META_IMAP_CONN);
1972 CURLcode result = CURLE_OK;
1974 *done = FALSE; /* default to not done yet */
1975 if(!imapc)
1976 return CURLE_FAILED_INIT;
1978 /* Parse the URL options */
1979 result = imap_parse_url_options(data->conn, imapc);
1980 if(result)
1981 return result;
1983 /* Start off waiting for the server greeting response */
1984 imap_state(data, imapc, IMAP_SERVERGREET);
1986 /* Start off with an response id of '*' */
1987 curlx_strcopy(imapc->resptag, sizeof(imapc->resptag), STRCONST("*"));
1989 result = imap_multi_statemach(data, done);
1991 return result;
1994/***********************************************************************
1996 * imap_done()
1998 * The DONE function. This does what needs to be done after a single DO has
1999 * performed.
2001 * Input argument is already checked for validity.
2002 */
2003static CURLcode imap_done(struct Curl_easy *data, CURLcode status,
2004 bool premature)
2006 CURLcode result = CURLE_OK;
2007 struct connectdata *conn = data->conn;
2008 struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN);
2009 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
2011 if(!imapc)
2012 return CURLE_FAILED_INIT;
2013 if(!imap)
2014 return CURLE_OK;
2016 if(status || premature) {
2017 CURL_TRC_M(data, "IMAP done, not finalizing transfer");
2018 connclose(conn); /* marked for closure */
2019 result = status; /* use the already set error code */
2021 else if(!data->set.connect_only &&
2022 ((!imap->custom && (imap->uid || imap->mindex)) ||
2023 (imap->custom && data->req.maxdownload > 0) ||
2024 data->state.upload || IS_MIME_POST(data))) {
2025 /* Handle responses after FETCH or APPEND transfer has finished.
2026 For custom commands, check if we set up a download which indicates
2027 a FETCH-like command with literal data. */
2029 if(!data->state.upload && !IS_MIME_POST(data))
2030 imap_state(data, imapc, IMAP_FETCH_FINAL);
2031 else {
2032 /* End the APPEND command first by sending an empty line */
2033 result = Curl_pp_sendf(data, &imapc->pp, "%s", "");
2034 if(!result)
2035 imap_state(data, imapc, IMAP_APPEND_FINAL);
2038 /* Run the state-machine */
2039 if(!result)
2040 result = imap_block_statemach(data, imapc, FALSE);
2043 imap_easy_reset(imap);
2044 return result;
2047/***********************************************************************
2049 * imap_perform()
2051 * This is the actual DO function for IMAP. Fetch or append a message, or do
2052 * other things according to the options previously setup.
2053 */
2054static CURLcode imap_perform(struct Curl_easy *data, bool *connected,
2055 bool *dophase_done)
2057 /* This is IMAP and no proxy */
2058 CURLcode result = CURLE_OK;
2059 struct connectdata *conn = data->conn;
2060 struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN);
2061 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
2062 bool selected = FALSE;
2064 DEBUGF(infof(data, "DO phase starts"));
2065 if(!imapc || !imap)
2066 return CURLE_FAILED_INIT;
2068 if(data->req.no_body) {
2069 /* Requested no body means no transfer */
2070 imap->transfer = PPTRANSFER_INFO;
2073 *dophase_done = FALSE; /* not done yet */
2075 /* Determine if the requested mailbox (with the same UIDVALIDITY if set)
2076 has already been selected on this connection */
2077 if(imap->mailbox && imapc->mailbox &&
2078 (!strcmp(imap->mailbox, imapc->mailbox) ||
2079 (curl_strequal(imap->mailbox, "INBOX") &&
2080 curl_strequal(imapc->mailbox, "INBOX"))) &&
2081 (!imap->uidvalidity_set || !imapc->mb_uidvalidity_set ||
2082 (imap->uidvalidity == imapc->mb_uidvalidity)))
2083 selected = TRUE;
2085 /* Start the first command in the DO phase */
2086 if(data->state.upload || IS_MIME_POST(data))
2087 /* APPEND can be executed directly */
2088 result = imap_perform_append(data, imapc, imap);
2089 else if(imap->custom && (selected || !imap->mailbox))
2090 /* Custom command using the same mailbox or no mailbox */
2091 result = imap_perform_list(data, imapc, imap);
2092 else if(!imap->custom && selected && (imap->uid || imap->mindex))
2093 /* FETCH from the same mailbox */
2094 result = imap_perform_fetch(data, imapc, imap);
2095 else if(!imap->custom && selected && imap->query)
2096 /* SEARCH the current mailbox */
2097 result = imap_perform_search(data, imapc, imap);
2098 else if(imap->mailbox && !selected &&
2099 (imap->custom || imap->uid || imap->mindex || imap->query))
2100 /* SELECT the mailbox */
2101 result = imap_perform_select(data, imapc, imap);
2102 else
2103 /* LIST */
2104 result = imap_perform_list(data, imapc, imap);
2106 if(result)
2107 return result;
2109 /* Run the state-machine */
2110 result = imap_multi_statemach(data, dophase_done);
2112 *connected = Curl_conn_is_connected(conn, FIRSTSOCKET);
2114 if(*dophase_done)
2115 DEBUGF(infof(data, "DO phase is complete"));
2117 return result;
2120/* Call this when the DO phase has completed */
2121static CURLcode imap_dophase_done(struct Curl_easy *data,
2122 struct IMAP *imap,
2123 bool connected)
2125 (void)connected;
2127 if(imap->transfer != PPTRANSFER_BODY)
2128 /* no data to transfer */
2129 Curl_xfer_setup_nop(data);
2131 return CURLE_OK;
2134/***********************************************************************
2136 * imap_regular_transfer()
2138 * The input argument is already checked for validity.
2140 * Performs all commands done before a regular transfer between a local and a
2141 * remote host.
2142 */
2143static CURLcode imap_regular_transfer(struct Curl_easy *data,
2144 struct IMAP *imap,
2145 bool *dophase_done)
2147 CURLcode result = CURLE_OK;
2148 bool connected = FALSE;
2150 /* Make sure size is unknown at this point */
2151 data->req.size = -1;
2153 /* Set the progress data */
2154 Curl_pgrsReset(data);
2156 /* Carry out the perform */
2157 result = imap_perform(data, &connected, dophase_done);
2159 /* Perform post DO phase operations if necessary */
2160 if(!result && *dophase_done)
2161 result = imap_dophase_done(data, imap, connected);
2163 return result;
2166/***********************************************************************
2168 * imap_do()
2170 * This function is registered as 'curl_do' function. It decodes the path
2171 * parts etc as a wrapper to the actual DO function (imap_perform).
2173 * The input argument is already checked for validity.
2174 */
2175static CURLcode imap_do(struct Curl_easy *data, bool *done)
2177 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
2178 CURLcode result = CURLE_OK;
2179 *done = FALSE; /* default to false */
2181 if(!imap)
2182 return CURLE_FAILED_INIT;
2183 /* Parse the URL path */
2184 result = imap_parse_url_path(data, imap);
2185 if(result)
2186 return result;
2188 /* Parse the custom request */
2189 result = imap_parse_custom_request(data, imap);
2190 if(result)
2191 return result;
2193 result = imap_regular_transfer(data, imap, done);
2195 return result;
2198/***********************************************************************
2200 * imap_disconnect()
2202 * Disconnect from an IMAP server. Cleanup protocol-specific per-connection
2203 * resources. BLOCKING.
2204 */
2205static CURLcode imap_disconnect(struct Curl_easy *data,
2206 struct connectdata *conn, bool dead_connection)
2208 struct imap_conn *imapc = Curl_conn_meta_get(conn, CURL_META_IMAP_CONN);
2210 if(imapc &&
2211 /* We cannot send quit unconditionally. If this connection is stale or
2212 bad in any way (pingpong has pending data to send),
2213 sending quit and waiting around here will make the
2214 disconnect wait in vain and cause more problems than we need to. */
2215 !dead_connection && conn->bits.protoconnstart &&
2216 !Curl_pp_needs_flush(data, &imapc->pp) &&
2217 !imap_perform_logout(data, imapc))
2218 (void)imap_block_statemach(data, imapc, TRUE); /* ignore errors */
2220 return CURLE_OK;
2223/* Called from multi.c while DOing */
2224static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done)
2226 struct IMAP *imap = Curl_meta_get(data, CURL_META_IMAP_EASY);
2227 CURLcode result;
2229 if(!imap)
2230 return CURLE_FAILED_INIT;
2232 result = imap_multi_statemach(data, dophase_done);
2233 if(result)
2234 DEBUGF(infof(data, "DO phase failed"));
2235 else if(*dophase_done) {
2236 result = imap_dophase_done(data, imap, FALSE /* not connected */);
2238 DEBUGF(infof(data, "DO phase is complete"));
2241 return result;
2244static void imap_easy_dtor(const void *key, size_t klen, void *entry)
2246 struct IMAP *imap = entry;
2247 (void)key;
2248 (void)klen;
2249 imap_easy_reset(imap);
2250 curlx_free(imap);
2253static void imap_conn_dtor(const void *key, size_t klen, void *entry)
2255 struct imap_conn *imapc = entry;
2256 (void)key;
2257 (void)klen;
2258 Curl_pp_disconnect(&imapc->pp);
2259 curlx_safefree(imapc->mailbox);
2260 curlx_free(imapc);
2263/* SASL parameters for the imap protocol */
2264static const struct SASLproto saslimap = {
2265 "imap", /* The service name */
2266 imap_perform_authenticate, /* Send authentication command */
2267 imap_continue_authenticate, /* Send authentication continuation */
2268 imap_cancel_authenticate, /* Send authentication cancellation */
2269 imap_get_message, /* Get SASL response message */
2270 0, /* No maximum initial response length */
2271 '+', /* Code received when continuation is expected */
2272 IMAP_RESP_OK, /* Code to receive upon authentication success */
2273 SASL_AUTH_DEFAULT, /* Default mechanisms */
2274 SASL_FLAG_BASE64 /* Configuration flags */
2277static CURLcode imap_setup_connection(struct Curl_easy *data,
2278 struct connectdata *conn)
2280 struct imap_conn *imapc;
2281 struct pingpong *pp;
2282 struct IMAP *imap;
2284 imapc = curlx_calloc(1, sizeof(*imapc));
2285 if(!imapc)
2286 return CURLE_OUT_OF_MEMORY;
2288 pp = &imapc->pp;
2289 PINGPONG_SETUP(pp, imap_pp_statemachine, imap_endofresp);
2291 /* Set the default preferred authentication type and mechanism */
2292 imapc->preftype = IMAP_TYPE_ANY;
2293 Curl_sasl_init(&imapc->sasl, data, &saslimap);
2295 Curl_pp_init(pp, Curl_pgrs_now(data));
2297 if(Curl_conn_meta_set(conn, CURL_META_IMAP_CONN, imapc, imap_conn_dtor))
2298 return CURLE_OUT_OF_MEMORY;
2300 imap = curlx_calloc(1, sizeof(struct IMAP));
2301 if(!imap ||
2302 Curl_meta_set(data, CURL_META_IMAP_EASY, imap, imap_easy_dtor))
2303 return CURLE_OUT_OF_MEMORY;
2305 return CURLE_OK;
2309 * IMAP protocol.
2310 */
2311const struct Curl_protocol Curl_protocol_imap = {
2312 imap_setup_connection, /* setup_connection */
2313 ZERO_NULL, /* setup_filters */
2314 imap_do, /* do_it */
2315 imap_done, /* done */
2316 ZERO_NULL, /* do_more */
2317 imap_connect, /* connect_it */
2318 imap_multi_statemach, /* connecting */
2319 imap_doing, /* doing */
2320 imap_pollset, /* proto_pollset */
2321 imap_pollset, /* doing_pollset */
2322 ZERO_NULL, /* domore_pollset */
2323 ZERO_NULL, /* perform_pollset */
2324 imap_disconnect, /* disconnect */
2325 ZERO_NULL, /* write_resp */
2326 ZERO_NULL, /* write_resp_hd */
2327 ZERO_NULL, /* connection_is_dead */
2328 ZERO_NULL, /* attach connection */
2329 ZERO_NULL, /* follow */
2332#endif /* CURL_DISABLE_IMAP */
Diagnostics4 git calls · 187 ms
CallStatusSizeTime0187 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=149
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=149
git.pkt.payload.max=78
git.ls_refs.count=2
git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=179
git.response.bytes=293470
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=10
git.pkt.data=8
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=293470
git.pkt.payload.max=65516
git.sideband.band1.bytes=293354
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=87
git.pack.bytes=293354
git.pack.ofs_delta=0
git.pack.ref_delta=1
git.pack.chain.max=1
git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0
git.pack.full=86
Open pack map
fetch20018 KiB182 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=18564
git.response.cache=MISS
git.response.duration_ms=182
git.fetch.wants=f99023245a429b8f4d96439afc32692faef8a178
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=18564
git.pkt.payload.max=18543
git.sideband.band1.bytes=18542
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
Ref
refs/heads/master
Commit
31c911efe5652725e930f4d2e60c9060e5f6646d
cf-ray
a5e171df9d5a6102
Request
dbaf4b9d…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format