Coverage Report

Created: 2026-01-25 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/smtp.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
 * RFC1870 SMTP Service Extension for Message Size
24
 * RFC2195 CRAM-MD5 authentication
25
 * RFC2831 DIGEST-MD5 authentication
26
 * RFC3207 SMTP over TLS
27
 * RFC4422 Simple Authentication and Security Layer (SASL)
28
 * RFC4616 PLAIN authentication
29
 * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
30
 * RFC4954 SMTP Authentication
31
 * RFC5321 SMTP protocol
32
 * RFC5890 Internationalized Domain Names for Applications (IDNA)
33
 * RFC6531 SMTP Extension for Internationalized Email
34
 * RFC6532 Internationalized Email Headers
35
 * RFC6749 OAuth 2.0 Authorization Framework
36
 * RFC8314 Use of TLS for Email Submission and Access
37
 * Draft   SMTP URL Interface   <draft-earhart-url-smtp-00.txt>
38
 * Draft   LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
39
 *
40
 ***************************************************************************/
41
#include "curl_setup.h"
42
#include "urldata.h"
43
#include "smtp.h"
44
45
#ifndef CURL_DISABLE_SMTP
46
47
#ifdef HAVE_NETINET_IN_H
48
#include <netinet/in.h>
49
#endif
50
#ifdef HAVE_ARPA_INET_H
51
#include <arpa/inet.h>
52
#endif
53
#ifdef HAVE_NETDB_H
54
#include <netdb.h>
55
#endif
56
#ifdef __VMS
57
#include <in.h>
58
#include <inet.h>
59
#endif
60
61
#include "sendf.h"
62
#include "curl_trc.h"
63
#include "hostip.h"
64
#include "progress.h"
65
#include "transfer.h"
66
#include "escape.h"
67
#include "pingpong.h"
68
#include "mime.h"
69
#include "vtls/vtls.h"
70
#include "cfilters.h"
71
#include "connect.h"
72
#include "select.h"
73
#include "url.h"
74
#include "curl_gethostname.h"
75
#include "bufref.h"
76
#include "curl_sasl.h"
77
#include "idn.h"
78
#include "curlx/strparse.h"
79
80
/* meta key for storing protocol meta at easy handle */
81
0
#define CURL_META_SMTP_EASY   "meta:proto:smtp:easy"
82
/* meta key for storing protocol meta at connection */
83
0
#define CURL_META_SMTP_CONN   "meta:proto:smtp:conn"
84
85
/****************************************************************************
86
 * SMTP unique setup
87
 ***************************************************************************/
88
typedef enum {
89
  SMTP_STOP,        /* do nothing state, stops the state machine */
90
  SMTP_SERVERGREET, /* waiting for the initial greeting immediately after
91
                       a connect */
92
  SMTP_EHLO,
93
  SMTP_HELO,
94
  SMTP_STARTTLS,
95
  SMTP_UPGRADETLS,  /* asynchronously upgrade the connection to SSL/TLS
96
                       (multi mode only) */
97
  SMTP_AUTH,
98
  SMTP_COMMAND,     /* VRFY, EXPN, NOOP, RSET and HELP */
99
  SMTP_MAIL,        /* MAIL FROM */
100
  SMTP_RCPT,        /* RCPT TO */
101
  SMTP_DATA,
102
  SMTP_POSTDATA,
103
  SMTP_QUIT,
104
  SMTP_LAST         /* never used */
105
} smtpstate;
106
107
/* smtp_conn is used for struct connection-oriented data in the connectdata
108
   struct */
109
struct smtp_conn {
110
  struct pingpong pp;
111
  struct SASL sasl;        /* SASL-related storage */
112
  smtpstate state;         /* Always use smtp.c:state() to change state! */
113
  char *domain;            /* Client address/name to send in the EHLO */
114
  BIT(ssldone);            /* Is connect() over SSL done? */
115
  BIT(tls_supported);      /* StartTLS capability supported by server */
116
  BIT(size_supported);     /* If server supports SIZE extension according to
117
                              RFC 1870 */
118
  BIT(utf8_supported);     /* If server supports SMTPUTF8 extension according
119
                              to RFC 6531 */
120
  BIT(auth_supported);     /* AUTH capability supported by server */
121
};
122
123
/* This SMTP struct is used in the Curl_easy. All SMTP data that is
124
   connection-oriented must be in smtp_conn to properly deal with the fact that
125
   perhaps the Curl_easy is changed between the times the connection is
126
   used. */
127
struct SMTP {
128
  curl_pp_transfer transfer;
129
  char *custom;            /* Custom Request */
130
  struct curl_slist *rcpt; /* Recipient list */
131
  int rcpt_last_error;     /* The last error received for RCPT TO command */
132
  size_t eob;              /* Number of bytes of the EOB (End Of Body) that
133
                              have been received so far */
134
  BIT(rcpt_had_ok);        /* Whether any of RCPT TO commands (depends on
135
                              total number of recipients) succeeded so far */
136
  BIT(trailing_crlf);      /* Specifies if the trailing CRLF is present */
137
};
138
139
/***********************************************************************
140
 *
141
 * smtp_parse_url_options()
142
 *
143
 * Parse the URL login options.
144
 */
145
static CURLcode smtp_parse_url_options(struct connectdata *conn,
146
                                       struct smtp_conn *smtpc)
147
0
{
148
0
  CURLcode result = CURLE_OK;
149
0
  const char *ptr = conn->options;
150
151
0
  while(!result && ptr && *ptr) {
152
0
    const char *key = ptr;
153
0
    const char *value;
154
155
0
    while(*ptr && *ptr != '=')
156
0
      ptr++;
157
158
0
    value = ptr + 1;
159
160
0
    while(*ptr && *ptr != ';')
161
0
      ptr++;
162
163
0
    if(curl_strnequal(key, "AUTH=", 5))
164
0
      result = Curl_sasl_parse_url_auth_option(&smtpc->sasl,
165
0
                                               value, ptr - value);
166
0
    else
167
0
      result = CURLE_URL_MALFORMAT;
168
169
0
    if(*ptr == ';')
170
0
      ptr++;
171
0
  }
172
173
0
  return result;
174
0
}
175
176
/***********************************************************************
177
 *
178
 * smtp_parse_url_path()
179
 *
180
 * Parse the URL path into separate path components.
181
 */
182
static CURLcode smtp_parse_url_path(struct Curl_easy *data,
183
                                    struct smtp_conn *smtpc)
184
0
{
185
  /* The SMTP struct is already initialised in smtp_connect() */
186
0
  const char *path = &data->state.up.path[1]; /* skip leading path */
187
0
  char localhost[HOSTNAME_MAX + 1];
188
189
  /* Calculate the path if necessary */
190
0
  if(!*path) {
191
0
    if(!Curl_gethostname(localhost, sizeof(localhost)))
192
0
      path = localhost;
193
0
    else
194
0
      path = "localhost";
195
0
  }
196
197
  /* URL decode the path and use it as the domain in our EHLO */
198
0
  return Curl_urldecode(path, 0, &smtpc->domain, NULL, REJECT_CTRL);
199
0
}
200
201
/***********************************************************************
202
 *
203
 * smtp_parse_custom_request()
204
 *
205
 * Parse the custom request.
206
 */
207
static CURLcode smtp_parse_custom_request(struct Curl_easy *data,
208
                                          struct SMTP *smtp)
209
0
{
210
0
  CURLcode result = CURLE_OK;
211
0
  const char *custom = data->set.str[STRING_CUSTOMREQUEST];
212
213
  /* URL decode the custom request */
214
0
  if(custom)
215
0
    result = Curl_urldecode(custom, 0, &smtp->custom, NULL, REJECT_CTRL);
216
217
0
  return result;
218
0
}
219
220
/***********************************************************************
221
 *
222
 * smtp_parse_address()
223
 *
224
 * Parse the fully qualified mailbox address into a local address part and the
225
 * hostname, converting the hostname to an IDN A-label, as per RFC-5890, if
226
 * necessary.
227
 *
228
 * Parameters:
229
 *
230
 * conn  [in]              - The connection handle.
231
 * fqma  [in]              - The fully qualified mailbox address (which may or
232
 *                           may not contain UTF-8 characters).
233
 * address        [in/out] - A new allocated buffer which holds the local
234
 *                           address part of the mailbox. This buffer must be
235
 *                           free'ed by the caller.
236
 * host           [in/out] - The hostname structure that holds the original,
237
 *                           and optionally encoded, hostname.
238
 *                           Curl_free_idnconverted_hostname() must be called
239
 *                           once the caller has finished with the structure.
240
 *
241
 * Returns CURLE_OK on success.
242
 *
243
 * Notes:
244
 *
245
 * Should a UTF-8 hostname require conversion to IDN ACE and we cannot honor
246
 * that conversion then we shall return success. This allow the caller to send
247
 * the data to the server as a U-label (as per RFC-6531 sect. 3.2).
248
 *
249
 * If an mailbox '@' separator cannot be located then the mailbox is considered
250
 * to be either a local mailbox or an invalid mailbox (depending on what the
251
 * calling function deems it to be) then the input will simply be returned in
252
 * the address part with the hostname being NULL.
253
 */
254
static CURLcode smtp_parse_address(const char *fqma, char **address,
255
                                   struct hostname *host, const char **suffix)
256
0
{
257
0
  CURLcode result = CURLE_OK;
258
0
  size_t length;
259
0
  char *addressend;
260
261
  /* Duplicate the fully qualified email address so we can manipulate it,
262
     ensuring it does not contain the delimiters if specified */
263
0
  char *dup = curlx_strdup(fqma[0] == '<' ? fqma + 1 : fqma);
264
0
  if(!dup)
265
0
    return CURLE_OUT_OF_MEMORY;
266
267
0
  if(fqma[0] != '<') {
268
0
    length = strlen(dup);
269
0
    if(length) {
270
0
      if(dup[length - 1] == '>')
271
0
        dup[length - 1] = '\0';
272
0
    }
273
0
  }
274
0
  else {
275
0
    addressend = strrchr(dup, '>');
276
0
    if(addressend) {
277
0
      *addressend = '\0';
278
0
      *suffix = addressend + 1;
279
0
    }
280
0
  }
281
282
  /* Extract the hostname from the address (if we can) */
283
0
  host->name = strpbrk(dup, "@");
284
0
  if(host->name) {
285
0
    *host->name = '\0';
286
0
    host->name = host->name + 1;
287
288
    /* Attempt to convert the hostname to IDN ACE */
289
0
    (void)Curl_idnconvert_hostname(host);
290
291
    /* If Curl_idnconvert_hostname() fails then we shall attempt to continue
292
       and send the hostname using UTF-8 rather than as 7-bit ACE (which is
293
       our preference) */
294
0
  }
295
296
  /* Extract the local address from the mailbox */
297
0
  *address = dup;
298
299
0
  return result;
300
0
}
301
302
struct cr_eob_ctx {
303
  struct Curl_creader super;
304
  struct bufq buf;
305
  size_t n_eob; /* how many EOB bytes we matched so far */
306
  size_t eob;       /* Number of bytes of the EOB (End Of Body) that
307
                       have been received so far */
308
  BIT(read_eos);  /* we read an EOS from the next reader */
309
  BIT(processed_eos);  /* we read and processed an EOS */
310
  BIT(eos);       /* we have returned an EOS */
311
};
312
313
static CURLcode cr_eob_init(struct Curl_easy *data,
314
                            struct Curl_creader *reader)
315
0
{
316
0
  struct cr_eob_ctx *ctx = reader->ctx;
317
0
  (void)data;
318
  /* The first char we read is the first on a line, as if we had
319
   * read CRLF just before */
320
0
  ctx->n_eob = 2;
321
0
  Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT);
322
0
  return CURLE_OK;
323
0
}
324
325
static void cr_eob_close(struct Curl_easy *data, struct Curl_creader *reader)
326
0
{
327
0
  struct cr_eob_ctx *ctx = reader->ctx;
328
0
  (void)data;
329
0
  Curl_bufq_free(&ctx->buf);
330
0
}
331
332
/* this is the 5-bytes End-Of-Body marker for SMTP */
333
0
#define SMTP_EOB          "\r\n.\r\n"
334
0
#define SMTP_EOB_FIND_LEN 3
335
336
/* client reader doing SMTP End-Of-Body escaping. */
337
static CURLcode cr_eob_read(struct Curl_easy *data,
338
                            struct Curl_creader *reader,
339
                            char *buf, size_t blen,
340
                            size_t *pnread, bool *peos)
341
0
{
342
0
  struct cr_eob_ctx *ctx = reader->ctx;
343
0
  CURLcode result = CURLE_OK;
344
0
  size_t nread, i, start, n;
345
0
  bool eos;
346
347
0
  if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) {
348
    /* Get more and convert it when needed */
349
0
    result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos);
350
0
    CURL_TRC_SMTP(data, "cr_eob_read, next_read(len=%zu) -> %d, %zu eos=%d",
351
0
                  blen, result, nread, eos);
352
0
    if(result)
353
0
      return result;
354
355
0
    ctx->read_eos = eos;
356
0
    if(nread) {
357
0
      if(!ctx->n_eob && !memchr(buf, SMTP_EOB[0], nread)) {
358
        /* not in the middle of a match, no EOB start found, just pass */
359
0
        *pnread = nread;
360
0
        *peos = FALSE;
361
0
        return CURLE_OK;
362
0
      }
363
      /* scan for EOB (continuation) and convert */
364
0
      for(i = start = 0; i < nread; ++i) {
365
0
        if(ctx->n_eob >= SMTP_EOB_FIND_LEN) {
366
          /* matched the EOB prefix and seeing additional char, add '.' */
367
0
          result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n);
368
0
          if(result)
369
0
            return result;
370
0
          result = Curl_bufq_cwrite(&ctx->buf, ".", 1, &n);
371
0
          if(result)
372
0
            return result;
373
0
          ctx->n_eob = 0;
374
0
          start = i;
375
0
          if(data->state.infilesize > 0)
376
0
            data->state.infilesize++;
377
0
        }
378
379
0
        if(buf[i] != SMTP_EOB[ctx->n_eob])
380
0
          ctx->n_eob = 0;
381
382
0
        if(buf[i] == SMTP_EOB[ctx->n_eob]) {
383
          /* matching another char of the EOB */
384
0
          ++ctx->n_eob;
385
0
        }
386
0
      }
387
388
      /* add any remainder to buf */
389
0
      if(start < nread) {
390
0
        result = Curl_bufq_cwrite(&ctx->buf, buf + start, nread - start, &n);
391
0
        if(result)
392
0
          return result;
393
0
      }
394
0
    }
395
0
  }
396
397
0
  *peos = FALSE;
398
399
0
  if(ctx->read_eos && !ctx->processed_eos) {
400
    /* if we last matched a CRLF or if the data was empty, add ".\r\n"
401
     * to end the body. If we sent something and it did not end with "\r\n",
402
     * add "\r\n.\r\n" to end the body */
403
0
    const char *eob = SMTP_EOB;
404
0
    CURL_TRC_SMTP(data, "auto-ending mail body with '\\r\\n.\\r\\n'");
405
0
    switch(ctx->n_eob) {
406
0
    case 2:
407
      /* seen a CRLF at the end, just add the remainder */
408
0
      eob = &SMTP_EOB[2];
409
0
      break;
410
0
    case 3:
411
      /* ended with '\r\n.', we should escape the last '.' */
412
0
      eob = "." SMTP_EOB;
413
0
      break;
414
0
    default:
415
0
      break;
416
0
    }
417
0
    result = Curl_bufq_cwrite(&ctx->buf, eob, strlen(eob), &n);
418
0
    if(result)
419
0
      return result;
420
0
    ctx->processed_eos = TRUE;
421
0
  }
422
423
0
  if(!Curl_bufq_is_empty(&ctx->buf)) {
424
0
    result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread);
425
0
  }
426
0
  else
427
0
    *pnread = 0;
428
429
0
  if(ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) {
430
    /* no more data, read all, done. */
431
0
    CURL_TRC_SMTP(data, "mail body complete, returning EOS");
432
0
    ctx->eos = TRUE;
433
0
  }
434
0
  *peos = (bool)ctx->eos;
435
0
  DEBUGF(infof(data, "cr_eob_read(%zu) -> %d, %zd, %d",
436
0
         blen, result, *pnread, *peos));
437
0
  return result;
438
0
}
439
440
static curl_off_t cr_eob_total_length(struct Curl_easy *data,
441
                                      struct Curl_creader *reader)
442
0
{
443
  /* this reader changes length depending on input */
444
0
  (void)data;
445
0
  (void)reader;
446
0
  return -1;
447
0
}
448
449
static const struct Curl_crtype cr_eob = {
450
  "cr-smtp-eob",
451
  cr_eob_init,
452
  cr_eob_read,
453
  cr_eob_close,
454
  Curl_creader_def_needs_rewind,
455
  cr_eob_total_length,
456
  Curl_creader_def_resume_from,
457
  Curl_creader_def_cntrl,
458
  Curl_creader_def_is_paused,
459
  Curl_creader_def_done,
460
  sizeof(struct cr_eob_ctx)
461
};
462
463
static CURLcode cr_eob_add(struct Curl_easy *data)
464
0
{
465
0
  struct Curl_creader *reader = NULL;
466
0
  CURLcode result;
467
468
0
  result = Curl_creader_create(&reader, data, &cr_eob, CURL_CR_CONTENT_ENCODE);
469
0
  if(!result)
470
0
    result = Curl_creader_add(data, reader);
471
472
0
  if(result && reader)
473
0
    Curl_creader_free(data, reader);
474
0
  return result;
475
0
}
476
477
/***********************************************************************
478
 *
479
 * smtp_endofresp()
480
 *
481
 * Checks for an ending SMTP status code at the start of the given string, but
482
 * also detects various capabilities from the EHLO response including the
483
 * supported authentication mechanisms.
484
 */
485
static bool smtp_endofresp(struct Curl_easy *data, struct connectdata *conn,
486
                           const char *line, size_t len, int *resp)
487
0
{
488
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
489
0
  bool result = FALSE;
490
0
  (void)data;
491
492
0
  DEBUGASSERT(smtpc);
493
0
  if(!smtpc)
494
0
    return FALSE;
495
496
  /* Nothing for us */
497
0
  if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
498
0
    return FALSE;
499
500
  /* Do we have a command response? This should be the response code followed
501
     by a space and optionally some text as per RFC-5321 and as outlined in
502
     Section 4. Examples of RFC-4954 but some email servers ignore this and
503
     only send the response code instead as per Section 4.2. */
504
0
  if(line[3] == ' ' || len == 5) {
505
0
    char tmpline[6];
506
0
    curl_off_t code;
507
0
    const char *p = tmpline;
508
0
    result = TRUE;
509
0
    memcpy(tmpline, line, (len == 5 ? 5 : 3));
510
0
    tmpline[len == 5 ? 5 : 3] = 0;
511
0
    if(curlx_str_number(&p, &code, len == 5 ? 99999 : 999))
512
0
      return FALSE;
513
0
    *resp = (int)code;
514
515
    /* Make sure real server never sends internal value */
516
0
    if(*resp == 1)
517
0
      *resp = 0;
518
0
  }
519
  /* Do we have a multiline (continuation) response? */
520
0
  else if(line[3] == '-' &&
521
0
          (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) {
522
0
    result = TRUE;
523
0
    *resp = 1;  /* Internal response code */
524
0
  }
525
526
0
  return result;
527
0
}
528
529
/***********************************************************************
530
 *
531
 * smtp_get_message()
532
 *
533
 * Gets the authentication message from the response buffer.
534
 */
535
static CURLcode smtp_get_message(struct Curl_easy *data, struct bufref *out)
536
0
{
537
0
  struct smtp_conn *smtpc =
538
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
539
0
  char *message;
540
0
  size_t len;
541
542
0
  if(!smtpc)
543
0
    return CURLE_FAILED_INIT;
544
545
0
  message = curlx_dyn_ptr(&smtpc->pp.recvbuf);
546
0
  len = smtpc->pp.nfinal;
547
0
  if(len > 4) {
548
    /* Find the start of the message */
549
0
    len -= 4;
550
0
    for(message += 4; ISBLANK(*message); message++, len--)
551
0
      ;
552
553
    /* Find the end of the message */
554
0
    while(len--)
555
0
      if(!ISNEWLINE(message[len]) && !ISBLANK(message[len]))
556
0
        break;
557
558
    /* Terminate the message */
559
0
    message[++len] = '\0';
560
0
    Curl_bufref_set(out, message, len, NULL);
561
0
  }
562
0
  else
563
    /* junk input => zero length output */
564
0
    Curl_bufref_set(out, "", 0, NULL);
565
566
0
  return CURLE_OK;
567
0
}
568
569
/***********************************************************************
570
 *
571
 * smtp_state()
572
 *
573
 * This is the ONLY way to change SMTP state!
574
 */
575
static void smtp_state(struct Curl_easy *data,
576
                       struct smtp_conn *smtpc,
577
                       smtpstate newstate)
578
0
{
579
0
#ifdef CURLVERBOSE
580
  /* for debug purposes */
581
0
  static const char * const names[] = {
582
0
    "STOP",
583
0
    "SERVERGREET",
584
0
    "EHLO",
585
0
    "HELO",
586
0
    "STARTTLS",
587
0
    "UPGRADETLS",
588
0
    "AUTH",
589
0
    "COMMAND",
590
0
    "MAIL",
591
0
    "RCPT",
592
0
    "DATA",
593
0
    "POSTDATA",
594
0
    "QUIT",
595
    /* LAST */
596
0
  };
597
598
0
  if(smtpc->state != newstate)
599
0
    CURL_TRC_SMTP(data, "state change from %s to %s",
600
0
                  names[smtpc->state], names[newstate]);
601
#else
602
  (void)data;
603
#endif
604
605
0
  smtpc->state = newstate;
606
0
}
607
608
/***********************************************************************
609
 *
610
 * smtp_perform_ehlo()
611
 *
612
 * Sends the EHLO command to not only initialise communication with the ESMTP
613
 * server but to also obtain a list of server side supported capabilities.
614
 */
615
static CURLcode smtp_perform_ehlo(struct Curl_easy *data,
616
                                  struct smtp_conn *smtpc)
617
0
{
618
0
  CURLcode result = CURLE_OK;
619
620
0
  smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */
621
0
  smtpc->sasl.authused = SASL_AUTH_NONE;  /* Clear the authentication mechanism
622
                                             used for esmtp connections */
623
0
  smtpc->tls_supported = FALSE;           /* Clear the TLS capability */
624
0
  smtpc->auth_supported = FALSE;          /* Clear the AUTH capability */
625
626
  /* Send the EHLO command */
627
0
  result = Curl_pp_sendf(data, &smtpc->pp, "EHLO %s", smtpc->domain);
628
629
0
  if(!result)
630
0
    smtp_state(data, smtpc, SMTP_EHLO);
631
632
0
  return result;
633
0
}
634
635
/***********************************************************************
636
 *
637
 * smtp_perform_helo()
638
 *
639
 * Sends the HELO command to initialise communication with the SMTP server.
640
 */
641
static CURLcode smtp_perform_helo(struct Curl_easy *data,
642
                                  struct smtp_conn *smtpc)
643
0
{
644
0
  CURLcode result = CURLE_OK;
645
646
0
  smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used
647
                                            in smtp connections */
648
649
  /* Send the HELO command */
650
0
  result = Curl_pp_sendf(data, &smtpc->pp, "HELO %s", smtpc->domain);
651
652
0
  if(!result)
653
0
    smtp_state(data, smtpc, SMTP_HELO);
654
655
0
  return result;
656
0
}
657
658
/***********************************************************************
659
 *
660
 * smtp_perform_starttls()
661
 *
662
 * Sends the STLS command to start the upgrade to TLS.
663
 */
664
static CURLcode smtp_perform_starttls(struct Curl_easy *data,
665
                                      struct smtp_conn *smtpc)
666
0
{
667
  /* Send the STARTTLS command */
668
0
  CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "STARTTLS");
669
670
0
  if(!result)
671
0
    smtp_state(data, smtpc, SMTP_STARTTLS);
672
673
0
  return result;
674
0
}
675
676
/***********************************************************************
677
 *
678
 * smtp_perform_upgrade_tls()
679
 *
680
 * Performs the upgrade to TLS.
681
 */
682
static CURLcode smtp_perform_upgrade_tls(struct Curl_easy *data,
683
                                         struct smtp_conn *smtpc)
684
0
{
685
0
#ifdef USE_SSL
686
  /* Start the SSL connection */
687
0
  struct connectdata *conn = data->conn;
688
0
  CURLcode result;
689
0
  bool ssldone = FALSE;
690
691
0
  DEBUGASSERT(smtpc->state == SMTP_UPGRADETLS);
692
0
  if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) {
693
0
    result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET);
694
0
    if(result)
695
0
      goto out;
696
    /* Change the connection handler and SMTP state */
697
0
    conn->scheme = &Curl_scheme_smtps;
698
0
  }
699
700
0
  DEBUGASSERT(!smtpc->ssldone);
701
0
  result = Curl_conn_connect(data, FIRSTSOCKET, FALSE, &ssldone);
702
0
  DEBUGF(infof(data, "smtp_perform_upgrade_tls, connect -> %d, %d",
703
0
           result, ssldone));
704
0
  if(!result && ssldone) {
705
0
    smtpc->ssldone = ssldone;
706
    /* perform EHLO now, changes smtp->state out of SMTP_UPGRADETLS */
707
0
    result = smtp_perform_ehlo(data, smtpc);
708
0
  }
709
0
out:
710
0
  return result;
711
#else
712
  (void)data;
713
  (void)smtpc;
714
  return CURLE_NOT_BUILT_IN;
715
#endif
716
0
}
717
718
/***********************************************************************
719
 *
720
 * smtp_perform_auth()
721
 *
722
 * Sends an AUTH command allowing the client to login with the given SASL
723
 * authentication mechanism.
724
 */
725
static CURLcode smtp_perform_auth(struct Curl_easy *data,
726
                                  const char *mech,
727
                                  const struct bufref *initresp)
728
0
{
729
0
  CURLcode result = CURLE_OK;
730
0
  struct smtp_conn *smtpc =
731
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
732
0
  const char *ir = Curl_bufref_ptr(initresp);
733
734
0
  if(!smtpc)
735
0
    return CURLE_FAILED_INIT;
736
737
0
  if(ir) {                                  /* AUTH <mech> ...<crlf> */
738
    /* Send the AUTH command with the initial response */
739
0
    result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s %s", mech, ir);
740
0
  }
741
0
  else {
742
    /* Send the AUTH command */
743
0
    result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s", mech);
744
0
  }
745
746
0
  return result;
747
0
}
748
749
/***********************************************************************
750
 *
751
 * smtp_continue_auth()
752
 *
753
 * Sends SASL continuation data.
754
 */
755
static CURLcode smtp_continue_auth(struct Curl_easy *data,
756
                                   const char *mech,
757
                                   const struct bufref *resp)
758
0
{
759
0
  struct smtp_conn *smtpc =
760
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
761
762
0
  (void)mech;
763
0
  if(!smtpc)
764
0
    return CURLE_FAILED_INIT;
765
0
  return Curl_pp_sendf(data, &smtpc->pp, "%s", Curl_bufref_ptr(resp));
766
0
}
767
768
/***********************************************************************
769
 *
770
 * smtp_cancel_auth()
771
 *
772
 * Sends SASL cancellation.
773
 */
774
static CURLcode smtp_cancel_auth(struct Curl_easy *data, const char *mech)
775
0
{
776
0
  struct smtp_conn *smtpc =
777
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
778
779
0
  (void)mech;
780
0
  if(!smtpc)
781
0
    return CURLE_FAILED_INIT;
782
0
  return Curl_pp_sendf(data, &smtpc->pp, "*");
783
0
}
784
785
/***********************************************************************
786
 *
787
 * smtp_perform_authentication()
788
 *
789
 * Initiates the authentication sequence, with the appropriate SASL
790
 * authentication mechanism.
791
 */
792
static CURLcode smtp_perform_authentication(struct Curl_easy *data,
793
                                            struct smtp_conn *smtpc)
794
0
{
795
0
  CURLcode result = CURLE_OK;
796
0
  saslprogress progress;
797
798
  /* Check we have enough data to authenticate with, and the
799
     server supports authentication, and end the connect phase if not */
800
0
  if(!smtpc->auth_supported ||
801
0
     !Curl_sasl_can_authenticate(&smtpc->sasl, data)) {
802
0
    smtp_state(data, smtpc, SMTP_STOP);
803
0
    return result;
804
0
  }
805
806
  /* Calculate the SASL login details */
807
0
  result = Curl_sasl_start(&smtpc->sasl, data, FALSE, &progress);
808
809
0
  if(!result) {
810
0
    if(progress == SASL_INPROGRESS)
811
0
      smtp_state(data, smtpc, SMTP_AUTH);
812
0
    else
813
0
      result = Curl_sasl_is_blocked(&smtpc->sasl, data);
814
0
  }
815
816
0
  return result;
817
0
}
818
819
/***********************************************************************
820
 *
821
 * smtp_perform_command()
822
 *
823
 * Sends an SMTP based command.
824
 */
825
static CURLcode smtp_perform_command(struct Curl_easy *data,
826
                                     struct smtp_conn *smtpc,
827
                                     struct SMTP *smtp)
828
0
{
829
0
  CURLcode result = CURLE_OK;
830
831
0
  if(smtp->rcpt) {
832
    /* We notify the server we are sending UTF-8 data if a) it supports the
833
       SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in
834
       either the local address or hostname parts. This is regardless of
835
       whether the hostname is encoded using IDN ACE */
836
0
    bool utf8 = FALSE;
837
838
0
    if((!smtp->custom) || (!smtp->custom[0])) {
839
0
      char *address = NULL;
840
0
      struct hostname host = { NULL, NULL, NULL, NULL };
841
0
      const char *suffix = "";
842
843
      /* Parse the mailbox to verify into the local address and hostname
844
         parts, converting the hostname to an IDN A-label if necessary */
845
0
      result = smtp_parse_address(smtp->rcpt->data,
846
0
                                  &address, &host, &suffix);
847
0
      if(result)
848
0
        return result;
849
850
      /* Establish whether we should report SMTPUTF8 to the server for this
851
         mailbox as per RFC-6531 sect. 3.1 point 6 */
852
0
      utf8 = (smtpc->utf8_supported) &&
853
0
             ((host.encalloc) || (!Curl_is_ASCII_name(address)) ||
854
0
              (!Curl_is_ASCII_name(host.name)));
855
856
      /* Send the VRFY command (Note: The hostname part may be absent when the
857
         host is a local system) */
858
0
      result = Curl_pp_sendf(data, &smtpc->pp, "VRFY %s%s%s%s",
859
0
                             address,
860
0
                             host.name ? "@" : "",
861
0
                             host.name ? host.name : "",
862
0
                             utf8 ? " SMTPUTF8" : "");
863
864
0
      Curl_free_idnconverted_hostname(&host);
865
0
      curlx_free(address);
866
0
    }
867
0
    else {
868
      /* Establish whether we should report that we support SMTPUTF8 for EXPN
869
         commands to the server as per RFC-6531 sect. 3.1 point 6 */
870
0
      utf8 = (smtpc->utf8_supported) && (!strcmp(smtp->custom, "EXPN"));
871
872
      /* Send the custom recipient based command such as the EXPN command */
873
0
      result = Curl_pp_sendf(data, &smtpc->pp,
874
0
                             "%s %s%s", smtp->custom,
875
0
                             smtp->rcpt->data,
876
0
                             utf8 ? " SMTPUTF8" : "");
877
0
    }
878
0
  }
879
0
  else
880
    /* Send the non-recipient based command such as HELP */
881
0
    result = Curl_pp_sendf(data, &smtpc->pp, "%s",
882
0
                           smtp->custom && smtp->custom[0] != '\0' ?
883
0
                           smtp->custom : "HELP");
884
885
0
  if(!result)
886
0
    smtp_state(data, smtpc, SMTP_COMMAND);
887
888
0
  return result;
889
0
}
890
891
/***********************************************************************
892
 *
893
 * smtp_perform_mail()
894
 *
895
 * Sends an MAIL command to initiate the upload of a message.
896
 */
897
static CURLcode smtp_perform_mail(struct Curl_easy *data,
898
                                  struct smtp_conn *smtpc,
899
                                  struct SMTP *smtp)
900
0
{
901
0
  char *from = NULL;
902
0
  char *auth = NULL;
903
0
  char *size = NULL;
904
0
  CURLcode result = CURLE_OK;
905
906
  /* We notify the server we are sending UTF-8 data if a) it supports the
907
     SMTPUTF8 extension and b) The mailbox contains UTF-8 characters, in
908
     either the local address or hostname parts. This is regardless of
909
     whether the hostname is encoded using IDN ACE */
910
0
  bool utf8 = FALSE;
911
912
  /* Calculate the FROM parameter */
913
0
  if(data->set.str[STRING_MAIL_FROM]) {
914
0
    char *address = NULL;
915
0
    struct hostname host = { NULL, NULL, NULL, NULL };
916
0
    const char *suffix = "";
917
918
    /* Parse the FROM mailbox into the local address and hostname parts,
919
       converting the hostname to an IDN A-label if necessary */
920
0
    result = smtp_parse_address(data->set.str[STRING_MAIL_FROM],
921
0
                                &address, &host, &suffix);
922
0
    if(result)
923
0
      goto out;
924
925
    /* Establish whether we should report SMTPUTF8 to the server for this
926
       mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */
927
0
    utf8 = (smtpc->utf8_supported) &&
928
0
           ((host.encalloc) || (!Curl_is_ASCII_name(address)) ||
929
0
            (!Curl_is_ASCII_name(host.name)));
930
931
0
    if(host.name) {
932
0
      from = curl_maprintf("<%s@%s>%s", address, host.name, suffix);
933
934
0
      Curl_free_idnconverted_hostname(&host);
935
0
    }
936
0
    else
937
      /* An invalid mailbox was provided but we will simply let the server
938
         worry about that and reply with a 501 error */
939
0
      from = curl_maprintf("<%s>%s", address, suffix);
940
941
0
    curlx_free(address);
942
0
  }
943
0
  else
944
    /* Null reverse-path, RFC-5321, sect. 3.6.3 */
945
0
    from = curlx_strdup("<>");
946
947
0
  if(!from) {
948
0
    result = CURLE_OUT_OF_MEMORY;
949
0
    goto out;
950
0
  }
951
952
  /* Calculate the optional AUTH parameter */
953
0
  if(data->set.str[STRING_MAIL_AUTH] && smtpc->sasl.authused) {
954
0
    if(data->set.str[STRING_MAIL_AUTH][0] != '\0') {
955
0
      char *address = NULL;
956
0
      struct hostname host = { NULL, NULL, NULL, NULL };
957
0
      const char *suffix = "";
958
959
      /* Parse the AUTH mailbox into the local address and hostname parts,
960
         converting the hostname to an IDN A-label if necessary */
961
0
      result = smtp_parse_address(data->set.str[STRING_MAIL_AUTH],
962
0
                                  &address, &host, &suffix);
963
0
      if(result)
964
0
        goto out;
965
966
      /* Establish whether we should report SMTPUTF8 to the server for this
967
         mailbox as per RFC-6531 sect. 3.1 point 4 and sect. 3.4 */
968
0
      if((!utf8) && (smtpc->utf8_supported) &&
969
0
         ((host.encalloc) || (!Curl_is_ASCII_name(address)) ||
970
0
          (!Curl_is_ASCII_name(host.name))))
971
0
        utf8 = TRUE;
972
973
0
      if(host.name) {
974
0
        auth = curl_maprintf("<%s@%s>%s", address, host.name, suffix);
975
976
0
        Curl_free_idnconverted_hostname(&host);
977
0
      }
978
0
      else
979
        /* An invalid mailbox was provided but we will simply let the server
980
           worry about it */
981
0
        auth = curl_maprintf("<%s>%s", address, suffix);
982
0
      curlx_free(address);
983
0
    }
984
0
    else
985
      /* Empty AUTH, RFC-2554, sect. 5 */
986
0
      auth = curlx_strdup("<>");
987
988
0
    if(!auth) {
989
0
      result = CURLE_OUT_OF_MEMORY;
990
0
      goto out;
991
0
    }
992
0
  }
993
994
0
#ifndef CURL_DISABLE_MIME
995
  /* Prepare the mime data if some. */
996
0
  if(IS_MIME_POST(data)) {
997
0
    curl_mimepart *postp = data->set.mimepostp;
998
999
    /* Use the whole structure as data. */
1000
0
    postp->flags &= ~(unsigned int)MIME_BODY_ONLY;
1001
1002
    /* Add external headers and mime version. */
1003
0
    curl_mime_headers(postp, data->set.headers, 0);
1004
0
    result = Curl_mime_prepare_headers(data, postp, NULL,
1005
0
                                       NULL, MIMESTRATEGY_MAIL);
1006
1007
0
    if(!result)
1008
0
      if(!Curl_checkheaders(data, STRCONST("Mime-Version")))
1009
0
        result = Curl_mime_add_header(&postp->curlheaders,
1010
0
                                      "Mime-Version: 1.0");
1011
1012
0
    if(!result)
1013
0
      result = Curl_creader_set_mime(data, postp);
1014
0
    if(result)
1015
0
      goto out;
1016
0
    data->state.infilesize = Curl_creader_total_length(data);
1017
0
  }
1018
0
  else
1019
0
#endif
1020
0
  {
1021
0
    result = Curl_creader_set_fread(data, data->state.infilesize);
1022
0
    if(result)
1023
0
      goto out;
1024
0
  }
1025
1026
  /* Calculate the optional SIZE parameter */
1027
0
  if(smtpc->size_supported && data->state.infilesize > 0) {
1028
0
    size = curl_maprintf("%" FMT_OFF_T, data->state.infilesize);
1029
1030
0
    if(!size) {
1031
0
      result = CURLE_OUT_OF_MEMORY;
1032
0
      goto out;
1033
0
    }
1034
0
  }
1035
1036
  /* If the mailboxes in the FROM and AUTH parameters do not include a UTF-8
1037
     based address then quickly scan through the recipient list and check if
1038
     any there do, as we need to correctly identify our support for SMTPUTF8
1039
     in the envelope, as per RFC-6531 sect. 3.4 */
1040
0
  if(smtpc->utf8_supported && !utf8) {
1041
0
    struct curl_slist *rcpt = smtp->rcpt;
1042
1043
0
    while(rcpt && !utf8) {
1044
      /* Does the hostname contain non-ASCII characters? */
1045
0
      if(!Curl_is_ASCII_name(rcpt->data))
1046
0
        utf8 = TRUE;
1047
1048
0
      rcpt = rcpt->next;
1049
0
    }
1050
0
  }
1051
1052
  /* Add the client reader doing STMP EOB escaping */
1053
0
  result = cr_eob_add(data);
1054
0
  if(result)
1055
0
    goto out;
1056
1057
  /* Send the MAIL command */
1058
0
  result = Curl_pp_sendf(data, &smtpc->pp,
1059
0
                         "MAIL FROM:%s%s%s%s%s%s",
1060
0
                         from,                 /* Mandatory                 */
1061
0
                         auth ? " AUTH=" : "", /* Optional on AUTH support  */
1062
0
                         auth ? auth : "",     /*                           */
1063
0
                         size ? " SIZE=" : "", /* Optional on SIZE support  */
1064
0
                         size ? size : "",     /*                           */
1065
0
                         utf8 ? " SMTPUTF8"    /* Internationalised mailbox */
1066
0
                               : "");          /* included in our envelope  */
1067
1068
0
out:
1069
0
  curlx_free(from);
1070
0
  curlx_free(auth);
1071
0
  curlx_free(size);
1072
1073
0
  if(!result)
1074
0
    smtp_state(data, smtpc, SMTP_MAIL);
1075
1076
0
  return result;
1077
0
}
1078
1079
/***********************************************************************
1080
 *
1081
 * smtp_perform_rcpt_to()
1082
 *
1083
 * Sends a RCPT TO command for a given recipient as part of the message upload
1084
 * process.
1085
 */
1086
static CURLcode smtp_perform_rcpt_to(struct Curl_easy *data,
1087
                                     struct smtp_conn *smtpc,
1088
                                     struct SMTP *smtp)
1089
0
{
1090
0
  CURLcode result = CURLE_OK;
1091
0
  char *address = NULL;
1092
0
  struct hostname host = { NULL, NULL, NULL, NULL };
1093
0
  const char *suffix = "";
1094
1095
  /* Parse the recipient mailbox into the local address and hostname parts,
1096
     converting the hostname to an IDN A-label if necessary */
1097
0
  result = smtp_parse_address(smtp->rcpt->data,
1098
0
                              &address, &host, &suffix);
1099
0
  if(result)
1100
0
    return result;
1101
1102
  /* Send the RCPT TO command */
1103
0
  if(host.name)
1104
0
    result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s@%s>%s",
1105
0
                           address, host.name, suffix);
1106
0
  else
1107
    /* An invalid mailbox was provided but we will simply let the server worry
1108
       about that and reply with a 501 error */
1109
0
    result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s>%s",
1110
0
                           address, suffix);
1111
1112
0
  Curl_free_idnconverted_hostname(&host);
1113
0
  curlx_free(address);
1114
1115
0
  if(!result)
1116
0
    smtp_state(data, smtpc, SMTP_RCPT);
1117
1118
0
  return result;
1119
0
}
1120
1121
/***********************************************************************
1122
 *
1123
 * smtp_perform_quit()
1124
 *
1125
 * Performs the quit action prior to sclose() being called.
1126
 */
1127
static CURLcode smtp_perform_quit(struct Curl_easy *data,
1128
                                  struct smtp_conn *smtpc)
1129
0
{
1130
  /* Send the QUIT command */
1131
0
  CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "QUIT");
1132
1133
0
  if(!result)
1134
0
    smtp_state(data, smtpc, SMTP_QUIT);
1135
1136
0
  return result;
1137
0
}
1138
1139
/* For the initial server greeting */
1140
static CURLcode smtp_state_servergreet_resp(struct Curl_easy *data,
1141
                                            struct smtp_conn *smtpc,
1142
                                            int smtpcode,
1143
                                            smtpstate instate)
1144
0
{
1145
0
  CURLcode result = CURLE_OK;
1146
0
  (void)instate;
1147
1148
0
  if(smtpcode / 100 != 2) {
1149
0
    failf(data, "Got unexpected smtp-server response: %d", smtpcode);
1150
0
    result = CURLE_WEIRD_SERVER_REPLY;
1151
0
  }
1152
0
  else
1153
0
    result = smtp_perform_ehlo(data, smtpc);
1154
1155
0
  return result;
1156
0
}
1157
1158
/* For STARTTLS responses */
1159
static CURLcode smtp_state_starttls_resp(struct Curl_easy *data,
1160
                                         struct smtp_conn *smtpc,
1161
                                         int smtpcode,
1162
                                         smtpstate instate)
1163
0
{
1164
0
  CURLcode result = CURLE_OK;
1165
0
  (void)instate;
1166
1167
  /* Pipelining in response is forbidden. */
1168
0
  if(smtpc->pp.overflow)
1169
0
    return CURLE_WEIRD_SERVER_REPLY;
1170
1171
0
  if(smtpcode != 220) {
1172
0
    if(data->set.use_ssl != CURLUSESSL_TRY) {
1173
0
      failf(data, "STARTTLS denied, code %d", smtpcode);
1174
0
      result = CURLE_USE_SSL_FAILED;
1175
0
    }
1176
0
    else
1177
0
      result = smtp_perform_authentication(data, smtpc);
1178
0
  }
1179
0
  else
1180
0
    smtp_state(data, smtpc, SMTP_UPGRADETLS);
1181
1182
0
  return result;
1183
0
}
1184
1185
/* For EHLO responses */
1186
static CURLcode smtp_state_ehlo_resp(struct Curl_easy *data,
1187
                                     struct smtp_conn *smtpc,
1188
                                     int smtpcode,
1189
                                     smtpstate instate)
1190
0
{
1191
0
  CURLcode result = CURLE_OK;
1192
0
  const char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf);
1193
0
  size_t len = smtpc->pp.nfinal;
1194
1195
0
  (void)instate;
1196
1197
0
  if(smtpcode / 100 != 2 && smtpcode != 1) {
1198
0
    if(data->set.use_ssl <= CURLUSESSL_TRY ||
1199
0
       Curl_conn_is_ssl(data->conn, FIRSTSOCKET))
1200
0
      result = smtp_perform_helo(data, smtpc);
1201
0
    else {
1202
0
      failf(data, "Remote access denied: %d", smtpcode);
1203
0
      result = CURLE_REMOTE_ACCESS_DENIED;
1204
0
    }
1205
0
  }
1206
0
  else if(len >= 4) {
1207
0
    line += 4;
1208
0
    len -= 4;
1209
1210
    /* Does the server support the STARTTLS capability? */
1211
0
    if(len >= 8 && curl_strnequal(line, "STARTTLS", 8))
1212
0
      smtpc->tls_supported = TRUE;
1213
1214
    /* Does the server support the SIZE capability? */
1215
0
    else if(len >= 4 && curl_strnequal(line, "SIZE", 4))
1216
0
      smtpc->size_supported = TRUE;
1217
1218
    /* Does the server support the UTF-8 capability? */
1219
0
    else if(len >= 8 && curl_strnequal(line, "SMTPUTF8", 8))
1220
0
      smtpc->utf8_supported = TRUE;
1221
1222
    /* Does the server support authentication? */
1223
0
    else if(len >= 5 && curl_strnequal(line, "AUTH ", 5)) {
1224
0
      smtpc->auth_supported = TRUE;
1225
1226
      /* Advance past the AUTH keyword */
1227
0
      line += 5;
1228
0
      len -= 5;
1229
1230
      /* Loop through the data line */
1231
0
      for(;;) {
1232
0
        size_t llen;
1233
0
        size_t wordlen;
1234
0
        unsigned short mechbit;
1235
1236
0
        while(len && (ISBLANK(*line) || ISNEWLINE(*line))) {
1237
0
          line++;
1238
0
          len--;
1239
0
        }
1240
1241
0
        if(!len)
1242
0
          break;
1243
1244
        /* Extract the word */
1245
0
        for(wordlen = 0; wordlen < len && !ISBLANK(line[wordlen]) &&
1246
0
              !ISNEWLINE(line[wordlen]);)
1247
0
          wordlen++;
1248
1249
        /* Test the word for a matching authentication mechanism */
1250
0
        mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
1251
0
        if(mechbit && llen == wordlen)
1252
0
          smtpc->sasl.authmechs |= mechbit;
1253
1254
0
        line += wordlen;
1255
0
        len -= wordlen;
1256
0
      }
1257
0
    }
1258
1259
0
    if(smtpcode != 1) {
1260
0
      if(data->set.use_ssl && !Curl_conn_is_ssl(data->conn, FIRSTSOCKET)) {
1261
        /* We do not have an SSL/TLS connection yet, but SSL is requested */
1262
0
        if(smtpc->tls_supported)
1263
          /* Switch to TLS connection now */
1264
0
          result = smtp_perform_starttls(data, smtpc);
1265
0
        else if(data->set.use_ssl == CURLUSESSL_TRY)
1266
          /* Fallback and carry on with authentication */
1267
0
          result = smtp_perform_authentication(data, smtpc);
1268
0
        else {
1269
0
          failf(data, "STARTTLS not supported.");
1270
0
          result = CURLE_USE_SSL_FAILED;
1271
0
        }
1272
0
      }
1273
0
      else
1274
0
        result = smtp_perform_authentication(data, smtpc);
1275
0
    }
1276
0
  }
1277
0
  else {
1278
0
    failf(data, "Unexpectedly short EHLO response");
1279
0
    result = CURLE_WEIRD_SERVER_REPLY;
1280
0
  }
1281
1282
0
  return result;
1283
0
}
1284
1285
/* For HELO responses */
1286
static CURLcode smtp_state_helo_resp(struct Curl_easy *data,
1287
                                     struct smtp_conn *smtpc,
1288
                                     int smtpcode,
1289
                                     smtpstate instate)
1290
0
{
1291
0
  CURLcode result = CURLE_OK;
1292
0
  (void)instate;
1293
1294
0
  if(smtpcode / 100 != 2) {
1295
0
    failf(data, "Remote access denied: %d", smtpcode);
1296
0
    result = CURLE_REMOTE_ACCESS_DENIED;
1297
0
  }
1298
0
  else
1299
    /* End of connect phase */
1300
0
    smtp_state(data, smtpc, SMTP_STOP);
1301
1302
0
  return result;
1303
0
}
1304
1305
/* For SASL authentication responses */
1306
static CURLcode smtp_state_auth_resp(struct Curl_easy *data,
1307
                                     struct smtp_conn *smtpc,
1308
                                     int smtpcode,
1309
                                     smtpstate instate)
1310
0
{
1311
0
  CURLcode result = CURLE_OK;
1312
0
  saslprogress progress;
1313
1314
0
  (void)instate;
1315
1316
0
  result = Curl_sasl_continue(&smtpc->sasl, data, smtpcode, &progress);
1317
0
  if(!result)
1318
0
    switch(progress) {
1319
0
    case SASL_DONE:
1320
0
      smtp_state(data, smtpc, SMTP_STOP);  /* Authenticated */
1321
0
      break;
1322
0
    case SASL_IDLE:            /* No mechanism left after cancellation */
1323
0
      failf(data, "Authentication cancelled");
1324
0
      result = CURLE_LOGIN_DENIED;
1325
0
      break;
1326
0
    default:
1327
0
      break;
1328
0
    }
1329
1330
0
  return result;
1331
0
}
1332
1333
/* For command responses */
1334
static CURLcode smtp_state_command_resp(struct Curl_easy *data,
1335
                                        struct smtp_conn *smtpc,
1336
                                        struct SMTP *smtp,
1337
                                        int smtpcode,
1338
                                        smtpstate instate)
1339
0
{
1340
0
  CURLcode result = CURLE_OK;
1341
0
  char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf);
1342
0
  size_t len = smtpc->pp.nfinal;
1343
1344
0
  (void)instate;
1345
1346
0
  if((smtp->rcpt && smtpcode / 100 != 2 && smtpcode != 553 && smtpcode != 1) ||
1347
0
     (!smtp->rcpt && smtpcode / 100 != 2 && smtpcode != 1)) {
1348
0
    failf(data, "Command failed: %d", smtpcode);
1349
0
    result = CURLE_WEIRD_SERVER_REPLY;
1350
0
  }
1351
0
  else {
1352
0
    if(!data->req.no_body)
1353
0
      result = Curl_client_write(data, CLIENTWRITE_BODY, line, len);
1354
1355
0
    if(!result && (smtpcode != 1)) {
1356
0
      if(smtp->rcpt) {
1357
0
        smtp->rcpt = smtp->rcpt->next;
1358
1359
0
        if(smtp->rcpt) {
1360
          /* Send the next command */
1361
0
          result = smtp_perform_command(data, smtpc, smtp);
1362
0
        }
1363
0
        else
1364
          /* End of DO phase */
1365
0
          smtp_state(data, smtpc, SMTP_STOP);
1366
0
      }
1367
0
      else
1368
        /* End of DO phase */
1369
0
        smtp_state(data, smtpc, SMTP_STOP);
1370
0
    }
1371
0
  }
1372
1373
0
  return result;
1374
0
}
1375
1376
/* For MAIL responses */
1377
static CURLcode smtp_state_mail_resp(struct Curl_easy *data,
1378
                                     struct smtp_conn *smtpc,
1379
                                     struct SMTP *smtp,
1380
                                     int smtpcode,
1381
                                     smtpstate instate)
1382
0
{
1383
0
  CURLcode result = CURLE_OK;
1384
0
  (void)instate;
1385
1386
0
  if(smtpcode / 100 != 2) {
1387
0
    failf(data, "MAIL failed: %d", smtpcode);
1388
0
    result = CURLE_SEND_ERROR;
1389
0
  }
1390
0
  else
1391
    /* Start the RCPT TO command */
1392
0
    result = smtp_perform_rcpt_to(data, smtpc, smtp);
1393
1394
0
  return result;
1395
0
}
1396
1397
/* For RCPT responses */
1398
static CURLcode smtp_state_rcpt_resp(struct Curl_easy *data,
1399
                                     struct smtp_conn *smtpc,
1400
                                     struct SMTP *smtp,
1401
                                     int smtpcode,
1402
                                     smtpstate instate)
1403
0
{
1404
0
  CURLcode result = CURLE_OK;
1405
0
  bool is_smtp_err = FALSE;
1406
0
  bool is_smtp_blocking_err = FALSE;
1407
1408
0
  (void)instate;
1409
1410
0
  is_smtp_err = (smtpcode / 100 != 2);
1411
1412
  /* If there is multiple RCPT TO to be issued, it is possible to ignore errors
1413
     and proceed with only the valid addresses. */
1414
0
  is_smtp_blocking_err = (is_smtp_err && !data->set.mail_rcpt_allowfails);
1415
1416
0
  if(is_smtp_err) {
1417
    /* Remembering the last failure which we can report if all "RCPT TO" have
1418
       failed and we cannot proceed. */
1419
0
    smtp->rcpt_last_error = smtpcode;
1420
1421
0
    if(is_smtp_blocking_err) {
1422
0
      failf(data, "RCPT failed: %d", smtpcode);
1423
0
      result = CURLE_SEND_ERROR;
1424
0
    }
1425
0
  }
1426
0
  else {
1427
    /* Some RCPT TO commands have succeeded. */
1428
0
    smtp->rcpt_had_ok = TRUE;
1429
0
  }
1430
1431
0
  if(!is_smtp_blocking_err) {
1432
0
    smtp->rcpt = smtp->rcpt->next;
1433
1434
0
    if(smtp->rcpt)
1435
      /* Send the next RCPT TO command */
1436
0
      result = smtp_perform_rcpt_to(data, smtpc, smtp);
1437
0
    else {
1438
      /* We were not able to issue a successful RCPT TO command while going
1439
         over recipients (potentially multiple). Sending back last error. */
1440
0
      if(!smtp->rcpt_had_ok) {
1441
0
        failf(data, "RCPT failed: %d (last error)", smtp->rcpt_last_error);
1442
0
        result = CURLE_SEND_ERROR;
1443
0
      }
1444
0
      else {
1445
        /* Send the DATA command */
1446
0
        result = Curl_pp_sendf(data, &smtpc->pp, "%s", "DATA");
1447
1448
0
        if(!result)
1449
0
          smtp_state(data, smtpc, SMTP_DATA);
1450
0
      }
1451
0
    }
1452
0
  }
1453
1454
0
  return result;
1455
0
}
1456
1457
/* For DATA response */
1458
static CURLcode smtp_state_data_resp(struct Curl_easy *data,
1459
                                     struct smtp_conn *smtpc,
1460
                                     int smtpcode,
1461
                                     smtpstate instate)
1462
0
{
1463
0
  CURLcode result = CURLE_OK;
1464
0
  (void)instate;
1465
1466
0
  if(smtpcode != 354) {
1467
0
    failf(data, "DATA failed: %d", smtpcode);
1468
0
    result = CURLE_SEND_ERROR;
1469
0
  }
1470
0
  else {
1471
    /* Set the progress upload size */
1472
0
    Curl_pgrsSetUploadSize(data, data->state.infilesize);
1473
1474
    /* SMTP upload */
1475
0
    Curl_xfer_setup_send(data, FIRSTSOCKET);
1476
1477
    /* End of DO phase */
1478
0
    smtp_state(data, smtpc, SMTP_STOP);
1479
0
  }
1480
1481
0
  return result;
1482
0
}
1483
1484
/* For POSTDATA responses, which are received after the entire DATA
1485
   part has been sent to the server */
1486
static CURLcode smtp_state_postdata_resp(struct Curl_easy *data,
1487
                                         struct smtp_conn *smtpc,
1488
                                         int smtpcode,
1489
                                         smtpstate instate)
1490
0
{
1491
0
  CURLcode result = CURLE_OK;
1492
1493
0
  (void)instate;
1494
1495
0
  if(smtpcode != 250)
1496
0
    result = CURLE_WEIRD_SERVER_REPLY;
1497
1498
  /* End of DONE phase */
1499
0
  smtp_state(data, smtpc, SMTP_STOP);
1500
1501
0
  return result;
1502
0
}
1503
1504
static CURLcode smtp_pp_statemachine(struct Curl_easy *data,
1505
                                     struct connectdata *conn)
1506
0
{
1507
0
  CURLcode result = CURLE_OK;
1508
0
  int smtpcode;
1509
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
1510
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1511
0
  size_t nread = 0;
1512
1513
0
  if(!smtpc || !smtp)
1514
0
    return CURLE_FAILED_INIT;
1515
1516
  /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */
1517
0
upgrade_tls:
1518
0
  if(smtpc->state == SMTP_UPGRADETLS) {
1519
0
    result = smtp_perform_upgrade_tls(data, smtpc);
1520
0
    if(result || (smtpc->state == SMTP_UPGRADETLS))
1521
0
      return result;
1522
0
  }
1523
1524
  /* Flush any data that needs to be sent */
1525
0
  if(smtpc->pp.sendleft)
1526
0
    return Curl_pp_flushsend(data, &smtpc->pp);
1527
1528
0
  do {
1529
    /* Read the response from the server */
1530
0
    result = Curl_pp_readresp(data, FIRSTSOCKET, &smtpc->pp,
1531
0
                              &smtpcode, &nread);
1532
0
    if(result)
1533
0
      return result;
1534
1535
    /* Store the latest response for later retrieval if necessary */
1536
0
    if(smtpc->state != SMTP_QUIT && smtpcode != 1)
1537
0
      data->info.httpcode = smtpcode;
1538
1539
0
    if(!smtpcode)
1540
0
      break;
1541
1542
    /* We have now received a full SMTP server response */
1543
0
    switch(smtpc->state) {
1544
0
    case SMTP_SERVERGREET:
1545
0
      result = smtp_state_servergreet_resp(data, smtpc,
1546
0
                                           smtpcode, smtpc->state);
1547
0
      break;
1548
1549
0
    case SMTP_EHLO:
1550
0
      result = smtp_state_ehlo_resp(data, smtpc, smtpcode, smtpc->state);
1551
0
      break;
1552
1553
0
    case SMTP_HELO:
1554
0
      result = smtp_state_helo_resp(data, smtpc, smtpcode, smtpc->state);
1555
0
      break;
1556
1557
0
    case SMTP_STARTTLS:
1558
0
      result = smtp_state_starttls_resp(data, smtpc, smtpcode, smtpc->state);
1559
      /* During UPGRADETLS, leave the read loop as we need to connect
1560
       * (e.g. TLS handshake) before we continue sending/receiving. */
1561
0
      if(!result && (smtpc->state == SMTP_UPGRADETLS))
1562
0
        goto upgrade_tls;
1563
0
      break;
1564
1565
0
    case SMTP_AUTH:
1566
0
      result = smtp_state_auth_resp(data, smtpc, smtpcode, smtpc->state);
1567
0
      break;
1568
1569
0
    case SMTP_COMMAND:
1570
0
      result = smtp_state_command_resp(data, smtpc, smtp,
1571
0
                                       smtpcode, smtpc->state);
1572
0
      break;
1573
1574
0
    case SMTP_MAIL:
1575
0
      result = smtp_state_mail_resp(data, smtpc, smtp, smtpcode, smtpc->state);
1576
0
      break;
1577
1578
0
    case SMTP_RCPT:
1579
0
      result = smtp_state_rcpt_resp(data, smtpc, smtp, smtpcode, smtpc->state);
1580
0
      break;
1581
1582
0
    case SMTP_DATA:
1583
0
      result = smtp_state_data_resp(data, smtpc, smtpcode, smtpc->state);
1584
0
      break;
1585
1586
0
    case SMTP_POSTDATA:
1587
0
      result = smtp_state_postdata_resp(data, smtpc, smtpcode, smtpc->state);
1588
0
      break;
1589
1590
0
    case SMTP_QUIT:
1591
0
    default:
1592
      /* internal error */
1593
0
      smtp_state(data, smtpc, SMTP_STOP);
1594
0
      break;
1595
0
    }
1596
0
  } while(!result && smtpc->state != SMTP_STOP &&
1597
0
          Curl_pp_moredata(&smtpc->pp));
1598
1599
0
  return result;
1600
0
}
1601
1602
/* Called repeatedly until done from multi.c */
1603
static CURLcode smtp_multi_statemach(struct Curl_easy *data, bool *done)
1604
0
{
1605
0
  CURLcode result = CURLE_OK;
1606
0
  struct smtp_conn *smtpc =
1607
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1608
1609
0
  *done = FALSE;
1610
0
  if(!smtpc)
1611
0
    return CURLE_FAILED_INIT;
1612
1613
0
  result = Curl_pp_statemach(data, &smtpc->pp, FALSE, FALSE);
1614
0
  *done = (smtpc->state == SMTP_STOP);
1615
0
  return result;
1616
0
}
1617
1618
static CURLcode smtp_block_statemach(struct Curl_easy *data,
1619
                                     struct smtp_conn *smtpc,
1620
                                     bool disconnecting)
1621
0
{
1622
0
  CURLcode result = CURLE_OK;
1623
1624
0
  while(smtpc->state != SMTP_STOP && !result)
1625
0
    result = Curl_pp_statemach(data, &smtpc->pp, TRUE, disconnecting);
1626
1627
0
  return result;
1628
0
}
1629
1630
/* For the SMTP "protocol connect" and "doing" phases only */
1631
static CURLcode smtp_pollset(struct Curl_easy *data,
1632
                             struct easy_pollset *ps)
1633
0
{
1634
0
  struct smtp_conn *smtpc =
1635
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1636
0
  return smtpc ? Curl_pp_pollset(data, &smtpc->pp, ps) : CURLE_OK;
1637
0
}
1638
1639
/* SASL parameters for the smtp protocol */
1640
static const struct SASLproto saslsmtp = {
1641
  "smtp",               /* The service name */
1642
  smtp_perform_auth,    /* Send authentication command */
1643
  smtp_continue_auth,   /* Send authentication continuation */
1644
  smtp_cancel_auth,     /* Cancel authentication */
1645
  smtp_get_message,     /* Get SASL response message */
1646
  512 - 8,              /* Max line len - strlen("AUTH ") - 1 space - crlf */
1647
  334,                  /* Code received when continuation is expected */
1648
  235,                  /* Code to receive upon authentication success */
1649
  SASL_AUTH_DEFAULT,    /* Default mechanisms */
1650
  SASL_FLAG_BASE64      /* Configuration flags */
1651
};
1652
1653
/***********************************************************************
1654
 *
1655
 * smtp_connect()
1656
 *
1657
 * This function should do everything that is to be considered a part of
1658
 * the connection phase.
1659
 *
1660
 * The variable pointed to by 'done' will be TRUE if the protocol-layer
1661
 * connect phase is done when this function returns, or FALSE if not.
1662
 */
1663
static CURLcode smtp_connect(struct Curl_easy *data, bool *done)
1664
0
{
1665
0
  struct smtp_conn *smtpc =
1666
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1667
0
  CURLcode result = CURLE_OK;
1668
1669
0
  *done = FALSE; /* default to not done yet */
1670
0
  if(!smtpc)
1671
0
    return CURLE_FAILED_INIT;
1672
1673
0
  PINGPONG_SETUP(&smtpc->pp, smtp_pp_statemachine, smtp_endofresp);
1674
1675
  /* Initialize the SASL storage */
1676
0
  Curl_sasl_init(&smtpc->sasl, data, &saslsmtp);
1677
1678
  /* Initialise the pingpong layer */
1679
0
  Curl_pp_init(&smtpc->pp, Curl_pgrs_now(data));
1680
1681
  /* Parse the URL options */
1682
0
  result = smtp_parse_url_options(data->conn, smtpc);
1683
0
  if(result)
1684
0
    return result;
1685
1686
  /* Parse the URL path */
1687
0
  result = smtp_parse_url_path(data, smtpc);
1688
0
  if(result)
1689
0
    return result;
1690
1691
  /* Start off waiting for the server greeting response */
1692
0
  smtp_state(data, smtpc, SMTP_SERVERGREET);
1693
1694
0
  result = smtp_multi_statemach(data, done);
1695
1696
0
  return result;
1697
0
}
1698
1699
/***********************************************************************
1700
 *
1701
 * smtp_done()
1702
 *
1703
 * The DONE function. This does what needs to be done after a single DO has
1704
 * performed.
1705
 *
1706
 * Input argument is already checked for validity.
1707
 */
1708
static CURLcode smtp_done(struct Curl_easy *data, CURLcode status,
1709
                          bool premature)
1710
0
{
1711
0
  struct smtp_conn *smtpc =
1712
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1713
0
  CURLcode result = CURLE_OK;
1714
0
  struct connectdata *conn = data->conn;
1715
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1716
1717
0
  (void)premature;
1718
1719
0
  if(!smtpc)
1720
0
    return CURLE_FAILED_INIT;
1721
0
  if(!smtp)
1722
0
    return CURLE_OK;
1723
1724
  /* Cleanup our per-request based variables */
1725
0
  Curl_safefree(smtp->custom);
1726
1727
0
  if(status) {
1728
0
    connclose(conn, "SMTP done with bad status"); /* marked for closure */
1729
0
    result = status;         /* use the already set error code */
1730
0
  }
1731
0
  else if(!data->set.connect_only && data->set.mail_rcpt &&
1732
0
          (data->state.upload || IS_MIME_POST(data))) {
1733
1734
0
    smtp_state(data, smtpc, SMTP_POSTDATA);
1735
1736
    /* Run the state-machine */
1737
0
    result = smtp_block_statemach(data, smtpc, FALSE);
1738
0
  }
1739
1740
  /* Clear the transfer mode for the next request */
1741
0
  smtp->transfer = PPTRANSFER_BODY;
1742
0
  CURL_TRC_SMTP(data, "smtp_done(status=%d, premature=%d) -> %d",
1743
0
                status, premature, result);
1744
0
  return result;
1745
0
}
1746
1747
/***********************************************************************
1748
 *
1749
 * smtp_perform()
1750
 *
1751
 * This is the actual DO function for SMTP. Transfer a mail, send a command
1752
 * or get some data according to the options previously setup.
1753
 */
1754
static CURLcode smtp_perform(struct Curl_easy *data,
1755
                             struct smtp_conn *smtpc,
1756
                             struct SMTP *smtp,
1757
                             bool *connected,
1758
                             bool *dophase_done)
1759
0
{
1760
  /* This is SMTP and no proxy */
1761
0
  CURLcode result = CURLE_OK;
1762
1763
0
  CURL_TRC_SMTP(data, "smtp_perform(), start");
1764
1765
0
  if(data->req.no_body) {
1766
    /* Requested no body means no transfer */
1767
0
    smtp->transfer = PPTRANSFER_INFO;
1768
0
  }
1769
1770
0
  *dophase_done = FALSE; /* not done yet */
1771
1772
  /* Store the first recipient (or NULL if not specified) */
1773
0
  smtp->rcpt = data->set.mail_rcpt;
1774
1775
  /* Track of whether we have successfully sent at least one RCPT TO command */
1776
0
  smtp->rcpt_had_ok = FALSE;
1777
1778
  /* Track of the last error we have received by sending RCPT TO command */
1779
0
  smtp->rcpt_last_error = 0;
1780
1781
  /* Initial data character is the first character in line: it is implicitly
1782
     preceded by a virtual CRLF. */
1783
0
  smtp->trailing_crlf = TRUE;
1784
0
  smtp->eob = 2;
1785
1786
  /* Start the first command in the DO phase */
1787
0
  if((data->state.upload || IS_MIME_POST(data)) && data->set.mail_rcpt)
1788
    /* MAIL transfer */
1789
0
    result = smtp_perform_mail(data, smtpc, smtp);
1790
0
  else
1791
    /* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */
1792
0
    result = smtp_perform_command(data, smtpc, smtp);
1793
1794
0
  if(result)
1795
0
    goto out;
1796
1797
  /* Run the state-machine */
1798
0
  result = smtp_multi_statemach(data, dophase_done);
1799
1800
0
  *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET);
1801
1802
0
out:
1803
0
  CURL_TRC_SMTP(data, "smtp_perform() -> %d, connected=%d, done=%d",
1804
0
                result, *connected, *dophase_done);
1805
0
  return result;
1806
0
}
1807
1808
/* Call this when the DO phase has completed */
1809
static CURLcode smtp_dophase_done(struct Curl_easy *data,
1810
                                  struct SMTP *smtp,
1811
                                  bool connected)
1812
0
{
1813
0
  (void)connected;
1814
1815
0
  if(smtp->transfer != PPTRANSFER_BODY)
1816
    /* no data to transfer */
1817
0
    Curl_xfer_setup_nop(data);
1818
1819
0
  return CURLE_OK;
1820
0
}
1821
1822
/***********************************************************************
1823
 *
1824
 * smtp_regular_transfer()
1825
 *
1826
 * The input argument is already checked for validity.
1827
 *
1828
 * Performs all commands done before a regular transfer between a local and a
1829
 * remote host.
1830
 */
1831
static CURLcode smtp_regular_transfer(struct Curl_easy *data,
1832
                                      struct smtp_conn *smtpc,
1833
                                      struct SMTP *smtp,
1834
                                      bool *dophase_done)
1835
0
{
1836
0
  CURLcode result = CURLE_OK;
1837
0
  bool connected = FALSE;
1838
1839
  /* Make sure size is unknown at this point */
1840
0
  data->req.size = -1;
1841
1842
  /* Set the progress data */
1843
0
  Curl_pgrsReset(data);
1844
1845
  /* Carry out the perform */
1846
0
  result = smtp_perform(data, smtpc, smtp, &connected, dophase_done);
1847
1848
  /* Perform post DO phase operations if necessary */
1849
0
  if(!result && *dophase_done)
1850
0
    result = smtp_dophase_done(data, smtp, connected);
1851
1852
0
  CURL_TRC_SMTP(data, "smtp_regular_transfer() -> %d, done=%d",
1853
0
                result, *dophase_done);
1854
0
  return result;
1855
0
}
1856
1857
/***********************************************************************
1858
 *
1859
 * smtp_do()
1860
 *
1861
 * This function is registered as 'curl_do' function. It decodes the path
1862
 * parts etc as a wrapper to the actual DO function (smtp_perform).
1863
 *
1864
 * The input argument is already checked for validity.
1865
 */
1866
static CURLcode smtp_do(struct Curl_easy *data, bool *done)
1867
0
{
1868
0
  struct smtp_conn *smtpc =
1869
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1870
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1871
0
  CURLcode result = CURLE_OK;
1872
1873
0
  DEBUGASSERT(data);
1874
0
  DEBUGASSERT(data->conn);
1875
0
  *done = FALSE; /* default to false */
1876
0
  if(!smtpc || !smtp)
1877
0
    return CURLE_FAILED_INIT;
1878
1879
  /* Parse the custom request */
1880
0
  result = smtp_parse_custom_request(data, smtp);
1881
0
  if(result)
1882
0
    return result;
1883
1884
0
  result = smtp_regular_transfer(data, smtpc, smtp, done);
1885
0
  CURL_TRC_SMTP(data, "smtp_do() -> %d, done=%d", result, *done);
1886
0
  return result;
1887
0
}
1888
1889
/***********************************************************************
1890
 *
1891
 * smtp_disconnect()
1892
 *
1893
 * Disconnect from an SMTP server. Cleanup protocol-specific per-connection
1894
 * resources. BLOCKING.
1895
 */
1896
static CURLcode smtp_disconnect(struct Curl_easy *data,
1897
                                struct connectdata *conn,
1898
                                bool dead_connection)
1899
0
{
1900
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
1901
1902
0
  if(!smtpc)
1903
0
    return CURLE_FAILED_INIT;
1904
1905
  /* We cannot send quit unconditionally. If this connection is stale or
1906
     bad in any way, sending quit and waiting around here will make the
1907
     disconnect wait in vain and cause more problems than we need to. */
1908
1909
0
  if(!dead_connection && conn->bits.protoconnstart &&
1910
0
     !Curl_pp_needs_flush(data, &smtpc->pp)) {
1911
0
    if(!smtp_perform_quit(data, smtpc))
1912
0
      (void)smtp_block_statemach(data, smtpc, TRUE); /* ignore on QUIT */
1913
0
  }
1914
1915
0
  CURL_TRC_SMTP(data, "smtp_disconnect(), finished");
1916
0
  return CURLE_OK;
1917
0
}
1918
1919
/* Called from multi.c while DOing */
1920
static CURLcode smtp_doing(struct Curl_easy *data, bool *dophase_done)
1921
0
{
1922
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1923
0
  CURLcode result;
1924
1925
0
  if(!smtp)
1926
0
    return CURLE_FAILED_INIT;
1927
0
  result = smtp_multi_statemach(data, dophase_done);
1928
0
  if(result)
1929
0
    DEBUGF(infof(data, "DO phase failed"));
1930
0
  else if(*dophase_done) {
1931
0
    result = smtp_dophase_done(data, smtp, FALSE /* not connected */);
1932
1933
0
    DEBUGF(infof(data, "DO phase is complete"));
1934
0
  }
1935
1936
0
  CURL_TRC_SMTP(data, "smtp_doing() -> %d, done=%d", result, *dophase_done);
1937
0
  return result;
1938
0
}
1939
1940
static void smtp_easy_dtor(void *key, size_t klen, void *entry)
1941
0
{
1942
0
  struct SMTP *smtp = entry;
1943
0
  (void)key;
1944
0
  (void)klen;
1945
0
  curlx_free(smtp);
1946
0
}
1947
1948
static void smtp_conn_dtor(void *key, size_t klen, void *entry)
1949
0
{
1950
0
  struct smtp_conn *smtpc = entry;
1951
0
  (void)key;
1952
0
  (void)klen;
1953
0
  Curl_pp_disconnect(&smtpc->pp);
1954
0
  Curl_safefree(smtpc->domain);
1955
0
  curlx_free(smtpc);
1956
0
}
1957
1958
static CURLcode smtp_setup_connection(struct Curl_easy *data,
1959
                                      struct connectdata *conn)
1960
0
{
1961
0
  struct smtp_conn *smtpc;
1962
0
  struct SMTP *smtp;
1963
0
  CURLcode result = CURLE_OK;
1964
1965
0
  smtpc = curlx_calloc(1, sizeof(*smtpc));
1966
0
  if(!smtpc ||
1967
0
     Curl_conn_meta_set(conn, CURL_META_SMTP_CONN, smtpc, smtp_conn_dtor)) {
1968
0
    result = CURLE_OUT_OF_MEMORY;
1969
0
    goto out;
1970
0
  }
1971
1972
0
  smtp = curlx_calloc(1, sizeof(*smtp));
1973
0
  if(!smtp ||
1974
0
     Curl_meta_set(data, CURL_META_SMTP_EASY, smtp, smtp_easy_dtor))
1975
0
    result = CURLE_OUT_OF_MEMORY;
1976
1977
0
out:
1978
0
  CURL_TRC_SMTP(data, "smtp_setup_connection() -> %d", result);
1979
0
  return result;
1980
0
}
1981
1982
/*
1983
 * SMTP protocol handler.
1984
 */
1985
static const struct Curl_protocol Curl_protocol_smtp = {
1986
  smtp_setup_connection,            /* setup_connection */
1987
  smtp_do,                          /* do_it */
1988
  smtp_done,                        /* done */
1989
  ZERO_NULL,                        /* do_more */
1990
  smtp_connect,                     /* connect_it */
1991
  smtp_multi_statemach,             /* connecting */
1992
  smtp_doing,                       /* doing */
1993
  smtp_pollset,                     /* proto_pollset */
1994
  smtp_pollset,                     /* doing_pollset */
1995
  ZERO_NULL,                        /* domore_pollset */
1996
  ZERO_NULL,                        /* perform_pollset */
1997
  smtp_disconnect,                  /* disconnect */
1998
  ZERO_NULL,                        /* write_resp */
1999
  ZERO_NULL,                        /* write_resp_hd */
2000
  ZERO_NULL,                        /* connection_check */
2001
  ZERO_NULL,                        /* attach connection */
2002
  ZERO_NULL,                        /* follow */
2003
};
2004
2005
#endif /* CURL_DISABLE_SMTP */
2006
2007
/*
2008
 * SMTP protocol handler.
2009
 */
2010
const struct Curl_scheme Curl_scheme_smtp = {
2011
  "smtp",                           /* scheme */
2012
#ifdef CURL_DISABLE_SMTP
2013
  ZERO_NULL,
2014
#else
2015
  &Curl_protocol_smtp,
2016
#endif
2017
  CURLPROTO_SMTP,                   /* protocol */
2018
  CURLPROTO_SMTP,                   /* family */
2019
  PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
2020
  PROTOPT_URLOPTIONS | PROTOPT_SSL_REUSE | PROTOPT_CONN_REUSE,
2021
  PORT_SMTP,                        /* defport */
2022
};
2023
2024
/*
2025
 * SMTPS protocol handler.
2026
 */
2027
const struct Curl_scheme Curl_scheme_smtps = {
2028
  "smtps",                          /* scheme */
2029
#if defined(CURL_DISABLE_SMTP) || !defined(USE_SSL)
2030
  ZERO_NULL,
2031
#else
2032
  &Curl_protocol_smtp,
2033
#endif
2034
  CURLPROTO_SMTPS,                  /* protocol */
2035
  CURLPROTO_SMTP,                   /* family */
2036
  PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */
2037
  PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS | PROTOPT_CONN_REUSE,
2038
  PORT_SMTPS,                       /* defport */
2039
};