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