smtp.c 55 KB

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