Coverage Report

Created: 2026-12-01 06:33

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