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 #endif /* CYRUS_SASL */
77 static int sm_addrs = 0;
78 static int sm_alarmed = 0;
79 static int sm_child = NOTOK;
80 static int sm_debug = 0;
81 static int sm_nl = TRUE;
82 static int sm_verbose = 0;
84 static FILE *sm_rfp = NULL;
85 static FILE *sm_wfp = NULL;
89 * Some globals needed by SASL
92 static sasl_conn_t *conn = NULL; /* SASL connection state */
93 static int sasl_complete = 0; /* Has authentication succeded? */
94 static sasl_ssf_t sasl_ssf; /* Our security strength factor */
95 static char *sasl_pw_context[2]; /* Context to pass into sm_get_pass */
96 static int maxoutbuf; /* Maximum crypto output buffer */
97 static char *sasl_outbuffer; /* SASL output buffer for encryption */
98 static int sasl_outbuflen; /* Current length of data in outbuf */
99 static int sm_get_user(void *, int, const char **, unsigned *);
100 static int sm_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
102 static sasl_callback_t callbacks[] = {
103 { SASL_CB_USER, sm_get_user, NULL },
104 #define SM_SASL_N_CB_USER 0
105 { SASL_CB_PASS, sm_get_pass, NULL },
106 #define SM_SASL_N_CB_PASS 1
107 { SASL_CB_AUTHNAME, sm_get_user, NULL },
108 #define SM_SASL_N_CB_AUTHNAME 2
109 { SASL_CB_LIST_END, NULL, NULL },
112 #else /* CYRUS_SASL */
114 #endif /* CYRUS_SASL */
117 static SSL_CTX *sslctx = NULL;
118 static SSL *ssl = NULL;
119 static BIO *sbior = NULL;
120 static BIO *sbiow = NULL;
121 static BIO *io = NULL;
122 #endif /* TLS_SUPPORT */
124 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
125 #define SASL_MAXRECVBUF 65536
126 static int sm_fgetc(FILE *);
127 static char *sasl_inbuffer; /* SASL input buffer for encryption */
128 static char *sasl_inptr; /* Pointer to current inbuf position */
129 static int sasl_inbuflen; /* Current length of data in inbuf */
131 #define sm_fgetc fgetc
134 static int tls_active = 0;
136 static char *sm_noreply = "No reply text given";
137 static char *sm_moreply = "; ";
139 struct smtp sm_reply; /* global... */
143 static int doingEHLO;
144 char *EHLOkeys[MAXEHLO + 1];
149 static int smtp_init (char *, char *, char *, int, int, int, int, int, int,
150 int, char *, char *, int);
151 static int sendmail_init (char *, char *, int, int, int, int, int, int,
152 int, char *, char *);
154 static int rclient (char *, char *);
155 static int sm_ierror (char *fmt, ...);
156 static int smtalk (int time, char *fmt, ...);
157 static int sm_wrecord (char *, int);
158 static int sm_wstream (char *, int);
159 static int sm_werror (void);
160 static int smhear (void);
161 static int sm_rrecord (char *, int *);
162 static int sm_rerror (int);
163 static void alrmser (int);
164 static char *EHLOset (char *);
165 static int sm_fwrite(char *, int);
166 static int sm_fputs(char *);
167 static int sm_fputc(int);
168 static void sm_fflush(void);
169 static int sm_fgets(char *, int, FILE *);
173 * Function prototypes needed for SASL
176 static int sm_auth_sasl(char *, int, char *, char *);
177 #endif /* CYRUS_SASL */
180 sm_init (char *client, char *server, char *port, int watch, int verbose,
181 int debug, int onex, int queued, int sasl, int saslssf,
182 char *saslmech, char *user, int tls)
184 if (sm_mts == MTS_SMTP)
185 return smtp_init (client, server, port, watch, verbose,
186 debug, onex, queued, sasl, saslssf, saslmech,
189 return sendmail_init (client, server, watch, verbose,
190 debug, onex, queued, sasl, saslssf, saslmech,
195 smtp_init (char *client, char *server, char *port, int watch, int verbose,
196 int debug, int onex, int queued,
197 int sasl, int saslssf, char *saslmech, char *user, int tls)
201 #else /* CYRUS_SASL */
203 NMH_UNUSED (saslmech);
205 #endif /* CYRUS_SASL */
206 int result, sd1, sd2;
211 sm_verbose = verbose;
214 if (sm_rfp != NULL && sm_wfp != NULL)
217 if (client == NULL || *client == '\0') {
221 client = LocalName(1); /* no clientname -> LocalName */
226 * Last-ditch check just in case client still isn't set to anything
229 if (client == NULL || *client == '\0')
230 client = "localhost";
232 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
233 sasl_inbuffer = malloc(SASL_MAXRECVBUF);
235 return sm_ierror("Unable to allocate %d bytes for read buffer",
237 #endif /* CYRUS_SASL || TLS_SUPPORT */
239 if ((sd1 = rclient (server, port)) == NOTOK)
242 if ((sd2 = dup (sd1)) == NOTOK) {
244 return sm_ierror ("unable to dup");
247 SIGNAL (SIGALRM, alrmser);
248 SIGNAL (SIGPIPE, SIG_IGN);
250 if ((sm_rfp = fdopen (sd1, "r")) == NULL
251 || (sm_wfp = fdopen (sd2, "w")) == NULL) {
254 sm_rfp = sm_wfp = NULL;
255 return sm_ierror ("unable to fdopen");
275 * Give EHLO or HELO command
279 result = smtalk (SM_HELO, "EHLO %s", client);
282 if (result >= 500 && result <= 599)
283 result = smtalk (SM_HELO, "HELO %s", client);
292 * If the user requested TLS support, then try to do the STARTTLS command
293 * as part of the initial dialog. Assuming this works, we then need to
294 * restart the EHLO dialog after TLS negotiation is complete.
300 if (! EHLOset("STARTTLS")) {
302 return sm_ierror("SMTP server does not support TLS");
305 result = smtalk(SM_HELO, "STARTTLS");
313 * Okay, the other side should be waiting for us to start TLS
314 * negotiation. Oblige them.
321 SSL_load_error_strings();
323 method = TLSv1_client_method(); /* Not sure about this */
325 sslctx = SSL_CTX_new(method);
329 return sm_ierror("Unable to initialize OpenSSL context: %s",
330 ERR_error_string(ERR_get_error(), NULL));
334 ssl = SSL_new(sslctx);
338 return sm_ierror("Unable to create SSL connection: %s",
339 ERR_error_string(ERR_get_error(), NULL));
342 sbior = BIO_new_socket(fileno(sm_rfp), BIO_NOCLOSE);
343 sbiow = BIO_new_socket(fileno(sm_wfp), BIO_NOCLOSE);
345 if (sbior == NULL || sbiow == NULL) {
347 return sm_ierror("Unable to create BIO endpoints: %s",
348 ERR_error_string(ERR_get_error(), NULL));
351 SSL_set_bio(ssl, sbior, sbiow);
352 SSL_set_connect_state(ssl);
355 * Set up a BIO to handle buffering for us
358 io = BIO_new(BIO_f_buffer());
362 return sm_ierror("Unable to create a buffer BIO: %s",
363 ERR_error_string(ERR_get_error(), NULL));
366 ssl_bio = BIO_new(BIO_f_ssl());
370 return sm_ierror("Unable to create a SSL BIO: %s",
371 ERR_error_string(ERR_get_error(), NULL));
374 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
375 BIO_push(io, ssl_bio);
378 * Try doing the handshake now
381 if (BIO_do_handshake(io) < 1) {
383 return sm_ierror("Unable to negotiate SSL connection: %s",
384 ERR_error_string(ERR_get_error(), NULL));
388 SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
389 printf("SSL negotiation successful: %s(%d) %s\n",
390 SSL_CIPHER_get_name(cipher),
391 SSL_CIPHER_get_bits(cipher, NULL),
392 SSL_CIPHER_get_version(cipher));
399 result = smtalk (SM_HELO, "EHLO %s", client);
407 #else /* TLS_SUPPORT */
409 #endif /* TLS_SUPPORT */
413 * If the user asked for SASL, then check to see if the SMTP server
414 * supports it. Otherwise, error out (because the SMTP server
415 * might have been spoofed; we don't want to just silently not
420 if (! (server_mechs = EHLOset("AUTH"))) {
422 return sm_ierror("SMTP server does not support SASL");
425 if (saslmech && stringdex(saslmech, server_mechs) == -1) {
427 return sm_ierror("Requested SASL mech \"%s\" is not in the "
428 "list of supported mechanisms:\n%s",
429 saslmech, server_mechs);
432 if (sm_auth_sasl(user, saslssf, saslmech ? saslmech : server_mechs,
438 #endif /* CYRUS_SASL */
441 if (watch && EHLOset ("XVRB"))
442 smtalk (SM_HELO, "VERB on");
443 if (onex && EHLOset ("XONE"))
444 smtalk (SM_HELO, "ONEX");
445 if (queued && EHLOset ("XQUE"))
446 smtalk (SM_HELO, "QUED");
452 sendmail_init (char *client, char *server, int watch, int verbose,
453 int debug, int onex, int queued,
454 int sasl, int saslssf, char *saslmech, char *user)
458 #else /* CYRUS_SASL */
461 NMH_UNUSED (saslssf);
462 NMH_UNUSED (saslmech);
464 #endif /* CYRUS_SASL */
465 unsigned int i, result, vecp;
472 sm_verbose = verbose;
474 if (sm_rfp != NULL && sm_wfp != NULL)
477 if (client == NULL || *client == '\0') {
481 client = LocalName(1); /* no clientname -> LocalName */
485 * Last-ditch check just in case client still isn't set to anything
488 if (client == NULL || *client == '\0')
489 client = "localhost";
491 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
492 sasl_inbuffer = malloc(SASL_MAXRECVBUF);
494 return sm_ierror("Unable to allocate %d bytes for read buffer",
496 #endif /* CYRUS_SASL || TLS_SUPPORT */
498 if (pipe (pdi) == NOTOK)
499 return sm_ierror ("no pipes");
500 if (pipe (pdo) == NOTOK) {
503 return sm_ierror ("no pipes");
506 for (i = 0; (sm_child = fork ()) == NOTOK && i < 5; i++)
515 return sm_ierror ("unable to fork");
518 if (pdo[0] != fileno (stdin))
519 dup2 (pdo[0], fileno (stdin));
520 if (pdi[1] != fileno (stdout))
521 dup2 (pdi[1], fileno (stdout));
522 if (pdi[1] != fileno (stderr))
523 dup2 (pdi[1], fileno (stderr));
524 for (i = fileno (stderr) + 1; i < NBITS; i++)
528 vec[vecp++] = r1bindex (sendmail, '/');
530 vec[vecp++] = watch ? "-odi" : queued ? "-odq" : "-odb";
531 vec[vecp++] = "-oem";
536 # endif /* not RAND */
541 execvp (sendmail, vec);
542 fprintf (stderr, "unable to exec ");
544 _exit (-1); /* NOTREACHED */
547 SIGNAL (SIGALRM, alrmser);
548 SIGNAL (SIGPIPE, SIG_IGN);
552 if ((sm_rfp = fdopen (pdi[0], "r")) == NULL
553 || (sm_wfp = fdopen (pdo[1], "w")) == NULL) {
556 sm_rfp = sm_wfp = NULL;
557 return sm_ierror ("unable to fdopen");
573 result = smtalk (SM_HELO, "EHLO %s", client);
576 if (500 <= result && result <= 599)
577 result = smtalk (SM_HELO, "HELO %s", client);
590 * If the user asked for SASL, then check to see if the SMTP server
591 * supports it. Otherwise, error out (because the SMTP server
592 * might have been spoofed; we don't want to just silently not
597 if (! (server_mechs = EHLOset("AUTH"))) {
599 return sm_ierror("SMTP server does not support SASL");
602 if (saslmech && stringdex(saslmech, server_mechs) == -1) {
604 return sm_ierror("Requested SASL mech \"%s\" is not in the "
605 "list of supported mechanisms:\n%s",
606 saslmech, server_mechs);
609 if (sm_auth_sasl(user, saslssf, saslmech ? saslmech : server_mechs,
615 #endif /* CYRUS_SASL */
618 smtalk (SM_HELO, "ONEX");
620 smtalk (SM_HELO, "VERB on");
627 rclient (char *server, char *service)
630 char response[BUFSIZ];
632 if ((sd = client (server, service, response, sizeof(response),
636 sm_ierror ("%s", response);
641 sm_winit (int mode, char *from)
643 char *smtpcom = NULL;
663 /* Hopefully, we do not get here. */
667 switch (smtalk (SM_MAIL, "%s FROM:<%s>", smtpcom, from)) {
684 sm_wadr (char *mbox, char *host, char *path)
686 switch (smtalk (SM_RCPT, host && *host ? "RCPT TO:<%s%s@%s>"
688 path ? path : "", mbox, host)) {
698 #endif /* SENDMAILBUG */
723 switch (smtalk (SM_DATA, "DATA")) {
732 #endif /* SENDMAILBUG */
749 sm_wtxt (char *buffer, int len)
755 result = sm_wstream (buffer, len);
758 return (result == NOTOK ? RP_BHST : RP_OK);
765 if (sm_wstream ((char *) NULL, 0) == NOTOK)
768 switch (smtalk (SM_DOT + 3 * sm_addrs, ".")) {
776 #endif /* SENDMAILBUG */
794 if (sm_mts == MTS_SENDMAIL) {
805 if (sm_rfp == NULL && sm_wfp == NULL)
810 smtalk (SM_QUIT, "QUIT");
814 sm_note.code = sm_reply.code;
815 sm_note.length = sm_reply.length;
816 memcpy (sm_note.text, sm_reply.text, sm_reply.length + 1);/* fall */
818 if (smtalk (SM_RSET, "RSET") == 250 && type == DONE)
820 if (sm_mts == MTS_SMTP)
821 smtalk (SM_QUIT, "QUIT");
823 kill (sm_child, SIGKILL);
828 sm_reply.code = sm_note.code;
829 sm_reply.length = sm_note.length;
830 memcpy (sm_reply.text, sm_note.text, sm_note.length + 1);
837 BIO_ssl_shutdown(io);
840 #endif /* TLS_SUPPORT */
842 if (sm_rfp != NULL) {
847 if (sm_wfp != NULL) {
853 if (sm_mts == MTS_SMTP) {
858 if (sasl_outbuffer) {
859 free(sasl_outbuffer);
864 #endif /* CYRUS_SASL */
866 status = pidwait (sm_child, OK);
870 sm_rfp = sm_wfp = NULL;
871 return (status ? RP_BHST : RP_OK);
876 * This function implements SASL authentication for SMTP. If this function
877 * completes successfully, then authentication is successful and we've
878 * (optionally) negotiated a security layer.
881 sm_auth_sasl(char *user, int saslssf, char *mechlist, char *inhost)
884 unsigned int buflen, outlen;
885 char *buf, outbuf[BUFSIZ], host[NI_MAXHOST];
886 const char *chosen_mech;
887 sasl_security_properties_t secprops;
892 * Initialize the callback contexts
896 user = getusername();
898 callbacks[SM_SASL_N_CB_USER].context = user;
899 callbacks[SM_SASL_N_CB_AUTHNAME].context = user;
902 * This is a _bit_ of a hack ... but if the hostname wasn't supplied
903 * to us on the command line, then call getpeername and do a
904 * reverse-address lookup on the IP address to get the name.
907 memset(host, 0, sizeof(host));
910 struct sockaddr_storage sin;
911 socklen_t len = sizeof(sin);
914 if (getpeername(fileno(sm_wfp), (struct sockaddr *) &sin, &len) < 0) {
915 sm_ierror("getpeername on SMTP socket failed: %s",
920 result = getnameinfo((struct sockaddr *) &sin, len, host, sizeof(host),
921 NULL, 0, NI_NAMEREQD);
923 sm_ierror("Unable to look up name of connected host: %s",
924 gai_strerror(result));
928 strncpy(host, inhost, sizeof(host) - 1);
931 sasl_pw_context[0] = host;
932 sasl_pw_context[1] = user;
934 callbacks[SM_SASL_N_CB_PASS].context = sasl_pw_context;
936 result = sasl_client_init(callbacks);
938 if (result != SASL_OK) {
939 sm_ierror("SASL library initialization failed: %s",
940 sasl_errstring(result, NULL, NULL));
944 result = sasl_client_new("smtp", host, NULL, NULL, NULL, 0, &conn);
946 if (result != SASL_OK) {
947 sm_ierror("SASL client initialization failed: %s",
948 sasl_errstring(result, NULL, NULL));
953 * Initialize the security properties. But if TLS is active, then
954 * don't negotiate encryption here.
957 memset(&secprops, 0, sizeof(secprops));
958 secprops.maxbufsize = SASL_MAXRECVBUF;
959 secprops.max_ssf = tls_active ? 0 : (saslssf != -1 ? saslssf : UINT_MAX);
961 result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
963 if (result != SASL_OK) {
964 sm_ierror("SASL security property initialization failed: %s",
965 sasl_errstring(result, NULL, NULL));
970 * Start the actual protocol. Feed the mech list into the library
971 * and get out a possible initial challenge
974 result = sasl_client_start(conn, mechlist, NULL, (const char **) &buf,
975 &buflen, (const char **) &chosen_mech);
977 if (result != SASL_OK && result != SASL_CONTINUE) {
978 sm_ierror("SASL client start failed: %s", sasl_errdetail(conn));
983 * If we got an initial challenge, send it as part of the AUTH
984 * command; otherwise, just send a plain AUTH command.
988 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
989 if (status != SASL_OK) {
990 sm_ierror("SASL base64 encode failed: %s",
991 sasl_errstring(status, NULL, NULL));
995 status = smtalk(SM_AUTH, "AUTH %s %s", chosen_mech, outbuf);
997 status = smtalk(SM_AUTH, "AUTH %s", chosen_mech);
1000 * Now we loop until we either fail, get a SASL_OK, or a 235
1001 * response code. Receive the challenges and process them until
1005 while (result == SASL_CONTINUE) {
1008 * If we get a 235 response, that means authentication has
1009 * succeeded and we need to break out of the loop (yes, even if
1010 * we still get SASL_CONTINUE from sasl_client_step()).
1012 * Otherwise, if we get a message that doesn't seem to be a
1013 * valid response, then abort
1018 else if (status < 300 || status > 399)
1022 * Special case; a zero-length response from the SMTP server
1023 * is returned as a single =. If we get that, then set buflen
1024 * to be zero. Otherwise, just decode the response.
1027 if (strcmp("=", sm_reply.text) == 0) {
1030 result = sasl_decode64(sm_reply.text, sm_reply.length,
1031 outbuf, sizeof(outbuf), &outlen);
1033 if (result != SASL_OK) {
1034 smtalk(SM_AUTH, "*");
1035 sm_ierror("SASL base64 decode failed: %s",
1036 sasl_errstring(result, NULL, NULL));
1041 result = sasl_client_step(conn, outbuf, outlen, NULL,
1042 (const char **) &buf, &buflen);
1044 if (result != SASL_OK && result != SASL_CONTINUE) {
1045 smtalk(SM_AUTH, "*");
1046 sm_ierror("SASL client negotiation failed: %s",
1047 sasl_errstring(result, NULL, NULL));
1051 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
1053 if (status != SASL_OK) {
1054 smtalk(SM_AUTH, "*");
1055 sm_ierror("SASL base64 encode failed: %s",
1056 sasl_errstring(status, NULL, NULL));
1060 status = smtalk(SM_AUTH, outbuf);
1064 * Make sure that we got the correct response
1067 if (status < 200 || status > 299)
1071 * We _should_ have completed the authentication successfully.
1072 * Get a few properties from the authentication exchange.
1075 result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &outbufmax);
1077 if (result != SASL_OK) {
1078 sm_ierror("Cannot retrieve SASL negotiated output buffer size: %s",
1079 sasl_errstring(result, NULL, NULL));
1083 maxoutbuf = *outbufmax;
1085 result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
1089 if (result != SASL_OK) {
1090 sm_ierror("Cannot retrieve SASL negotiated security strength "
1091 "factor: %s", sasl_errstring(result, NULL, NULL));
1096 sasl_outbuffer = malloc(maxoutbuf);
1098 if (sasl_outbuffer == NULL) {
1099 sm_ierror("Unable to allocate %d bytes for SASL output "
1100 "buffer", maxoutbuf);
1105 sasl_inptr = sasl_inbuffer;
1107 sasl_outbuffer = NULL;
1108 /* Don't NULL out sasl_inbuffer because it could be used in
1118 * Our callback functions to feed data to the SASL library
1122 sm_get_user(void *context, int id, const char **result, unsigned *len)
1124 char *user = (char *) context;
1126 if (! result || ((id != SASL_CB_USER) && (id != SASL_CB_AUTHNAME)))
1127 return SASL_BADPARAM;
1131 *len = strlen(user);
1137 sm_get_pass(sasl_conn_t *conn, void *context, int id,
1138 sasl_secret_t **psecret)
1142 char **pw_context = (char **) context;
1146 if (! psecret || id != SASL_CB_PASS)
1147 return SASL_BADPARAM;
1149 ruserpass(pw_context[0], &(pw_context[1]), &pass);
1153 *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
1160 (*psecret)->len = len;
1161 strcpy((char *) (*psecret)->data, pass);
1166 #endif /* CYRUS_SASL */
1169 sm_ierror (char *fmt, ...)
1174 vsnprintf (sm_reply.text, sizeof(sm_reply.text), fmt, ap);
1177 sm_reply.length = strlen (sm_reply.text);
1178 sm_reply.code = NOTOK;
1184 smtalk (int time, char *fmt, ...)
1188 char buffer[BUFSIZ];
1191 vsnprintf (buffer, sizeof(buffer), fmt, ap);
1196 printf("(sasl-encrypted) ");
1198 printf("(tls-encrypted) ");
1199 printf ("=> %s\n", buffer);
1204 alarm ((unsigned) time);
1205 if ((result = sm_wrecord (buffer, strlen (buffer))) != NOTOK)
1214 * write the buffer to the open SMTP channel
1218 sm_wrecord (char *buffer, int len)
1221 return sm_werror ();
1223 sm_fwrite (buffer, len);
1227 return (ferror (sm_wfp) ? sm_werror () : OK);
1232 sm_wstream (char *buffer, int len)
1235 static char lc = '\0';
1238 return sm_werror ();
1240 if (buffer == NULL && len == 0) {
1244 return (ferror (sm_wfp) ? sm_werror () : OK);
1247 for (bp = buffer; len > 0; bp++, len--) {
1256 sm_fputc ('.');/* FALL THROUGH */
1261 if (ferror (sm_wfp))
1262 return sm_werror ();
1267 return (ferror (sm_wfp) ? sm_werror () : OK);
1271 * Write out to the network, but do buffering for SASL (if enabled)
1275 sm_fwrite(char *buffer, int len)
1279 unsigned int outputlen;
1281 if (sasl_complete == 0 || sasl_ssf == 0) {
1282 #endif /* CYRUS_SASL */
1287 ret = BIO_write(io, buffer, len);
1290 sm_ierror("TLS error during write: %s",
1291 ERR_error_string(ERR_get_error(), NULL));
1295 #endif /* TLS_SUPPORT */
1296 fwrite(buffer, sizeof(*buffer), len, sm_wfp);
1299 while (len >= maxoutbuf - sasl_outbuflen) {
1300 memcpy(sasl_outbuffer + sasl_outbuflen, buffer,
1301 maxoutbuf - sasl_outbuflen);
1302 len -= maxoutbuf - sasl_outbuflen;
1305 if (sasl_encode(conn, sasl_outbuffer, maxoutbuf,
1306 &output, &outputlen) != SASL_OK) {
1307 sm_ierror("Unable to SASL encode connection data: %s",
1308 sasl_errdetail(conn));
1312 fwrite(output, sizeof(*output), outputlen, sm_wfp);
1316 memcpy(sasl_outbuffer + sasl_outbuflen, buffer, len);
1317 sasl_outbuflen += len;
1320 #endif /* CYRUS_SASL */
1321 return ferror(sm_wfp) ? NOTOK : RP_OK;
1325 * Convenience functions to replace occurences of fputs() and fputc()
1329 sm_fputs(char *buffer)
1331 return sm_fwrite(buffer, strlen(buffer));
1339 return sm_fwrite(&h, 1);
1343 * Flush out any pending data on the connection
1351 unsigned int outputlen;
1354 if (sasl_complete == 1 && sasl_ssf > 0 && sasl_outbuflen > 0) {
1355 result = sasl_encode(conn, sasl_outbuffer, sasl_outbuflen,
1356 &output, &outputlen);
1357 if (result != SASL_OK) {
1358 sm_ierror("Unable to SASL encode connection data: %s",
1359 sasl_errdetail(conn));
1363 fwrite(output, sizeof(*output), outputlen, sm_wfp);
1366 #endif /* CYRUS_SASL */
1370 (void) BIO_flush(io);
1372 #endif /* TLS_SUPPORT */
1381 strlen (strcpy (sm_reply.text, sm_wfp == NULL ? "no socket opened"
1382 : sm_alarmed ? "write to socket timed out"
1383 : "error writing to socket"));
1385 return (sm_reply.code = NOTOK);
1392 int i, code, cont, bc = 0, rc, more;
1395 char **ehlo = NULL, buffer[BUFSIZ];
1398 static int at_least_once = 0;
1400 if (at_least_once) {
1403 for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1417 sm_reply.length = 0;
1418 sm_reply.text[0] = 0;
1420 rc = sizeof(sm_reply.text) - 1;
1422 for (more = FALSE; sm_rrecord ((char *) (bp = (unsigned char *) buffer),
1426 printf("(sasl-decrypted) ");
1428 printf("(tls-decrypted) ");
1429 printf ("<= %s\n", buffer);
1434 && strncmp (buffer, "250", sizeof("250") - 1) == 0
1435 && (buffer[3] == '-' || doingEHLO == 2)
1437 if (doingEHLO == 2) {
1438 if ((*ehlo = malloc ((size_t) (strlen (buffer + 4) + 1)))) {
1439 strcpy (*ehlo++, buffer + 4);
1441 if (ehlo >= EHLOkeys + MAXEHLO)
1451 for (; bc > 0 && (!isascii (*bp) || !isdigit (*bp)); bp++, bc--)
1455 code = atoi ((char *) bp);
1457 for (; bc > 0 && isspace (*bp); bp++, bc--)
1459 if (bc > 0 && *bp == '-') {
1462 for (; bc > 0 && isspace (*bp); bp++, bc--)
1467 if (code != sm_reply.code || cont)
1471 sm_reply.code = code;
1474 /* can never fail to 0-terminate because of size of buffer vs fixed string */
1475 strncpy (buffer, sm_noreply, sizeof(buffer));
1476 bp = (unsigned char *) buffer;
1477 bc = strlen (sm_noreply);
1481 if ((i = min (bc, rc)) > 0) {
1485 i = strlen(sm_moreply);
1486 if (more && rc > i + 1) {
1487 memcpy (rp, sm_moreply, i); /* safe because of check in if() */
1494 if (sm_reply.code < 100) {
1496 printf ("%s\n", sm_reply.text);
1502 sm_reply.length = rp - sm_reply.text;
1503 sm_reply.text[sm_reply.length] = 0;
1504 return sm_reply.code;
1511 sm_rrecord (char *buffer, int *len)
1516 return sm_rerror(0);
1518 buffer[*len = 0] = 0;
1520 if ((retval = sm_fgets (buffer, BUFSIZ, sm_rfp)) != RP_OK)
1522 *len = strlen (buffer);
1523 /* *len should be >0 except on EOF, but check for safety's sake */
1525 return sm_rerror (RP_EOF);
1526 if (buffer[*len - 1] != '\n')
1527 while ((retval = sm_fgetc (sm_rfp)) != '\n' && retval != EOF &&
1531 if ((*len > 1) && (buffer[*len - 2] == '\r'))
1540 * Our version of fgets, which calls our private fgetc function
1544 sm_fgets(char *buffer, int size, FILE *f)
1558 } while (size > 1 && c != '\n');
1566 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
1568 * Read from the network, but do SASL or TLS encryption
1574 char tmpbuf[BUFSIZ], *retbuf;
1575 unsigned int retbufsize = 0;
1579 * If we have leftover data, return it
1582 if (sasl_inbuflen) {
1584 return (int) *sasl_inptr++;
1588 * If not, read from the network until we have some data to return
1591 while (retbufsize == 0) {
1595 cc = SSL_read(ssl, tmpbuf, sizeof(tmpbuf));
1598 result = SSL_get_error(ssl, cc);
1600 if (result != SSL_ERROR_ZERO_RETURN) {
1601 sm_ierror("TLS peer aborted connection");
1608 sm_ierror("SSL_read failed: %s",
1609 ERR_error_string(ERR_get_error(), NULL));
1613 #endif /* TLS_SUPPORT */
1615 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1621 sm_ierror("Unable to read from network: %s", strerror(errno));
1626 * Don't call sasl_decode unless sasl is complete and we have
1627 * encryption working
1631 if (sasl_complete == 0 || sasl_ssf == 0) {
1635 result = sasl_decode(conn, tmpbuf, cc, (const char **) &retbuf,
1638 if (result != SASL_OK) {
1639 sm_ierror("Unable to decode SASL network data: %s",
1640 sasl_errdetail(conn));
1644 #else /* ! CYRUS_SASL */
1647 #endif /* CYRUS_SASL */
1650 if (retbufsize > SASL_MAXRECVBUF) {
1651 sm_ierror("Received data (%d bytes) is larger than the buffer "
1652 "size (%d bytes)", retbufsize, SASL_MAXRECVBUF);
1656 memcpy(sasl_inbuffer, retbuf, retbufsize);
1657 sasl_inptr = sasl_inbuffer + 1;
1658 sasl_inbuflen = retbufsize - 1;
1660 return (int) sasl_inbuffer[0];
1662 #endif /* CYRUS_SASL || TLS_SUPPORT */
1667 if (sm_mts == MTS_SMTP)
1669 strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no socket opened"
1670 : sm_alarmed ? "read from socket timed out"
1671 : rc == RP_EOF ? "premature end-of-file on socket"
1672 : "error reading from socket"));
1675 strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no pipe opened"
1676 : sm_alarmed ? "read from pipe timed out"
1677 : rc == RP_EOF ? "premature end-of-file on pipe"
1678 : "error reading from pipe"));
1680 return (sm_reply.code = NOTOK);
1689 #ifndef RELIABLE_SIGNALS
1690 SIGNAL (SIGALRM, alrmser);
1695 printf ("timed out...\n");
1702 rp_string (int code)
1705 static char buffer[BUFSIZ];
1707 switch (sm_reply.code != NOTOK ? code : NOTOK) {
1727 snprintf (buffer, sizeof(buffer), "[%s] %s", text, sm_reply.text);
1747 snprintf (buffer, sizeof(buffer), "[%s] %3d %s",
1748 text, sm_reply.code, sm_reply.text);
1760 for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1762 if (strncmp (ep, s, len) == 0) {
1763 for (ep += len; *ep == ' '; ep++)