Coverage Report

Created: 2025-08-26 07:08

/src/PROJ/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
0
#define CURL_META_SMTP_EASY   "meta:proto:smtp:easy"
91
/* meta key for storing protocol meta at connection */
92
0
#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
0
{
269
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
270
0
  bool result = FALSE;
271
0
  (void)data;
272
273
0
  DEBUGASSERT(smtpc);
274
0
  if(!smtpc)
275
0
    return FALSE;
276
277
  /* Nothing for us */
278
0
  if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
279
0
    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
0
  if(line[3] == ' ' || len == 5) {
286
0
    char tmpline[6];
287
0
    curl_off_t code;
288
0
    const char *p = tmpline;
289
0
    result = TRUE;
290
0
    memcpy(tmpline, line, (len == 5 ? 5 : 3));
291
0
    tmpline[len == 5 ? 5 : 3 ] = 0;
292
0
    if(curlx_str_number(&p, &code, len == 5 ? 99999 : 999))
293
0
      return FALSE;
294
0
    *resp = (int) code;
295
296
    /* Make sure real server never sends internal value */
297
0
    if(*resp == 1)
298
0
      *resp = 0;
299
0
  }
300
  /* Do we have a multiline (continuation) response? */
301
0
  else if(line[3] == '-' &&
302
0
          (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) {
303
0
    result = TRUE;
304
0
    *resp = 1;  /* Internal response code */
305
0
  }
306
307
0
  return result;
308
0
}
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
0
{
318
0
  struct smtp_conn *smtpc =
319
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
320
0
  char *message;
321
0
  size_t len;
322
323
0
  if(!smtpc)
324
0
    return CURLE_FAILED_INIT;
325
326
0
  message = curlx_dyn_ptr(&smtpc->pp.recvbuf);
327
0
  len = smtpc->pp.nfinal;
328
0
  if(len > 4) {
329
    /* Find the start of the message */
330
0
    len -= 4;
331
0
    for(message += 4; *message == ' ' || *message == '\t'; message++, len--)
332
0
      ;
333
334
    /* Find the end of the message */
335
0
    while(len--)
336
0
      if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
337
0
         message[len] != '\t')
338
0
        break;
339
340
    /* Terminate the message */
341
0
    message[++len] = '\0';
342
0
    Curl_bufref_set(out, message, len, NULL);
343
0
  }
344
0
  else
345
    /* junk input => zero length output */
346
0
    Curl_bufref_set(out, "", 0, NULL);
347
348
0
  return CURLE_OK;
349
0
}
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
0
{
361
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
362
  /* for debug purposes */
363
0
  static const char * const names[] = {
364
0
    "STOP",
365
0
    "SERVERGREET",
366
0
    "EHLO",
367
0
    "HELO",
368
0
    "STARTTLS",
369
0
    "UPGRADETLS",
370
0
    "AUTH",
371
0
    "COMMAND",
372
0
    "MAIL",
373
0
    "RCPT",
374
0
    "DATA",
375
0
    "POSTDATA",
376
0
    "QUIT",
377
    /* LAST */
378
0
  };
379
380
0
  if(smtpc->state != newstate)
381
0
    CURL_TRC_SMTP(data, "state change from %s to %s",
382
0
                  names[smtpc->state], names[newstate]);
383
#else
384
  (void)data;
385
#endif
386
387
0
  smtpc->state = newstate;
388
0
}
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
0
{
400
0
  CURLcode result = CURLE_OK;
401
402
0
  smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */
403
0
  smtpc->sasl.authused = SASL_AUTH_NONE;  /* Clear the authentication mechanism
404
                                             used for esmtp connections */
405
0
  smtpc->tls_supported = FALSE;           /* Clear the TLS capability */
406
0
  smtpc->auth_supported = FALSE;          /* Clear the AUTH capability */
407
408
  /* Send the EHLO command */
409
0
  result = Curl_pp_sendf(data, &smtpc->pp, "EHLO %s", smtpc->domain);
410
411
0
  if(!result)
412
0
    smtp_state(data, smtpc, SMTP_EHLO);
413
414
0
  return result;
415
0
}
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
0
{
426
0
  CURLcode result = CURLE_OK;
427
428
0
  smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used
429
                                            in smtp connections */
430
431
  /* Send the HELO command */
432
0
  result = Curl_pp_sendf(data, &smtpc->pp, "HELO %s", smtpc->domain);
433
434
0
  if(!result)
435
0
    smtp_state(data, smtpc, SMTP_HELO);
436
437
0
  return result;
438
0
}
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
0
{
449
  /* Send the STARTTLS command */
450
0
  CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "STARTTLS");
451
452
0
  if(!result)
453
0
    smtp_state(data, smtpc, SMTP_STARTTLS);
454
455
0
  return result;
456
0
}
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
0
{
511
0
  CURLcode result = CURLE_OK;
512
0
  struct smtp_conn *smtpc =
513
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
514
0
  const char *ir = (const char *) Curl_bufref_ptr(initresp);
515
516
0
  if(!smtpc)
517
0
    return CURLE_FAILED_INIT;
518
519
0
  if(ir) {                                  /* AUTH <mech> ...<crlf> */
520
    /* Send the AUTH command with the initial response */
521
0
    result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s %s", mech, ir);
522
0
  }
523
0
  else {
524
    /* Send the AUTH command */
525
0
    result = Curl_pp_sendf(data, &smtpc->pp, "AUTH %s", mech);
526
0
  }
527
528
0
  return result;
529
0
}
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
0
{
541
0
  struct smtp_conn *smtpc =
542
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
543
544
0
  (void)mech;
545
0
  if(!smtpc)
546
0
    return CURLE_FAILED_INIT;
547
0
  return Curl_pp_sendf(data, &smtpc->pp,
548
0
                       "%s", (const char *) Curl_bufref_ptr(resp));
549
0
}
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
0
{
559
0
  struct smtp_conn *smtpc =
560
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
561
562
0
  (void)mech;
563
0
  if(!smtpc)
564
0
    return CURLE_FAILED_INIT;
565
0
  return Curl_pp_sendf(data, &smtpc->pp, "*");
566
0
}
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
0
{
578
0
  CURLcode result = CURLE_OK;
579
0
  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
0
  if(!smtpc->auth_supported ||
584
0
     !Curl_sasl_can_authenticate(&smtpc->sasl, data)) {
585
0
    smtp_state(data, smtpc, SMTP_STOP);
586
0
    return result;
587
0
  }
588
589
  /* Calculate the SASL login details */
590
0
  result = Curl_sasl_start(&smtpc->sasl, data, FALSE, &progress);
591
592
0
  if(!result) {
593
0
    if(progress == SASL_INPROGRESS)
594
0
      smtp_state(data, smtpc, SMTP_AUTH);
595
0
    else
596
0
      result = Curl_sasl_is_blocked(&smtpc->sasl, data);
597
0
  }
598
599
0
  return result;
600
0
}
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
0
{
612
0
  CURLcode result = CURLE_OK;
613
614
0
  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
0
    bool utf8 = FALSE;
620
621
0
    if((!smtp->custom) || (!smtp->custom[0])) {
622
0
      char *address = NULL;
623
0
      struct hostname host = { NULL, NULL, NULL, NULL };
624
0
      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
0
      result = smtp_parse_address(smtp->rcpt->data,
629
0
                                  &address, &host, &suffix);
630
0
      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
0
      utf8 = (smtpc->utf8_supported) &&
636
0
             ((host.encalloc) || (!Curl_is_ASCII_name(address)) ||
637
0
              (!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
0
      result = Curl_pp_sendf(data, &smtpc->pp, "VRFY %s%s%s%s",
642
0
                             address,
643
0
                             host.name ? "@" : "",
644
0
                             host.name ? host.name : "",
645
0
                             utf8 ? " SMTPUTF8" : "");
646
647
0
      Curl_free_idnconverted_hostname(&host);
648
0
      free(address);
649
0
    }
650
0
    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
0
      utf8 = (smtpc->utf8_supported) && (!strcmp(smtp->custom, "EXPN"));
654
655
      /* Send the custom recipient based command such as the EXPN command */
656
0
      result = Curl_pp_sendf(data, &smtpc->pp,
657
0
                             "%s %s%s", smtp->custom,
658
0
                             smtp->rcpt->data,
659
0
                             utf8 ? " SMTPUTF8" : "");
660
0
    }
661
0
  }
662
0
  else
663
    /* Send the non-recipient based command such as HELP */
664
0
    result = Curl_pp_sendf(data, &smtpc->pp, "%s",
665
0
                           smtp->custom && smtp->custom[0] != '\0' ?
666
0
                           smtp->custom : "HELP");
667
668
0
  if(!result)
669
0
    smtp_state(data, smtpc, SMTP_COMMAND);
670
671
0
  return result;
672
0
}
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
0
{
684
0
  char *from = NULL;
685
0
  char *auth = NULL;
686
0
  char *size = NULL;
687
0
  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
0
  bool utf8 = FALSE;
694
695
  /* Calculate the FROM parameter */
696
0
  if(data->set.str[STRING_MAIL_FROM]) {
697
0
    char *address = NULL;
698
0
    struct hostname host = { NULL, NULL, NULL, NULL };
699
0
    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
0
    result = smtp_parse_address(data->set.str[STRING_MAIL_FROM],
704
0
                                &address, &host, &suffix);
705
0
    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
0
    utf8 = (smtpc->utf8_supported) &&
711
0
           ((host.encalloc) || (!Curl_is_ASCII_name(address)) ||
712
0
            (!Curl_is_ASCII_name(host.name)));
713
714
0
    if(host.name) {
715
0
      from = aprintf("<%s@%s>%s", address, host.name, suffix);
716
717
0
      Curl_free_idnconverted_hostname(&host);
718
0
    }
719
0
    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
0
      from = aprintf("<%s>%s", address, suffix);
723
724
0
    free(address);
725
0
  }
726
0
  else
727
    /* Null reverse-path, RFC-5321, sect. 3.6.3 */
728
0
    from = strdup("<>");
729
730
0
  if(!from) {
731
0
    result = CURLE_OUT_OF_MEMORY;
732
0
    goto out;
733
0
  }
734
735
  /* Calculate the optional AUTH parameter */
736
0
  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
0
#ifndef CURL_DISABLE_MIME
778
  /* Prepare the mime data if some. */
779
0
  if(data->set.mimepost.kind != MIMEKIND_NONE) {
780
    /* Use the whole structure as data. */
781
0
    data->set.mimepost.flags &= ~(unsigned int)MIME_BODY_ONLY;
782
783
    /* Add external headers and mime version. */
784
0
    curl_mime_headers(&data->set.mimepost, data->set.headers, 0);
785
0
    result = Curl_mime_prepare_headers(data, &data->set.mimepost, NULL,
786
0
                                       NULL, MIMESTRATEGY_MAIL);
787
788
0
    if(!result)
789
0
      if(!Curl_checkheaders(data, STRCONST("Mime-Version")))
790
0
        result = Curl_mime_add_header(&data->set.mimepost.curlheaders,
791
0
                                      "Mime-Version: 1.0");
792
793
0
    if(!result)
794
0
      result = Curl_creader_set_mime(data, &data->set.mimepost);
795
0
    if(result)
796
0
      goto out;
797
0
    data->state.infilesize = Curl_creader_total_length(data);
798
0
  }
799
0
  else
800
0
#endif
801
0
  {
802
0
    result = Curl_creader_set_fread(data, data->state.infilesize);
803
0
    if(result)
804
0
      goto out;
805
0
  }
806
807
  /* Calculate the optional SIZE parameter */
808
0
  if(smtpc->size_supported && data->state.infilesize > 0) {
809
0
    size = aprintf("%" FMT_OFF_T, data->state.infilesize);
810
811
0
    if(!size) {
812
0
      result = CURLE_OUT_OF_MEMORY;
813
0
      goto out;
814
0
    }
815
0
  }
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
0
  if(smtpc->utf8_supported && !utf8) {
822
0
    struct curl_slist *rcpt = smtp->rcpt;
823
824
0
    while(rcpt && !utf8) {
825
      /* Does the hostname contain non-ASCII characters? */
826
0
      if(!Curl_is_ASCII_name(rcpt->data))
827
0
        utf8 = TRUE;
828
829
0
      rcpt = rcpt->next;
830
0
    }
831
0
  }
832
833
  /* Add the client reader doing STMP EOB escaping */
834
0
  result = cr_eob_add(data);
835
0
  if(result)
836
0
    goto out;
837
838
  /* Send the MAIL command */
839
0
  result = Curl_pp_sendf(data, &smtpc->pp,
840
0
                         "MAIL FROM:%s%s%s%s%s%s",
841
0
                         from,                 /* Mandatory                 */
842
0
                         auth ? " AUTH=" : "", /* Optional on AUTH support  */
843
0
                         auth ? auth : "",     /*                           */
844
0
                         size ? " SIZE=" : "", /* Optional on SIZE support  */
845
0
                         size ? size : "",     /*                           */
846
0
                         utf8 ? " SMTPUTF8"    /* Internationalised mailbox */
847
0
                               : "");          /* included in our envelope  */
848
849
0
out:
850
0
  free(from);
851
0
  free(auth);
852
0
  free(size);
853
854
0
  if(!result)
855
0
    smtp_state(data, smtpc, SMTP_MAIL);
856
857
0
  return result;
858
0
}
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
0
{
871
0
  CURLcode result = CURLE_OK;
872
0
  char *address = NULL;
873
0
  struct hostname host = { NULL, NULL, NULL, NULL };
874
0
  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
0
  result = smtp_parse_address(smtp->rcpt->data,
879
0
                              &address, &host, &suffix);
880
0
  if(result)
881
0
    return result;
882
883
  /* Send the RCPT TO command */
884
0
  if(host.name)
885
0
    result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s@%s>%s",
886
0
                           address, host.name, suffix);
887
0
  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
0
    result = Curl_pp_sendf(data, &smtpc->pp, "RCPT TO:<%s>%s",
891
0
                           address, suffix);
892
893
0
  Curl_free_idnconverted_hostname(&host);
894
0
  free(address);
895
896
0
  if(!result)
897
0
    smtp_state(data, smtpc, SMTP_RCPT);
898
899
0
  return result;
900
0
}
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
0
{
911
  /* Send the QUIT command */
912
0
  CURLcode result = Curl_pp_sendf(data, &smtpc->pp, "%s", "QUIT");
913
914
0
  if(!result)
915
0
    smtp_state(data, smtpc, SMTP_QUIT);
916
917
0
  return result;
918
0
}
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
0
{
926
0
  CURLcode result = CURLE_OK;
927
0
  (void)instate; /* no use for this yet */
928
929
0
  if(smtpcode/100 != 2) {
930
0
    failf(data, "Got unexpected smtp-server response: %d", smtpcode);
931
0
    result = CURLE_WEIRD_SERVER_REPLY;
932
0
  }
933
0
  else
934
0
    result = smtp_perform_ehlo(data, smtpc);
935
936
0
  return result;
937
0
}
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
0
{
945
0
  CURLcode result = CURLE_OK;
946
0
  (void)instate; /* no use for this yet */
947
948
  /* Pipelining in response is forbidden. */
949
0
  if(smtpc->pp.overflow)
950
0
    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
0
}
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
0
{
972
0
  CURLcode result = CURLE_OK;
973
0
  const char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf);
974
0
  size_t len = smtpc->pp.nfinal;
975
976
0
  (void)instate; /* no use for this yet */
977
978
0
  if(smtpcode/100 != 2 && smtpcode != 1) {
979
0
    if(data->set.use_ssl <= CURLUSESSL_TRY
980
0
       || Curl_conn_is_ssl(data->conn, FIRSTSOCKET))
981
0
      result = smtp_perform_helo(data, smtpc);
982
0
    else {
983
0
      failf(data, "Remote access denied: %d", smtpcode);
984
0
      result = CURLE_REMOTE_ACCESS_DENIED;
985
0
    }
986
0
  }
987
0
  else if(len >= 4) {
988
0
    line += 4;
989
0
    len -= 4;
990
991
    /* Does the server support the STARTTLS capability? */
992
0
    if(len >= 8 && !memcmp(line, "STARTTLS", 8))
993
0
      smtpc->tls_supported = TRUE;
994
995
    /* Does the server support the SIZE capability? */
996
0
    else if(len >= 4 && !memcmp(line, "SIZE", 4))
997
0
      smtpc->size_supported = TRUE;
998
999
    /* Does the server support the UTF-8 capability? */
1000
0
    else if(len >= 8 && !memcmp(line, "SMTPUTF8", 8))
1001
0
      smtpc->utf8_supported = TRUE;
1002
1003
    /* Does the server support authentication? */
1004
0
    else if(len >= 5 && !memcmp(line, "AUTH ", 5)) {
1005
0
      smtpc->auth_supported = TRUE;
1006
1007
      /* Advance past the AUTH keyword */
1008
0
      line += 5;
1009
0
      len -= 5;
1010
1011
      /* Loop through the data line */
1012
0
      for(;;) {
1013
0
        size_t llen;
1014
0
        size_t wordlen;
1015
0
        unsigned short mechbit;
1016
1017
0
        while(len &&
1018
0
              (*line == ' ' || *line == '\t' ||
1019
0
               *line == '\r' || *line == '\n')) {
1020
1021
0
          line++;
1022
0
          len--;
1023
0
        }
1024
1025
0
        if(!len)
1026
0
          break;
1027
1028
        /* Extract the word */
1029
0
        for(wordlen = 0; wordlen < len && line[wordlen] != ' ' &&
1030
0
              line[wordlen] != '\t' && line[wordlen] != '\r' &&
1031
0
              line[wordlen] != '\n';)
1032
0
          wordlen++;
1033
1034
        /* Test the word for a matching authentication mechanism */
1035
0
        mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
1036
0
        if(mechbit && llen == wordlen)
1037
0
          smtpc->sasl.authmechs |= mechbit;
1038
1039
0
        line += wordlen;
1040
0
        len -= wordlen;
1041
0
      }
1042
0
    }
1043
1044
0
    if(smtpcode != 1) {
1045
0
      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
0
        if(smtpc->tls_supported)
1048
          /* Switch to TLS connection now */
1049
0
          result = smtp_perform_starttls(data, smtpc);
1050
0
        else if(data->set.use_ssl == CURLUSESSL_TRY)
1051
          /* Fallback and carry on with authentication */
1052
0
          result = smtp_perform_authentication(data, smtpc);
1053
0
        else {
1054
0
          failf(data, "STARTTLS not supported.");
1055
0
          result = CURLE_USE_SSL_FAILED;
1056
0
        }
1057
0
      }
1058
0
      else
1059
0
        result = smtp_perform_authentication(data, smtpc);
1060
0
    }
1061
0
  }
1062
0
  else {
1063
0
    failf(data, "Unexpectedly short EHLO response");
1064
0
    result = CURLE_WEIRD_SERVER_REPLY;
1065
0
  }
1066
1067
0
  return result;
1068
0
}
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
0
{
1076
0
  CURLcode result = CURLE_OK;
1077
0
  (void)instate; /* no use for this yet */
1078
1079
0
  if(smtpcode/100 != 2) {
1080
0
    failf(data, "Remote access denied: %d", smtpcode);
1081
0
    result = CURLE_REMOTE_ACCESS_DENIED;
1082
0
  }
1083
0
  else
1084
    /* End of connect phase */
1085
0
    smtp_state(data, smtpc, SMTP_STOP);
1086
1087
0
  return result;
1088
0
}
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
0
{
1096
0
  CURLcode result = CURLE_OK;
1097
0
  saslprogress progress;
1098
1099
0
  (void)instate; /* no use for this yet */
1100
1101
0
  result = Curl_sasl_continue(&smtpc->sasl, data, smtpcode, &progress);
1102
0
  if(!result)
1103
0
    switch(progress) {
1104
0
    case SASL_DONE:
1105
0
      smtp_state(data, smtpc, SMTP_STOP);  /* Authenticated */
1106
0
      break;
1107
0
    case SASL_IDLE:            /* No mechanism left after cancellation */
1108
0
      failf(data, "Authentication cancelled");
1109
0
      result = CURLE_LOGIN_DENIED;
1110
0
      break;
1111
0
    default:
1112
0
      break;
1113
0
    }
1114
1115
0
  return result;
1116
0
}
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
0
{
1125
0
  CURLcode result = CURLE_OK;
1126
0
  char *line = curlx_dyn_ptr(&smtpc->pp.recvbuf);
1127
0
  size_t len = smtpc->pp.nfinal;
1128
1129
0
  (void)instate; /* no use for this yet */
1130
1131
0
  if((smtp->rcpt && smtpcode/100 != 2 && smtpcode != 553 && smtpcode != 1) ||
1132
0
     (!smtp->rcpt && smtpcode/100 != 2 && smtpcode != 1)) {
1133
0
    failf(data, "Command failed: %d", smtpcode);
1134
0
    result = CURLE_WEIRD_SERVER_REPLY;
1135
0
  }
1136
0
  else {
1137
0
    if(!data->req.no_body)
1138
0
      result = Curl_client_write(data, CLIENTWRITE_BODY, line, len);
1139
1140
0
    if(smtpcode != 1) {
1141
0
      if(smtp->rcpt) {
1142
0
        smtp->rcpt = smtp->rcpt->next;
1143
1144
0
        if(smtp->rcpt) {
1145
          /* Send the next command */
1146
0
          result = smtp_perform_command(data, smtpc, smtp);
1147
0
        }
1148
0
        else
1149
          /* End of DO phase */
1150
0
          smtp_state(data, smtpc, SMTP_STOP);
1151
0
      }
1152
0
      else
1153
        /* End of DO phase */
1154
0
        smtp_state(data, smtpc, SMTP_STOP);
1155
0
    }
1156
0
  }
1157
1158
0
  return result;
1159
0
}
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
0
{
1168
0
  CURLcode result = CURLE_OK;
1169
0
  (void)instate; /* no use for this yet */
1170
1171
0
  if(smtpcode/100 != 2) {
1172
0
    failf(data, "MAIL failed: %d", smtpcode);
1173
0
    result = CURLE_SEND_ERROR;
1174
0
  }
1175
0
  else
1176
    /* Start the RCPT TO command */
1177
0
    result = smtp_perform_rcpt_to(data, smtpc, smtp);
1178
1179
0
  return result;
1180
0
}
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
0
{
1189
0
  CURLcode result = CURLE_OK;
1190
0
  bool is_smtp_err = FALSE;
1191
0
  bool is_smtp_blocking_err = FALSE;
1192
1193
0
  (void)instate; /* no use for this yet */
1194
1195
0
  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
0
  is_smtp_blocking_err = (is_smtp_err && !data->set.mail_rcpt_allowfails);
1200
1201
0
  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
0
    smtp->rcpt_last_error = smtpcode;
1205
1206
0
    if(is_smtp_blocking_err) {
1207
0
      failf(data, "RCPT failed: %d", smtpcode);
1208
0
      result = CURLE_SEND_ERROR;
1209
0
    }
1210
0
  }
1211
0
  else {
1212
    /* Some RCPT TO commands have succeeded. */
1213
0
    smtp->rcpt_had_ok = TRUE;
1214
0
  }
1215
1216
0
  if(!is_smtp_blocking_err) {
1217
0
    smtp->rcpt = smtp->rcpt->next;
1218
1219
0
    if(smtp->rcpt)
1220
      /* Send the next RCPT TO command */
1221
0
      result = smtp_perform_rcpt_to(data, smtpc, smtp);
1222
0
    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
0
      if(!smtp->rcpt_had_ok) {
1226
0
        failf(data, "RCPT failed: %d (last error)", smtp->rcpt_last_error);
1227
0
        result = CURLE_SEND_ERROR;
1228
0
      }
1229
0
      else {
1230
        /* Send the DATA command */
1231
0
        result = Curl_pp_sendf(data, &smtpc->pp, "%s", "DATA");
1232
1233
0
        if(!result)
1234
0
          smtp_state(data, smtpc, SMTP_DATA);
1235
0
      }
1236
0
    }
1237
0
  }
1238
1239
0
  return result;
1240
0
}
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
0
{
1248
0
  CURLcode result = CURLE_OK;
1249
0
  (void)instate; /* no use for this yet */
1250
1251
0
  if(smtpcode != 354) {
1252
0
    failf(data, "DATA failed: %d", smtpcode);
1253
0
    result = CURLE_SEND_ERROR;
1254
0
  }
1255
0
  else {
1256
    /* Set the progress upload size */
1257
0
    Curl_pgrsSetUploadSize(data, data->state.infilesize);
1258
1259
    /* SMTP upload */
1260
0
    Curl_xfer_setup_send(data, FIRSTSOCKET);
1261
1262
    /* End of DO phase */
1263
0
    smtp_state(data, smtpc, SMTP_STOP);
1264
0
  }
1265
1266
0
  return result;
1267
0
}
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
0
{
1276
0
  CURLcode result = CURLE_OK;
1277
1278
0
  (void)instate; /* no use for this yet */
1279
1280
0
  if(smtpcode != 250)
1281
0
    result = CURLE_WEIRD_SERVER_REPLY;
1282
1283
  /* End of DONE phase */
1284
0
  smtp_state(data, smtpc, SMTP_STOP);
1285
1286
0
  return result;
1287
0
}
1288
1289
static CURLcode smtp_pp_statemachine(struct Curl_easy *data,
1290
                                     struct connectdata *conn)
1291
0
{
1292
0
  CURLcode result = CURLE_OK;
1293
0
  int smtpcode;
1294
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
1295
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1296
0
  size_t nread = 0;
1297
1298
0
  if(!smtpc || !smtp)
1299
0
    return CURLE_FAILED_INIT;
1300
1301
  /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */
1302
0
upgrade_tls:
1303
0
  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
0
  if(smtpc->pp.sendleft)
1311
0
    return Curl_pp_flushsend(data, &smtpc->pp);
1312
1313
0
  do {
1314
    /* Read the response from the server */
1315
0
    result = Curl_pp_readresp(data, FIRSTSOCKET, &smtpc->pp,
1316
0
                              &smtpcode, &nread);
1317
0
    if(result)
1318
0
      return result;
1319
1320
    /* Store the latest response for later retrieval if necessary */
1321
0
    if(smtpc->state != SMTP_QUIT && smtpcode != 1)
1322
0
      data->info.httpcode = smtpcode;
1323
1324
0
    if(!smtpcode)
1325
0
      break;
1326
1327
    /* We have now received a full SMTP server response */
1328
0
    switch(smtpc->state) {
1329
0
    case SMTP_SERVERGREET:
1330
0
      result = smtp_state_servergreet_resp(data, smtpc,
1331
0
                                           smtpcode, smtpc->state);
1332
0
      break;
1333
1334
0
    case SMTP_EHLO:
1335
0
      result = smtp_state_ehlo_resp(data, smtpc, smtpcode, smtpc->state);
1336
0
      break;
1337
1338
0
    case SMTP_HELO:
1339
0
      result = smtp_state_helo_resp(data, smtpc, smtpcode, smtpc->state);
1340
0
      break;
1341
1342
0
    case SMTP_STARTTLS:
1343
0
      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
0
      if(!result && (smtpc->state == SMTP_UPGRADETLS))
1347
0
        goto upgrade_tls;
1348
0
      break;
1349
1350
0
    case SMTP_AUTH:
1351
0
      result = smtp_state_auth_resp(data, smtpc, smtpcode, smtpc->state);
1352
0
      break;
1353
1354
0
    case SMTP_COMMAND:
1355
0
      result = smtp_state_command_resp(data, smtpc, smtp,
1356
0
                                       smtpcode, smtpc->state);
1357
0
      break;
1358
1359
0
    case SMTP_MAIL:
1360
0
      result = smtp_state_mail_resp(data, smtpc, smtp, smtpcode, smtpc->state);
1361
0
      break;
1362
1363
0
    case SMTP_RCPT:
1364
0
      result = smtp_state_rcpt_resp(data, smtpc, smtp, smtpcode, smtpc->state);
1365
0
      break;
1366
1367
0
    case SMTP_DATA:
1368
0
      result = smtp_state_data_resp(data, smtpc, smtpcode, smtpc->state);
1369
0
      break;
1370
1371
0
    case SMTP_POSTDATA:
1372
0
      result = smtp_state_postdata_resp(data, smtpc, smtpcode, smtpc->state);
1373
0
      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
0
    }
1381
0
  } while(!result && smtpc->state != SMTP_STOP &&
1382
0
          Curl_pp_moredata(&smtpc->pp));
1383
1384
0
  return result;
1385
0
}
1386
1387
/* Called repeatedly until done from multi.c */
1388
static CURLcode smtp_multi_statemach(struct Curl_easy *data, bool *done)
1389
0
{
1390
0
  CURLcode result = CURLE_OK;
1391
0
  struct smtp_conn *smtpc =
1392
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1393
1394
0
  *done = FALSE;
1395
0
  if(!smtpc)
1396
0
    return CURLE_FAILED_INIT;
1397
1398
0
  result = Curl_pp_statemach(data, &smtpc->pp, FALSE, FALSE);
1399
0
  *done = (smtpc->state == SMTP_STOP);
1400
0
  return result;
1401
0
}
1402
1403
static CURLcode smtp_block_statemach(struct Curl_easy *data,
1404
                                     struct smtp_conn *smtpc,
1405
                                     bool disconnecting)
1406
0
{
1407
0
  CURLcode result = CURLE_OK;
1408
1409
0
  while(smtpc->state != SMTP_STOP && !result)
1410
0
    result = Curl_pp_statemach(data, &smtpc->pp, TRUE, disconnecting);
1411
1412
0
  return result;
1413
0
}
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
0
{
1419
0
  struct smtp_conn *smtpc =
1420
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1421
0
  return smtpc ? Curl_pp_pollset(data, &smtpc->pp, ps) : CURLE_OK;
1422
0
}
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
0
{
1436
0
  struct smtp_conn *smtpc =
1437
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1438
0
  CURLcode result = CURLE_OK;
1439
1440
0
  *done = FALSE; /* default to not done yet */
1441
0
  if(!smtpc)
1442
0
    return CURLE_FAILED_INIT;
1443
1444
  /* We always support persistent connections in SMTP */
1445
0
  connkeep(data->conn, "SMTP default");
1446
1447
0
  PINGPONG_SETUP(&smtpc->pp, smtp_pp_statemachine, smtp_endofresp);
1448
1449
  /* Initialize the SASL storage */
1450
0
  Curl_sasl_init(&smtpc->sasl, data, &saslsmtp);
1451
1452
  /* Initialise the pingpong layer */
1453
0
  Curl_pp_init(&smtpc->pp);
1454
1455
  /* Parse the URL options */
1456
0
  result = smtp_parse_url_options(data->conn, smtpc);
1457
0
  if(result)
1458
0
    return result;
1459
1460
  /* Parse the URL path */
1461
0
  result = smtp_parse_url_path(data, smtpc);
1462
0
  if(result)
1463
0
    return result;
1464
1465
  /* Start off waiting for the server greeting response */
1466
0
  smtp_state(data, smtpc, SMTP_SERVERGREET);
1467
1468
0
  result = smtp_multi_statemach(data, done);
1469
1470
0
  return result;
1471
0
}
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
0
{
1485
0
  struct smtp_conn *smtpc =
1486
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1487
0
  CURLcode result = CURLE_OK;
1488
0
  struct connectdata *conn = data->conn;
1489
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1490
1491
0
  (void)premature;
1492
1493
0
  if(!smtpc)
1494
0
    return CURLE_FAILED_INIT;
1495
0
  if(!smtp)
1496
0
    return CURLE_OK;
1497
1498
  /* Cleanup our per-request based variables */
1499
0
  Curl_safefree(smtp->custom);
1500
1501
0
  if(status) {
1502
0
    connclose(conn, "SMTP done with bad status"); /* marked for closure */
1503
0
    result = status;         /* use the already set error code */
1504
0
  }
1505
0
  else if(!data->set.connect_only && data->set.mail_rcpt &&
1506
0
          (data->state.upload || IS_MIME_POST(data))) {
1507
1508
0
    smtp_state(data, smtpc, SMTP_POSTDATA);
1509
1510
    /* Run the state-machine */
1511
0
    result = smtp_block_statemach(data, smtpc, FALSE);
1512
0
  }
1513
1514
  /* Clear the transfer mode for the next request */
1515
0
  smtp->transfer = PPTRANSFER_BODY;
1516
0
  CURL_TRC_SMTP(data, "smtp_done(status=%d, premature=%d) -> %d",
1517
0
                status, premature, result);
1518
0
  return result;
1519
0
}
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
0
{
1534
  /* This is SMTP and no proxy */
1535
0
  CURLcode result = CURLE_OK;
1536
1537
0
  CURL_TRC_SMTP(data, "smtp_perform(), start");
1538
1539
0
  if(data->req.no_body) {
1540
    /* Requested no body means no transfer */
1541
0
    smtp->transfer = PPTRANSFER_INFO;
1542
0
  }
1543
1544
0
  *dophase_done = FALSE; /* not done yet */
1545
1546
  /* Store the first recipient (or NULL if not specified) */
1547
0
  smtp->rcpt = data->set.mail_rcpt;
1548
1549
  /* Track of whether we have successfully sent at least one RCPT TO command */
1550
0
  smtp->rcpt_had_ok = FALSE;
1551
1552
  /* Track of the last error we have received by sending RCPT TO command */
1553
0
  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
0
  smtp->trailing_crlf = TRUE;
1558
0
  smtp->eob = 2;
1559
1560
  /* Start the first command in the DO phase */
1561
0
  if((data->state.upload || IS_MIME_POST(data)) && data->set.mail_rcpt)
1562
    /* MAIL transfer */
1563
0
    result = smtp_perform_mail(data, smtpc, smtp);
1564
0
  else
1565
    /* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */
1566
0
    result = smtp_perform_command(data, smtpc, smtp);
1567
1568
0
  if(result)
1569
0
    goto out;
1570
1571
  /* Run the state-machine */
1572
0
  result = smtp_multi_statemach(data, dophase_done);
1573
1574
0
  *connected = Curl_conn_is_connected(data->conn, FIRSTSOCKET);
1575
1576
0
out:
1577
0
  CURL_TRC_SMTP(data, "smtp_perform() -> %d, connected=%d, done=%d",
1578
0
                result, *connected, *dophase_done);
1579
0
  return result;
1580
0
}
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
0
{
1593
0
  struct smtp_conn *smtpc =
1594
0
    Curl_conn_meta_get(data->conn, CURL_META_SMTP_CONN);
1595
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1596
0
  CURLcode result = CURLE_OK;
1597
1598
0
  DEBUGASSERT(data);
1599
0
  DEBUGASSERT(data->conn);
1600
0
  *done = FALSE; /* default to false */
1601
0
  if(!smtpc || !smtp)
1602
0
    return CURLE_FAILED_INIT;
1603
1604
  /* Parse the custom request */
1605
0
  result = smtp_parse_custom_request(data, smtp);
1606
0
  if(result)
1607
0
    return result;
1608
1609
0
  result = smtp_regular_transfer(data, smtpc, smtp, done);
1610
0
  CURL_TRC_SMTP(data, "smtp_do() -> %d, done=%d", result, *done);
1611
0
  return result;
1612
0
}
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
0
{
1625
0
  struct smtp_conn *smtpc = Curl_conn_meta_get(conn, CURL_META_SMTP_CONN);
1626
1627
0
  (void)data;
1628
0
  if(!smtpc)
1629
0
    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
0
  if(!dead_connection && conn->bits.protoconnstart &&
1636
0
     !Curl_pp_needs_flush(data, &smtpc->pp)) {
1637
0
    if(!smtp_perform_quit(data, smtpc))
1638
0
      (void)smtp_block_statemach(data, smtpc, TRUE); /* ignore on QUIT */
1639
0
  }
1640
1641
0
  CURL_TRC_SMTP(data, "smtp_disconnect(), finished");
1642
0
  return CURLE_OK;
1643
0
}
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
0
{
1650
0
  (void)connected;
1651
1652
0
  if(smtp->transfer != PPTRANSFER_BODY)
1653
    /* no data to transfer */
1654
0
    Curl_xfer_setup_nop(data);
1655
1656
0
  return CURLE_OK;
1657
0
}
1658
1659
/* Called from multi.c while DOing */
1660
static CURLcode smtp_doing(struct Curl_easy *data, bool *dophase_done)
1661
0
{
1662
0
  struct SMTP *smtp = Curl_meta_get(data, CURL_META_SMTP_EASY);
1663
0
  CURLcode result;
1664
1665
0
  if(!smtp)
1666
0
    return CURLE_FAILED_INIT;
1667
0
  result = smtp_multi_statemach(data, dophase_done);
1668
0
  if(result)
1669
0
    DEBUGF(infof(data, "DO phase failed"));
1670
0
  else if(*dophase_done) {
1671
0
    result = smtp_dophase_done(data, smtp, FALSE /* not connected */);
1672
1673
0
    DEBUGF(infof(data, "DO phase is complete"));
1674
0
  }
1675
1676
0
  CURL_TRC_SMTP(data, "smtp_doing() -> %d, done=%d", result, *dophase_done);
1677
0
  return result;
1678
0
}
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
0
{
1694
0
  CURLcode result = CURLE_OK;
1695
0
  bool connected = FALSE;
1696
1697
  /* Make sure size is unknown at this point */
1698
0
  data->req.size = -1;
1699
1700
  /* Set the progress data */
1701
0
  Curl_pgrsSetUploadCounter(data, 0);
1702
0
  Curl_pgrsSetDownloadCounter(data, 0);
1703
0
  Curl_pgrsSetUploadSize(data, -1);
1704
0
  Curl_pgrsSetDownloadSize(data, -1);
1705
1706
  /* Carry out the perform */
1707
0
  result = smtp_perform(data, smtpc, smtp, &connected, dophase_done);
1708
1709
  /* Perform post DO phase operations if necessary */
1710
0
  if(!result && *dophase_done)
1711
0
    result = smtp_dophase_done(data, smtp, connected);
1712
1713
0
  CURL_TRC_SMTP(data, "smtp_regular_transfer() -> %d, done=%d",
1714
0
                result, *dophase_done);
1715
0
  return result;
1716
0
}
1717
1718
1719
static void smtp_easy_dtor(void *key, size_t klen, void *entry)
1720
0
{
1721
0
  struct SMTP *smtp = entry;
1722
0
  (void)key;
1723
0
  (void)klen;
1724
0
  free(smtp);
1725
0
}
1726
1727
static void smtp_conn_dtor(void *key, size_t klen, void *entry)
1728
0
{
1729
0
  struct smtp_conn *smtpc = entry;
1730
0
  (void)key;
1731
0
  (void)klen;
1732
0
  Curl_pp_disconnect(&smtpc->pp);
1733
0
  Curl_safefree(smtpc->domain);
1734
0
  free(smtpc);
1735
0
}
1736
1737
static CURLcode smtp_setup_connection(struct Curl_easy *data,
1738
                                      struct connectdata *conn)
1739
0
{
1740
0
  struct smtp_conn *smtpc;
1741
0
  struct SMTP *smtp;
1742
0
  CURLcode result = CURLE_OK;
1743
1744
0
  smtpc = calloc(1, sizeof(*smtpc));
1745
0
  if(!smtpc ||
1746
0
     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
0
  smtp = calloc(1, sizeof(*smtp));
1752
0
  if(!smtp ||
1753
0
     Curl_meta_set(data, CURL_META_SMTP_EASY, smtp, smtp_easy_dtor))
1754
0
    result = CURLE_OUT_OF_MEMORY;
1755
1756
0
out:
1757
0
  CURL_TRC_SMTP(data, "smtp_setup_connection() -> %d", result);
1758
0
  return result;
1759
0
}
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
0
{
1770
0
  CURLcode result = CURLE_OK;
1771
0
  const char *ptr = conn->options;
1772
1773
0
  while(!result && ptr && *ptr) {
1774
0
    const char *key = ptr;
1775
0
    const char *value;
1776
1777
0
    while(*ptr && *ptr != '=')
1778
0
      ptr++;
1779
1780
0
    value = ptr + 1;
1781
1782
0
    while(*ptr && *ptr != ';')
1783
0
      ptr++;
1784
1785
0
    if(curl_strnequal(key, "AUTH=", 5))
1786
0
      result = Curl_sasl_parse_url_auth_option(&smtpc->sasl,
1787
0
                                               value, ptr - value);
1788
0
    else
1789
0
      result = CURLE_URL_MALFORMAT;
1790
1791
0
    if(*ptr == ';')
1792
0
      ptr++;
1793
0
  }
1794
1795
0
  return result;
1796
0
}
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
0
{
1807
  /* The SMTP struct is already initialised in smtp_connect() */
1808
0
  const char *path = &data->state.up.path[1]; /* skip leading path */
1809
0
  char localhost[HOSTNAME_MAX + 1];
1810
1811
  /* Calculate the path if necessary */
1812
0
  if(!*path) {
1813
0
    if(!Curl_gethostname(localhost, sizeof(localhost)))
1814
0
      path = localhost;
1815
0
    else
1816
0
      path = "localhost";
1817
0
  }
1818
1819
  /* URL decode the path and use it as the domain in our EHLO */
1820
0
  return Curl_urldecode(path, 0, &smtpc->domain, NULL, REJECT_CTRL);
1821
0
}
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
0
{
1832
0
  CURLcode result = CURLE_OK;
1833
0
  const char *custom = data->set.str[STRING_CUSTOMREQUEST];
1834
1835
  /* URL decode the custom request */
1836
0
  if(custom)
1837
0
    result = Curl_urldecode(custom, 0, &smtp->custom, NULL, REJECT_CTRL);
1838
1839
0
  return result;
1840
0
}
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
0
{
1879
0
  CURLcode result = CURLE_OK;
1880
0
  size_t length;
1881
0
  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
0
  char *dup = strdup(fqma[0] == '<' ? fqma + 1  : fqma);
1886
0
  if(!dup)
1887
0
    return CURLE_OUT_OF_MEMORY;
1888
1889
0
  if(fqma[0] != '<') {
1890
0
    length = strlen(dup);
1891
0
    if(length) {
1892
0
      if(dup[length - 1] == '>')
1893
0
        dup[length - 1] = '\0';
1894
0
    }
1895
0
  }
1896
0
  else {
1897
0
    addressend = strrchr(dup, '>');
1898
0
    if(addressend) {
1899
0
      *addressend = '\0';
1900
0
      *suffix = addressend + 1;
1901
0
    }
1902
0
  }
1903
1904
  /* Extract the hostname from the address (if we can) */
1905
0
  host->name = strpbrk(dup, "@");
1906
0
  if(host->name) {
1907
0
    *host->name = '\0';
1908
0
    host->name = host->name + 1;
1909
1910
    /* Attempt to convert the hostname to IDN ACE */
1911
0
    (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
0
  }
1917
1918
  /* Extract the local address from the mailbox */
1919
0
  *address = dup;
1920
1921
0
  return result;
1922
0
}
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
0
{
1937
0
  struct cr_eob_ctx *ctx = reader->ctx;
1938
0
  (void)data;
1939
  /* The first char we read is the first on a line, as if we had
1940
   * read CRLF just before */
1941
0
  ctx->n_eob = 2;
1942
0
  Curl_bufq_init2(&ctx->buf, (16 * 1024), 1, BUFQ_OPT_SOFT_LIMIT);
1943
0
  return CURLE_OK;
1944
0
}
1945
1946
static void cr_eob_close(struct Curl_easy *data, struct Curl_creader *reader)
1947
0
{
1948
0
  struct cr_eob_ctx *ctx = reader->ctx;
1949
0
  (void)data;
1950
0
  Curl_bufq_free(&ctx->buf);
1951
0
}
1952
1953
/* this is the 5-bytes End-Of-Body marker for SMTP */
1954
0
#define SMTP_EOB "\r\n.\r\n"
1955
0
#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
0
{
1963
0
  struct cr_eob_ctx *ctx = reader->ctx;
1964
0
  CURLcode result = CURLE_OK;
1965
0
  size_t nread, i, start, n;
1966
0
  bool eos;
1967
1968
0
  if(!ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) {
1969
    /* Get more and convert it when needed */
1970
0
    result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos);
1971
0
    if(result)
1972
0
      return result;
1973
1974
0
    ctx->read_eos = eos;
1975
0
    if(nread) {
1976
0
      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
0
        *pnread = nread;
1979
0
        *peos = FALSE;
1980
0
        return CURLE_OK;
1981
0
      }
1982
      /* scan for EOB (continuation) and convert */
1983
0
      for(i = start = 0; i < nread; ++i) {
1984
0
        if(ctx->n_eob >= SMTP_EOB_FIND_LEN) {
1985
          /* matched the EOB prefix and seeing additional char, add '.' */
1986
0
          result = Curl_bufq_cwrite(&ctx->buf, buf + start, i - start, &n);
1987
0
          if(result)
1988
0
            return result;
1989
0
          result = Curl_bufq_cwrite(&ctx->buf, ".", 1, &n);
1990
0
          if(result)
1991
0
            return result;
1992
0
          ctx->n_eob = 0;
1993
0
          start = i;
1994
0
          if(data->state.infilesize > 0)
1995
0
            data->state.infilesize++;
1996
0
        }
1997
1998
0
        if(buf[i] != SMTP_EOB[ctx->n_eob])
1999
0
          ctx->n_eob = 0;
2000
2001
0
        if(buf[i] == SMTP_EOB[ctx->n_eob]) {
2002
          /* matching another char of the EOB */
2003
0
          ++ctx->n_eob;
2004
0
        }
2005
0
      }
2006
2007
      /* add any remainder to buf */
2008
0
      if(start < nread) {
2009
0
        result = Curl_bufq_cwrite(&ctx->buf, buf + start, nread - start, &n);
2010
0
        if(result)
2011
0
          return result;
2012
0
      }
2013
0
    }
2014
2015
0
    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
0
      const char *eob = SMTP_EOB;
2020
0
      switch(ctx->n_eob) {
2021
0
        case 2:
2022
          /* seen a CRLF at the end, just add the remainder */
2023
0
          eob = &SMTP_EOB[2];
2024
0
          break;
2025
0
        case 3:
2026
          /* ended with '\r\n.', we should escape the last '.' */
2027
0
          eob = "." SMTP_EOB;
2028
0
          break;
2029
0
        default:
2030
0
          break;
2031
0
      }
2032
0
      result = Curl_bufq_cwrite(&ctx->buf, eob, strlen(eob), &n);
2033
0
      if(result)
2034
0
        return result;
2035
0
    }
2036
0
  }
2037
2038
0
  *peos = FALSE;
2039
0
  if(!Curl_bufq_is_empty(&ctx->buf)) {
2040
0
    result = Curl_bufq_cread(&ctx->buf, buf, blen, pnread);
2041
0
  }
2042
0
  else
2043
0
    *pnread = 0;
2044
2045
0
  if(ctx->read_eos && Curl_bufq_is_empty(&ctx->buf)) {
2046
    /* no more data, read all, done. */
2047
0
    ctx->eos = TRUE;
2048
0
  }
2049
0
  *peos = ctx->eos;
2050
0
  DEBUGF(infof(data, "cr_eob_read(%zu) -> %d, %zd, %d",
2051
0
         blen, result, *pnread, *peos));
2052
0
  return result;
2053
0
}
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
0
{
2081
0
  struct Curl_creader *reader = NULL;
2082
0
  CURLcode result;
2083
2084
0
  result = Curl_creader_create(&reader, data, &cr_eob,
2085
0
                               CURL_CR_CONTENT_ENCODE);
2086
0
  if(!result)
2087
0
    result = Curl_creader_add(data, reader);
2088
2089
0
  if(result && reader)
2090
0
    Curl_creader_free(data, reader);
2091
0
  return result;
2092
0
}
2093
2094
#endif /* CURL_DISABLE_SMTP */