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.
12 #include <h/signals.h>
15 #include <sasl/sasl.h>
16 #include <sasl/saslutil.h>
17 # if SASL_VERSION_FULL < 0x020125
18 /* Cyrus SASL 2.1.25 introduced the sasl_callback_ft prototype,
19 which has an explicit void parameter list, according to best
20 practice. So we need to cast to avoid compile warnings.
21 Provide this prototype for earlier versions. */
22 typedef int (*sasl_callback_ft
)();
23 # endif /* SASL_VERSION_FULL < 0x020125 */
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
28 #endif /* CYRUS_SASL */
31 #include <openssl/ssl.h>
32 #include <openssl/err.h>
33 #endif /* TLS_SUPPORT */
36 * This module implements an interface to SendMail very similar
37 * to the MMDF mm_(3) routines. The sm_() routines herein talk
38 * SMTP to a sendmail process, mapping SMTP reply codes into
43 * On older 4.2BSD machines without the POSIX function `sigaction',
44 * the alarm handing stuff for time-outs will NOT work due to the way
45 * syscalls get restarted. This is not really crucial, since SendMail
46 * is generally well-behaved in this area.
51 * It appears that some versions of Sendmail will return Code 451
52 * when they don't really want to indicate a failure.
53 * "Code 451 almost always means sendmail has deferred; we don't
54 * really want bomb out at this point since sendmail will rectify
55 * things later." So, if you define SENDMAILBUG, Code 451 is
56 * considered the same as Code 250. Yuck!
63 #define NBITS ((sizeof (int)) * 8)
66 * these codes must all be different!
68 #define SM_OPEN 300 /* Changed to 5 minutes to comply with a SHOULD in RFC 1123 */
71 #define SM_MAIL 301 /* changed to 5 minutes and a second (for uniqueness), see above */
72 #define SM_RCPT 302 /* see above */
73 #define SM_DATA 120 /* see above */
74 #define SM_TEXT 180 /* see above */
75 #define SM_DOT 600 /* see above */
80 #endif /* CYRUS_SASL */
82 static int sm_addrs
= 0;
83 static int sm_alarmed
= 0;
84 static int sm_child
= NOTOK
;
85 static int sm_debug
= 0;
86 static int sm_nl
= TRUE
;
87 static int sm_verbose
= 0;
89 static FILE *sm_rfp
= NULL
;
90 static FILE *sm_wfp
= NULL
;
94 * Some globals needed by SASL
97 static sasl_conn_t
*conn
= NULL
; /* SASL connection state */
98 static int sasl_complete
= 0; /* Has authentication succeded? */
99 static sasl_ssf_t sasl_ssf
; /* Our security strength factor */
100 static char *sasl_pw_context
[3]; /* Context to pass into sm_get_pass */
101 static int maxoutbuf
; /* Maximum crypto output buffer */
102 static char *sasl_outbuffer
; /* SASL output buffer for encryption */
103 static int sasl_outbuflen
; /* Current length of data in outbuf */
104 static int sm_get_user(void *, int, const char **, unsigned *);
105 static int sm_get_pass(sasl_conn_t
*, void *, int, sasl_secret_t
**);
107 static sasl_callback_t callbacks
[] = {
108 { SASL_CB_USER
, (sasl_callback_ft
) sm_get_user
, NULL
},
109 #define SM_SASL_N_CB_USER 0
110 { SASL_CB_AUTHNAME
, (sasl_callback_ft
) sm_get_user
, NULL
},
111 #define SM_SASL_N_CB_AUTHNAME 1
112 { SASL_CB_PASS
, (sasl_callback_ft
) sm_get_pass
, NULL
},
113 #define SM_SASL_N_CB_PASS 2
114 { SASL_CB_LIST_END
, NULL
, NULL
},
117 #else /* CYRUS_SASL */
119 #endif /* CYRUS_SASL */
122 static SSL_CTX
*sslctx
= NULL
;
123 static SSL
*ssl
= NULL
;
124 static BIO
*sbior
= NULL
;
125 static BIO
*sbiow
= NULL
;
126 static BIO
*io
= NULL
;
128 static int tls_negotiate(void);
129 #endif /* TLS_SUPPORT */
131 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
132 #define SASL_MAXRECVBUF 65536
133 static int sm_fgetc(FILE *);
134 static char *sasl_inbuffer
; /* SASL input buffer for encryption */
135 static char *sasl_inptr
; /* Pointer to current inbuf position */
136 static int sasl_inbuflen
; /* Current length of data in inbuf */
138 #define sm_fgetc fgetc
141 static int tls_active
= 0;
143 static char *sm_noreply
= "No reply text given";
144 static char *sm_moreply
= "; ";
146 struct smtp sm_reply
; /* global... */
150 static int doingEHLO
;
151 char *EHLOkeys
[MAXEHLO
+ 1];
156 static int smtp_init (char *, char *, char *, int, int, int, int, int, int,
157 char *, char *, int);
158 static int sendmail_init (char *, char *, int, int, int, int, int, int,
161 static int rclient (char *, char *);
162 static int sm_ierror (char *fmt
, ...);
163 static int smtalk (int time
, char *fmt
, ...);
164 static int sm_wrecord (char *, int);
165 static int sm_wstream (char *, int);
166 static int sm_werror (void);
167 static int smhear (void);
168 static int sm_rrecord (char *, int *);
169 static int sm_rerror (int);
170 static void alrmser (int);
171 static char *EHLOset (char *);
172 static int sm_fwrite(char *, int);
173 static int sm_fputs(char *);
174 static int sm_fputc(int);
175 static void sm_fflush(void);
176 static int sm_fgets(char *, int, FILE *);
180 * Function prototypes needed for SASL
183 static int sm_auth_sasl(char *, int, char *, char *);
184 #endif /* CYRUS_SASL */
187 sm_init (char *client
, char *server
, char *port
, int watch
, int verbose
,
188 int debug
, int queued
, int sasl
, int saslssf
,
189 char *saslmech
, char *user
, int tls
)
191 if (sm_mts
== MTS_SMTP
)
192 return smtp_init (client
, server
, port
, watch
, verbose
,
193 debug
, queued
, sasl
, saslssf
, saslmech
,
196 return sendmail_init (client
, server
, watch
, verbose
,
197 debug
, queued
, sasl
, saslssf
, saslmech
,
202 smtp_init (char *client
, char *server
, char *port
, int watch
, int verbose
,
203 int debug
, int queued
,
204 int sasl
, int saslssf
, char *saslmech
, char *user
, int tls
)
206 int result
, sd1
, sd2
;
209 #else /* CYRUS_SASL */
211 NMH_UNUSED (saslssf
);
212 NMH_UNUSED (saslmech
);
214 #endif /* CYRUS_SASL */
219 sm_verbose
= verbose
;
222 if (sm_rfp
!= NULL
&& sm_wfp
!= NULL
)
225 if (client
== NULL
|| *client
== '\0') {
229 client
= LocalName(1); /* no clientname -> LocalName */
234 * Last-ditch check just in case client still isn't set to anything
237 if (client
== NULL
|| *client
== '\0')
238 client
= "localhost";
240 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
241 sasl_inbuffer
= malloc(SASL_MAXRECVBUF
);
243 return sm_ierror("Unable to allocate %d bytes for read buffer",
245 #endif /* CYRUS_SASL || TLS_SUPPORT */
247 if ((sd1
= rclient (server
, port
)) == NOTOK
)
250 if ((sd2
= dup (sd1
)) == NOTOK
) {
252 return sm_ierror ("unable to dup");
255 SIGNAL (SIGALRM
, alrmser
);
256 SIGNAL (SIGPIPE
, SIG_IGN
);
258 if ((sm_rfp
= fdopen (sd1
, "r")) == NULL
259 || (sm_wfp
= fdopen (sd2
, "w")) == NULL
) {
262 sm_rfp
= sm_wfp
= NULL
;
263 return sm_ierror ("unable to fdopen");
270 * If tls == 2, that means that the user requested "initial" TLS,
271 * which happens right after the connection has opened. Do that
276 result
= tls_negotiate();
279 * Note: if tls_negotiate() fails it will call sm_end() for us,
280 * which closes the connection.
285 #endif /* TLS_SUPPORT */
302 * Give EHLO or HELO command
306 result
= smtalk (SM_HELO
, "EHLO %s", client
);
309 if (result
>= 500 && result
<= 599)
310 result
= smtalk (SM_HELO
, "HELO %s", client
);
319 * If the user requested TLS support, then try to do the STARTTLS command
320 * as part of the initial dialog. Assuming this works, we then need to
321 * restart the EHLO dialog after TLS negotiation is complete.
325 if (! EHLOset("STARTTLS")) {
327 return sm_ierror("SMTP server does not support TLS");
330 result
= smtalk(SM_HELO
, "STARTTLS");
338 * Okay, the other side should be waiting for us to start TLS
339 * negotiation. Oblige them.
342 result
= tls_negotiate();
348 result
= smtalk (SM_HELO
, "EHLO %s", client
);
356 #else /* TLS_SUPPORT */
358 #endif /* TLS_SUPPORT */
362 * If the user asked for SASL, then check to see if the SMTP server
363 * supports it. Otherwise, error out (because the SMTP server
364 * might have been spoofed; we don't want to just silently not
369 if (! (server_mechs
= EHLOset("AUTH"))) {
371 return sm_ierror("SMTP server does not support SASL");
374 if (saslmech
&& stringdex(saslmech
, server_mechs
) == -1) {
376 return sm_ierror("Requested SASL mech \"%s\" is not in the "
377 "list of supported mechanisms:\n%s",
378 saslmech
, server_mechs
);
381 if (sm_auth_sasl(user
, saslssf
, saslmech
? saslmech
: server_mechs
,
387 #endif /* CYRUS_SASL */
390 if (watch
&& EHLOset ("XVRB"))
391 smtalk (SM_HELO
, "VERB on");
392 if (queued
&& EHLOset ("XQUE"))
393 smtalk (SM_HELO
, "QUED");
399 sendmail_init (char *client
, char *server
, int watch
, int verbose
,
400 int debug
, int queued
,
401 int sasl
, int saslssf
, char *saslmech
, char *user
)
403 unsigned int i
, result
, vecp
;
408 #else /* CYRUS_SASL */
411 NMH_UNUSED (saslssf
);
412 NMH_UNUSED (saslmech
);
414 #endif /* CYRUS_SASL */
419 sm_verbose
= verbose
;
421 if (sm_rfp
!= NULL
&& sm_wfp
!= NULL
)
424 if (client
== NULL
|| *client
== '\0') {
428 client
= LocalName(1); /* no clientname -> LocalName */
432 * Last-ditch check just in case client still isn't set to anything
435 if (client
== NULL
|| *client
== '\0')
436 client
= "localhost";
438 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
439 sasl_inbuffer
= malloc(SASL_MAXRECVBUF
);
441 return sm_ierror("Unable to allocate %d bytes for read buffer",
443 #endif /* CYRUS_SASL || TLS_SUPPORT */
445 if (pipe (pdi
) == NOTOK
)
446 return sm_ierror ("no pipes");
447 if (pipe (pdo
) == NOTOK
) {
450 return sm_ierror ("no pipes");
453 for (i
= 0; (sm_child
= fork ()) == NOTOK
&& i
< 5; i
++)
462 return sm_ierror ("unable to fork");
465 if (pdo
[0] != fileno (stdin
))
466 dup2 (pdo
[0], fileno (stdin
));
467 if (pdi
[1] != fileno (stdout
))
468 dup2 (pdi
[1], fileno (stdout
));
469 if (pdi
[1] != fileno (stderr
))
470 dup2 (pdi
[1], fileno (stderr
));
471 for (i
= fileno (stderr
) + 1; i
< NBITS
; i
++)
475 vec
[vecp
++] = r1bindex (sendmail
, '/');
477 vec
[vecp
++] = watch
? "-odi" : queued
? "-odq" : "-odb";
478 vec
[vecp
++] = "-oem";
486 execvp (sendmail
, vec
);
487 fprintf (stderr
, "unable to exec ");
489 _exit (-1); /* NOTREACHED */
492 SIGNAL (SIGALRM
, alrmser
);
493 SIGNAL (SIGPIPE
, SIG_IGN
);
497 if ((sm_rfp
= fdopen (pdi
[0], "r")) == NULL
498 || (sm_wfp
= fdopen (pdo
[1], "w")) == NULL
) {
501 sm_rfp
= sm_wfp
= NULL
;
502 return sm_ierror ("unable to fdopen");
518 result
= smtalk (SM_HELO
, "EHLO %s", client
);
521 if (500 <= result
&& result
<= 599)
522 result
= smtalk (SM_HELO
, "HELO %s", client
);
535 * If the user asked for SASL, then check to see if the SMTP server
536 * supports it. Otherwise, error out (because the SMTP server
537 * might have been spoofed; we don't want to just silently not
542 if (! (server_mechs
= EHLOset("AUTH"))) {
544 return sm_ierror("SMTP server does not support SASL");
547 if (saslmech
&& stringdex(saslmech
, server_mechs
) == -1) {
549 return sm_ierror("Requested SASL mech \"%s\" is not in the "
550 "list of supported mechanisms:\n%s",
551 saslmech
, server_mechs
);
554 if (sm_auth_sasl(user
, saslssf
, saslmech
? saslmech
: server_mechs
,
560 #endif /* CYRUS_SASL */
563 smtalk (SM_HELO
, "VERB on");
570 rclient (char *server
, char *service
)
573 char response
[BUFSIZ
];
575 if ((sd
= client (server
, service
, response
, sizeof(response
),
579 sm_ierror ("%s", response
);
584 sm_winit (char *from
)
586 switch (smtalk (SM_MAIL
, "MAIL FROM:<%s>", from
)) {
603 sm_wadr (char *mbox
, char *host
, char *path
)
605 switch (smtalk (SM_RCPT
, host
&& *host
? "RCPT TO:<%s%s@%s>"
607 path
? path
: "", mbox
, host
)) {
617 #endif /* SENDMAILBUG */
642 switch (smtalk (SM_DATA
, "DATA")) {
651 #endif /* SENDMAILBUG */
668 sm_wtxt (char *buffer
, int len
)
674 result
= sm_wstream (buffer
, len
);
677 return (result
== NOTOK
? RP_BHST
: RP_OK
);
684 if (sm_wstream ((char *) NULL
, 0) == NOTOK
)
687 switch (smtalk (SM_DOT
+ 3 * sm_addrs
, ".")) {
695 #endif /* SENDMAILBUG */
713 if (sm_mts
== MTS_SENDMAIL_SMTP
) {
724 if (sm_rfp
== NULL
&& sm_wfp
== NULL
)
729 smtalk (SM_QUIT
, "QUIT");
733 sm_note
.code
= sm_reply
.code
;
734 sm_note
.length
= sm_reply
.length
;
735 memcpy (sm_note
.text
, sm_reply
.text
, sm_reply
.length
+ 1);/* fall */
737 if (smtalk (SM_RSET
, "RSET") == 250 && type
== DONE
)
739 if (sm_mts
== MTS_SMTP
)
740 smtalk (SM_QUIT
, "QUIT");
742 /* The SIGPIPE block replaces old calls to discard ().
743 We're not sure what the discard () calls were for,
744 maybe to prevent deadlock on old systems. In any
745 case, blocking SIGPIPE should be harmless.
746 Because the file handles are closed below, leave it
750 sigaddset (&set
, SIGPIPE
);
751 sigprocmask (SIG_BLOCK
, &set
, &oset
);
753 kill (sm_child
, SIGKILL
);
757 sm_reply
.code
= sm_note
.code
;
758 sm_reply
.length
= sm_note
.length
;
759 memcpy (sm_reply
.text
, sm_note
.text
, sm_note
.length
+ 1);
766 BIO_ssl_shutdown(io
);
769 #endif /* TLS_SUPPORT */
771 if (sm_rfp
!= NULL
) {
776 if (sm_wfp
!= NULL
) {
782 if (sm_mts
== MTS_SMTP
) {
787 if (sasl_outbuffer
) {
788 free(sasl_outbuffer
);
793 #endif /* CYRUS_SASL */
794 } else if (sm_child
!= NOTOK
) {
795 status
= pidwait (sm_child
, OK
);
801 sm_rfp
= sm_wfp
= NULL
;
802 return (status
? RP_BHST
: RP_OK
);
807 * This function implements SASL authentication for SMTP. If this function
808 * completes successfully, then authentication is successful and we've
809 * (optionally) negotiated a security layer.
812 sm_auth_sasl(char *user
, int saslssf
, char *mechlist
, char *inhost
)
815 unsigned int buflen
, outlen
;
816 char *buf
, outbuf
[BUFSIZ
], host
[NI_MAXHOST
];
817 const char *chosen_mech
;
818 sasl_security_properties_t secprops
;
821 struct nmh_creds creds
= { 0, 0, 0 };
824 * Initialize the callback contexts
828 * This is a _bit_ of a hack ... but if the hostname wasn't supplied
829 * to us on the command line, then call getpeername and do a
830 * reverse-address lookup on the IP address to get the name.
833 memset(host
, 0, sizeof(host
));
836 struct sockaddr_storage sin
;
837 socklen_t len
= sizeof(sin
);
840 if (getpeername(fileno(sm_wfp
), (struct sockaddr
*) &sin
, &len
) < 0) {
841 sm_ierror("getpeername on SMTP socket failed: %s",
846 result
= getnameinfo((struct sockaddr
*) &sin
, len
, host
, sizeof(host
),
847 NULL
, 0, NI_NAMEREQD
);
849 sm_ierror("Unable to look up name of connected host: %s",
850 gai_strerror(result
));
854 strncpy(host
, inhost
, sizeof(host
) - 1);
857 callbacks
[SM_SASL_N_CB_USER
].context
= user
;
858 callbacks
[SM_SASL_N_CB_AUTHNAME
].context
= user
;
860 nmh_get_credentials (host
, user
, 1, &creds
);
862 sasl_pw_context
[0] = host
;
863 sasl_pw_context
[1] = creds
.user
;
864 sasl_pw_context
[2] = creds
.password
;
866 callbacks
[SM_SASL_N_CB_PASS
].context
= sasl_pw_context
;
868 result
= sasl_client_init(callbacks
);
870 if (result
!= SASL_OK
) {
871 sm_ierror("SASL library initialization failed: %s",
872 sasl_errstring(result
, NULL
, NULL
));
876 result
= sasl_client_new("smtp", host
, NULL
, NULL
, NULL
, 0, &conn
);
878 if (result
!= SASL_OK
) {
879 sm_ierror("SASL client initialization failed: %s",
880 sasl_errstring(result
, NULL
, NULL
));
885 * Initialize the security properties. But if TLS is active, then
886 * don't negotiate encryption here.
889 memset(&secprops
, 0, sizeof(secprops
));
890 secprops
.maxbufsize
= SASL_MAXRECVBUF
;
892 tls_active
? 0 : (saslssf
!= -1 ? (unsigned int) saslssf
: UINT_MAX
);
894 result
= sasl_setprop(conn
, SASL_SEC_PROPS
, &secprops
);
896 if (result
!= SASL_OK
) {
897 sm_ierror("SASL security property initialization failed: %s",
898 sasl_errstring(result
, NULL
, NULL
));
903 * Start the actual protocol. Feed the mech list into the library
904 * and get out a possible initial challenge
907 result
= sasl_client_start(conn
, mechlist
, NULL
, (const char **) &buf
,
908 &buflen
, (const char **) &chosen_mech
);
910 if (result
!= SASL_OK
&& result
!= SASL_CONTINUE
) {
911 sm_ierror("SASL client start failed: %s", sasl_errdetail(conn
));
916 * If we got an initial challenge, send it as part of the AUTH
917 * command; otherwise, just send a plain AUTH command.
921 status
= sasl_encode64(buf
, buflen
, outbuf
, sizeof(outbuf
), NULL
);
922 if (status
!= SASL_OK
) {
923 sm_ierror("SASL base64 encode failed: %s",
924 sasl_errstring(status
, NULL
, NULL
));
928 status
= smtalk(SM_AUTH
, "AUTH %s %s", chosen_mech
, outbuf
);
930 status
= smtalk(SM_AUTH
, "AUTH %s", chosen_mech
);
933 * Now we loop until we either fail, get a SASL_OK, or a 235
934 * response code. Receive the challenges and process them until
938 while (result
== SASL_CONTINUE
) {
941 * If we get a 235 response, that means authentication has
942 * succeeded and we need to break out of the loop (yes, even if
943 * we still get SASL_CONTINUE from sasl_client_step()).
945 * Otherwise, if we get a message that doesn't seem to be a
946 * valid response, then abort
951 else if (status
< 300 || status
> 399)
955 * Special case; a zero-length response from the SMTP server
956 * is returned as a single =. If we get that, then set buflen
957 * to be zero. Otherwise, just decode the response.
960 if (strcmp("=", sm_reply
.text
) == 0) {
963 result
= sasl_decode64(sm_reply
.text
, sm_reply
.length
,
964 outbuf
, sizeof(outbuf
), &outlen
);
965 if (result
!= SASL_OK
) {
966 smtalk(SM_AUTH
, "*");
967 sm_ierror("SASL base64 decode failed: %s",
968 sasl_errstring(result
, NULL
, NULL
));
973 result
= sasl_client_step(conn
, outbuf
, outlen
, NULL
,
974 (const char **) &buf
, &buflen
);
976 if (result
!= SASL_OK
&& result
!= SASL_CONTINUE
) {
977 smtalk(SM_AUTH
, "*");
978 sm_ierror("SASL client negotiation failed: %s",
979 sasl_errstring(result
, NULL
, NULL
));
983 status
= sasl_encode64(buf
, buflen
, outbuf
, sizeof(outbuf
), NULL
);
985 if (status
!= SASL_OK
) {
986 smtalk(SM_AUTH
, "*");
987 sm_ierror("SASL base64 encode failed: %s",
988 sasl_errstring(status
, NULL
, NULL
));
992 status
= smtalk(SM_AUTH
, outbuf
);
996 * Make sure that we got the correct response
999 if (status
< 200 || status
> 299)
1003 * We _should_ have completed the authentication successfully.
1004 * Get a few properties from the authentication exchange.
1007 result
= sasl_getprop(conn
, SASL_MAXOUTBUF
, (const void **) &outbufmax
);
1009 if (result
!= SASL_OK
) {
1010 sm_ierror("Cannot retrieve SASL negotiated output buffer size: %s",
1011 sasl_errstring(result
, NULL
, NULL
));
1015 maxoutbuf
= *outbufmax
;
1017 result
= sasl_getprop(conn
, SASL_SSF
, (const void **) &ssf
);
1021 if (result
!= SASL_OK
) {
1022 sm_ierror("Cannot retrieve SASL negotiated security strength "
1023 "factor: %s", sasl_errstring(result
, NULL
, NULL
));
1028 sasl_outbuffer
= malloc(maxoutbuf
);
1030 if (sasl_outbuffer
== NULL
) {
1031 sm_ierror("Unable to allocate %d bytes for SASL output "
1032 "buffer", maxoutbuf
);
1037 sasl_inptr
= sasl_inbuffer
;
1039 sasl_outbuffer
= NULL
;
1040 /* Don't NULL out sasl_inbuffer because it could be used in
1050 * Our callback functions to feed data to the SASL library
1054 sm_get_user(void *context
, int id
, const char **result
, unsigned *len
)
1056 char *user
= (char *) context
;
1058 if (! result
|| ((id
!= SASL_CB_USER
) && (id
!= SASL_CB_AUTHNAME
)))
1059 return SASL_BADPARAM
;
1063 *len
= strlen(user
);
1069 sm_get_pass(sasl_conn_t
*conn
, void *context
, int id
,
1070 sasl_secret_t
**psecret
)
1072 char **pw_context
= (char **) context
;
1077 if (! psecret
|| id
!= SASL_CB_PASS
)
1078 return SASL_BADPARAM
;
1080 len
= strlen (pw_context
[2]);
1082 if (! (*psecret
= (sasl_secret_t
*) malloc(sizeof(sasl_secret_t
) + len
))) {
1086 (*psecret
)->len
= len
;
1087 strcpy((char *) (*psecret
)->data
, pw_context
[2]);
1091 #endif /* CYRUS_SASL */
1094 sm_ierror (char *fmt
, ...)
1099 vsnprintf (sm_reply
.text
, sizeof(sm_reply
.text
), fmt
, ap
);
1102 sm_reply
.length
= strlen (sm_reply
.text
);
1103 sm_reply
.code
= NOTOK
;
1109 smtalk (int time
, char *fmt
, ...)
1113 char buffer
[BUFSIZ
];
1116 vsnprintf (buffer
, sizeof(buffer
), fmt
, ap
);
1121 printf("(sasl-encrypted) ");
1123 printf("(tls-encrypted) ");
1124 printf ("=> %s\n", buffer
);
1129 alarm ((unsigned) time
);
1130 if ((result
= sm_wrecord (buffer
, strlen (buffer
))) != NOTOK
)
1139 * write the buffer to the open SMTP channel
1143 sm_wrecord (char *buffer
, int len
)
1146 return sm_werror ();
1148 sm_fwrite (buffer
, len
);
1152 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1157 sm_wstream (char *buffer
, int len
)
1160 static char lc
= '\0';
1163 return sm_werror ();
1165 if (buffer
== NULL
&& len
== 0) {
1169 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1172 for (bp
= buffer
; len
> 0; bp
++, len
--) {
1181 sm_fputc ('.');/* FALL THROUGH */
1186 if (ferror (sm_wfp
))
1187 return sm_werror ();
1192 return (ferror (sm_wfp
) ? sm_werror () : OK
);
1196 * Write out to the network, but do buffering for SASL (if enabled)
1200 sm_fwrite(char *buffer
, int len
)
1204 unsigned int outputlen
;
1206 if (sasl_complete
== 0 || sasl_ssf
== 0) {
1207 #endif /* CYRUS_SASL */
1212 ret
= BIO_write(io
, buffer
, len
);
1215 sm_ierror("TLS error during write: %s",
1216 ERR_error_string(ERR_get_error(), NULL
));
1220 #endif /* TLS_SUPPORT */
1221 fwrite(buffer
, sizeof(*buffer
), len
, sm_wfp
);
1224 while (len
>= maxoutbuf
- sasl_outbuflen
) {
1225 memcpy(sasl_outbuffer
+ sasl_outbuflen
, buffer
,
1226 maxoutbuf
- sasl_outbuflen
);
1227 len
-= maxoutbuf
- sasl_outbuflen
;
1230 if (sasl_encode(conn
, sasl_outbuffer
, maxoutbuf
,
1231 &output
, &outputlen
) != SASL_OK
) {
1232 sm_ierror("Unable to SASL encode connection data: %s",
1233 sasl_errdetail(conn
));
1237 fwrite(output
, sizeof(*output
), outputlen
, sm_wfp
);
1241 memcpy(sasl_outbuffer
+ sasl_outbuflen
, buffer
, len
);
1242 sasl_outbuflen
+= len
;
1245 #endif /* CYRUS_SASL */
1246 return ferror(sm_wfp
) ? NOTOK
: RP_OK
;
1251 * Negotiate Transport Layer Security
1260 const SSL_METHOD
*method
;
1263 SSL_load_error_strings();
1265 method
= TLSv1_client_method(); /* Not sure about this */
1267 /* Older ssl takes a non-const arg. */
1268 sslctx
= SSL_CTX_new((SSL_METHOD
*) method
);
1272 return sm_ierror("Unable to initialize OpenSSL context: %s",
1273 ERR_error_string(ERR_get_error(), NULL
));
1277 ssl
= SSL_new(sslctx
);
1281 return sm_ierror("Unable to create SSL connection: %s",
1282 ERR_error_string(ERR_get_error(), NULL
));
1285 sbior
= BIO_new_socket(fileno(sm_rfp
), BIO_NOCLOSE
);
1286 sbiow
= BIO_new_socket(fileno(sm_wfp
), BIO_NOCLOSE
);
1288 if (sbior
== NULL
|| sbiow
== NULL
) {
1290 return sm_ierror("Unable to create BIO endpoints: %s",
1291 ERR_error_string(ERR_get_error(), NULL
));
1294 SSL_set_bio(ssl
, sbior
, sbiow
);
1295 SSL_set_connect_state(ssl
);
1298 * Set up a BIO to handle buffering for us
1301 io
= BIO_new(BIO_f_buffer());
1305 return sm_ierror("Unable to create a buffer BIO: %s",
1306 ERR_error_string(ERR_get_error(), NULL
));
1309 ssl_bio
= BIO_new(BIO_f_ssl());
1313 return sm_ierror("Unable to create a SSL BIO: %s",
1314 ERR_error_string(ERR_get_error(), NULL
));
1317 BIO_set_ssl(ssl_bio
, ssl
, BIO_CLOSE
);
1318 BIO_push(io
, ssl_bio
);
1321 * Try doing the handshake now
1324 if (BIO_do_handshake(io
) < 1) {
1326 return sm_ierror("Unable to negotiate SSL connection: %s",
1327 ERR_error_string(ERR_get_error(), NULL
));
1331 const SSL_CIPHER
*cipher
= SSL_get_current_cipher(ssl
);
1332 printf("SSL negotiation successful: %s(%d) %s\n",
1333 SSL_CIPHER_get_name(cipher
),
1334 SSL_CIPHER_get_bits(cipher
, NULL
),
1335 SSL_CIPHER_get_version(cipher
));
1343 #endif /* TLS_SUPPORT */
1346 * Convenience functions to replace occurences of fputs() and fputc()
1350 sm_fputs(char *buffer
)
1352 return sm_fwrite(buffer
, strlen(buffer
));
1360 return sm_fwrite(&h
, 1);
1364 * Flush out any pending data on the connection
1372 unsigned int outputlen
;
1375 if (sasl_complete
== 1 && sasl_ssf
> 0 && sasl_outbuflen
> 0) {
1376 result
= sasl_encode(conn
, sasl_outbuffer
, sasl_outbuflen
,
1377 &output
, &outputlen
);
1378 if (result
!= SASL_OK
) {
1379 sm_ierror("Unable to SASL encode connection data: %s",
1380 sasl_errdetail(conn
));
1384 fwrite(output
, sizeof(*output
), outputlen
, sm_wfp
);
1387 #endif /* CYRUS_SASL */
1391 (void) BIO_flush(io
);
1393 #endif /* TLS_SUPPORT */
1402 strlen (strcpy (sm_reply
.text
, sm_wfp
== NULL
? "no socket opened"
1403 : sm_alarmed
? "write to socket timed out"
1404 : "error writing to socket"));
1406 return (sm_reply
.code
= NOTOK
);
1413 int i
, code
, cont
, bc
= 0, rc
, more
;
1416 char **ehlo
= NULL
, buffer
[BUFSIZ
];
1419 static int at_least_once
= 0;
1421 if (at_least_once
) {
1424 for (ehlo
= EHLOkeys
; *ehlo
; ehlo
++) {
1438 sm_reply
.length
= 0;
1439 sm_reply
.text
[0] = 0;
1441 rc
= sizeof(sm_reply
.text
) - 1;
1443 for (more
= FALSE
; sm_rrecord ((char *) (bp
= (unsigned char *) buffer
),
1447 printf("(sasl-decrypted) ");
1449 printf("(tls-decrypted) ");
1450 printf ("<= %s\n", buffer
);
1455 && strncmp (buffer
, "250", sizeof("250") - 1) == 0
1456 && (buffer
[3] == '-' || doingEHLO
== 2)
1458 if (doingEHLO
== 2) {
1459 if ((*ehlo
= malloc ((size_t) (strlen (buffer
+ 4) + 1)))) {
1460 strcpy (*ehlo
++, buffer
+ 4);
1462 if (ehlo
>= EHLOkeys
+ MAXEHLO
)
1472 for (; bc
> 0 && (!isascii (*bp
) || !isdigit (*bp
)); bp
++, bc
--)
1476 code
= atoi ((char *) bp
);
1478 for (; bc
> 0 && isspace (*bp
); bp
++, bc
--)
1480 if (bc
> 0 && *bp
== '-') {
1483 for (; bc
> 0 && isspace (*bp
); bp
++, bc
--)
1488 if (code
!= sm_reply
.code
|| cont
)
1492 sm_reply
.code
= code
;
1495 /* can never fail to 0-terminate because of size of buffer vs fixed string */
1496 strncpy (buffer
, sm_noreply
, sizeof(buffer
));
1497 bp
= (unsigned char *) buffer
;
1498 bc
= strlen (sm_noreply
);
1502 if ((i
= min (bc
, rc
)) > 0) {
1506 i
= strlen(sm_moreply
);
1507 if (more
&& rc
> i
+ 1) {
1508 memcpy (rp
, sm_moreply
, i
); /* safe because of check in if() */
1515 if (sm_reply
.code
< 100) {
1517 printf ("%s\n", sm_reply
.text
);
1523 sm_reply
.length
= rp
- sm_reply
.text
;
1524 sm_reply
.text
[sm_reply
.length
] = 0;
1525 return sm_reply
.code
;
1532 sm_rrecord (char *buffer
, int *len
)
1537 return sm_rerror(0);
1539 buffer
[*len
= 0] = 0;
1541 if ((retval
= sm_fgets (buffer
, BUFSIZ
, sm_rfp
)) != RP_OK
)
1542 return sm_rerror (retval
);
1543 *len
= strlen (buffer
);
1544 /* *len should be >0 except on EOF, but check for safety's sake */
1546 return sm_rerror (RP_EOF
);
1547 if (buffer
[*len
- 1] != '\n')
1548 while ((retval
= sm_fgetc (sm_rfp
)) != '\n' && retval
!= EOF
&&
1552 if ((*len
> 1) && (buffer
[*len
- 2] == '\r'))
1561 * Our version of fgets, which calls our private fgetc function
1565 sm_fgets(char *buffer
, int size
, FILE *f
)
1579 } while (size
> 1 && c
!= '\n');
1587 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
1589 * Read from the network, but do SASL or TLS encryption
1595 char tmpbuf
[BUFSIZ
], *retbuf
;
1596 unsigned int retbufsize
= 0;
1600 * If we have leftover data, return it
1603 if (sasl_inbuflen
) {
1605 return (int) *sasl_inptr
++;
1609 * If not, read from the network until we have some data to return
1612 while (retbufsize
== 0) {
1616 cc
= SSL_read(ssl
, tmpbuf
, sizeof(tmpbuf
));
1619 result
= SSL_get_error(ssl
, cc
);
1621 if (result
!= SSL_ERROR_ZERO_RETURN
) {
1622 sm_ierror("TLS peer aborted connection");
1629 sm_ierror("SSL_read failed: %s",
1630 ERR_error_string(ERR_get_error(), NULL
));
1634 #endif /* TLS_SUPPORT */
1636 cc
= read(fileno(f
), tmpbuf
, sizeof(tmpbuf
));
1642 sm_ierror("Unable to read from network: %s", strerror(errno
));
1647 * Don't call sasl_decode unless sasl is complete and we have
1648 * encryption working
1652 if (sasl_complete
== 0 || sasl_ssf
== 0) {
1656 result
= sasl_decode(conn
, tmpbuf
, cc
, (const char **) &retbuf
,
1659 if (result
!= SASL_OK
) {
1660 sm_ierror("Unable to decode SASL network data: %s",
1661 sasl_errdetail(conn
));
1665 #else /* ! CYRUS_SASL */
1668 #endif /* CYRUS_SASL */
1671 if (retbufsize
> SASL_MAXRECVBUF
) {
1672 sm_ierror("Received data (%d bytes) is larger than the buffer "
1673 "size (%d bytes)", retbufsize
, SASL_MAXRECVBUF
);
1677 memcpy(sasl_inbuffer
, retbuf
, retbufsize
);
1678 sasl_inptr
= sasl_inbuffer
+ 1;
1679 sasl_inbuflen
= retbufsize
- 1;
1681 return (int) sasl_inbuffer
[0];
1683 #endif /* CYRUS_SASL || TLS_SUPPORT */
1688 if (sm_mts
== MTS_SMTP
)
1690 strlen (strcpy (sm_reply
.text
, sm_rfp
== NULL
? "no socket opened"
1691 : sm_alarmed
? "read from socket timed out"
1692 : rc
== RP_EOF
? "premature end-of-file on socket"
1693 : "error reading from socket"));
1696 strlen (strcpy (sm_reply
.text
, sm_rfp
== NULL
? "no pipe opened"
1697 : sm_alarmed
? "read from pipe timed out"
1698 : rc
== RP_EOF
? "premature end-of-file on pipe"
1699 : "error reading from pipe"));
1701 return (sm_reply
.code
= NOTOK
);
1710 #ifndef RELIABLE_SIGNALS
1711 SIGNAL (SIGALRM
, alrmser
);
1716 printf ("timed out...\n");
1723 rp_string (int code
)
1726 static char buffer
[BUFSIZ
];
1728 switch (sm_reply
.code
!= NOTOK
? code
: NOTOK
) {
1748 snprintf (buffer
, sizeof(buffer
), "[%s] %s", text
, sm_reply
.text
);
1768 snprintf (buffer
, sizeof(buffer
), "[%s] %3d %s",
1769 text
, sm_reply
.code
, sm_reply
.text
);
1781 for (ehlo
= EHLOkeys
; *ehlo
; ehlo
++) {
1783 if (strncmp (ep
, s
, len
) == 0) {
1784 for (ep
+= len
; *ep
== ' '; ep
++)