Coverage Report

Created: 2025-10-10 06:31

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