sendmail.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. /*
  2. * PHP Sendmail for Windows.
  3. *
  4. * This file is rewriten specificly for PHPFI. Some functionality
  5. * has been removed (MIME and file attachments). This code was
  6. * modified from code based on code writen by Jarle Aase.
  7. *
  8. * This class is based on the original code by Jarle Aase, see bellow:
  9. * wSendmail.cpp It has been striped of some functionality to match
  10. * the requirements of phpfi.
  11. *
  12. * Very simple SMTP Send-mail program for sending command-line level
  13. * emails and CGI-BIN form response for the Windows platform.
  14. *
  15. * The complete wSendmail package with source code can be located
  16. * from http://www.jgaa.com
  17. *
  18. */
  19. /* $Id$ */
  20. #include "php.h" /*php specific */
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #ifndef NETWARE
  24. #include <winsock2.h>
  25. #include "time.h"
  26. # include <Ws2tcpip.h>
  27. #else /* NETWARE */
  28. #include <netware/sendmail_nw.h>
  29. #endif /* NETWARE */
  30. #include <string.h>
  31. #include <math.h>
  32. #ifndef NETWARE
  33. #include <malloc.h>
  34. #include <memory.h>
  35. #include <winbase.h>
  36. #endif /* NETWARE */
  37. #include "sendmail.h"
  38. #include "php_ini.h"
  39. #include "inet.h"
  40. #if HAVE_PCRE || HAVE_BUNDLED_PCRE
  41. #include "ext/pcre/php_pcre.h"
  42. #endif
  43. #include "ext/standard/php_string.h"
  44. #include "ext/date/php_date.h"
  45. /*enum
  46. {
  47. DO_CONNECT = WM_USER +1
  48. };
  49. */
  50. /* '*error_message' has to be passed around from php_mail() */
  51. #define SMTP_ERROR_RESPONSE_SPEC "SMTP server response: %s"
  52. /* Convinient way to handle error messages from the SMTP server.
  53. response is ecalloc()d in Ack() itself and efree()d here
  54. because the content is in *error_message now */
  55. #define SMTP_ERROR_RESPONSE(response) { \
  56. if (response && error_message) { \
  57. if (NULL != (*error_message = ecalloc(1, sizeof(SMTP_ERROR_RESPONSE_SPEC) + strlen(response)))) { \
  58. snprintf(*error_message, sizeof(SMTP_ERROR_RESPONSE_SPEC) + strlen(response), SMTP_ERROR_RESPONSE_SPEC, response); \
  59. } \
  60. efree(response); \
  61. } \
  62. }
  63. #define SMTP_SKIP_SPACE(str) { while (isspace(*str)) { str++; } }
  64. #ifndef THREAD_SAFE
  65. char Buffer[MAIL_BUFFER_SIZE];
  66. /* socket related data */
  67. SOCKET sc;
  68. #ifndef NETWARE
  69. WSADATA Data;
  70. struct hostent *adr;
  71. int WinsockStarted;
  72. /* values set by the constructor */
  73. char *AppName;
  74. #endif /* NETWARE */
  75. SOCKADDR_IN sock_in;
  76. char MailHost[HOST_NAME_LEN];
  77. char LocalHost[HOST_NAME_LEN];
  78. #endif
  79. char seps[] = " ,\t\n";
  80. #ifndef NETWARE
  81. char *php_mailer = "PHP 5 WIN32";
  82. #else
  83. char *php_mailer = "PHP 5 NetWare";
  84. #endif /* NETWARE */
  85. /* Error messages */
  86. static char *ErrorMessages[] =
  87. {
  88. {"Success"}, /* 0 */
  89. {"Bad arguments from form"}, /* 1 */
  90. {"Unable to open temporary mailfile for read"},
  91. {"Failed to Start Sockets"},
  92. {"Failed to Resolve Host"},
  93. {"Failed to obtain socket handle"}, /* 5 */
  94. {"Failed to connect to mailserver, verify your \"SMTP\" setting in php.ini"},
  95. {"Failed to Send"},
  96. {"Failed to Receive"},
  97. {"Server Error"},
  98. {"Failed to resolve the host IP name"}, /* 10 */
  99. {"Out of memory"},
  100. {"Unknown error"},
  101. {"Bad Message Contents"},
  102. {"Bad Message Subject"},
  103. {"Bad Message destination"}, /* 15 */
  104. {"Bad Message Return Path"},
  105. {"Bad Mail Host"},
  106. {"Bad Message File"},
  107. {"\"sendmail_from\" not set in php.ini or custom \"From:\" header missing"},
  108. {"Mailserver rejected our \"sendmail_from\" setting"}, /* 20 */
  109. {"Error while trimming mail header with PCRE, please file a bug report at http://bugs.php.net/"} /* 21 */
  110. };
  111. /* This pattern converts all single occurrences of \n (Unix)
  112. * withour a leading \r to \r\n and all occurrences of \r (Mac)
  113. * without a trailing \n to \r\n
  114. * Thx to Nibbler from ircnet/#linuxger
  115. */
  116. #define PHP_WIN32_MAIL_UNIFY_PATTERN "/(\r\n?)|\n/"
  117. #define PHP_WIN32_MAIL_UNIFY_REPLACE "\r\n"
  118. /* This pattern removes \r\n from the start of the string,
  119. * \r\n from the end of the string and also makes sure every line
  120. * is only wrapped with a single \r\n (thus reduces multiple
  121. * occurrences of \r\n between lines to a single \r\n) */
  122. #define PHP_WIN32_MAIL_RMVDBL_PATTERN "/^\r\n|(\r\n)+$/m"
  123. #define PHP_WIN32_MAIL_RMVDBL_REPLACE ""
  124. /* This pattern escapes \n. inside the message body. It prevents
  125. * premature end of message if \n.\n or \r\n.\r\n is encountered
  126. * and ensures that \n. sequences are properly displayed in the
  127. * message body. */
  128. #define PHP_WIN32_MAIL_DOT_PATTERN "\n."
  129. #define PHP_WIN32_MAIL_DOT_REPLACE "\n.."
  130. /* This function is meant to unify the headers passed to to mail()
  131. * This means, use PCRE to transform single occurrences of \n or \r in \r\n
  132. * As a second step we also eleminate all \r\n occurrences which are:
  133. * 1) At the start of the header
  134. * 2) At the end of the header
  135. * 3) Two or more occurrences in the header are removed so only one is left
  136. *
  137. * Returns NULL on error, or the new char* buffer on success.
  138. * You have to take care and efree() the buffer on your own.
  139. */
  140. static char *php_win32_mail_trim_header(char *header TSRMLS_DC)
  141. {
  142. #if HAVE_PCRE || HAVE_BUNDLED_PCRE
  143. char *result, *result2;
  144. int result_len;
  145. zval *replace;
  146. if (!header) {
  147. return NULL;
  148. }
  149. MAKE_STD_ZVAL(replace);
  150. ZVAL_STRING(replace, PHP_WIN32_MAIL_UNIFY_REPLACE, 0);
  151. result = php_pcre_replace(PHP_WIN32_MAIL_UNIFY_PATTERN, sizeof(PHP_WIN32_MAIL_UNIFY_PATTERN)-1,
  152. header, strlen(header),
  153. replace,
  154. 0,
  155. &result_len,
  156. -1,
  157. NULL TSRMLS_CC);
  158. if (NULL == result) {
  159. FREE_ZVAL(replace);
  160. return NULL;
  161. }
  162. ZVAL_STRING(replace, PHP_WIN32_MAIL_RMVDBL_REPLACE, 0);
  163. result2 = php_pcre_replace(PHP_WIN32_MAIL_RMVDBL_PATTERN, sizeof(PHP_WIN32_MAIL_RMVDBL_PATTERN)-1,
  164. result, result_len,
  165. replace,
  166. 0,
  167. &result_len,
  168. -1,
  169. NULL TSRMLS_CC);
  170. efree(result);
  171. FREE_ZVAL(replace);
  172. return result2;
  173. #else
  174. /* In case we don't have PCRE support (for whatever reason...) simply do nothing and return the unmodified header */
  175. return estrdup(header);
  176. #endif
  177. }
  178. /*********************************************************************
  179. // Name: TSendMail
  180. // Input: 1) host: Name of the mail host where the SMTP server resides
  181. // max accepted length of name = 256
  182. // 2) appname: Name of the application to use in the X-mailer
  183. // field of the message. if NULL is given the application
  184. // name is used as given by the GetCommandLine() function
  185. // max accespted length of name = 100
  186. // Output: 1) error: Returns the error code if something went wrong or
  187. // SUCCESS otherwise.
  188. //
  189. // See SendText() for additional args!
  190. //********************************************************************/
  191. PHPAPI int TSendMail(char *host, int *error, char **error_message,
  192. char *headers, char *Subject, char *mailTo, char *data,
  193. char *mailCc, char *mailBcc, char *mailRPath TSRMLS_DC)
  194. {
  195. int ret;
  196. char *RPath = NULL;
  197. char *headers_lc = NULL; /* headers_lc is only created if we've a header at all */
  198. char *pos1 = NULL, *pos2 = NULL;
  199. #ifndef NETWARE
  200. WinsockStarted = FALSE;
  201. #endif
  202. if (host == NULL) {
  203. *error = BAD_MAIL_HOST;
  204. return FAILURE;
  205. } else if (strlen(host) >= HOST_NAME_LEN) {
  206. *error = BAD_MAIL_HOST;
  207. return FAILURE;
  208. } else {
  209. strcpy(MailHost, host);
  210. }
  211. if (headers) {
  212. char *pos = NULL;
  213. size_t i;
  214. /* Use PCRE to trim the header into the right format */
  215. if (NULL == (headers = php_win32_mail_trim_header(headers TSRMLS_CC))) {
  216. *error = W32_SM_PCRE_ERROR;
  217. return FAILURE;
  218. }
  219. /* Create a lowercased header for all the searches so we're finally case
  220. * insensitive when searching for a pattern. */
  221. if (NULL == (headers_lc = estrdup(headers))) {
  222. efree(headers);
  223. *error = OUT_OF_MEMORY;
  224. return FAILURE;
  225. }
  226. for (i = 0; i < strlen(headers_lc); i++) {
  227. headers_lc[i] = tolower(headers_lc[i]);
  228. }
  229. }
  230. /* Fall back to sendmail_from php.ini setting */
  231. if (mailRPath && *mailRPath) {
  232. RPath = estrdup(mailRPath);
  233. } else if (INI_STR("sendmail_from")) {
  234. RPath = estrdup(INI_STR("sendmail_from"));
  235. } else if ( headers_lc &&
  236. (pos1 = strstr(headers_lc, "from:")) &&
  237. ((pos1 == headers_lc) || (*(pos1-1) == '\n'))
  238. ) {
  239. /* Real offset is memaddress from the original headers + difference of
  240. * string found in the lowercase headrs + 5 characters to jump over
  241. * the from: */
  242. pos1 = headers + (pos1 - headers_lc) + 5;
  243. if (NULL == (pos2 = strstr(pos1, "\r\n"))) {
  244. RPath = estrndup(pos1, strlen(pos1));
  245. } else {
  246. RPath = estrndup(pos1, pos2 - pos1);
  247. }
  248. } else {
  249. if (headers) {
  250. efree(headers);
  251. efree(headers_lc);
  252. }
  253. *error = W32_SM_SENDMAIL_FROM_NOT_SET;
  254. return FAILURE;
  255. }
  256. /* attempt to connect with mail host */
  257. *error = MailConnect();
  258. if (*error != 0) {
  259. if (RPath) {
  260. efree(RPath);
  261. }
  262. if (headers) {
  263. efree(headers);
  264. efree(headers_lc);
  265. }
  266. /* 128 is safe here, the specifier in snprintf isn't longer than that */
  267. if (NULL == (*error_message = ecalloc(1, HOST_NAME_LEN + 128))) {
  268. return FAILURE;
  269. }
  270. snprintf(*error_message, HOST_NAME_LEN + 128,
  271. "Failed to connect to mailserver at \"%s\" port %d, verify your \"SMTP\" "
  272. "and \"smtp_port\" setting in php.ini or use ini_set()",
  273. MailHost, !INI_INT("smtp_port") ? 25 : INI_INT("smtp_port"));
  274. return FAILURE;
  275. } else {
  276. ret = SendText(RPath, Subject, mailTo, mailCc, mailBcc, data, headers, headers_lc, error_message TSRMLS_CC);
  277. TSMClose();
  278. if (RPath) {
  279. efree(RPath);
  280. }
  281. if (headers) {
  282. efree(headers);
  283. efree(headers_lc);
  284. }
  285. if (ret != SUCCESS) {
  286. *error = ret;
  287. return FAILURE;
  288. }
  289. return SUCCESS;
  290. }
  291. }
  292. //********************************************************************
  293. // Name: TSendMail::~TSendMail
  294. // Input:
  295. // Output:
  296. // Description: DESTRUCTOR
  297. // Author/Date: jcar 20/9/96
  298. // History:
  299. //********************************************************************/
  300. PHPAPI void TSMClose()
  301. {
  302. Post("QUIT\r\n");
  303. Ack(NULL);
  304. /* to guarantee that the cleanup is not made twice and
  305. compomise the rest of the application if sockets are used
  306. elesewhere
  307. */
  308. shutdown(sc, 0);
  309. closesocket(sc);
  310. }
  311. /*********************************************************************
  312. // Name: char *GetSMErrorText
  313. // Input: Error index returned by the menber functions
  314. // Output: pointer to a string containing the error description
  315. // Description:
  316. // Author/Date: jcar 20/9/96
  317. // History:
  318. //*******************************************************************/
  319. PHPAPI char *GetSMErrorText(int index)
  320. {
  321. if (MIN_ERROR_INDEX <= index && index < MAX_ERROR_INDEX) {
  322. return (ErrorMessages[index]);
  323. } else {
  324. return (ErrorMessages[UNKNOWN_ERROR]);
  325. }
  326. }
  327. /*********************************************************************
  328. // Name: SendText
  329. // Input: 1) RPath: return path of the message
  330. // Is used to fill the "Return-Path" and the
  331. // "X-Sender" fields of the message.
  332. // 2) Subject: Subject field of the message. If NULL is given
  333. // the subject is set to "No Subject"
  334. // 3) mailTo: Destination address
  335. // 4) data: Null terminated string containing the data to be send.
  336. // 5,6) headers of the message. Note that the second
  337. // parameter, headers_lc, is actually a lowercased version of
  338. // headers. The should match exactly (in terms of length),
  339. // only differ in case
  340. // Output: Error code or SUCCESS
  341. // Description:
  342. // Author/Date: jcar 20/9/96
  343. // History:
  344. //*******************************************************************/
  345. static int SendText(char *RPath, char *Subject, char *mailTo, char *mailCc, char *mailBcc, char *data,
  346. char *headers, char *headers_lc, char **error_message TSRMLS_DC)
  347. {
  348. int res;
  349. char *p;
  350. char *tempMailTo, *token, *pos1, *pos2;
  351. char *server_response = NULL;
  352. char *stripped_header = NULL;
  353. char *data_cln;
  354. int data_cln_len;
  355. /* check for NULL parameters */
  356. if (data == NULL)
  357. return (BAD_MSG_CONTENTS);
  358. if (mailTo == NULL)
  359. return (BAD_MSG_DESTINATION);
  360. if (RPath == NULL)
  361. return (BAD_MSG_RPATH);
  362. /* simple checks for the mailto address */
  363. /* have ampersand ? */
  364. /* mfischer, 20020514: I commented this out because it really
  365. seems bogus. Only a username for example may still be a
  366. valid address at the destination system.
  367. if (strchr(mailTo, '@') == NULL)
  368. return (BAD_MSG_DESTINATION);
  369. */
  370. snprintf(Buffer, sizeof(Buffer), "HELO %s\r\n", LocalHost);
  371. /* in the beginning of the dialog */
  372. /* attempt reconnect if the first Post fail */
  373. if ((res = Post(Buffer)) != SUCCESS) {
  374. MailConnect();
  375. if ((res = Post(Buffer)) != SUCCESS) {
  376. return (res);
  377. }
  378. }
  379. if ((res = Ack(&server_response)) != SUCCESS) {
  380. SMTP_ERROR_RESPONSE(server_response);
  381. return (res);
  382. }
  383. SMTP_SKIP_SPACE(RPath);
  384. FormatEmailAddress(Buffer, RPath, "MAIL FROM:<%s>\r\n");
  385. if ((res = Post(Buffer)) != SUCCESS) {
  386. return (res);
  387. }
  388. if ((res = Ack(&server_response)) != SUCCESS) {
  389. SMTP_ERROR_RESPONSE(server_response);
  390. return W32_SM_SENDMAIL_FROM_MALFORMED;
  391. }
  392. tempMailTo = estrdup(mailTo);
  393. /* Send mail to all rcpt's */
  394. token = strtok(tempMailTo, ",");
  395. while (token != NULL)
  396. {
  397. SMTP_SKIP_SPACE(token);
  398. FormatEmailAddress(Buffer, token, "RCPT TO:<%s>\r\n");
  399. if ((res = Post(Buffer)) != SUCCESS) {
  400. efree(tempMailTo);
  401. return (res);
  402. }
  403. if ((res = Ack(&server_response)) != SUCCESS) {
  404. SMTP_ERROR_RESPONSE(server_response);
  405. efree(tempMailTo);
  406. return (res);
  407. }
  408. token = strtok(NULL, ",");
  409. }
  410. efree(tempMailTo);
  411. if (mailCc && *mailCc) {
  412. tempMailTo = estrdup(mailCc);
  413. /* Send mail to all rcpt's */
  414. token = strtok(tempMailTo, ",");
  415. while (token != NULL)
  416. {
  417. SMTP_SKIP_SPACE(token);
  418. FormatEmailAddress(Buffer, token, "RCPT TO:<%s>\r\n");
  419. if ((res = Post(Buffer)) != SUCCESS) {
  420. efree(tempMailTo);
  421. return (res);
  422. }
  423. if ((res = Ack(&server_response)) != SUCCESS) {
  424. SMTP_ERROR_RESPONSE(server_response);
  425. efree(tempMailTo);
  426. return (res);
  427. }
  428. token = strtok(NULL, ",");
  429. }
  430. efree(tempMailTo);
  431. }
  432. /* Send mail to all Cc rcpt's */
  433. else if (headers && (pos1 = strstr(headers_lc, "cc:")) && ((pos1 == headers_lc) || (*(pos1-1) == '\n'))) {
  434. /* Real offset is memaddress from the original headers + difference of
  435. * string found in the lowercase headrs + 3 characters to jump over
  436. * the cc: */
  437. pos1 = headers + (pos1 - headers_lc) + 3;
  438. if (NULL == (pos2 = strstr(pos1, "\r\n"))) {
  439. tempMailTo = estrndup(pos1, strlen(pos1));
  440. } else {
  441. tempMailTo = estrndup(pos1, pos2 - pos1);
  442. }
  443. token = strtok(tempMailTo, ",");
  444. while (token != NULL)
  445. {
  446. SMTP_SKIP_SPACE(token);
  447. FormatEmailAddress(Buffer, token, "RCPT TO:<%s>\r\n");
  448. if ((res = Post(Buffer)) != SUCCESS) {
  449. efree(tempMailTo);
  450. return (res);
  451. }
  452. if ((res = Ack(&server_response)) != SUCCESS) {
  453. SMTP_ERROR_RESPONSE(server_response);
  454. efree(tempMailTo);
  455. return (res);
  456. }
  457. token = strtok(NULL, ",");
  458. }
  459. efree(tempMailTo);
  460. }
  461. /* Send mail to all Bcc rcpt's
  462. This is basically a rip of the Cc code above.
  463. Just don't forget to remove the Bcc: from the header afterwards. */
  464. if (mailBcc && *mailBcc) {
  465. tempMailTo = estrdup(mailBcc);
  466. /* Send mail to all rcpt's */
  467. token = strtok(tempMailTo, ",");
  468. while (token != NULL)
  469. {
  470. SMTP_SKIP_SPACE(token);
  471. FormatEmailAddress(Buffer, token, "RCPT TO:<%s>\r\n");
  472. if ((res = Post(Buffer)) != SUCCESS) {
  473. efree(tempMailTo);
  474. return (res);
  475. }
  476. if ((res = Ack(&server_response)) != SUCCESS) {
  477. SMTP_ERROR_RESPONSE(server_response);
  478. efree(tempMailTo);
  479. return (res);
  480. }
  481. token = strtok(NULL, ",");
  482. }
  483. efree(tempMailTo);
  484. }
  485. else if (headers) {
  486. if (pos1 = strstr(headers_lc, "bcc:")) {
  487. /* Real offset is memaddress from the original headers + difference of
  488. * string found in the lowercase headrs + 4 characters to jump over
  489. * the bcc: */
  490. pos1 = headers + (pos1 - headers_lc) + 4;
  491. if (NULL == (pos2 = strstr(pos1, "\r\n"))) {
  492. tempMailTo = estrndup(pos1, strlen(pos1));
  493. /* Later, when we remove the Bcc: out of the
  494. header we know it was the last thing. */
  495. pos2 = pos1;
  496. } else {
  497. tempMailTo = estrndup(pos1, pos2 - pos1);
  498. }
  499. token = strtok(tempMailTo, ",");
  500. while (token != NULL)
  501. {
  502. SMTP_SKIP_SPACE(token);
  503. FormatEmailAddress(Buffer, token, "RCPT TO:<%s>\r\n");
  504. if ((res = Post(Buffer)) != SUCCESS) {
  505. efree(tempMailTo);
  506. return (res);
  507. }
  508. if ((res = Ack(&server_response)) != SUCCESS) {
  509. SMTP_ERROR_RESPONSE(server_response);
  510. efree(tempMailTo);
  511. return (res);
  512. }
  513. token = strtok(NULL, ",");
  514. }
  515. efree(tempMailTo);
  516. /* Now that we've identified that we've a Bcc list,
  517. remove it from the current header. */
  518. if (NULL == (stripped_header = ecalloc(1, strlen(headers)))) {
  519. return OUT_OF_MEMORY;
  520. }
  521. /* headers = point to string start of header
  522. pos1 = pointer IN headers where the Bcc starts
  523. '4' = Length of the characters 'bcc:'
  524. Because we've added +4 above for parsing the Emails
  525. we've to substract them here. */
  526. memcpy(stripped_header, headers, pos1 - headers - 4);
  527. if (pos1 != pos2) {
  528. /* if pos1 != pos2 , pos2 points to the rest of the headers.
  529. Since pos1 != pos2 if "\r\n" was found, we know those characters
  530. are there and so we jump over them (else we would generate a new header
  531. which would look like "\r\n\r\n". */
  532. memcpy(stripped_header + (pos1 - headers - 4), pos2 + 2, strlen(pos2) - 2);
  533. }
  534. }
  535. }
  536. /* Simplify the code that we create a copy of stripped_header no matter if
  537. we actually strip something or not. So we've a single efree() later. */
  538. if (headers && !stripped_header) {
  539. if (NULL == (stripped_header = estrndup(headers, strlen(headers)))) {
  540. return OUT_OF_MEMORY;
  541. }
  542. }
  543. if ((res = Post("DATA\r\n")) != SUCCESS) {
  544. if (stripped_header) {
  545. efree(stripped_header);
  546. }
  547. return (res);
  548. }
  549. if ((res = Ack(&server_response)) != SUCCESS) {
  550. SMTP_ERROR_RESPONSE(server_response);
  551. if (stripped_header) {
  552. efree(stripped_header);
  553. }
  554. return (res);
  555. }
  556. /* send message header */
  557. if (Subject == NULL) {
  558. res = PostHeader(RPath, "No Subject", mailTo, stripped_header TSRMLS_CC);
  559. } else {
  560. res = PostHeader(RPath, Subject, mailTo, stripped_header TSRMLS_CC);
  561. }
  562. if (stripped_header) {
  563. efree(stripped_header);
  564. }
  565. if (res != SUCCESS) {
  566. return (res);
  567. }
  568. /* Escape \n. sequences
  569. * We use php_str_to_str() and not php_str_replace_in_subject(), since the latter
  570. * uses ZVAL as it's parameters */
  571. data_cln = php_str_to_str(data, strlen(data), PHP_WIN32_MAIL_DOT_PATTERN, sizeof(PHP_WIN32_MAIL_DOT_PATTERN) - 1,
  572. PHP_WIN32_MAIL_DOT_REPLACE, sizeof(PHP_WIN32_MAIL_DOT_REPLACE) - 1, &data_cln_len);
  573. if (!data_cln) {
  574. data_cln = estrdup("");
  575. data_cln_len = 1;
  576. }
  577. /* send message contents in 1024 chunks */
  578. {
  579. char c, *e2, *e = data_cln + data_cln_len;
  580. p = data_cln;
  581. while (e - p > 1024) {
  582. e2 = p + 1024;
  583. c = *e2;
  584. *e2 = '\0';
  585. if ((res = Post(p)) != SUCCESS) {
  586. efree(data_cln);
  587. return(res);
  588. }
  589. *e2 = c;
  590. p = e2;
  591. }
  592. if ((res = Post(p)) != SUCCESS) {
  593. efree(data_cln);
  594. return(res);
  595. }
  596. }
  597. efree(data_cln);
  598. /*send termination dot */
  599. if ((res = Post("\r\n.\r\n")) != SUCCESS)
  600. return (res);
  601. if ((res = Ack(&server_response)) != SUCCESS) {
  602. SMTP_ERROR_RESPONSE(server_response);
  603. return (res);
  604. }
  605. return (SUCCESS);
  606. }
  607. static int addToHeader(char **header_buffer, const char *specifier, char *string)
  608. {
  609. if (NULL == (*header_buffer = erealloc(*header_buffer, strlen(*header_buffer) + strlen(specifier) + strlen(string) + 1))) {
  610. return 0;
  611. }
  612. sprintf(*header_buffer + strlen(*header_buffer), specifier, string);
  613. return 1;
  614. }
  615. /*********************************************************************
  616. // Name: PostHeader
  617. // Input: 1) return path
  618. // 2) Subject
  619. // 3) destination address
  620. // 4) headers
  621. // Output: Error code or Success
  622. // Description:
  623. // Author/Date: jcar 20/9/96
  624. // History:
  625. //********************************************************************/
  626. static int PostHeader(char *RPath, char *Subject, char *mailTo, char *xheaders TSRMLS_DC)
  627. {
  628. /* Print message header according to RFC 822 */
  629. /* Return-path, Received, Date, From, Subject, Sender, To, cc */
  630. int res;
  631. char *header_buffer;
  632. char *headers_lc = NULL;
  633. size_t i;
  634. if (xheaders) {
  635. if (NULL == (headers_lc = estrdup(xheaders))) {
  636. return OUT_OF_MEMORY;
  637. }
  638. for (i = 0; i < strlen(headers_lc); i++) {
  639. headers_lc[i] = tolower(headers_lc[i]);
  640. }
  641. }
  642. header_buffer = ecalloc(1, MAIL_BUFFER_SIZE);
  643. if (!xheaders || !strstr(headers_lc, "date:")) {
  644. time_t tNow = time(NULL);
  645. char *dt = php_format_date("r", 1, tNow, 1 TSRMLS_CC);
  646. snprintf(header_buffer, MAIL_BUFFER_SIZE, "Date: %s\r\n", dt);
  647. efree(dt);
  648. }
  649. if (!headers_lc || !strstr(headers_lc, "from:")) {
  650. if (!addToHeader(&header_buffer, "From: %s\r\n", RPath)) {
  651. goto PostHeader_outofmem;
  652. }
  653. }
  654. if (!addToHeader(&header_buffer, "Subject: %s\r\n", Subject)) {
  655. goto PostHeader_outofmem;
  656. }
  657. /* Only add the To: field from the $to parameter if isn't in the custom headers */
  658. if ((headers_lc && (!strstr(headers_lc, "\r\nto:") && (strncmp(headers_lc, "to:", 3) != 0))) || !headers_lc) {
  659. if (!addToHeader(&header_buffer, "To: %s\r\n", mailTo)) {
  660. goto PostHeader_outofmem;
  661. }
  662. }
  663. if (xheaders) {
  664. if (!addToHeader(&header_buffer, "%s\r\n", xheaders)) {
  665. goto PostHeader_outofmem;
  666. }
  667. }
  668. if (headers_lc) {
  669. efree(headers_lc);
  670. }
  671. if ((res = Post(header_buffer)) != SUCCESS) {
  672. efree(header_buffer);
  673. return (res);
  674. }
  675. efree(header_buffer);
  676. if ((res = Post("\r\n")) != SUCCESS) {
  677. return (res);
  678. }
  679. return (SUCCESS);
  680. PostHeader_outofmem:
  681. if (headers_lc) {
  682. efree(headers_lc);
  683. }
  684. return OUT_OF_MEMORY;
  685. }
  686. /*********************************************************************
  687. // Name: MailConnect
  688. // Input: None
  689. // Output: None
  690. // Description: Connect to the mail host and receive the welcome message.
  691. // Author/Date: jcar 20/9/96
  692. // History:
  693. //********************************************************************/
  694. static int MailConnect()
  695. {
  696. int res, namelen;
  697. short portnum;
  698. struct hostent *ent;
  699. IN_ADDR addr;
  700. #ifdef HAVE_IPV6
  701. IN6_ADDR addr6;
  702. #endif
  703. /* Create Socket */
  704. if ((sc = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  705. return (FAILED_TO_OBTAIN_SOCKET_HANDLE);
  706. }
  707. /* Get our own host name */
  708. if (gethostname(LocalHost, HOST_NAME_LEN)) {
  709. return (FAILED_TO_GET_HOSTNAME);
  710. }
  711. ent = gethostbyname(LocalHost);
  712. if (!ent) {
  713. return (FAILED_TO_GET_HOSTNAME);
  714. }
  715. namelen = strlen(ent->h_name);
  716. #ifdef HAVE_IPV6
  717. if (inet_pton(AF_INET, ent->h_name, &addr) == 1 || inet_pton(AF_INET6, ent->h_name, &addr6) == 1)
  718. #else
  719. if (inet_pton(AF_INET, ent->h_name, &addr) == 1)
  720. #endif
  721. {
  722. if (namelen + 2 >= HOST_NAME_LEN) {
  723. return (FAILED_TO_GET_HOSTNAME);
  724. }
  725. strcpy(LocalHost, "[");
  726. strcpy(LocalHost + 1, ent->h_name);
  727. strcpy(LocalHost + namelen + 1, "]");
  728. } else {
  729. if (namelen >= HOST_NAME_LEN) {
  730. return (FAILED_TO_GET_HOSTNAME);
  731. }
  732. strcpy(LocalHost, ent->h_name);
  733. }
  734. /* Resolve the servers IP */
  735. /*
  736. if (!isdigit(MailHost[0])||!gethostbyname(MailHost))
  737. {
  738. return (FAILED_TO_RESOLVE_HOST);
  739. }
  740. */
  741. portnum = (short) INI_INT("smtp_port");
  742. if (!portnum) {
  743. portnum = 25;
  744. }
  745. /* Connect to server */
  746. sock_in.sin_family = AF_INET;
  747. sock_in.sin_port = htons(portnum);
  748. sock_in.sin_addr.S_un.S_addr = GetAddr(MailHost);
  749. if (connect(sc, (LPSOCKADDR) & sock_in, sizeof(sock_in))) {
  750. return (FAILED_TO_CONNECT);
  751. }
  752. /* receive Server welcome message */
  753. res = Ack(NULL);
  754. return (res);
  755. }
  756. /*********************************************************************
  757. // Name: Post
  758. // Input:
  759. // Output:
  760. // Description:
  761. // Author/Date: jcar 20/9/96
  762. // History:
  763. //********************************************************************/
  764. static int Post(LPCSTR msg)
  765. {
  766. int len = strlen(msg);
  767. int slen;
  768. int index = 0;
  769. while (len > 0) {
  770. if ((slen = send(sc, msg + index, len, 0)) < 1)
  771. return (FAILED_TO_SEND);
  772. len -= slen;
  773. index += slen;
  774. }
  775. return (SUCCESS);
  776. }
  777. /*********************************************************************
  778. // Name: Ack
  779. // Input:
  780. // Output:
  781. // Description:
  782. // Get the response from the server. We only want to know if the
  783. // last command was successful.
  784. // Author/Date: jcar 20/9/96
  785. // History:
  786. //********************************************************************/
  787. static int Ack(char **server_response)
  788. {
  789. static char buf[MAIL_BUFFER_SIZE];
  790. int rlen;
  791. int Index = 0;
  792. int Received = 0;
  793. again:
  794. if ((rlen = recv(sc, buf + Index, ((MAIL_BUFFER_SIZE) - 1) - Received, 0)) < 1) {
  795. return (FAILED_TO_RECEIVE);
  796. }
  797. Received += rlen;
  798. buf[Received] = 0;
  799. /*err_msg fprintf(stderr,"Received: (%d bytes) %s", rlen, buf + Index); */
  800. /* Check for newline */
  801. Index += rlen;
  802. /* SMPT RFC says \r\n is the only valid line ending, who are we to argue ;)
  803. * The response code must contain at least 5 characters ex. 220\r\n */
  804. if (Received < 5 || buf[Received - 1] != '\n' || buf[Received - 2] != '\r') {
  805. goto again;
  806. }
  807. if (buf[0] > '3') {
  808. /* If we've a valid pointer, return the SMTP server response so the error message contains more information */
  809. if (server_response) {
  810. int dec = 0;
  811. /* See if we have something like \r, \n, \r\n or \n\r at the end of the message and chop it off */
  812. if (Received > 2) {
  813. if (buf[Received-1] == '\n' || buf[Received-1] == '\r') {
  814. dec++;
  815. if (buf[Received-2] == '\r' || buf[Received-2] == '\n') {
  816. dec++;
  817. }
  818. }
  819. }
  820. *server_response = estrndup(buf, Received - dec);
  821. }
  822. return (SMTP_SERVER_ERROR);
  823. }
  824. return (SUCCESS);
  825. }
  826. /*********************************************************************
  827. // Name: unsigned long GetAddr (LPSTR szHost)
  828. // Input:
  829. // Output:
  830. // Description: Given a string, it will return an IP address.
  831. // - first it tries to convert the string directly
  832. // - if that fails, it tries o resolve it as a hostname
  833. //
  834. // WARNING: gethostbyname() is a blocking function
  835. // Author/Date: jcar 20/9/96
  836. // History:
  837. //********************************************************************/
  838. static unsigned long GetAddr(LPSTR szHost)
  839. {
  840. LPHOSTENT lpstHost;
  841. u_long lAddr = INADDR_ANY;
  842. /* check that we have a string */
  843. if (*szHost) {
  844. /* check for a dotted-IP address string */
  845. lAddr = inet_addr(szHost);
  846. /* If not an address, then try to resolve it as a hostname */
  847. if ((lAddr == INADDR_NONE) && (strcmp(szHost, "255.255.255.255"))) {
  848. lpstHost = gethostbyname(szHost);
  849. if (lpstHost) { /* success */
  850. lAddr = *((u_long FAR *) (lpstHost->h_addr));
  851. } else {
  852. lAddr = INADDR_ANY; /* failure */
  853. }
  854. }
  855. }
  856. return (lAddr);
  857. } /* end GetAddr() */
  858. /*********************************************************************
  859. // Name: int FormatEmailAddress
  860. // Input:
  861. // Output:
  862. // Description: Formats the email address to remove any content ouside
  863. // of the angle brackets < > as per RFC 2821.
  864. //
  865. // Returns the invalidly formatted mail address if the < > are
  866. // unbalanced (the SMTP server should reject it if it's out of spec.)
  867. //
  868. // Author/Date: garretts 08/18/2009
  869. // History:
  870. //********************************************************************/
  871. static int FormatEmailAddress(char* Buf, char* EmailAddress, char* FormatString) {
  872. char *tmpAddress1, *tmpAddress2;
  873. int result;
  874. if( (tmpAddress1 = strchr(EmailAddress, '<')) && (tmpAddress2 = strchr(tmpAddress1, '>')) ) {
  875. *tmpAddress2 = 0; // terminate the string temporarily.
  876. result = snprintf(Buf, MAIL_BUFFER_SIZE, FormatString , tmpAddress1+1);
  877. *tmpAddress2 = '>'; // put it back the way it was.
  878. return result;
  879. }
  880. return snprintf(Buf, MAIL_BUFFER_SIZE , FormatString , EmailAddress );
  881. } /* end FormatEmailAddress() */