Imported Upstream version 7.48.0
[platform/upstream/curl.git] / lib / pop3.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2016, 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  * RFC1734 POP3 Authentication
22  * RFC1939 POP3 protocol
23  * RFC2195 CRAM-MD5 authentication
24  * RFC2384 POP URL Scheme
25  * RFC2449 POP3 Extension Mechanism
26  * RFC2595 Using TLS with IMAP, POP3 and ACAP
27  * RFC2831 DIGEST-MD5 authentication
28  * RFC4422 Simple Authentication and Security Layer (SASL)
29  * RFC4616 PLAIN authentication
30  * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
31  * RFC5034 POP3 SASL Authentication Mechanism
32  * RFC6749 OAuth 2.0 Authorization Framework
33  * Draft   LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
34  *
35  ***************************************************************************/
36
37 #include "curl_setup.h"
38
39 #ifndef CURL_DISABLE_POP3
40
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
43 #endif
44 #ifdef HAVE_ARPA_INET_H
45 #include <arpa/inet.h>
46 #endif
47 #ifdef HAVE_UTSNAME_H
48 #include <sys/utsname.h>
49 #endif
50 #ifdef HAVE_NETDB_H
51 #include <netdb.h>
52 #endif
53 #ifdef __VMS
54 #include <in.h>
55 #include <inet.h>
56 #endif
57
58 #if (defined(NETWARE) && defined(__NOVELL_LIBC__))
59 #undef in_addr_t
60 #define in_addr_t unsigned long
61 #endif
62
63 #include <curl/curl.h>
64 #include "urldata.h"
65 #include "sendf.h"
66 #include "hostip.h"
67 #include "progress.h"
68 #include "transfer.h"
69 #include "escape.h"
70 #include "http.h" /* for HTTP proxy tunnel stuff */
71 #include "socks.h"
72 #include "pop3.h"
73
74 #include "strtoofft.h"
75 #include "strequal.h"
76 #include "vtls/vtls.h"
77 #include "connect.h"
78 #include "strerror.h"
79 #include "select.h"
80 #include "multiif.h"
81 #include "url.h"
82 #include "rawstr.h"
83 #include "curl_sasl.h"
84 #include "curl_md5.h"
85 #include "warnless.h"
86 #include "curl_printf.h"
87 #include "curl_memory.h"
88 /* The last #include file should be: */
89 #include "memdebug.h"
90
91 /* Local API functions */
92 static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done);
93 static CURLcode pop3_do(struct connectdata *conn, bool *done);
94 static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
95                           bool premature);
96 static CURLcode pop3_connect(struct connectdata *conn, bool *done);
97 static CURLcode pop3_disconnect(struct connectdata *conn, bool dead);
98 static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done);
99 static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks,
100                         int numsocks);
101 static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done);
102 static CURLcode pop3_setup_connection(struct connectdata *conn);
103 static CURLcode pop3_parse_url_options(struct connectdata *conn);
104 static CURLcode pop3_parse_url_path(struct connectdata *conn);
105 static CURLcode pop3_parse_custom_request(struct connectdata *conn);
106 static CURLcode pop3_perform_auth(struct connectdata *conn, const char *mech,
107                                   const char *initresp);
108 static CURLcode pop3_continue_auth(struct connectdata *conn, const char *resp);
109 static void pop3_get_message(char *buffer, char** outptr);
110
111 /*
112  * POP3 protocol handler.
113  */
114
115 const struct Curl_handler Curl_handler_pop3 = {
116   "POP3",                           /* scheme */
117   pop3_setup_connection,            /* setup_connection */
118   pop3_do,                          /* do_it */
119   pop3_done,                        /* done */
120   ZERO_NULL,                        /* do_more */
121   pop3_connect,                     /* connect_it */
122   pop3_multi_statemach,             /* connecting */
123   pop3_doing,                       /* doing */
124   pop3_getsock,                     /* proto_getsock */
125   pop3_getsock,                     /* doing_getsock */
126   ZERO_NULL,                        /* domore_getsock */
127   ZERO_NULL,                        /* perform_getsock */
128   pop3_disconnect,                  /* disconnect */
129   ZERO_NULL,                        /* readwrite */
130   PORT_POP3,                        /* defport */
131   CURLPROTO_POP3,                   /* protocol */
132   PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
133 };
134
135 #ifdef USE_SSL
136 /*
137  * POP3S protocol handler.
138  */
139
140 const struct Curl_handler Curl_handler_pop3s = {
141   "POP3S",                          /* scheme */
142   pop3_setup_connection,            /* setup_connection */
143   pop3_do,                          /* do_it */
144   pop3_done,                        /* done */
145   ZERO_NULL,                        /* do_more */
146   pop3_connect,                     /* connect_it */
147   pop3_multi_statemach,             /* connecting */
148   pop3_doing,                       /* doing */
149   pop3_getsock,                     /* proto_getsock */
150   pop3_getsock,                     /* doing_getsock */
151   ZERO_NULL,                        /* domore_getsock */
152   ZERO_NULL,                        /* perform_getsock */
153   pop3_disconnect,                  /* disconnect */
154   ZERO_NULL,                        /* readwrite */
155   PORT_POP3S,                       /* defport */
156   CURLPROTO_POP3S,                  /* protocol */
157   PROTOPT_CLOSEACTION | PROTOPT_SSL
158   | PROTOPT_NOURLQUERY              /* flags */
159 };
160 #endif
161
162 #ifndef CURL_DISABLE_HTTP
163 /*
164  * HTTP-proxyed POP3 protocol handler.
165  */
166
167 static const struct Curl_handler Curl_handler_pop3_proxy = {
168   "POP3",                               /* scheme */
169   Curl_http_setup_conn,                 /* setup_connection */
170   Curl_http,                            /* do_it */
171   Curl_http_done,                       /* done */
172   ZERO_NULL,                            /* do_more */
173   ZERO_NULL,                            /* connect_it */
174   ZERO_NULL,                            /* connecting */
175   ZERO_NULL,                            /* doing */
176   ZERO_NULL,                            /* proto_getsock */
177   ZERO_NULL,                            /* doing_getsock */
178   ZERO_NULL,                            /* domore_getsock */
179   ZERO_NULL,                            /* perform_getsock */
180   ZERO_NULL,                            /* disconnect */
181   ZERO_NULL,                            /* readwrite */
182   PORT_POP3,                            /* defport */
183   CURLPROTO_HTTP,                       /* protocol */
184   PROTOPT_NONE                          /* flags */
185 };
186
187 #ifdef USE_SSL
188 /*
189  * HTTP-proxyed POP3S protocol handler.
190  */
191
192 static const struct Curl_handler Curl_handler_pop3s_proxy = {
193   "POP3S",                              /* scheme */
194   Curl_http_setup_conn,                 /* setup_connection */
195   Curl_http,                            /* do_it */
196   Curl_http_done,                       /* done */
197   ZERO_NULL,                            /* do_more */
198   ZERO_NULL,                            /* connect_it */
199   ZERO_NULL,                            /* connecting */
200   ZERO_NULL,                            /* doing */
201   ZERO_NULL,                            /* proto_getsock */
202   ZERO_NULL,                            /* doing_getsock */
203   ZERO_NULL,                            /* domore_getsock */
204   ZERO_NULL,                            /* perform_getsock */
205   ZERO_NULL,                            /* disconnect */
206   ZERO_NULL,                            /* readwrite */
207   PORT_POP3S,                           /* defport */
208   CURLPROTO_HTTP,                       /* protocol */
209   PROTOPT_NONE                          /* flags */
210 };
211 #endif
212 #endif
213
214 /* SASL parameters for the pop3 protocol */
215 static const struct SASLproto saslpop3 = {
216   "pop",                      /* The service name */
217   '*',                        /* Code received when continuation is expected */
218   '+',                        /* Code to receive upon authentication success */
219   255 - 8,                    /* Maximum initial response length (no max) */
220   pop3_perform_auth,          /* Send authentication command */
221   pop3_continue_auth,         /* Send authentication continuation */
222   pop3_get_message            /* Get SASL response message */
223 };
224
225 #ifdef USE_SSL
226 static void pop3_to_pop3s(struct connectdata *conn)
227 {
228   /* Change the connection handler */
229   conn->handler = &Curl_handler_pop3s;
230
231   /* Set the connection's upgraded to TLS flag */
232   conn->tls_upgraded = TRUE;
233 }
234 #else
235 #define pop3_to_pop3s(x) Curl_nop_stmt
236 #endif
237
238 /***********************************************************************
239  *
240  * pop3_endofresp()
241  *
242  * Checks for an ending POP3 status code at the start of the given string, but
243  * also detects the APOP timestamp from the server greeting and various
244  * capabilities from the CAPA response including the supported authentication
245  * types and allowed SASL mechanisms.
246  */
247 static bool pop3_endofresp(struct connectdata *conn, char *line, size_t len,
248                            int *resp)
249 {
250   struct pop3_conn *pop3c = &conn->proto.pop3c;
251
252   /* Do we have an error response? */
253   if(len >= 4 && !memcmp("-ERR", line, 4)) {
254     *resp = '-';
255
256     return TRUE;
257   }
258
259   /* Are we processing CAPA command responses? */
260   if(pop3c->state == POP3_CAPA) {
261     /* Do we have the terminating line? */
262     if(len >= 1 && !memcmp(line, ".", 1))
263       /* Treat the response as a success */
264       *resp = '+';
265     else
266       /* Treat the response as an untagged continuation */
267       *resp = '*';
268
269     return TRUE;
270   }
271
272   /* Do we have a success response? */
273   if(len >= 3 && !memcmp("+OK", line, 3)) {
274     *resp = '+';
275
276     return TRUE;
277   }
278
279   /* Do we have a continuation response? */
280   if(len >= 1 && !memcmp("+", line, 1)) {
281     *resp = '*';
282
283     return TRUE;
284   }
285
286   return FALSE; /* Nothing for us */
287 }
288
289 /***********************************************************************
290  *
291  * pop3_get_message()
292  *
293  * Gets the authentication message from the response buffer.
294  */
295 static void pop3_get_message(char *buffer, char** outptr)
296 {
297   size_t len = 0;
298   char* message = NULL;
299
300   /* Find the start of the message */
301   for(message = buffer + 2; *message == ' ' || *message == '\t'; message++)
302     ;
303
304   /* Find the end of the message */
305   for(len = strlen(message); len--;)
306     if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
307         message[len] != '\t')
308       break;
309
310   /* Terminate the message */
311   if(++len) {
312     message[len] = '\0';
313   }
314
315   *outptr = message;
316 }
317
318 /***********************************************************************
319  *
320  * state()
321  *
322  * This is the ONLY way to change POP3 state!
323  */
324 static void state(struct connectdata *conn, pop3state newstate)
325 {
326   struct pop3_conn *pop3c = &conn->proto.pop3c;
327 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
328   /* for debug purposes */
329   static const char * const names[] = {
330     "STOP",
331     "SERVERGREET",
332     "CAPA",
333     "STARTTLS",
334     "UPGRADETLS",
335     "AUTH",
336     "APOP",
337     "USER",
338     "PASS",
339     "COMMAND",
340     "QUIT",
341     /* LAST */
342   };
343
344   if(pop3c->state != newstate)
345     infof(conn->data, "POP3 %p state change from %s to %s\n",
346           (void *)pop3c, names[pop3c->state], names[newstate]);
347 #endif
348
349   pop3c->state = newstate;
350 }
351
352 /***********************************************************************
353  *
354  * pop3_perform_capa()
355  *
356  * Sends the CAPA command in order to obtain a list of server side supported
357  * capabilities.
358  */
359 static CURLcode pop3_perform_capa(struct connectdata *conn)
360 {
361   CURLcode result = CURLE_OK;
362   struct pop3_conn *pop3c = &conn->proto.pop3c;
363
364   pop3c->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
365   pop3c->sasl.authused = SASL_AUTH_NONE;  /* Clear the auth. mechanism used */
366   pop3c->tls_supported = FALSE;           /* Clear the TLS capability */
367
368   /* Send the CAPA command */
369   result = Curl_pp_sendf(&pop3c->pp, "%s", "CAPA");
370
371   if(!result)
372     state(conn, POP3_CAPA);
373
374   return result;
375 }
376
377 /***********************************************************************
378  *
379  * pop3_perform_starttls()
380  *
381  * Sends the STLS command to start the upgrade to TLS.
382  */
383 static CURLcode pop3_perform_starttls(struct connectdata *conn)
384 {
385   CURLcode result = CURLE_OK;
386
387   /* Send the STLS command */
388   result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "STLS");
389
390   if(!result)
391     state(conn, POP3_STARTTLS);
392
393   return result;
394 }
395
396 /***********************************************************************
397  *
398  * pop3_perform_upgrade_tls()
399  *
400  * Performs the upgrade to TLS.
401  */
402 static CURLcode pop3_perform_upgrade_tls(struct connectdata *conn)
403 {
404   CURLcode result = CURLE_OK;
405   struct pop3_conn *pop3c = &conn->proto.pop3c;
406
407   /* Start the SSL connection */
408   result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone);
409
410   if(!result) {
411     if(pop3c->state != POP3_UPGRADETLS)
412       state(conn, POP3_UPGRADETLS);
413
414     if(pop3c->ssldone) {
415       pop3_to_pop3s(conn);
416       result = pop3_perform_capa(conn);
417     }
418   }
419
420   return result;
421 }
422
423 /***********************************************************************
424  *
425  * pop3_perform_user()
426  *
427  * Sends a clear text USER command to authenticate with.
428  */
429 static CURLcode pop3_perform_user(struct connectdata *conn)
430 {
431   CURLcode result = CURLE_OK;
432
433   /* Check we have a username and password to authenticate with and end the
434      connect phase if we don't */
435   if(!conn->bits.user_passwd) {
436     state(conn, POP3_STOP);
437
438     return result;
439   }
440
441   /* Send the USER command */
442   result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s",
443                          conn->user ? conn->user : "");
444   if(!result)
445     state(conn, POP3_USER);
446
447   return result;
448 }
449
450 #ifndef CURL_DISABLE_CRYPTO_AUTH
451 /***********************************************************************
452  *
453  * pop3_perform_apop()
454  *
455  * Sends an APOP command to authenticate with.
456  */
457 static CURLcode pop3_perform_apop(struct connectdata *conn)
458 {
459   CURLcode result = CURLE_OK;
460   struct pop3_conn *pop3c = &conn->proto.pop3c;
461   size_t i;
462   MD5_context *ctxt;
463   unsigned char digest[MD5_DIGEST_LEN];
464   char secret[2 * MD5_DIGEST_LEN + 1];
465
466   /* Check we have a username and password to authenticate with and end the
467      connect phase if we don't */
468   if(!conn->bits.user_passwd) {
469     state(conn, POP3_STOP);
470
471     return result;
472   }
473
474   /* Create the digest */
475   ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
476   if(!ctxt)
477     return CURLE_OUT_OF_MEMORY;
478
479   Curl_MD5_update(ctxt, (const unsigned char *) pop3c->apoptimestamp,
480                   curlx_uztoui(strlen(pop3c->apoptimestamp)));
481
482   Curl_MD5_update(ctxt, (const unsigned char *) conn->passwd,
483                   curlx_uztoui(strlen(conn->passwd)));
484
485   /* Finalise the digest */
486   Curl_MD5_final(ctxt, digest);
487
488   /* Convert the calculated 16 octet digest into a 32 byte hex string */
489   for(i = 0; i < MD5_DIGEST_LEN; i++)
490     snprintf(&secret[2 * i], 3, "%02x", digest[i]);
491
492   result = Curl_pp_sendf(&pop3c->pp, "APOP %s %s", conn->user, secret);
493
494   if(!result)
495     state(conn, POP3_APOP);
496
497   return result;
498 }
499 #endif
500
501 /***********************************************************************
502  *
503  * pop3_perform_auth()
504  *
505  * Sends an AUTH command allowing the client to login with the given SASL
506  * authentication mechanism.
507  */
508 static CURLcode pop3_perform_auth(struct connectdata *conn,
509                                   const char *mech,
510                                   const char *initresp)
511 {
512   CURLcode result = CURLE_OK;
513   struct pop3_conn *pop3c = &conn->proto.pop3c;
514
515   if(initresp) {                                  /* AUTH <mech> ...<crlf> */
516     /* Send the AUTH command with the initial response */
517     result = Curl_pp_sendf(&pop3c->pp, "AUTH %s %s", mech, initresp);
518   }
519   else {
520     /* Send the AUTH command */
521     result = Curl_pp_sendf(&pop3c->pp, "AUTH %s", mech);
522   }
523
524   return result;
525 }
526
527 /***********************************************************************
528  *
529  * pop3_continue_auth()
530  *
531  * Sends SASL continuation data or cancellation.
532  */
533 static CURLcode pop3_continue_auth(struct connectdata *conn,
534                                    const char *resp)
535 {
536   struct pop3_conn *pop3c = &conn->proto.pop3c;
537
538   return Curl_pp_sendf(&pop3c->pp, "%s", resp);
539 }
540
541 /***********************************************************************
542  *
543  * pop3_perform_authentication()
544  *
545  * Initiates the authentication sequence, with the appropriate SASL
546  * authentication mechanism, falling back to APOP and clear text should a
547  * common mechanism not be available between the client and server.
548  */
549 static CURLcode pop3_perform_authentication(struct connectdata *conn)
550 {
551   CURLcode result = CURLE_OK;
552   struct pop3_conn *pop3c = &conn->proto.pop3c;
553   saslprogress progress = SASL_IDLE;
554
555   /* Check we have enough data to authenticate with and end the
556      connect phase if we don't */
557   if(!Curl_sasl_can_authenticate(&pop3c->sasl, conn)) {
558     state(conn, POP3_STOP);
559     return result;
560   }
561
562   if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_SASL) {
563     /* Calculate the SASL login details */
564     result = Curl_sasl_start(&pop3c->sasl, conn, FALSE, &progress);
565
566     if(!result)
567       if(progress == SASL_INPROGRESS)
568         state(conn, POP3_AUTH);
569   }
570
571   if(!result && progress == SASL_IDLE) {
572 #ifndef CURL_DISABLE_CRYPTO_AUTH
573     if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP)
574       /* Perform APOP authentication */
575       result = pop3_perform_apop(conn);
576     else
577 #endif
578     if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT)
579       /* Perform clear text authentication */
580       result = pop3_perform_user(conn);
581     else {
582       /* Other mechanisms not supported */
583       infof(conn->data, "No known authentication mechanisms supported!\n");
584       result = CURLE_LOGIN_DENIED;
585     }
586   }
587
588   return result;
589 }
590
591 /***********************************************************************
592  *
593  * pop3_perform_command()
594  *
595  * Sends a POP3 based command.
596  */
597 static CURLcode pop3_perform_command(struct connectdata *conn)
598 {
599   CURLcode result = CURLE_OK;
600   struct SessionHandle *data = conn->data;
601   struct POP3 *pop3 = data->req.protop;
602   const char *command = NULL;
603
604   /* Calculate the default command */
605   if(pop3->id[0] == '\0' || conn->data->set.ftp_list_only) {
606     command = "LIST";
607
608     if(pop3->id[0] != '\0')
609       /* Message specific LIST so skip the BODY transfer */
610       pop3->transfer = FTPTRANSFER_INFO;
611   }
612   else
613     command = "RETR";
614
615   /* Send the command */
616   if(pop3->id[0] != '\0')
617     result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s %s",
618                            (pop3->custom && pop3->custom[0] != '\0' ?
619                             pop3->custom : command), pop3->id);
620   else
621     result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s",
622                            (pop3->custom && pop3->custom[0] != '\0' ?
623                             pop3->custom : command));
624
625   if(!result)
626     state(conn, POP3_COMMAND);
627
628   return result;
629 }
630
631 /***********************************************************************
632  *
633  * pop3_perform_quit()
634  *
635  * Performs the quit action prior to sclose() be called.
636  */
637 static CURLcode pop3_perform_quit(struct connectdata *conn)
638 {
639   CURLcode result = CURLE_OK;
640
641   /* Send the QUIT command */
642   result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "QUIT");
643
644   if(!result)
645     state(conn, POP3_QUIT);
646
647   return result;
648 }
649
650 /* For the initial server greeting */
651 static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
652                                             int pop3code,
653                                             pop3state instate)
654 {
655   CURLcode result = CURLE_OK;
656   struct SessionHandle *data = conn->data;
657   struct pop3_conn *pop3c = &conn->proto.pop3c;
658   const char *line = data->state.buffer;
659   size_t len = strlen(line);
660   size_t i;
661
662   (void)instate; /* no use for this yet */
663
664   if(pop3code != '+') {
665     failf(data, "Got unexpected pop3-server response");
666     result = CURLE_FTP_WEIRD_SERVER_REPLY;
667   }
668   else {
669     /* Does the server support APOP authentication? */
670     if(len >= 4 && line[len - 2] == '>') {
671       /* Look for the APOP timestamp */
672       for(i = 3; i < len - 2; ++i) {
673         if(line[i] == '<') {
674           /* Calculate the length of the timestamp */
675           size_t timestamplen = len - 1 - i;
676           if(!timestamplen)
677             break;
678
679           /* Allocate some memory for the timestamp */
680           pop3c->apoptimestamp = (char *)calloc(1, timestamplen + 1);
681
682           if(!pop3c->apoptimestamp)
683             break;
684
685           /* Copy the timestamp */
686           memcpy(pop3c->apoptimestamp, line + i, timestamplen);
687           pop3c->apoptimestamp[timestamplen] = '\0';
688
689           /* Store the APOP capability */
690           pop3c->authtypes |= POP3_TYPE_APOP;
691           break;
692         }
693       }
694     }
695
696     result = pop3_perform_capa(conn);
697   }
698
699   return result;
700 }
701
702 /* For CAPA responses */
703 static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code,
704                                      pop3state instate)
705 {
706   CURLcode result = CURLE_OK;
707   struct SessionHandle *data = conn->data;
708   struct pop3_conn *pop3c = &conn->proto.pop3c;
709   const char *line = data->state.buffer;
710   size_t len = strlen(line);
711   size_t wordlen;
712
713   (void)instate; /* no use for this yet */
714
715   /* Do we have a untagged continuation response? */
716   if(pop3code == '*') {
717     /* Does the server support the STLS capability? */
718     if(len >= 4 && !memcmp(line, "STLS", 4))
719       pop3c->tls_supported = TRUE;
720
721     /* Does the server support clear text authentication? */
722     else if(len >= 4 && !memcmp(line, "USER", 4))
723       pop3c->authtypes |= POP3_TYPE_CLEARTEXT;
724
725     /* Does the server support SASL based authentication? */
726     else if(len >= 5 && !memcmp(line, "SASL ", 5)) {
727       pop3c->authtypes |= POP3_TYPE_SASL;
728
729       /* Advance past the SASL keyword */
730       line += 5;
731       len -= 5;
732
733       /* Loop through the data line */
734       for(;;) {
735         size_t llen;
736         unsigned int mechbit;
737
738         while(len &&
739               (*line == ' ' || *line == '\t' ||
740                *line == '\r' || *line == '\n')) {
741
742           line++;
743           len--;
744         }
745
746         if(!len)
747           break;
748
749         /* Extract the word */
750         for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
751               line[wordlen] != '\t' && line[wordlen] != '\r' &&
752               line[wordlen] != '\n';)
753           wordlen++;
754
755         /* Test the word for a matching authentication mechanism */
756         mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
757         if(mechbit && llen == wordlen)
758           pop3c->sasl.authmechs |= mechbit;
759
760         line += wordlen;
761         len -= wordlen;
762       }
763     }
764   }
765   else if(pop3code == '+') {
766     if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
767       /* We don't have a SSL/TLS connection yet, but SSL is requested */
768       if(pop3c->tls_supported)
769         /* Switch to TLS connection now */
770         result = pop3_perform_starttls(conn);
771       else if(data->set.use_ssl == CURLUSESSL_TRY)
772         /* Fallback and carry on with authentication */
773         result = pop3_perform_authentication(conn);
774       else {
775         failf(data, "STLS not supported.");
776         result = CURLE_USE_SSL_FAILED;
777       }
778     }
779     else
780       result = pop3_perform_authentication(conn);
781   }
782   else {
783     /* Clear text is supported when CAPA isn't recognised */
784     pop3c->authtypes |= POP3_TYPE_CLEARTEXT;
785
786     result = pop3_perform_authentication(conn);
787   }
788
789   return result;
790 }
791
792 /* For STARTTLS responses */
793 static CURLcode pop3_state_starttls_resp(struct connectdata *conn,
794                                          int pop3code,
795                                          pop3state instate)
796 {
797   CURLcode result = CURLE_OK;
798   struct SessionHandle *data = conn->data;
799
800   (void)instate; /* no use for this yet */
801
802   if(pop3code != '+') {
803     if(data->set.use_ssl != CURLUSESSL_TRY) {
804       failf(data, "STARTTLS denied. %c", pop3code);
805       result = CURLE_USE_SSL_FAILED;
806     }
807     else
808       result = pop3_perform_authentication(conn);
809   }
810   else
811     result = pop3_perform_upgrade_tls(conn);
812
813   return result;
814 }
815
816 /* For SASL authentication responses */
817 static CURLcode pop3_state_auth_resp(struct connectdata *conn,
818                                      int pop3code,
819                                      pop3state instate)
820 {
821   CURLcode result = CURLE_OK;
822   struct SessionHandle *data = conn->data;
823   struct pop3_conn *pop3c = &conn->proto.pop3c;
824   saslprogress progress;
825
826   (void)instate; /* no use for this yet */
827
828   result = Curl_sasl_continue(&pop3c->sasl, conn, pop3code, &progress);
829   if(!result)
830     switch(progress) {
831     case SASL_DONE:
832       state(conn, POP3_STOP);  /* Authenticated */
833       break;
834     case SASL_IDLE:            /* No mechanism left after cancellation */
835 #ifndef CURL_DISABLE_CRYPTO_AUTH
836       if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP)
837         /* Perform APOP authentication */
838         result = pop3_perform_apop(conn);
839       else
840 #endif
841       if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT)
842         /* Perform clear text authentication */
843         result = pop3_perform_user(conn);
844       else {
845         failf(data, "Authentication cancelled");
846         result = CURLE_LOGIN_DENIED;
847       }
848       break;
849     default:
850       break;
851     }
852
853   return result;
854 }
855
856 #ifndef CURL_DISABLE_CRYPTO_AUTH
857 /* For APOP responses */
858 static CURLcode pop3_state_apop_resp(struct connectdata *conn, int pop3code,
859                                      pop3state instate)
860 {
861   CURLcode result = CURLE_OK;
862   struct SessionHandle *data = conn->data;
863
864   (void)instate; /* no use for this yet */
865
866   if(pop3code != '+') {
867     failf(data, "Authentication failed: %d", pop3code);
868     result = CURLE_LOGIN_DENIED;
869   }
870   else
871     /* End of connect phase */
872     state(conn, POP3_STOP);
873
874   return result;
875 }
876 #endif
877
878 /* For USER responses */
879 static CURLcode pop3_state_user_resp(struct connectdata *conn, int pop3code,
880                                      pop3state instate)
881 {
882   CURLcode result = CURLE_OK;
883   struct SessionHandle *data = conn->data;
884
885   (void)instate; /* no use for this yet */
886
887   if(pop3code != '+') {
888     failf(data, "Access denied. %c", pop3code);
889     result = CURLE_LOGIN_DENIED;
890   }
891   else
892     /* Send the PASS command */
893     result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s",
894                            conn->passwd ? conn->passwd : "");
895   if(!result)
896     state(conn, POP3_PASS);
897
898   return result;
899 }
900
901 /* For PASS responses */
902 static CURLcode pop3_state_pass_resp(struct connectdata *conn, int pop3code,
903                                      pop3state instate)
904 {
905   CURLcode result = CURLE_OK;
906   struct SessionHandle *data = conn->data;
907
908   (void)instate; /* no use for this yet */
909
910   if(pop3code != '+') {
911     failf(data, "Access denied. %c", pop3code);
912     result = CURLE_LOGIN_DENIED;
913   }
914   else
915     /* End of connect phase */
916     state(conn, POP3_STOP);
917
918   return result;
919 }
920
921 /* For command responses */
922 static CURLcode pop3_state_command_resp(struct connectdata *conn,
923                                         int pop3code,
924                                         pop3state instate)
925 {
926   CURLcode result = CURLE_OK;
927   struct SessionHandle *data = conn->data;
928   struct POP3 *pop3 = data->req.protop;
929   struct pop3_conn *pop3c = &conn->proto.pop3c;
930   struct pingpong *pp = &pop3c->pp;
931
932   (void)instate; /* no use for this yet */
933
934   if(pop3code != '+') {
935     state(conn, POP3_STOP);
936     return CURLE_RECV_ERROR;
937   }
938
939   /* This 'OK' line ends with a CR LF pair which is the two first bytes of the
940      EOB string so count this is two matching bytes. This is necessary to make
941      the code detect the EOB if the only data than comes now is %2e CR LF like
942      when there is no body to return. */
943   pop3c->eob = 2;
944
945   /* But since this initial CR LF pair is not part of the actual body, we set
946      the strip counter here so that these bytes won't be delivered. */
947   pop3c->strip = 2;
948
949   if(pop3->transfer == FTPTRANSFER_BODY) {
950     /* POP3 download */
951     Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE, NULL, -1, NULL);
952
953     if(pp->cache) {
954       /* The header "cache" contains a bunch of data that is actually body
955          content so send it as such. Note that there may even be additional
956          "headers" after the body */
957
958       if(!data->set.opt_no_body) {
959         result = Curl_pop3_write(conn, pp->cache, pp->cache_size);
960         if(result)
961           return result;
962       }
963
964       /* Free the cache */
965       Curl_safefree(pp->cache);
966
967       /* Reset the cache size */
968       pp->cache_size = 0;
969     }
970   }
971
972   /* End of DO phase */
973   state(conn, POP3_STOP);
974
975   return result;
976 }
977
978 static CURLcode pop3_statemach_act(struct connectdata *conn)
979 {
980   CURLcode result = CURLE_OK;
981   curl_socket_t sock = conn->sock[FIRSTSOCKET];
982   int pop3code;
983   struct pop3_conn *pop3c = &conn->proto.pop3c;
984   struct pingpong *pp = &pop3c->pp;
985   size_t nread = 0;
986
987   /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */
988   if(pop3c->state == POP3_UPGRADETLS)
989     return pop3_perform_upgrade_tls(conn);
990
991   /* Flush any data that needs to be sent */
992   if(pp->sendleft)
993     return Curl_pp_flushsend(pp);
994
995  do {
996     /* Read the response from the server */
997     result = Curl_pp_readresp(sock, pp, &pop3code, &nread);
998     if(result)
999       return result;
1000
1001     if(!pop3code)
1002       break;
1003
1004     /* We have now received a full POP3 server response */
1005     switch(pop3c->state) {
1006     case POP3_SERVERGREET:
1007       result = pop3_state_servergreet_resp(conn, pop3code, pop3c->state);
1008       break;
1009
1010     case POP3_CAPA:
1011       result = pop3_state_capa_resp(conn, pop3code, pop3c->state);
1012       break;
1013
1014     case POP3_STARTTLS:
1015       result = pop3_state_starttls_resp(conn, pop3code, pop3c->state);
1016       break;
1017
1018     case POP3_AUTH:
1019       result = pop3_state_auth_resp(conn, pop3code, pop3c->state);
1020       break;
1021
1022 #ifndef CURL_DISABLE_CRYPTO_AUTH
1023     case POP3_APOP:
1024       result = pop3_state_apop_resp(conn, pop3code, pop3c->state);
1025       break;
1026 #endif
1027
1028     case POP3_USER:
1029       result = pop3_state_user_resp(conn, pop3code, pop3c->state);
1030       break;
1031
1032     case POP3_PASS:
1033       result = pop3_state_pass_resp(conn, pop3code, pop3c->state);
1034       break;
1035
1036     case POP3_COMMAND:
1037       result = pop3_state_command_resp(conn, pop3code, pop3c->state);
1038       break;
1039
1040     case POP3_QUIT:
1041       /* fallthrough, just stop! */
1042     default:
1043       /* internal error */
1044       state(conn, POP3_STOP);
1045       break;
1046     }
1047   } while(!result && pop3c->state != POP3_STOP && Curl_pp_moredata(pp));
1048
1049   return result;
1050 }
1051
1052 /* Called repeatedly until done from multi.c */
1053 static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done)
1054 {
1055   CURLcode result = CURLE_OK;
1056   struct pop3_conn *pop3c = &conn->proto.pop3c;
1057
1058   if((conn->handler->flags & PROTOPT_SSL) && !pop3c->ssldone) {
1059     result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone);
1060     if(result || !pop3c->ssldone)
1061       return result;
1062   }
1063
1064   result = Curl_pp_statemach(&pop3c->pp, FALSE);
1065   *done = (pop3c->state == POP3_STOP) ? TRUE : FALSE;
1066
1067   return result;
1068 }
1069
1070 static CURLcode pop3_block_statemach(struct connectdata *conn)
1071 {
1072   CURLcode result = CURLE_OK;
1073   struct pop3_conn *pop3c = &conn->proto.pop3c;
1074
1075   while(pop3c->state != POP3_STOP && !result)
1076     result = Curl_pp_statemach(&pop3c->pp, TRUE);
1077
1078   return result;
1079 }
1080
1081 /* Allocate and initialize the POP3 struct for the current SessionHandle if
1082    required */
1083 static CURLcode pop3_init(struct connectdata *conn)
1084 {
1085   CURLcode result = CURLE_OK;
1086   struct SessionHandle *data = conn->data;
1087   struct POP3 *pop3;
1088
1089   pop3 = data->req.protop = calloc(sizeof(struct POP3), 1);
1090   if(!pop3)
1091     result = CURLE_OUT_OF_MEMORY;
1092
1093   return result;
1094 }
1095
1096 /* For the POP3 "protocol connect" and "doing" phases only */
1097 static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks,
1098                         int numsocks)
1099 {
1100   return Curl_pp_getsock(&conn->proto.pop3c.pp, socks, numsocks);
1101 }
1102
1103 /***********************************************************************
1104  *
1105  * pop3_connect()
1106  *
1107  * This function should do everything that is to be considered a part of the
1108  * connection phase.
1109  *
1110  * The variable 'done' points to will be TRUE if the protocol-layer connect
1111  * phase is done when this function returns, or FALSE if not.
1112  */
1113 static CURLcode pop3_connect(struct connectdata *conn, bool *done)
1114 {
1115   CURLcode result = CURLE_OK;
1116   struct pop3_conn *pop3c = &conn->proto.pop3c;
1117   struct pingpong *pp = &pop3c->pp;
1118
1119   *done = FALSE; /* default to not done yet */
1120
1121   /* We always support persistent connections in POP3 */
1122   connkeep(conn, "POP3 default");
1123
1124   /* Set the default response time-out */
1125   pp->response_time = RESP_TIMEOUT;
1126   pp->statemach_act = pop3_statemach_act;
1127   pp->endofresp = pop3_endofresp;
1128   pp->conn = conn;
1129
1130   /* Set the default preferred authentication type and mechanism */
1131   pop3c->preftype = POP3_TYPE_ANY;
1132   Curl_sasl_init(&pop3c->sasl, &saslpop3);
1133
1134   /* Initialise the pingpong layer */
1135   Curl_pp_init(pp);
1136
1137   /* Parse the URL options */
1138   result = pop3_parse_url_options(conn);
1139   if(result)
1140     return result;
1141
1142   /* Start off waiting for the server greeting response */
1143   state(conn, POP3_SERVERGREET);
1144
1145   result = pop3_multi_statemach(conn, done);
1146
1147   return result;
1148 }
1149
1150 /***********************************************************************
1151  *
1152  * pop3_done()
1153  *
1154  * The DONE function. This does what needs to be done after a single DO has
1155  * performed.
1156  *
1157  * Input argument is already checked for validity.
1158  */
1159 static CURLcode pop3_done(struct connectdata *conn, CURLcode status,
1160                           bool premature)
1161 {
1162   CURLcode result = CURLE_OK;
1163   struct SessionHandle *data = conn->data;
1164   struct POP3 *pop3 = data->req.protop;
1165
1166   (void)premature;
1167
1168   if(!pop3)
1169     /* When the easy handle is removed from the multi interface while libcurl
1170        is still trying to resolve the host name, the POP3 struct is not yet
1171        initialized. However, the removal action calls Curl_done() which in
1172        turn calls this function, so we simply return success. */
1173     return CURLE_OK;
1174
1175   if(status) {
1176     connclose(conn, "POP3 done with bad status");
1177     result = status;         /* use the already set error code */
1178   }
1179
1180   /* Cleanup our per-request based variables */
1181   Curl_safefree(pop3->id);
1182   Curl_safefree(pop3->custom);
1183
1184   /* Clear the transfer mode for the next request */
1185   pop3->transfer = FTPTRANSFER_BODY;
1186
1187   return result;
1188 }
1189
1190 /***********************************************************************
1191  *
1192  * pop3_perform()
1193  *
1194  * This is the actual DO function for POP3. Get a message/listing according to
1195  * the options previously setup.
1196  */
1197 static CURLcode pop3_perform(struct connectdata *conn, bool *connected,
1198                              bool *dophase_done)
1199 {
1200   /* This is POP3 and no proxy */
1201   CURLcode result = CURLE_OK;
1202   struct POP3 *pop3 = conn->data->req.protop;
1203
1204   DEBUGF(infof(conn->data, "DO phase starts\n"));
1205
1206   if(conn->data->set.opt_no_body) {
1207     /* Requested no body means no transfer */
1208     pop3->transfer = FTPTRANSFER_INFO;
1209   }
1210
1211   *dophase_done = FALSE; /* not done yet */
1212
1213   /* Start the first command in the DO phase */
1214   result = pop3_perform_command(conn);
1215   if(result)
1216     return result;
1217
1218   /* Run the state-machine */
1219   result = pop3_multi_statemach(conn, dophase_done);
1220
1221   *connected = conn->bits.tcpconnect[FIRSTSOCKET];
1222
1223   if(*dophase_done)
1224     DEBUGF(infof(conn->data, "DO phase is complete\n"));
1225
1226   return result;
1227 }
1228
1229 /***********************************************************************
1230  *
1231  * pop3_do()
1232  *
1233  * This function is registered as 'curl_do' function. It decodes the path
1234  * parts etc as a wrapper to the actual DO function (pop3_perform).
1235  *
1236  * The input argument is already checked for validity.
1237  */
1238 static CURLcode pop3_do(struct connectdata *conn, bool *done)
1239 {
1240   CURLcode result = CURLE_OK;
1241
1242   *done = FALSE; /* default to false */
1243
1244   /* Parse the URL path */
1245   result = pop3_parse_url_path(conn);
1246   if(result)
1247     return result;
1248
1249   /* Parse the custom request */
1250   result = pop3_parse_custom_request(conn);
1251   if(result)
1252     return result;
1253
1254   result = pop3_regular_transfer(conn, done);
1255
1256   return result;
1257 }
1258
1259 /***********************************************************************
1260  *
1261  * pop3_disconnect()
1262  *
1263  * Disconnect from an POP3 server. Cleanup protocol-specific per-connection
1264  * resources. BLOCKING.
1265  */
1266 static CURLcode pop3_disconnect(struct connectdata *conn, bool dead_connection)
1267 {
1268   struct pop3_conn *pop3c = &conn->proto.pop3c;
1269
1270   /* We cannot send quit unconditionally. If this connection is stale or
1271      bad in any way, sending quit and waiting around here will make the
1272      disconnect wait in vain and cause more problems than we need to. */
1273
1274   /* The POP3 session may or may not have been allocated/setup at this
1275      point! */
1276   if(!dead_connection && pop3c->pp.conn && pop3c->pp.conn->bits.protoconnstart)
1277     if(!pop3_perform_quit(conn))
1278       (void)pop3_block_statemach(conn); /* ignore errors on QUIT */
1279
1280   /* Disconnect from the server */
1281   Curl_pp_disconnect(&pop3c->pp);
1282
1283   /* Cleanup the SASL module */
1284   Curl_sasl_cleanup(conn, pop3c->sasl.authused);
1285
1286   /* Cleanup our connection based variables */
1287   Curl_safefree(pop3c->apoptimestamp);
1288
1289   return CURLE_OK;
1290 }
1291
1292 /* Call this when the DO phase has completed */
1293 static CURLcode pop3_dophase_done(struct connectdata *conn, bool connected)
1294 {
1295   (void)conn;
1296   (void)connected;
1297
1298   return CURLE_OK;
1299 }
1300
1301 /* Called from multi.c while DOing */
1302 static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done)
1303 {
1304   CURLcode result = pop3_multi_statemach(conn, dophase_done);
1305
1306   if(result)
1307     DEBUGF(infof(conn->data, "DO phase failed\n"));
1308   else if(*dophase_done) {
1309     result = pop3_dophase_done(conn, FALSE /* not connected */);
1310
1311     DEBUGF(infof(conn->data, "DO phase is complete\n"));
1312   }
1313
1314   return result;
1315 }
1316
1317 /***********************************************************************
1318  *
1319  * pop3_regular_transfer()
1320  *
1321  * The input argument is already checked for validity.
1322  *
1323  * Performs all commands done before a regular transfer between a local and a
1324  * remote host.
1325  */
1326 static CURLcode pop3_regular_transfer(struct connectdata *conn,
1327                                       bool *dophase_done)
1328 {
1329   CURLcode result = CURLE_OK;
1330   bool connected = FALSE;
1331   struct SessionHandle *data = conn->data;
1332
1333   /* Make sure size is unknown at this point */
1334   data->req.size = -1;
1335
1336   /* Set the progress data */
1337   Curl_pgrsSetUploadCounter(data, 0);
1338   Curl_pgrsSetDownloadCounter(data, 0);
1339   Curl_pgrsSetUploadSize(data, -1);
1340   Curl_pgrsSetDownloadSize(data, -1);
1341
1342   /* Carry out the perform */
1343   result = pop3_perform(conn, &connected, dophase_done);
1344
1345   /* Perform post DO phase operations if necessary */
1346   if(!result && *dophase_done)
1347     result = pop3_dophase_done(conn, connected);
1348
1349   return result;
1350 }
1351
1352 static CURLcode pop3_setup_connection(struct connectdata *conn)
1353 {
1354   struct SessionHandle *data = conn->data;
1355
1356   /* Initialise the POP3 layer */
1357   CURLcode result = pop3_init(conn);
1358   if(result)
1359     return result;
1360
1361   /* Clear the TLS upgraded flag */
1362   conn->tls_upgraded = FALSE;
1363
1364   /* Set up the proxy if necessary */
1365   if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
1366     /* Unless we have asked to tunnel POP3 operations through the proxy, we
1367        switch and use HTTP operations only */
1368 #ifndef CURL_DISABLE_HTTP
1369     if(conn->handler == &Curl_handler_pop3)
1370       conn->handler = &Curl_handler_pop3_proxy;
1371     else {
1372 #ifdef USE_SSL
1373       conn->handler = &Curl_handler_pop3s_proxy;
1374 #else
1375       failf(data, "POP3S not supported!");
1376       return CURLE_UNSUPPORTED_PROTOCOL;
1377 #endif
1378     }
1379
1380     /* set it up as an HTTP connection instead */
1381     return conn->handler->setup_connection(conn);
1382 #else
1383     failf(data, "POP3 over http proxy requires HTTP support built-in!");
1384     return CURLE_UNSUPPORTED_PROTOCOL;
1385 #endif
1386   }
1387
1388   data->state.path++;   /* don't include the initial slash */
1389
1390   return CURLE_OK;
1391 }
1392
1393 /***********************************************************************
1394  *
1395  * pop3_parse_url_options()
1396  *
1397  * Parse the URL login options.
1398  */
1399 static CURLcode pop3_parse_url_options(struct connectdata *conn)
1400 {
1401   CURLcode result = CURLE_OK;
1402   struct pop3_conn *pop3c = &conn->proto.pop3c;
1403   const char *ptr = conn->options;
1404
1405   pop3c->sasl.resetprefs = TRUE;
1406
1407   while(!result && ptr && *ptr) {
1408     const char *key = ptr;
1409     const char *value;
1410
1411     while(*ptr && *ptr != '=')
1412         ptr++;
1413
1414     value = ptr + 1;
1415
1416     while(*ptr && *ptr != ';')
1417       ptr++;
1418
1419     if(strnequal(key, "AUTH=", 5)) {
1420       result = Curl_sasl_parse_url_auth_option(&pop3c->sasl,
1421                                                value, ptr - value);
1422
1423       if(result && strnequal(value, "+APOP", ptr - value)) {
1424         pop3c->preftype = POP3_TYPE_APOP;
1425         pop3c->sasl.prefmech = SASL_AUTH_NONE;
1426         result = CURLE_OK;
1427       }
1428     }
1429     else
1430       result = CURLE_URL_MALFORMAT;
1431
1432     if(*ptr == ';')
1433       ptr++;
1434   }
1435
1436   if(pop3c->preftype != POP3_TYPE_APOP)
1437     switch(pop3c->sasl.prefmech) {
1438     case SASL_AUTH_NONE:
1439       pop3c->preftype = POP3_TYPE_NONE;
1440       break;
1441     case SASL_AUTH_DEFAULT:
1442       pop3c->preftype = POP3_TYPE_ANY;
1443       break;
1444     default:
1445       pop3c->preftype = POP3_TYPE_SASL;
1446       break;
1447     }
1448
1449   return result;
1450 }
1451
1452 /***********************************************************************
1453  *
1454  * pop3_parse_url_path()
1455  *
1456  * Parse the URL path into separate path components.
1457  */
1458 static CURLcode pop3_parse_url_path(struct connectdata *conn)
1459 {
1460   /* The POP3 struct is already initialised in pop3_connect() */
1461   struct SessionHandle *data = conn->data;
1462   struct POP3 *pop3 = data->req.protop;
1463   const char *path = data->state.path;
1464
1465   /* URL decode the path for the message ID */
1466   return Curl_urldecode(data, path, 0, &pop3->id, NULL, TRUE);
1467 }
1468
1469 /***********************************************************************
1470  *
1471  * pop3_parse_custom_request()
1472  *
1473  * Parse the custom request.
1474  */
1475 static CURLcode pop3_parse_custom_request(struct connectdata *conn)
1476 {
1477   CURLcode result = CURLE_OK;
1478   struct SessionHandle *data = conn->data;
1479   struct POP3 *pop3 = data->req.protop;
1480   const char *custom = data->set.str[STRING_CUSTOMREQUEST];
1481
1482   /* URL decode the custom request */
1483   if(custom)
1484     result = Curl_urldecode(data, custom, 0, &pop3->custom, NULL, TRUE);
1485
1486   return result;
1487 }
1488
1489 /***********************************************************************
1490  *
1491  * Curl_pop3_write()
1492  *
1493  * This function scans the body after the end-of-body and writes everything
1494  * until the end is found.
1495  */
1496 CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread)
1497 {
1498   /* This code could be made into a special function in the handler struct */
1499   CURLcode result = CURLE_OK;
1500   struct SessionHandle *data = conn->data;
1501   struct SingleRequest *k = &data->req;
1502
1503   struct pop3_conn *pop3c = &conn->proto.pop3c;
1504   bool strip_dot = FALSE;
1505   size_t last = 0;
1506   size_t i;
1507
1508   /* Search through the buffer looking for the end-of-body marker which is
1509      5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches
1510      the eob so the server will have prefixed it with an extra dot which we
1511      need to strip out. Additionally the marker could of course be spread out
1512      over 5 different data chunks. */
1513   for(i = 0; i < nread; i++) {
1514     size_t prev = pop3c->eob;
1515
1516     switch(str[i]) {
1517     case 0x0d:
1518       if(pop3c->eob == 0) {
1519         pop3c->eob++;
1520
1521         if(i) {
1522           /* Write out the body part that didn't match */
1523           result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
1524                                      i - last);
1525
1526           if(result)
1527             return result;
1528
1529           last = i;
1530         }
1531       }
1532       else if(pop3c->eob == 3)
1533         pop3c->eob++;
1534       else
1535         /* If the character match wasn't at position 0 or 3 then restart the
1536            pattern matching */
1537         pop3c->eob = 1;
1538       break;
1539
1540     case 0x0a:
1541       if(pop3c->eob == 1 || pop3c->eob == 4)
1542         pop3c->eob++;
1543       else
1544         /* If the character match wasn't at position 1 or 4 then start the
1545            search again */
1546         pop3c->eob = 0;
1547       break;
1548
1549     case 0x2e:
1550       if(pop3c->eob == 2)
1551         pop3c->eob++;
1552       else if(pop3c->eob == 3) {
1553         /* We have an extra dot after the CRLF which we need to strip off */
1554         strip_dot = TRUE;
1555         pop3c->eob = 0;
1556       }
1557       else
1558         /* If the character match wasn't at position 2 then start the search
1559            again */
1560         pop3c->eob = 0;
1561       break;
1562
1563     default:
1564       pop3c->eob = 0;
1565       break;
1566     }
1567
1568     /* Did we have a partial match which has subsequently failed? */
1569     if(prev && prev >= pop3c->eob) {
1570       /* Strip can only be non-zero for the very first mismatch after CRLF
1571          and then both prev and strip are equal and nothing will be output
1572          below */
1573       while(prev && pop3c->strip) {
1574         prev--;
1575         pop3c->strip--;
1576       }
1577
1578       if(prev) {
1579         /* If the partial match was the CRLF and dot then only write the CRLF
1580            as the server would have inserted the dot */
1581         result = Curl_client_write(conn, CLIENTWRITE_BODY, (char*)POP3_EOB,
1582                                    strip_dot ? prev - 1 : prev);
1583
1584         if(result)
1585           return result;
1586
1587         last = i;
1588         strip_dot = FALSE;
1589       }
1590     }
1591   }
1592
1593   if(pop3c->eob == POP3_EOB_LEN) {
1594     /* We have a full match so the transfer is done, however we must transfer
1595     the CRLF at the start of the EOB as this is considered to be part of the
1596     message as per RFC-1939, sect. 3 */
1597     result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB, 2);
1598
1599     k->keepon &= ~KEEP_RECV;
1600     pop3c->eob = 0;
1601
1602     return result;
1603   }
1604
1605   if(pop3c->eob)
1606     /* While EOB is matching nothing should be output */
1607     return CURLE_OK;
1608
1609   if(nread - last) {
1610     result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last],
1611                                nread - last);
1612   }
1613
1614   return result;
1615 }
1616
1617 #endif /* CURL_DISABLE_POP3 */