Coverage Report

Created: 2025-08-24 06:12

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