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