Coverage Report

Created: 2025-06-09 07:42

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