Coverage Report

Created: 2025-12-14 06:23

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