2 * smtp.c -- nmh SMTP interface
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
13 #include <h/signals.h>
16 #include <sasl/sasl.h>
17 #include <sasl/saslutil.h>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
23 #endif /* CYRUS_SASL */
26 #include <openssl/ssl.h>
27 #include <openssl/err.h>
28 #endif /* TLS_SUPPORT */
31 * This module implements an interface to SendMail very similar
32 * to the MMDF mm_(3) routines. The sm_() routines herein talk
33 * SMTP to a sendmail process, mapping SMTP reply codes into
38 * On older 4.2BSD machines without the POSIX function `sigaction',
39 * the alarm handing stuff for time-outs will NOT work due to the way
40 * syscalls get restarted. This is not really crucial, since SendMail
41 * is generally well-behaved in this area.
46 * It appears that some versions of Sendmail will return Code 451
47 * when they don't really want to indicate a failure.
48 * "Code 451 almost always means sendmail has deferred; we don't
49 * really want bomb out at this point since sendmail will rectify
50 * things later." So, if you define SENDMAILBUG, Code 451 is
51 * considered the same as Code 250. Yuck!
58 #define NBITS ((sizeof (int)) * 8)
61 * these codes must all be different!
63 #define SM_OPEN 300 /* Changed to 5 minutes to comply with a SHOULD in RFC 1123 */
66 #define SM_MAIL 301 /* changed to 5 minutes and a second (for uniqueness), see above */
67 #define SM_RCPT 302 /* see above */
68 #define SM_DATA 120 /* see above */
69 #define SM_TEXT 180 /* see above */
70 #define SM_DOT 600 /* see above */
75 static int sm_addrs = 0;
76 static int sm_alarmed = 0;
77 static int sm_child = NOTOK;
78 static int sm_debug = 0;
79 static int sm_nl = TRUE;
80 static int sm_verbose = 0;
82 static FILE *sm_rfp = NULL;
83 static FILE *sm_wfp = NULL;
87 * Some globals needed by SASL
90 static sasl_conn_t *conn = NULL; /* SASL connection state */
91 static int sasl_complete = 0; /* Has authentication succeded? */
92 static sasl_ssf_t sasl_ssf; /* Our security strength factor */
93 static char *sasl_pw_context[2]; /* Context to pass into sm_get_pass */
94 static int maxoutbuf; /* Maximum crypto output buffer */
95 static char *sasl_outbuffer; /* SASL output buffer for encryption */
96 static int sasl_outbuflen; /* Current length of data in outbuf */
97 static int sm_get_user(void *, int, const char **, unsigned *);
98 static int sm_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
100 static sasl_callback_t callbacks[] = {
101 { SASL_CB_USER, sm_get_user, NULL },
102 #define SM_SASL_N_CB_USER 0
103 { SASL_CB_PASS, sm_get_pass, NULL },
104 #define SM_SASL_N_CB_PASS 1
105 { SASL_CB_AUTHNAME, sm_get_user, NULL },
106 #define SM_SASL_N_CB_AUTHNAME 2
107 { SASL_CB_LIST_END, NULL, NULL },
110 #else /* CYRUS_SASL */
112 #endif /* CYRUS_SASL */
115 static SSL_CTX *sslctx = NULL;
116 static SSL *ssl = NULL;
117 static BIO *sbior = NULL;
118 static BIO *sbiow = NULL;
119 static BIO *io = NULL;
120 #endif /* TLS_SUPPORT */
122 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
123 #define SASL_MAXRECVBUF 65536
124 static int sm_fgetc(FILE *);
125 static char *sasl_inbuffer; /* SASL input buffer for encryption */
126 static char *sasl_inptr; /* Pointer to current inbuf position */
127 static int sasl_inbuflen; /* Current length of data in inbuf */
129 #define sm_fgetc fgetc
132 static int tls_active = 0;
134 static char *sm_noreply = "No reply text given";
135 static char *sm_moreply = "; ";
137 struct smtp sm_reply; /* global... */
141 static int doingEHLO;
142 char *EHLOkeys[MAXEHLO + 1];
147 static int smtp_init (char *, char *, char *, int, int, int, int, int, int,
148 char *, char *, int);
149 static int sendmail_init (char *, char *, int, int, int, int, int, int,
152 static int rclient (char *, char *);
153 static int sm_ierror (char *fmt, ...);
154 static int smtalk (int time, char *fmt, ...);
155 static int sm_wrecord (char *, int);
156 static int sm_wstream (char *, int);
157 static int sm_werror (void);
158 static int smhear (void);
159 static int sm_rrecord (char *, int *);
160 static int sm_rerror (int);
161 static void alrmser (int);
162 static char *EHLOset (char *);
163 static int sm_fwrite(char *, int);
164 static int sm_fputs(char *);
165 static int sm_fputc(int);
166 static void sm_fflush(void);
167 static int sm_fgets(char *, int, FILE *);
171 * Function prototypes needed for SASL
174 static int sm_auth_sasl(char *, char *, char *);
175 #endif /* CYRUS_SASL */
178 sm_init (char *client, char *server, char *port, int watch, int verbose,
179 int debug, int onex, int queued, int sasl, char *saslmech,
182 if (sm_mts == MTS_SMTP)
183 return smtp_init (client, server, port, watch, verbose,
184 debug, onex, queued, sasl, saslmech, user, tls);
186 return sendmail_init (client, server, watch, verbose,
187 debug, onex, queued, sasl, saslmech, user);
191 smtp_init (char *client, char *server, char *port, int watch, int verbose,
192 int debug, int onex, int queued,
193 int sasl, char *saslmech, char *user, int tls)
197 #endif /* CYRUS_SASL */
198 int result, sd1, sd2;
203 sm_verbose = verbose;
206 if (sm_rfp != NULL && sm_wfp != NULL)
209 if (client == NULL || *client == '\0') {
213 client = LocalName(); /* no clientname -> LocalName */
218 * Last-ditch check just in case client still isn't set to anything
221 if (client == NULL || *client == '\0')
222 client = "localhost";
224 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
225 sasl_inbuffer = malloc(SASL_MAXRECVBUF);
227 return sm_ierror("Unable to allocate %d bytes for read buffer",
229 #endif /* CYRUS_SASL || TLS_SUPPORT */
231 if ((sd1 = rclient (server, port)) == NOTOK)
234 if ((sd2 = dup (sd1)) == NOTOK) {
236 return sm_ierror ("unable to dup");
239 SIGNAL (SIGALRM, alrmser);
240 SIGNAL (SIGPIPE, SIG_IGN);
242 if ((sm_rfp = fdopen (sd1, "r")) == NULL
243 || (sm_wfp = fdopen (sd2, "w")) == NULL) {
246 sm_rfp = sm_wfp = NULL;
247 return sm_ierror ("unable to fdopen");
267 * Give EHLO or HELO command
271 result = smtalk (SM_HELO, "EHLO %s", client);
274 if (result >= 500 && result <= 599)
275 result = smtalk (SM_HELO, "HELO %s", client);
284 * If the user requested TLS support, then try to do the STARTTLS command
285 * as part of the initial dialog. Assuming this works, we then need to
286 * restart the EHLO dialog after TLS negotiation is complete.
292 if (! EHLOset("STARTTLS")) {
294 return sm_ierror("SMTP server does not support TLS");
297 result = smtalk(SM_HELO, "STARTTLS");
305 * Okay, the other side should be waiting for us to start TLS
306 * negotiation. Oblige them.
313 SSL_load_error_strings();
315 method = TLSv1_client_method(); /* Not sure about this */
317 sslctx = SSL_CTX_new(method);
321 return sm_ierror("Unable to initialize OpenSSL context: %s",
322 ERR_error_string(ERR_get_error(), NULL));
326 ssl = SSL_new(sslctx);
330 return sm_ierror("Unable to create SSL connection: %s",
331 ERR_error_string(ERR_get_error(), NULL));
334 sbior = BIO_new_socket(fileno(sm_rfp), BIO_NOCLOSE);
335 sbiow = BIO_new_socket(fileno(sm_wfp), BIO_NOCLOSE);
337 if (sbior == NULL || sbiow == NULL) {
339 return sm_ierror("Unable to create BIO endpoints: %s",
340 ERR_error_string(ERR_get_error(), NULL));
343 SSL_set_bio(ssl, sbior, sbiow);
344 SSL_set_connect_state(ssl);
347 * Set up a BIO to handle buffering for us
350 io = BIO_new(BIO_f_buffer());
354 return sm_ierror("Unable to create a buffer BIO: %s",
355 ERR_error_string(ERR_get_error(), NULL));
358 ssl_bio = BIO_new(BIO_f_ssl());
362 return sm_ierror("Unable to create a SSL BIO: %s",
363 ERR_error_string(ERR_get_error(), NULL));
366 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
367 BIO_push(io, ssl_bio);
370 * Try doing the handshake now
373 if (BIO_do_handshake(io) < 1) {
375 return sm_ierror("Unable to negotiate SSL connection: %s",
376 ERR_error_string(ERR_get_error(), NULL));
380 SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
381 printf("SSL negotiation successful: %s(%d) %s\n",
382 SSL_CIPHER_get_name(cipher),
383 SSL_CIPHER_get_bits(cipher, NULL),
384 SSL_CIPHER_get_version(cipher));
391 result = smtalk (SM_HELO, "EHLO %s", client);
399 #else /* TLS_SUPPORT */
401 #endif /* TLS_SUPPORT */
405 * If the user asked for SASL, then check to see if the SMTP server
406 * supports it. Otherwise, error out (because the SMTP server
407 * might have been spoofed; we don't want to just silently not
412 if (! (server_mechs = EHLOset("AUTH"))) {
414 return sm_ierror("SMTP server does not support SASL");
417 if (saslmech && stringdex(saslmech, server_mechs) == -1) {
419 return sm_ierror("Requested SASL mech \"%s\" is not in the "
420 "list of supported mechanisms:\n%s",
421 saslmech, server_mechs);
424 if (sm_auth_sasl(user, saslmech ? saslmech : server_mechs,
430 #endif /* CYRUS_SASL */
433 if (watch && EHLOset ("XVRB"))
434 smtalk (SM_HELO, "VERB on");
435 if (onex && EHLOset ("XONE"))
436 smtalk (SM_HELO, "ONEX");
437 if (queued && EHLOset ("XQUE"))
438 smtalk (SM_HELO, "QUED");
444 sendmail_init (char *client, char *server, int watch, int verbose,
445 int debug, int onex, int queued,
446 int sasl, char *saslmech, char *user)
450 #endif /* CYRUS_SASL */
451 unsigned int i, result, vecp;
458 sm_verbose = verbose;
460 if (sm_rfp != NULL && sm_wfp != NULL)
463 if (client == NULL || *client == '\0') {
467 client = LocalName(); /* no clientname -> LocalName */
471 * Last-ditch check just in case client still isn't set to anything
474 if (client == NULL || *client == '\0')
475 client = "localhost";
477 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
478 sasl_inbuffer = malloc(SASL_MAXRECVBUF);
480 return sm_ierror("Unable to allocate %d bytes for read buffer",
482 #endif /* CYRUS_SASL || TLS_SUPPORT */
484 if (pipe (pdi) == NOTOK)
485 return sm_ierror ("no pipes");
486 if (pipe (pdo) == NOTOK) {
489 return sm_ierror ("no pipes");
492 for (i = 0; (sm_child = fork ()) == NOTOK && i < 5; i++)
501 return sm_ierror ("unable to fork");
504 if (pdo[0] != fileno (stdin))
505 dup2 (pdo[0], fileno (stdin));
506 if (pdi[1] != fileno (stdout))
507 dup2 (pdi[1], fileno (stdout));
508 if (pdi[1] != fileno (stderr))
509 dup2 (pdi[1], fileno (stderr));
510 for (i = fileno (stderr) + 1; i < NBITS; i++)
514 vec[vecp++] = r1bindex (sendmail, '/');
516 vec[vecp++] = watch ? "-odi" : queued ? "-odq" : "-odb";
517 vec[vecp++] = "-oem";
522 # endif /* not RAND */
527 execvp (sendmail, vec);
528 fprintf (stderr, "unable to exec ");
530 _exit (-1); /* NOTREACHED */
533 SIGNAL (SIGALRM, alrmser);
534 SIGNAL (SIGPIPE, SIG_IGN);
538 if ((sm_rfp = fdopen (pdi[0], "r")) == NULL
539 || (sm_wfp = fdopen (pdo[1], "w")) == NULL) {
542 sm_rfp = sm_wfp = NULL;
543 return sm_ierror ("unable to fdopen");
559 result = smtalk (SM_HELO, "EHLO %s", client);
562 if (500 <= result && result <= 599)
563 result = smtalk (SM_HELO, "HELO %s", client);
576 * If the user asked for SASL, then check to see if the SMTP server
577 * supports it. Otherwise, error out (because the SMTP server
578 * might have been spoofed; we don't want to just silently not
583 if (! (server_mechs = EHLOset("AUTH"))) {
585 return sm_ierror("SMTP server does not support SASL");
588 if (saslmech && stringdex(saslmech, server_mechs) == -1) {
590 return sm_ierror("Requested SASL mech \"%s\" is not in the "
591 "list of supported mechanisms:\n%s",
592 saslmech, server_mechs);
595 if (sm_auth_sasl(user, saslmech ? saslmech : server_mechs,
601 #endif /* CYRUS_SASL */
604 smtalk (SM_HELO, "ONEX");
606 smtalk (SM_HELO, "VERB on");
613 rclient (char *server, char *service)
616 char response[BUFSIZ];
618 if ((sd = client (server, service, response, sizeof(response),
622 sm_ierror ("%s", response);
627 sm_winit (int mode, char *from)
629 char *smtpcom = NULL;
649 /* Hopefully, we do not get here. */
653 switch (smtalk (SM_MAIL, "%s FROM:<%s>", smtpcom, from)) {
670 sm_wadr (char *mbox, char *host, char *path)
672 switch (smtalk (SM_RCPT, host && *host ? "RCPT TO:<%s%s@%s>"
674 path ? path : "", mbox, host)) {
684 #endif /* SENDMAILBUG */
709 switch (smtalk (SM_DATA, "DATA")) {
718 #endif /* SENDMAILBUG */
735 sm_wtxt (char *buffer, int len)
741 result = sm_wstream (buffer, len);
744 return (result == NOTOK ? RP_BHST : RP_OK);
751 if (sm_wstream ((char *) NULL, 0) == NOTOK)
754 switch (smtalk (SM_DOT + 3 * sm_addrs, ".")) {
762 #endif /* SENDMAILBUG */
780 if (sm_mts == MTS_SENDMAIL) {
791 if (sm_rfp == NULL && sm_wfp == NULL)
796 smtalk (SM_QUIT, "QUIT");
800 sm_note.code = sm_reply.code;
801 sm_note.length = sm_reply.length;
802 memcpy (sm_note.text, sm_reply.text, sm_reply.length + 1);/* fall */
804 if (smtalk (SM_RSET, "RSET") == 250 && type == DONE)
806 if (sm_mts == MTS_SMTP)
807 smtalk (SM_QUIT, "QUIT");
809 kill (sm_child, SIGKILL);
814 sm_reply.code = sm_note.code;
815 sm_reply.length = sm_note.length;
816 memcpy (sm_reply.text, sm_note.text, sm_note.length + 1);
823 BIO_ssl_shutdown(io);
826 #endif /* TLS_SUPPORT */
828 if (sm_rfp != NULL) {
833 if (sm_wfp != NULL) {
839 if (sm_mts == MTS_SMTP) {
844 if (sasl_outbuffer) {
845 free(sasl_outbuffer);
850 #endif /* CYRUS_SASL */
852 status = pidwait (sm_child, OK);
856 sm_rfp = sm_wfp = NULL;
857 return (status ? RP_BHST : RP_OK);
862 * This function implements SASL authentication for SMTP. If this function
863 * completes successfully, then authentication is successful and we've
864 * (optionally) negotiated a security layer.
867 sm_auth_sasl(char *user, char *mechlist, char *inhost)
870 unsigned int buflen, outlen;
871 char *buf, outbuf[BUFSIZ], host[NI_MAXHOST];
872 const char *chosen_mech;
873 sasl_security_properties_t secprops;
878 * Initialize the callback contexts
882 user = getusername();
884 callbacks[SM_SASL_N_CB_USER].context = user;
885 callbacks[SM_SASL_N_CB_AUTHNAME].context = user;
888 * This is a _bit_ of a hack ... but if the hostname wasn't supplied
889 * to us on the command line, then call getpeername and do a
890 * reverse-address lookup on the IP address to get the name.
893 memset(host, 0, sizeof(host));
896 struct sockaddr_storage sin;
897 socklen_t len = sizeof(sin);
900 if (getpeername(fileno(sm_wfp), (struct sockaddr *) &sin, &len) < 0) {
901 sm_ierror("getpeername on SMTP socket failed: %s",
906 result = getnameinfo((struct sockaddr *) &sin, len, host, sizeof(host),
907 NULL, 0, NI_NAMEREQD);
909 sm_ierror("Unable to look up name of connected host: %s",
910 gai_strerror(result));
914 strncpy(host, inhost, sizeof(host) - 1);
917 sasl_pw_context[0] = host;
918 sasl_pw_context[1] = user;
920 callbacks[SM_SASL_N_CB_PASS].context = sasl_pw_context;
922 result = sasl_client_init(callbacks);
924 if (result != SASL_OK) {
925 sm_ierror("SASL library initialization failed: %s",
926 sasl_errstring(result, NULL, NULL));
930 result = sasl_client_new("smtp", host, NULL, NULL, NULL, 0, &conn);
932 if (result != SASL_OK) {
933 sm_ierror("SASL client initialization failed: %s",
934 sasl_errstring(result, NULL, NULL));
939 * Initialize the security properties. But if TLS is active, then
940 * don't negotiate encryption here.
943 memset(&secprops, 0, sizeof(secprops));
944 secprops.maxbufsize = SASL_MAXRECVBUF;
945 secprops.max_ssf = tls_active ? 0 : UINT_MAX;
947 result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
949 if (result != SASL_OK) {
950 sm_ierror("SASL security property initialization failed: %s",
951 sasl_errstring(result, NULL, NULL));
956 * Start the actual protocol. Feed the mech list into the library
957 * and get out a possible initial challenge
960 result = sasl_client_start(conn, mechlist, NULL, (const char **) &buf,
961 &buflen, (const char **) &chosen_mech);
963 if (result != SASL_OK && result != SASL_CONTINUE) {
964 sm_ierror("SASL client start failed: %s", sasl_errdetail(conn));
969 * If we got an initial challenge, send it as part of the AUTH
970 * command; otherwise, just send a plain AUTH command.
974 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
975 if (status != SASL_OK) {
976 sm_ierror("SASL base64 encode failed: %s",
977 sasl_errstring(status, NULL, NULL));
981 status = smtalk(SM_AUTH, "AUTH %s %s", chosen_mech, outbuf);
983 status = smtalk(SM_AUTH, "AUTH %s", chosen_mech);
986 * Now we loop until we either fail, get a SASL_OK, or a 235
987 * response code. Receive the challenges and process them until
991 while (result == SASL_CONTINUE) {
994 * If we get a 235 response, that means authentication has
995 * succeeded and we need to break out of the loop (yes, even if
996 * we still get SASL_CONTINUE from sasl_client_step()).
998 * Otherwise, if we get a message that doesn't seem to be a
999 * valid response, then abort
1004 else if (status < 300 || status > 399)
1008 * Special case; a zero-length response from the SMTP server
1009 * is returned as a single =. If we get that, then set buflen
1010 * to be zero. Otherwise, just decode the response.
1013 if (strcmp("=", sm_reply.text) == 0) {
1016 result = sasl_decode64(sm_reply.text, sm_reply.length,
1017 outbuf, sizeof(outbuf), &outlen);
1019 if (result != SASL_OK) {
1020 smtalk(SM_AUTH, "*");
1021 sm_ierror("SASL base64 decode failed: %s",
1022 sasl_errstring(result, NULL, NULL));
1027 result = sasl_client_step(conn, outbuf, outlen, NULL,
1028 (const char **) &buf, &buflen);
1030 if (result != SASL_OK && result != SASL_CONTINUE) {
1031 smtalk(SM_AUTH, "*");
1032 sm_ierror("SASL client negotiation failed: %s",
1033 sasl_errstring(result, NULL, NULL));
1037 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
1039 if (status != SASL_OK) {
1040 smtalk(SM_AUTH, "*");
1041 sm_ierror("SASL base64 encode failed: %s",
1042 sasl_errstring(status, NULL, NULL));
1046 status = smtalk(SM_AUTH, outbuf);
1050 * Make sure that we got the correct response
1053 if (status < 200 || status > 299)
1057 * We _should_ have completed the authentication successfully.
1058 * Get a few properties from the authentication exchange.
1061 result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &outbufmax);
1063 if (result != SASL_OK) {
1064 sm_ierror("Cannot retrieve SASL negotiated output buffer size: %s",
1065 sasl_errstring(result, NULL, NULL));
1069 maxoutbuf = *outbufmax;
1071 result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
1075 if (result != SASL_OK) {
1076 sm_ierror("Cannot retrieve SASL negotiated security strength "
1077 "factor: %s", sasl_errstring(result, NULL, NULL));
1082 sasl_outbuffer = malloc(maxoutbuf);
1084 if (sasl_outbuffer == NULL) {
1085 sm_ierror("Unable to allocate %d bytes for SASL output "
1086 "buffer", maxoutbuf);
1091 sasl_inptr = sasl_inbuffer;
1093 sasl_outbuffer = NULL;
1094 /* Don't NULL out sasl_inbuffer because it could be used in
1104 * Our callback functions to feed data to the SASL library
1108 sm_get_user(void *context, int id, const char **result, unsigned *len)
1110 char *user = (char *) context;
1112 if (! result || ((id != SASL_CB_USER) && (id != SASL_CB_AUTHNAME)))
1113 return SASL_BADPARAM;
1117 *len = strlen(user);
1123 sm_get_pass(sasl_conn_t *conn, void *context, int id,
1124 sasl_secret_t **psecret)
1128 char **pw_context = (char **) context;
1132 if (! psecret || id != SASL_CB_PASS)
1133 return SASL_BADPARAM;
1135 ruserpass(pw_context[0], &(pw_context[1]), &pass);
1139 *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
1146 (*psecret)->len = len;
1147 strcpy((char *) (*psecret)->data, pass);
1152 #endif /* CYRUS_SASL */
1155 sm_ierror (char *fmt, ...)
1160 vsnprintf (sm_reply.text, sizeof(sm_reply.text), fmt, ap);
1163 sm_reply.length = strlen (sm_reply.text);
1164 sm_reply.code = NOTOK;
1170 smtalk (int time, char *fmt, ...)
1174 char buffer[BUFSIZ];
1177 vsnprintf (buffer, sizeof(buffer), fmt, ap);
1182 printf("(sasl-encrypted) ");
1184 printf("(tls-encrypted) ");
1185 printf ("=> %s\n", buffer);
1190 alarm ((unsigned) time);
1191 if ((result = sm_wrecord (buffer, strlen (buffer))) != NOTOK)
1200 * write the buffer to the open SMTP channel
1204 sm_wrecord (char *buffer, int len)
1207 return sm_werror ();
1209 sm_fwrite (buffer, len);
1213 return (ferror (sm_wfp) ? sm_werror () : OK);
1218 sm_wstream (char *buffer, int len)
1221 static char lc = '\0';
1224 return sm_werror ();
1226 if (buffer == NULL && len == 0) {
1230 return (ferror (sm_wfp) ? sm_werror () : OK);
1233 for (bp = buffer; len > 0; bp++, len--) {
1242 sm_fputc ('.');/* FALL THROUGH */
1247 if (ferror (sm_wfp))
1248 return sm_werror ();
1253 return (ferror (sm_wfp) ? sm_werror () : OK);
1257 * Write out to the network, but do buffering for SASL (if enabled)
1261 sm_fwrite(char *buffer, int len)
1265 unsigned int outputlen;
1267 if (sasl_complete == 0 || sasl_ssf == 0) {
1268 #endif /* CYRUS_SASL */
1273 ret = BIO_write(io, buffer, len);
1276 sm_ierror("TLS error during write: %s",
1277 ERR_error_string(ERR_get_error(), NULL));
1281 #endif /* TLS_SUPPORT */
1282 fwrite(buffer, sizeof(*buffer), len, sm_wfp);
1285 while (len >= maxoutbuf - sasl_outbuflen) {
1286 memcpy(sasl_outbuffer + sasl_outbuflen, buffer,
1287 maxoutbuf - sasl_outbuflen);
1288 len -= maxoutbuf - sasl_outbuflen;
1291 if (sasl_encode(conn, sasl_outbuffer, maxoutbuf,
1292 &output, &outputlen) != SASL_OK) {
1293 sm_ierror("Unable to SASL encode connection data: %s",
1294 sasl_errdetail(conn));
1298 fwrite(output, sizeof(*output), outputlen, sm_wfp);
1302 memcpy(sasl_outbuffer + sasl_outbuflen, buffer, len);
1303 sasl_outbuflen += len;
1306 #endif /* CYRUS_SASL */
1307 return ferror(sm_wfp) ? NOTOK : RP_OK;
1311 * Convenience functions to replace occurences of fputs() and fputc()
1315 sm_fputs(char *buffer)
1317 return sm_fwrite(buffer, strlen(buffer));
1325 return sm_fwrite(&h, 1);
1329 * Flush out any pending data on the connection
1337 unsigned int outputlen;
1340 if (sasl_complete == 1 && sasl_ssf > 0 && sasl_outbuflen > 0) {
1341 result = sasl_encode(conn, sasl_outbuffer, sasl_outbuflen,
1342 &output, &outputlen);
1343 if (result != SASL_OK) {
1344 sm_ierror("Unable to SASL encode connection data: %s",
1345 sasl_errdetail(conn));
1349 fwrite(output, sizeof(*output), outputlen, sm_wfp);
1352 #endif /* CYRUS_SASL */
1356 (void) BIO_flush(io);
1358 #endif /* TLS_SUPPORT */
1367 strlen (strcpy (sm_reply.text, sm_wfp == NULL ? "no socket opened"
1368 : sm_alarmed ? "write to socket timed out"
1369 : "error writing to socket"));
1371 return (sm_reply.code = NOTOK);
1378 int i, code, cont, bc = 0, rc, more;
1381 char **ehlo = NULL, buffer[BUFSIZ];
1384 static int at_least_once = 0;
1386 if (at_least_once) {
1389 for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1403 sm_reply.length = 0;
1404 sm_reply.text[0] = 0;
1406 rc = sizeof(sm_reply.text) - 1;
1408 for (more = FALSE; sm_rrecord ((char *) (bp = (unsigned char *) buffer),
1412 printf("(sasl-decrypted) ");
1414 printf("(tls-decrypted) ");
1415 printf ("<= %s\n", buffer);
1420 && strncmp (buffer, "250", sizeof("250") - 1) == 0
1421 && (buffer[3] == '-' || doingEHLO == 2)
1423 if (doingEHLO == 2) {
1424 if ((*ehlo = malloc ((size_t) (strlen (buffer + 4) + 1)))) {
1425 strcpy (*ehlo++, buffer + 4);
1427 if (ehlo >= EHLOkeys + MAXEHLO)
1437 for (; bc > 0 && (!isascii (*bp) || !isdigit (*bp)); bp++, bc--)
1441 code = atoi ((char *) bp);
1443 for (; bc > 0 && isspace (*bp); bp++, bc--)
1445 if (bc > 0 && *bp == '-') {
1448 for (; bc > 0 && isspace (*bp); bp++, bc--)
1453 if (code != sm_reply.code || cont)
1457 sm_reply.code = code;
1460 /* can never fail to 0-terminate because of size of buffer vs fixed string */
1461 strncpy (buffer, sm_noreply, sizeof(buffer));
1462 bp = (unsigned char *) buffer;
1463 bc = strlen (sm_noreply);
1467 if ((i = min (bc, rc)) > 0) {
1471 i = strlen(sm_moreply);
1472 if (more && rc > i + 1) {
1473 memcpy (rp, sm_moreply, i); /* safe because of check in if() */
1480 if (sm_reply.code < 100) {
1482 printf ("%s\n", sm_reply.text);
1488 sm_reply.length = rp - sm_reply.text;
1489 sm_reply.text[sm_reply.length] = 0;
1490 return sm_reply.code;
1497 sm_rrecord (char *buffer, int *len)
1502 return sm_rerror(0);
1504 buffer[*len = 0] = 0;
1506 if ((retval = sm_fgets (buffer, BUFSIZ, sm_rfp)) != RP_OK)
1508 *len = strlen (buffer);
1509 /* *len should be >0 except on EOF, but check for safety's sake */
1511 return sm_rerror (RP_EOF);
1512 if (buffer[*len - 1] != '\n')
1513 while ((retval = sm_fgetc (sm_rfp)) != '\n' && retval != EOF &&
1517 if ((*len > 1) && (buffer[*len - 2] == '\r'))
1526 * Our version of fgets, which calls our private fgetc function
1530 sm_fgets(char *buffer, int size, FILE *f)
1544 } while (size > 1 && c != '\n');
1552 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
1554 * Read from the network, but do SASL or TLS encryption
1560 char tmpbuf[BUFSIZ], *retbuf;
1561 unsigned int retbufsize = 0;
1565 * If we have leftover data, return it
1568 if (sasl_inbuflen) {
1570 return (int) *sasl_inptr++;
1574 * If not, read from the network until we have some data to return
1577 while (retbufsize == 0) {
1581 cc = SSL_read(ssl, tmpbuf, sizeof(tmpbuf));
1584 result = SSL_get_error(ssl, cc);
1586 if (result != SSL_ERROR_ZERO_RETURN) {
1587 sm_ierror("TLS peer aborted connection");
1594 sm_ierror("SSL_read failed: %s",
1595 ERR_error_string(ERR_get_error(), NULL));
1599 #endif /* TLS_SUPPORT */
1601 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1607 sm_ierror("Unable to read from network: %s", strerror(errno));
1612 * Don't call sasl_decode unless sasl is complete and we have
1613 * encryption working
1617 if (sasl_complete == 0 || sasl_ssf == 0) {
1621 result = sasl_decode(conn, tmpbuf, cc, (const char **) &retbuf,
1624 if (result != SASL_OK) {
1625 sm_ierror("Unable to decode SASL network data: %s",
1626 sasl_errdetail(conn));
1630 #else /* ! CYRUS_SASL */
1633 #endif /* CYRUS_SASL */
1636 if (retbufsize > SASL_MAXRECVBUF) {
1637 sm_ierror("Received data (%d bytes) is larger than the buffer "
1638 "size (%d bytes)", retbufsize, SASL_MAXRECVBUF);
1642 memcpy(sasl_inbuffer, retbuf, retbufsize);
1643 sasl_inptr = sasl_inbuffer + 1;
1644 sasl_inbuflen = retbufsize - 1;
1646 return (int) sasl_inbuffer[0];
1648 #endif /* CYRUS_SASL || TLS_SUPPORT */
1653 if (sm_mts == MTS_SMTP)
1655 strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no socket opened"
1656 : sm_alarmed ? "read from socket timed out"
1657 : rc == RP_EOF ? "premature end-of-file on socket"
1658 : "error reading from socket"));
1661 strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no pipe opened"
1662 : sm_alarmed ? "read from pipe timed out"
1663 : rc == RP_EOF ? "premature end-of-file on pipe"
1664 : "error reading from pipe"));
1666 return (sm_reply.code = NOTOK);
1675 #ifndef RELIABLE_SIGNALS
1676 SIGNAL (SIGALRM, alrmser);
1681 printf ("timed out...\n");
1688 rp_string (int code)
1691 static char buffer[BUFSIZ];
1693 switch (sm_reply.code != NOTOK ? code : NOTOK) {
1713 snprintf (buffer, sizeof(buffer), "[%s] %s", text, sm_reply.text);
1733 snprintf (buffer, sizeof(buffer), "[%s] %3d %s",
1734 text, sm_reply.code, sm_reply.text);
1746 for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1748 if (strncmp (ep, s, len) == 0) {
1749 for (ep += len; *ep == ' '; ep++)