2 * smtp.c -- nmh SMTP interface
6 * This code is Copyright (c) 2002, by the authors of nmh. See the
7 * COPYRIGHT file in the root directory of the nmh distribution for
8 * complete copyright information.
15 #include <h/signals.h>
18 #include <sasl/sasl.h>
19 #include <sasl/saslutil.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
25 #endif /* CYRUS_SASL */
28 #include <openssl/ssl.h>
29 #include <openssl/err.h>
30 #endif /* TLS_SUPPORT */
33 * This module implements an interface to SendMail very similar
34 * to the MMDF mm_(3) routines. The sm_() routines herein talk
35 * SMTP to a sendmail process, mapping SMTP reply codes into
40 * On older 4.2BSD machines without the POSIX function `sigaction',
41 * the alarm handing stuff for time-outs will NOT work due to the way
42 * syscalls get restarted. This is not really crucial, since SendMail
43 * is generally well-behaved in this area.
48 * It appears that some versions of Sendmail will return Code 451
49 * when they don't really want to indicate a failure.
50 * "Code 451 almost always means sendmail has deferred; we don't
51 * really want bomb out at this point since sendmail will rectify
52 * things later." So, if you define SENDMAILBUG, Code 451 is
53 * considered the same as Code 250. Yuck!
60 #define NBITS ((sizeof (int)) * 8)
63 * these codes must all be different!
65 #define SM_OPEN 300 /* Changed to 5 minutes to comply with a SHOULD in RFC 1123 */
68 #define SM_MAIL 301 /* changed to 5 minutes and a second (for uniqueness), see above */
69 #define SM_RCPT 302 /* see above */
70 #define SM_DATA 120 /* see above */
71 #define SM_TEXT 180 /* see above */
72 #define SM_DOT 600 /* see above */
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 #endif /* TLS_SUPPORT */
123 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
124 #define SASL_MAXRECVBUF 65536
125 static int sm_fgetc(FILE *);
126 static char *sasl_inbuffer
; /* SASL input buffer for encryption */
127 static char *sasl_inptr
; /* Pointer to current inbuf position */
128 static int sasl_inbuflen
; /* Current length of data in inbuf */
130 #define sm_fgetc fgetc
133 static int tls_active
= 0;
135 static char *sm_noreply
= "No reply text given";
136 static char *sm_moreply
= "; ";
138 struct smtp sm_reply
; /* global... */
142 static int doingEHLO
;
143 char *EHLOkeys
[MAXEHLO
+ 1];
148 static int smtp_init (char *, char *, char *, int, int, int, int, int, int,
149 char *, char *, int);
150 static int sendmail_init (char *, char *, int, int, int, int, int, int,
153 static int rclient (char *, char *);
154 static int sm_ierror (char *fmt
, ...);
155 static int smtalk (int time
, char *fmt
, ...);
156 static int sm_wrecord (char *, int);
157 static int sm_wstream (char *, int);
158 static int sm_werror (void);
159 static int smhear (void);
160 static int sm_rrecord (char *, int *);
161 static int sm_rerror (int);
162 static RETSIGTYPE
alrmser (int);
163 static char *EHLOset (char *);
164 static int sm_fwrite(char *, int);
165 static int sm_fputs(char *);
166 static int sm_fputc(int);
167 static void sm_fflush(void);
168 static int sm_fgets(char *, int, FILE *);
172 * Function prototypes needed for SASL
175 static int sm_auth_sasl(char *, char *, char *);
176 #endif /* CYRUS_SASL */
179 sm_init (char *client
, char *server
, char *port
, int watch
, int verbose
,
180 int debug
, int onex
, int queued
, int sasl
, char *saslmech
,
183 if (sm_mts
== MTS_SMTP
)
184 return smtp_init (client
, server
, port
, watch
, verbose
,
185 debug
, onex
, queued
, sasl
, saslmech
, user
, tls
);
187 return sendmail_init (client
, server
, watch
, verbose
,
188 debug
, onex
, queued
, sasl
, saslmech
, user
);
192 smtp_init (char *client
, char *server
, char *port
, int watch
, int verbose
,
193 int debug
, int onex
, int queued
,
194 int sasl
, char *saslmech
, char *user
, int tls
)
198 #endif /* CYRUS_SASL */
199 int result
, sd1
, sd2
;
204 sm_verbose
= verbose
;
207 if (sm_rfp
!= NULL
&& sm_wfp
!= NULL
)
210 if (client
== NULL
|| *client
== '\0') {
214 client
= LocalName(); /* no clientname -> LocalName */
219 * Last-ditch check just in case client still isn't set to anything
222 if (client
== NULL
|| *client
== '\0')
223 client
= "localhost";
225 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
226 sasl_inbuffer
= malloc(SASL_MAXRECVBUF
);
228 return sm_ierror("Unable to allocate %d bytes for read buffer",
230 #endif /* CYRUS_SASL || TLS_SUPPORT */
232 if ((sd1
= rclient (server
, port
)) == NOTOK
)
235 if ((sd2
= dup (sd1
)) == NOTOK
) {
237 return sm_ierror ("unable to dup");
240 SIGNAL (SIGALRM
, alrmser
);
241 SIGNAL (SIGPIPE
, SIG_IGN
);
243 if ((sm_rfp
= fdopen (sd1
, "r")) == NULL
244 || (sm_wfp
= fdopen (sd2
, "w")) == NULL
) {
247 sm_rfp
= sm_wfp
= NULL
;
248 return sm_ierror ("unable to fdopen");
268 * Give EHLO or HELO command
272 result
= smtalk (SM_HELO
, "EHLO %s", client
);
275 if (result
>= 500 && result
<= 599)
276 result
= smtalk (SM_HELO
, "HELO %s", client
);
285 * If the user requested TLS support, then try to do the STARTTLS command
286 * as part of the initial dialog. Assuming this works, we then need to
287 * restart the EHLO dialog after TLS negotiation is complete.
291 if (! EHLOset("STARTTLS")) {
293 return sm_ierror("SMTP server does not support TLS");
296 result
= smtalk(SM_HELO
, "STARTTLS");
304 * Okay, the other side should be waiting for us to start TLS
305 * negotiation. Oblige them.
312 SSL_load_error_strings();
314 method
= TLSv1_client_method(); /* Not sure about this */
316 sslctx
= SSL_CTX_new(method
);
320 return sm_ierror("Unable to initialize OpenSSL context: %s",
321 ERR_error_string(ERR_get_error(), NULL
));
325 ssl
= SSL_new(sslctx
);
329 return sm_ierror("Unable to create SSL connection: %s",
330 ERR_error_string(ERR_get_error(), NULL
));
333 sbior
= BIO_new_socket(fileno(sm_rfp
), BIO_NOCLOSE
);
334 sbiow
= BIO_new_socket(fileno(sm_wfp
), BIO_NOCLOSE
);
336 if (sbior
== NULL
|| sbiow
== NULL
) {
338 return sm_ierror("Unable to create BIO endpoints: %s",
339 ERR_error_string(ERR_get_error(), NULL
));
342 SSL_set_bio(ssl
, sbior
, sbiow
);
344 if (SSL_connect(ssl
) < 1) {
346 return sm_ierror("Unable to negotiate SSL connection: %s",
347 ERR_error_string(ERR_get_error(), NULL
));
351 SSL_CIPHER
*cipher
= SSL_get_current_cipher(ssl
);
352 printf("SSL negotiation successful: %s(%d) %s\n",
353 SSL_CIPHER_get_name(cipher
),
354 SSL_CIPHER_get_bits(cipher
, NULL
),
355 SSL_CIPHER_get_version(cipher
));
362 result
= smtalk (SM_HELO
, "EHLO %s", client
);
370 #endif /* TLS_SUPPORT */
374 * If the user asked for SASL, then check to see if the SMTP server
375 * supports it. Otherwise, error out (because the SMTP server
376 * might have been spoofed; we don't want to just silently not
381 if (! (server_mechs
= EHLOset("AUTH"))) {
383 return sm_ierror("SMTP server does not support SASL");
386 if (saslmech
&& stringdex(saslmech
, server_mechs
) == -1) {
388 return sm_ierror("Requested SASL mech \"%s\" is not in the "
389 "list of supported mechanisms:\n%s",
390 saslmech
, server_mechs
);
393 if (sm_auth_sasl(user
, saslmech
? saslmech
: server_mechs
,
399 #endif /* CYRUS_SASL */
402 if (watch
&& EHLOset ("XVRB"))
403 smtalk (SM_HELO
, "VERB on");
404 if (onex
&& EHLOset ("XONE"))
405 smtalk (SM_HELO
, "ONEX");
406 if (queued
&& EHLOset ("XQUE"))
407 smtalk (SM_HELO
, "QUED");
413 sendmail_init (char *client
, char *server
, int watch
, int verbose
,
414 int debug
, int onex
, int queued
,
415 int sasl
, char *saslmech
, char *user
)
419 #endif /* CYRUS_SASL */
427 sm_verbose
= verbose
;
429 if (sm_rfp
!= NULL
&& sm_wfp
!= NULL
)
432 if (client
== NULL
|| *client
== '\0') {
436 client
= LocalName(); /* no clientname -> LocalName */
440 * Last-ditch check just in case client still isn't set to anything
443 if (client
== NULL
|| *client
== '\0')
444 client
= "localhost";
447 sasl_inbuffer
= malloc(SASL_MAXRECVBUF
);
449 return sm_ierror("Unable to allocate %d bytes for read buffer",
451 #endif /* CYRUS_SASL */
453 if (pipe (pdi
) == NOTOK
)
454 return sm_ierror ("no pipes");
455 if (pipe (pdo
) == NOTOK
) {
458 return sm_ierror ("no pipes");
461 for (i
= 0; (sm_child
= fork ()) == NOTOK
&& i
< 5; i
++)
470 return sm_ierror ("unable to fork");
473 if (pdo
[0] != fileno (stdin
))
474 dup2 (pdo
[0], fileno (stdin
));
475 if (pdi
[1] != fileno (stdout
))
476 dup2 (pdi
[1], fileno (stdout
));
477 if (pdi
[1] != fileno (stderr
))
478 dup2 (pdi
[1], fileno (stderr
));
479 for (i
= fileno (stderr
) + 1; i
< NBITS
; i
++)
483 vec
[vecp
++] = r1bindex (sendmail
, '/');
485 vec
[vecp
++] = watch
? "-odi" : queued
? "-odq" : "-odb";
486 vec
[vecp
++] = "-oem";
491 # endif /* not RAND */
496 execvp (sendmail
, vec
);
497 fprintf (stderr
, "unable to exec ");
499 _exit (-1); /* NOTREACHED */
502 SIGNAL (SIGALRM
, alrmser
);
503 SIGNAL (SIGPIPE
, SIG_IGN
);
507 if ((sm_rfp
= fdopen (pdi
[0], "r")) == NULL
508 || (sm_wfp
= fdopen (pdo
[1], "w")) == NULL
) {
511 sm_rfp
= sm_wfp
= NULL
;
512 return sm_ierror ("unable to fdopen");
528 result
= smtalk (SM_HELO
, "EHLO %s", client
);
531 if (500 <= result
&& result
<= 599)
532 result
= smtalk (SM_HELO
, "HELO %s", client
);
545 * If the user asked for SASL, then check to see if the SMTP server
546 * supports it. Otherwise, error out (because the SMTP server
547 * might have been spoofed; we don't want to just silently not
552 if (! (server_mechs
= EHLOset("AUTH"))) {
554 return sm_ierror("SMTP server does not support SASL");
557 if (saslmech
&& stringdex(saslmech
, server_mechs
) == -1) {
559 return sm_ierror("Requested SASL mech \"%s\" is not in the "
560 "list of supported mechanisms:\n%s",
561 saslmech
, server_mechs
);
564 if (sm_auth_sasl(user
, saslmech
? saslmech
: server_mechs
,
570 #endif /* CYRUS_SASL */
573 smtalk (SM_HELO
, "ONEX");
575 smtalk (SM_HELO
, "VERB on");
582 rclient (char *server
, char *service
)
585 char response
[BUFSIZ
];
587 if ((sd
= client (server
, service
, response
, sizeof(response
),
591 sm_ierror ("%s", response
);
596 sm_winit (int mode
, char *from
)
598 char *smtpcom
= NULL
;
618 /* Hopefully, we do not get here. */
622 switch (smtalk (SM_MAIL
, "%s FROM:<%s>", smtpcom
, from
)) {
639 sm_wadr (char *mbox
, char *host
, char *path
)
641 switch (smtalk (SM_RCPT
, host
&& *host
? "RCPT TO:<%s%s@%s>"
643 path
? path
: "", mbox
, host
)) {
653 #endif /* SENDMAILBUG */
678 switch (smtalk (SM_DATA
, "DATA")) {
687 #endif /* SENDMAILBUG */
704 sm_wtxt (char *buffer
, int len
)
710 result
= sm_wstream (buffer
, len
);
713 return (result
== NOTOK
? RP_BHST
: RP_OK
);
720 if (sm_wstream ((char *) NULL
, 0) == NOTOK
)
723 switch (smtalk (SM_DOT
+ 3 * sm_addrs
, ".")) {
731 #endif /* SENDMAILBUG */
749 if (sm_mts
== MTS_SENDMAIL
) {
760 if (sm_rfp
== NULL
&& sm_wfp
== NULL
)
765 smtalk (SM_QUIT
, "QUIT");
769 sm_note
.code
= sm_reply
.code
;
770 sm_note
.length
= sm_reply
.length
;
771 memcpy (sm_note
.text
, sm_reply
.text
, sm_reply
.length
+ 1);/* fall */
773 if (smtalk (SM_RSET
, "RSET") == 250 && type
== DONE
)
775 if (sm_mts
== MTS_SMTP
)
776 smtalk (SM_QUIT
, "QUIT");
778 kill (sm_child
, SIGKILL
);
783 sm_reply
.code
= sm_note
.code
;
784 sm_reply
.length
= sm_note
.length
;
785 memcpy (sm_reply
.text
, sm_note
.text
, sm_note
.length
+ 1);
795 if (sm_rfp
!= NULL
) {
800 if (sm_wfp
!= NULL
) {
806 if (sm_mts
== MTS_SMTP
) {
811 if (sasl_outbuffer
) {
812 free(sasl_outbuffer
);
817 #endif /* CYRUS_SASL */
819 status
= pidwait (sm_child
, OK
);
823 sm_rfp
= sm_wfp
= NULL
;
824 return (status
? RP_BHST
: RP_OK
);
829 * This function implements SASL authentication for SMTP. If this function
830 * completes successfully, then authentication is successful and we've
831 * (optionally) negotiated a security layer.
834 sm_auth_sasl(char *user
, char *mechlist
, char *inhost
)
837 unsigned int buflen
, outlen
;
838 char *buf
, outbuf
[BUFSIZ
], host
[NI_MAXHOST
];
839 const char *chosen_mech
;
840 sasl_security_properties_t secprops
;
845 * Initialize the callback contexts
849 user
= getusername();
851 callbacks
[SM_SASL_N_CB_USER
].context
= user
;
852 callbacks
[SM_SASL_N_CB_AUTHNAME
].context
= user
;
855 * This is a _bit_ of a hack ... but if the hostname wasn't supplied
856 * to us on the command line, then call getpeername and do a
857 * reverse-address lookup on the IP address to get the name.
860 memset(host
, 0, sizeof(host
));
863 struct sockaddr_storage sin
;
864 socklen_t len
= sizeof(sin
);
867 if (getpeername(fileno(sm_wfp
), (struct sockaddr
*) &sin
, &len
) < 0) {
868 sm_ierror("getpeername on SMTP socket failed: %s",
873 result
= getnameinfo((struct sockaddr
*) &sin
, len
, host
, sizeof(host
),
874 NULL
, 0, NI_NAMEREQD
);
876 sm_ierror("Unable to look up name of connected host: %s",
877 gai_strerror(result
));
881 strncpy(host
, inhost
, sizeof(host
) - 1);
884 sasl_pw_context
[0] = host
;
885 sasl_pw_context
[1] = user
;
887 callbacks
[SM_SASL_N_CB_PASS
].context
= sasl_pw_context
;
889 result
= sasl_client_init(callbacks
);
891 if (result
!= SASL_OK
) {
892 sm_ierror("SASL library initialization failed: %s",
893 sasl_errstring(result
, NULL
, NULL
));
897 result
= sasl_client_new("smtp", host
, NULL
, NULL
, NULL
, 0, &conn
);
899 if (result
!= SASL_OK
) {
900 sm_ierror("SASL client initialization failed: %s",
901 sasl_errstring(result
, NULL
, NULL
));
906 * Initialize the security properties. But if TLS is active, then
907 * don't negotiate encryption here.
910 memset(&secprops
, 0, sizeof(secprops
));
911 secprops
.maxbufsize
= SASL_MAXRECVBUF
;
912 secprops
.max_ssf
= tls_active
? 0 : UINT_MAX
;
914 result
= sasl_setprop(conn
, SASL_SEC_PROPS
, &secprops
);
916 if (result
!= SASL_OK
) {
917 sm_ierror("SASL security property initialization failed: %s",
918 sasl_errstring(result
, NULL
, NULL
));
923 * Start the actual protocol. Feed the mech list into the library
924 * and get out a possible initial challenge
927 result
= sasl_client_start(conn
, mechlist
, NULL
, (const char **) &buf
,
928 &buflen
, (const char **) &chosen_mech
);
930 if (result
!= SASL_OK
&& result
!= SASL_CONTINUE
) {
931 sm_ierror("SASL client start failed: %s", sasl_errdetail(conn
));
936 * If we got an initial challenge, send it as part of the AUTH
937 * command; otherwise, just send a plain AUTH command.
941 status
= sasl_encode64(buf
, buflen
, outbuf
, sizeof(outbuf
), NULL
);
942 if (status
!= SASL_OK
) {
943 sm_ierror("SASL base64 encode failed: %s",
944 sasl_errstring(status
, NULL
, NULL
));
948 status
= smtalk(SM_AUTH
, "AUTH %s %s", chosen_mech
, outbuf
);
950 status
= smtalk(SM_AUTH
, "AUTH %s", chosen_mech
);
953 * Now we loop until we either fail, get a SASL_OK, or a 235
954 * response code. Receive the challenges and process them until
958 while (result
== SASL_CONTINUE
) {
961 * If we get a 235 response, that means authentication has
962 * succeeded and we need to break out of the loop (yes, even if
963 * we still get SASL_CONTINUE from sasl_client_step()).
965 * Otherwise, if we get a message that doesn't seem to be a
966 * valid response, then abort
971 else if (status
< 300 || status
> 399)
975 * Special case; a zero-length response from the SMTP server
976 * is returned as a single =. If we get that, then set buflen
977 * to be zero. Otherwise, just decode the response.
980 if (strcmp("=", sm_reply
.text
) == 0) {
983 result
= sasl_decode64(sm_reply
.text
, sm_reply
.length
,
984 outbuf
, sizeof(outbuf
), &outlen
);
986 if (result
!= SASL_OK
) {
987 smtalk(SM_AUTH
, "*");
988 sm_ierror("SASL base64 decode failed: %s",
989 sasl_errstring(result
, NULL
, NULL
));
994 result
= sasl_client_step(conn
, outbuf
, outlen
, NULL
,
995 (const char **) &buf
, &buflen
);
997 if (result
!= SASL_OK
&& result
!= SASL_CONTINUE
) {
998 smtalk(SM_AUTH
, "*");
999 sm_ierror("SASL client negotiation failed: %s",
1000 sasl_errstring(result
, NULL
, NULL
));
1004 status
= sasl_encode64(buf
, buflen
, outbuf
, sizeof(outbuf
), NULL
);
1006 if (status
!= SASL_OK
) {
1007 smtalk(SM_AUTH
, "*");
1008 sm_ierror("SASL base64 encode failed: %s",
1009 sasl_errstring(status
, NULL
, NULL
));
1013 status
= smtalk(SM_AUTH
, outbuf
);
1017 * Make sure that we got the correct response
1020 if (status
< 200 || status
> 299)
1024 * We _should_ have completed the authentication successfully.
1025 * Get a few properties from the authentication exchange.
1028 result
= sasl_getprop(conn
, SASL_MAXOUTBUF
, (const void **) &outbufmax
);
1030 if (result
!= SASL_OK
) {
1031 sm_ierror("Cannot retrieve SASL negotiated output buffer size: %s",
1032 sasl_errstring(result
, NULL
, NULL
));
1036 maxoutbuf
= *outbufmax
;
1038 result
= sasl_getprop(conn
, SASL_SSF
, (const void **) &ssf
);
1042 if (result
!= SASL_OK
) {
1043 sm_ierror("Cannot retrieve SASL negotiated security strength "
1044 "factor: %s", sasl_errstring(result
, NULL
, NULL
));
1049 sasl_outbuffer
= malloc(maxoutbuf
);
1051 if (sasl_outbuffer
== NULL
) {
1052 sm_ierror("Unable to allocate %d bytes for SASL output "
1053 "buffer", maxoutbuf
);
1058 sasl_inptr
= sasl_inbuffer
;
1060 sasl_outbuffer
= NULL
;
1061 /* Don't NULL out sasl_inbuffer because it could be used in
1071 * Our callback functions to feed data to the SASL library
1075 sm_get_user(void *context
, int id
, const char **result
, unsigned *len
)
1077 char *user
= (char *) context
;
1079 if (! result
|| ((id
!= SASL_CB_USER
) && (id
!= SASL_CB_AUTHNAME
)))
1080 return SASL_BADPARAM
;
1084 *len
= strlen(user
);
1090 sm_get_pass(sasl_conn_t
*conn
, void *context
, int id
,
1091 sasl_secret_t
**psecret
)
1093 char **pw_context
= (char **) context
;
1097 if (! psecret
|| id
!= SASL_CB_PASS
)
1098 return SASL_BADPARAM
;
1100 ruserpass(pw_context
[0], &(pw_context
[1]), &pass
);
1104 *psecret
= (sasl_secret_t
*) malloc(sizeof(sasl_secret_t
) + len
);
1111 (*psecret
)->len
= len
;
1112 strcpy((char *) (*psecret
)->data
, pass
);
1117 #endif /* CYRUS_SASL */
1120 sm_ierror (char *fmt
, ...)
1125 vsnprintf (sm_reply
.text
, sizeof(sm_reply
.text
), fmt
, ap
);
1128 sm_reply
.length
= strlen (sm_reply
.text
);
1129 sm_reply
.code
= NOTOK
;
1135 smtalk (int time
, char *fmt
, ...)
1139 char buffer
[BUFSIZ
];
1142 vsnprintf (buffer
, sizeof(buffer
), fmt
, ap
);
1147 printf("(sasl-encrypted) ");
1149 printf("(tls-encrypted) ");
1150 printf ("=> %s\n", buffer
);
1155 alarm ((unsigned) time
);
1156 if ((result
= sm_wrecord (buffer
, strlen (buffer
))) != NOTOK
)
1165 * write the buffer to the open SMTP channel
1169 sm_wrecord (char *buffer
, int len
)
1172 return sm_werror ();
1174 sm_fwrite (buffer
, len
);
1178 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1183 sm_wstream (char *buffer
, int len
)
1186 static char lc
= '\0';
1189 return sm_werror ();
1191 if (buffer
== NULL
&& len
== 0) {
1195 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1198 for (bp
= buffer
; len
> 0; bp
++, len
--) {
1207 sm_fputc ('.');/* FALL THROUGH */
1212 if (ferror (sm_wfp
))
1213 return sm_werror ();
1218 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1222 * Write out to the network, but do buffering for SASL (if enabled)
1226 sm_fwrite(char *buffer
, int len
)
1230 unsigned int outputlen
;
1232 if (sasl_complete
== 0 || sasl_ssf
== 0) {
1233 #endif /* CYRUS_SASL */
1238 ret
= SSL_write(ssl
, buffer
, len
);
1240 if (SSL_get_error(ssl
, ret
) != SSL_ERROR_NONE
) {
1241 sm_ierror("TLS error during write: %s",
1242 ERR_error_string(ERR_get_error(), NULL
));
1246 #endif /* TLS_SUPPORT */
1247 fwrite(buffer
, sizeof(*buffer
), len
, sm_wfp
);
1250 while (len
>= maxoutbuf
- sasl_outbuflen
) {
1251 memcpy(sasl_outbuffer
+ sasl_outbuflen
, buffer
,
1252 maxoutbuf
- sasl_outbuflen
);
1253 len
-= maxoutbuf
- sasl_outbuflen
;
1256 if (sasl_encode(conn
, sasl_outbuffer
, maxoutbuf
,
1257 &output
, &outputlen
) != SASL_OK
) {
1258 sm_ierror("Unable to SASL encode connection data: %s",
1259 sasl_errdetail(conn
));
1263 fwrite(output
, sizeof(*output
), outputlen
, sm_wfp
);
1267 memcpy(sasl_outbuffer
+ sasl_outbuflen
, buffer
, len
);
1268 sasl_outbuflen
+= len
;
1271 #endif /* CYRUS_SASL */
1272 return ferror(sm_wfp
) ? NOTOK
: RP_OK
;
1276 * Convenience functions to replace occurences of fputs() and fputc()
1280 sm_fputs(char *buffer
)
1282 return sm_fwrite(buffer
, strlen(buffer
));
1290 return sm_fwrite(&h
, 1);
1294 * Flush out any pending data on the connection
1302 unsigned int outputlen
;
1305 if (sasl_complete
== 1 && sasl_ssf
> 0 && sasl_outbuflen
> 0) {
1306 result
= sasl_encode(conn
, sasl_outbuffer
, sasl_outbuflen
,
1307 &output
, &outputlen
);
1308 if (result
!= SASL_OK
) {
1309 sm_ierror("Unable to SASL encode connection data: %s",
1310 sasl_errdetail(conn
));
1314 fwrite(output
, sizeof(*output
), outputlen
, sm_wfp
);
1317 #endif /* CYRUS_SASL */
1326 strlen (strcpy (sm_reply
.text
, sm_wfp
== NULL
? "no socket opened"
1327 : sm_alarmed
? "write to socket timed out"
1328 : "error writing to socket"));
1330 return (sm_reply
.code
= NOTOK
);
1337 int i
, code
, cont
, bc
= 0, rc
, more
;
1340 char **ehlo
= NULL
, buffer
[BUFSIZ
];
1343 static int at_least_once
= 0;
1345 if (at_least_once
) {
1348 for (ehlo
= EHLOkeys
; *ehlo
; ehlo
++) {
1362 sm_reply
.length
= 0;
1363 sm_reply
.text
[0] = 0;
1365 rc
= sizeof(sm_reply
.text
) - 1;
1367 for (more
= FALSE
; sm_rrecord ((char *) (bp
= (unsigned char *) buffer
),
1371 printf("(sasl-decrypted) ");
1373 printf("(tls-decrypted) ");
1374 printf ("<= %s\n", buffer
);
1379 && strncmp (buffer
, "250", sizeof("250") - 1) == 0
1380 && (buffer
[3] == '-' || doingEHLO
== 2)
1382 if (doingEHLO
== 2) {
1383 if ((*ehlo
= malloc ((size_t) (strlen (buffer
+ 4) + 1)))) {
1384 strcpy (*ehlo
++, buffer
+ 4);
1386 if (ehlo
>= EHLOkeys
+ MAXEHLO
)
1396 for (; bc
> 0 && (!isascii (*bp
) || !isdigit (*bp
)); bp
++, bc
--)
1400 code
= atoi ((char *) bp
);
1402 for (; bc
> 0 && isspace (*bp
); bp
++, bc
--)
1404 if (bc
> 0 && *bp
== '-') {
1407 for (; bc
> 0 && isspace (*bp
); bp
++, bc
--)
1412 if (code
!= sm_reply
.code
|| cont
)
1416 sm_reply
.code
= code
;
1419 /* can never fail to 0-terminate because of size of buffer vs fixed string */
1420 strncpy (buffer
, sm_noreply
, sizeof(buffer
));
1421 bp
= (unsigned char *) buffer
;
1422 bc
= strlen (sm_noreply
);
1426 if ((i
= min (bc
, rc
)) > 0) {
1430 i
= strlen(sm_moreply
);
1431 if (more
&& rc
> i
+ 1) {
1432 memcpy (rp
, sm_moreply
, i
); /* safe because of check in if() */
1439 if (sm_reply
.code
< 100) {
1441 printf ("%s\n", sm_reply
.text
);
1447 sm_reply
.length
= rp
- sm_reply
.text
;
1448 sm_reply
.text
[sm_reply
.length
] = 0;
1449 return sm_reply
.code
;
1456 sm_rrecord (char *buffer
, int *len
)
1461 return sm_rerror(0);
1463 buffer
[*len
= 0] = 0;
1465 if ((retval
= sm_fgets (buffer
, BUFSIZ
, sm_rfp
)) != RP_OK
)
1467 *len
= strlen (buffer
);
1468 /* *len should be >0 except on EOF, but check for safety's sake */
1470 return sm_rerror (RP_EOF
);
1471 if (buffer
[*len
- 1] != '\n')
1472 while ((retval
= sm_fgetc (sm_rfp
)) != '\n' && retval
!= EOF
&&
1476 if ((*len
> 1) && (buffer
[*len
- 2] == '\r'))
1485 * Our version of fgets, which calls our private fgetc function
1489 sm_fgets(char *buffer
, int size
, FILE *f
)
1503 } while (size
> 1 && c
!= '\n');
1511 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
1513 * Read from the network, but do SASL or TLS encryption
1519 char tmpbuf
[BUFSIZ
], *retbuf
;
1520 unsigned int retbufsize
= 0;
1524 * If we have leftover data, return it
1527 if (sasl_inbuflen
) {
1529 return (int) *sasl_inptr
++;
1533 * If not, read from the network until we have some data to return
1536 while (retbufsize
== 0) {
1540 cc
= SSL_read(ssl
, tmpbuf
, sizeof(tmpbuf
));
1543 result
= SSL_get_error(ssl
, cc
);
1545 if (result
!= SSL_ERROR_ZERO_RETURN
) {
1546 sm_ierror("TLS peer aborted connection");
1553 sm_ierror("SSL_read failed: %s",
1554 ERR_error_string(ERR_get_error(), NULL
));
1558 #endif /* TLS_SUPPORT */
1560 cc
= read(fileno(f
), tmpbuf
, sizeof(tmpbuf
));
1566 sm_ierror("Unable to read from network: %s", strerror(errno
));
1571 * Don't call sasl_decode unless sasl is complete and we have
1572 * encryption working
1575 if (sasl_complete
== 0 || sasl_ssf
== 0) {
1579 result
= sasl_decode(conn
, tmpbuf
, cc
, (const char **) &retbuf
,
1582 if (result
!= SASL_OK
) {
1583 sm_ierror("Unable to decode SASL network data: %s",
1584 sasl_errdetail(conn
));
1590 if (retbufsize
> SASL_MAXRECVBUF
) {
1591 sm_ierror("Received data (%d bytes) is larger than the buffer "
1592 "size (%d bytes)", retbufsize
, SASL_MAXRECVBUF
);
1596 memcpy(sasl_inbuffer
, retbuf
, retbufsize
);
1597 sasl_inptr
= sasl_inbuffer
+ 1;
1598 sasl_inbuflen
= retbufsize
- 1;
1600 return (int) sasl_inbuffer
[0];
1602 #endif /* CYRUS_SASL || TLS_SUPPORT */
1607 if (sm_mts
== MTS_SMTP
)
1609 strlen (strcpy (sm_reply
.text
, sm_rfp
== NULL
? "no socket opened"
1610 : sm_alarmed
? "read from socket timed out"
1611 : rc
== RP_EOF
? "premature end-of-file on socket"
1612 : "error reading from socket"));
1615 strlen (strcpy (sm_reply
.text
, sm_rfp
== NULL
? "no pipe opened"
1616 : sm_alarmed
? "read from pipe timed out"
1617 : rc
== RP_EOF
? "premature end-of-file on pipe"
1618 : "error reading from pipe"));
1620 return (sm_reply
.code
= NOTOK
);
1627 #ifndef RELIABLE_SIGNALS
1628 SIGNAL (SIGALRM
, alrmser
);
1633 printf ("timed out...\n");
1640 rp_string (int code
)
1643 static char buffer
[BUFSIZ
];
1645 switch (sm_reply
.code
!= NOTOK
? code
: NOTOK
) {
1665 snprintf (buffer
, sizeof(buffer
), "[%s] %s", text
, sm_reply
.text
);
1685 snprintf (buffer
, sizeof(buffer
), "[%s] %3d %s",
1686 text
, sm_reply
.code
, sm_reply
.text
);
1698 for (ehlo
= EHLOkeys
; *ehlo
; ehlo
++) {
1700 if (strncmp (ep
, s
, len
) == 0) {
1701 for (ep
+= len
; *ep
== ' '; ep
++)