Add support for -nosasl and -saslmaxssf switches.
[mmh] / mts / smtp / smtp.c
1 /*
2  * smtp.c -- nmh SMTP interface
3  *
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.
7  */
8
9 #include <h/mh.h>
10 #include "smtp.h"
11 #include <h/mts.h>
12 #include <signal.h>
13 #include <h/signals.h>
14
15 #ifdef CYRUS_SASL
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>
21 #include <netdb.h>
22 #include <errno.h>
23 #endif /* CYRUS_SASL */
24
25 #ifdef TLS_SUPPORT
26 #include <openssl/ssl.h>
27 #include <openssl/err.h>
28 #endif /* TLS_SUPPORT */
29
30 /*
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
34  * RP_-style codes.
35  */
36
37 /*
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.
42  */
43
44 #ifdef SENDMAILBUG
45 /*
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!
52  */
53 #endif
54
55 #define TRUE    1
56 #define FALSE   0
57
58 #define NBITS ((sizeof (int)) * 8)
59
60 /*
61  * these codes must all be different!
62  */
63 #define SM_OPEN  300      /* Changed to 5 minutes to comply with a SHOULD in RFC 1123 */
64 #define SM_HELO  20
65 #define SM_RSET  15
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 */
71 #define SM_QUIT  30
72 #define SM_CLOS  10
73 #ifdef CYRUS_SASL
74 #define SM_AUTH  45
75 #endif /* CYRUS_SASL */
76
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;
83
84 static FILE *sm_rfp = NULL;
85 static FILE *sm_wfp = NULL;
86
87 #ifdef CYRUS_SASL
88 /*
89  * Some globals needed by SASL
90  */
91
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 **);
101
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 },
110 };
111
112 #else /* CYRUS_SASL */
113 int sasl_ssf = 0;
114 #endif /* CYRUS_SASL */
115
116 #ifdef TLS_SUPPORT
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 */
123
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 */
130 #else
131 #define sm_fgetc fgetc
132 #endif
133
134 static int tls_active = 0;
135
136 static char *sm_noreply = "No reply text given";
137 static char *sm_moreply = "; ";
138
139 struct smtp sm_reply;           /* global... */
140
141 #define MAXEHLO 20
142
143 static int doingEHLO;
144 char *EHLOkeys[MAXEHLO + 1];
145
146 /*
147  * static prototypes
148  */
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 *);
153
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 *);
170
171 #ifdef CYRUS_SASL
172 /*
173  * Function prototypes needed for SASL
174  */
175
176 static int sm_auth_sasl(char *, int, char *, char *);
177 #endif /* CYRUS_SASL */
178
179 int
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)
183 {
184     if (sm_mts == MTS_SMTP)
185         return smtp_init (client, server, port, watch, verbose,
186                           debug, onex, queued, sasl, saslssf, saslmech,
187                           user, tls);
188     else
189         return sendmail_init (client, server, watch, verbose,
190                               debug, onex, queued, sasl, saslssf, saslmech,
191                               user);
192 }
193
194 static int
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)
198 {
199 #ifdef CYRUS_SASL
200     char *server_mechs;
201 #else  /* CYRUS_SASL */
202     NMH_UNUSED (sasl);
203     NMH_UNUSED (saslmech);
204     NMH_UNUSED (user);
205 #endif /* CYRUS_SASL */
206     int result, sd1, sd2;
207
208     if (watch)
209         verbose = TRUE;
210
211     sm_verbose = verbose;
212     sm_debug = debug;
213
214     if (sm_rfp != NULL && sm_wfp != NULL)
215         goto send_options;
216
217     if (client == NULL || *client == '\0') {
218         if (clientname) {
219             client = clientname;
220         } else {
221             client = LocalName(1);      /* no clientname -> LocalName */
222         }
223     }
224
225     /*
226      * Last-ditch check just in case client still isn't set to anything
227      */
228
229     if (client == NULL || *client == '\0')
230         client = "localhost";
231
232 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
233     sasl_inbuffer = malloc(SASL_MAXRECVBUF);
234     if (!sasl_inbuffer)
235         return sm_ierror("Unable to allocate %d bytes for read buffer",
236                          SASL_MAXRECVBUF);
237 #endif /* CYRUS_SASL || TLS_SUPPORT */
238
239     if ((sd1 = rclient (server, port)) == NOTOK)
240         return RP_BHST;
241
242     if ((sd2 = dup (sd1)) == NOTOK) {
243         close (sd1);
244         return sm_ierror ("unable to dup");
245     }
246
247     SIGNAL (SIGALRM, alrmser);
248     SIGNAL (SIGPIPE, SIG_IGN);
249
250     if ((sm_rfp = fdopen (sd1, "r")) == NULL
251             || (sm_wfp = fdopen (sd2, "w")) == NULL) {
252         close (sd1);
253         close (sd2);
254         sm_rfp = sm_wfp = NULL;
255         return sm_ierror ("unable to fdopen");
256     }
257
258     tls_active = 0;
259
260     sm_alarmed = 0;
261     alarm (SM_OPEN);
262     result = smhear ();
263     alarm (0);
264
265     switch (result) {
266         case 220: 
267             break;
268
269         default: 
270             sm_end (NOTOK);
271             return RP_RPLY;
272     }
273
274     /*
275      * Give EHLO or HELO command
276      */
277
278     doingEHLO = 1;
279     result = smtalk (SM_HELO, "EHLO %s", client);
280     doingEHLO = 0;
281
282     if (result >= 500 && result <= 599)
283         result = smtalk (SM_HELO, "HELO %s", client);
284
285     if (result != 250) {
286         sm_end (NOTOK);
287         return RP_RPLY;
288     }
289
290 #ifdef TLS_SUPPORT
291     /*
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.
295      */
296
297     if (tls) {
298         BIO *ssl_bio;
299
300         if (! EHLOset("STARTTLS")) {
301             sm_end(NOTOK);
302             return sm_ierror("SMTP server does not support TLS");
303         }
304
305         result = smtalk(SM_HELO, "STARTTLS");
306
307         if (result != 220) {
308             sm_end(NOTOK);
309             return RP_RPLY;
310         }
311
312         /*
313          * Okay, the other side should be waiting for us to start TLS
314          * negotiation.  Oblige them.
315          */
316
317         if (! sslctx) {
318             SSL_METHOD *method;
319
320             SSL_library_init();
321             SSL_load_error_strings();
322
323             method = TLSv1_client_method();     /* Not sure about this */
324
325             sslctx = SSL_CTX_new(method);
326
327             if (! sslctx) {
328                 sm_end(NOTOK);
329                 return sm_ierror("Unable to initialize OpenSSL context: %s",
330                                  ERR_error_string(ERR_get_error(), NULL));
331             }
332         }
333
334         ssl = SSL_new(sslctx);
335
336         if (! ssl) {
337             sm_end(NOTOK);
338             return sm_ierror("Unable to create SSL connection: %s",
339                              ERR_error_string(ERR_get_error(), NULL));
340         }
341
342         sbior = BIO_new_socket(fileno(sm_rfp), BIO_NOCLOSE);
343         sbiow = BIO_new_socket(fileno(sm_wfp), BIO_NOCLOSE);
344
345         if (sbior == NULL || sbiow == NULL) {
346             sm_end(NOTOK);
347             return sm_ierror("Unable to create BIO endpoints: %s",
348                              ERR_error_string(ERR_get_error(), NULL));
349         }
350
351         SSL_set_bio(ssl, sbior, sbiow);
352         SSL_set_connect_state(ssl);
353
354         /*
355          * Set up a BIO to handle buffering for us
356          */
357
358         io = BIO_new(BIO_f_buffer());
359
360         if (! io) {
361             sm_end(NOTOK);
362             return sm_ierror("Unable to create a buffer BIO: %s",
363                              ERR_error_string(ERR_get_error(), NULL));
364         }
365
366         ssl_bio = BIO_new(BIO_f_ssl());
367
368         if (! ssl_bio) {
369             sm_end(NOTOK);
370             return sm_ierror("Unable to create a SSL BIO: %s",
371                              ERR_error_string(ERR_get_error(), NULL));
372         }
373
374         BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
375         BIO_push(io, ssl_bio);
376
377         /*
378          * Try doing the handshake now
379          */
380
381         if (BIO_do_handshake(io) < 1) {
382             sm_end(NOTOK);
383             return sm_ierror("Unable to negotiate SSL connection: %s",
384                              ERR_error_string(ERR_get_error(), NULL));
385         }
386
387         if (sm_debug) {
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));
393
394         }
395
396         tls_active = 1;
397
398         doingEHLO = 1;
399         result = smtalk (SM_HELO, "EHLO %s", client);
400         doingEHLO = 0;
401
402         if (result != 250) {
403             sm_end (NOTOK);
404             return RP_RPLY;
405         }
406     }
407 #else  /* TLS_SUPPORT */
408     NMH_UNUSED (tls);
409 #endif /* TLS_SUPPORT */
410
411 #ifdef CYRUS_SASL
412     /*
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
416      * do authentication
417      */
418
419     if (sasl) {
420         if (! (server_mechs = EHLOset("AUTH"))) {
421             sm_end(NOTOK);
422             return sm_ierror("SMTP server does not support SASL");
423         }
424
425         if (saslmech && stringdex(saslmech, server_mechs) == -1) {
426             sm_end(NOTOK);
427             return sm_ierror("Requested SASL mech \"%s\" is not in the "
428                              "list of supported mechanisms:\n%s",
429                              saslmech, server_mechs);
430         }
431
432         if (sm_auth_sasl(user, saslssf, saslmech ? saslmech : server_mechs,
433                          server) != RP_OK) {
434             sm_end(NOTOK);
435             return NOTOK;
436         }
437     }
438 #endif /* CYRUS_SASL */
439
440 send_options: ;
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");
447
448     return RP_OK;
449 }
450
451 int
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)
455 {
456 #ifdef CYRUS_SASL
457     char *server_mechs;
458 #else  /* CYRUS_SASL */
459     NMH_UNUSED (server);
460     NMH_UNUSED (sasl);
461     NMH_UNUSED (saslssf);
462     NMH_UNUSED (saslmech);
463     NMH_UNUSED (user);
464 #endif /* CYRUS_SASL */
465     unsigned int i, result, vecp;
466     int pdi[2], pdo[2];
467     char *vec[15];
468
469     if (watch)
470         verbose = TRUE;
471
472     sm_verbose = verbose;
473     sm_debug = debug;
474     if (sm_rfp != NULL && sm_wfp != NULL)
475         return RP_OK;
476
477     if (client == NULL || *client == '\0') {
478         if (clientname)
479             client = clientname;
480         else
481             client = LocalName(1);      /* no clientname -> LocalName */
482     }
483
484     /*
485      * Last-ditch check just in case client still isn't set to anything
486      */
487
488     if (client == NULL || *client == '\0')
489         client = "localhost";
490
491 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
492     sasl_inbuffer = malloc(SASL_MAXRECVBUF);
493     if (!sasl_inbuffer)
494         return sm_ierror("Unable to allocate %d bytes for read buffer",
495                          SASL_MAXRECVBUF);
496 #endif /* CYRUS_SASL || TLS_SUPPORT */
497
498     if (pipe (pdi) == NOTOK)
499         return sm_ierror ("no pipes");
500     if (pipe (pdo) == NOTOK) {
501         close (pdi[0]);
502         close (pdi[1]);
503         return sm_ierror ("no pipes");
504     }
505
506     for (i = 0; (sm_child = fork ()) == NOTOK && i < 5; i++)
507         sleep (5);
508
509     switch (sm_child) {
510         case NOTOK: 
511             close (pdo[0]);
512             close (pdo[1]);
513             close (pdi[0]);
514             close (pdi[1]);
515             return sm_ierror ("unable to fork");
516
517         case OK: 
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++)
525                 close (i);
526
527             vecp = 0;
528             vec[vecp++] = r1bindex (sendmail, '/');
529             vec[vecp++] = "-bs";
530             vec[vecp++] = watch ? "-odi" : queued ? "-odq" : "-odb";
531             vec[vecp++] = "-oem";
532             vec[vecp++] = "-om";
533 # ifndef RAND
534             if (verbose)
535                 vec[vecp++] = "-ov";
536 # endif /* not RAND */
537             vec[vecp++] = NULL;
538
539             setgid (getegid ());
540             setuid (geteuid ());
541             execvp (sendmail, vec);
542             fprintf (stderr, "unable to exec ");
543             perror (sendmail);
544             _exit (-1);         /* NOTREACHED */
545
546         default: 
547             SIGNAL (SIGALRM, alrmser);
548             SIGNAL (SIGPIPE, SIG_IGN);
549
550             close (pdi[1]);
551             close (pdo[0]);
552             if ((sm_rfp = fdopen (pdi[0], "r")) == NULL
553                     || (sm_wfp = fdopen (pdo[1], "w")) == NULL) {
554                 close (pdi[0]);
555                 close (pdo[1]);
556                 sm_rfp = sm_wfp = NULL;
557                 return sm_ierror ("unable to fdopen");
558             }
559             sm_alarmed = 0;
560             alarm (SM_OPEN);
561             result = smhear ();
562             alarm (0);
563             switch (result) {
564                 case 220: 
565                     break;
566
567                 default: 
568                     sm_end (NOTOK);
569                     return RP_RPLY;
570             }
571
572             doingEHLO = 1;
573             result = smtalk (SM_HELO, "EHLO %s", client);
574             doingEHLO = 0;
575
576             if (500 <= result && result <= 599)
577                 result = smtalk (SM_HELO, "HELO %s", client);
578
579             switch (result) {
580                 case 250:
581                     break;
582
583                 default:
584                     sm_end (NOTOK);
585                     return RP_RPLY;
586             }
587
588 #ifdef CYRUS_SASL
589     /*
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
593      * do authentication
594      */
595
596     if (sasl) {
597         if (! (server_mechs = EHLOset("AUTH"))) {
598             sm_end(NOTOK);
599             return sm_ierror("SMTP server does not support SASL");
600         }
601
602         if (saslmech && stringdex(saslmech, server_mechs) == -1) {
603             sm_end(NOTOK);
604             return sm_ierror("Requested SASL mech \"%s\" is not in the "
605                              "list of supported mechanisms:\n%s",
606                              saslmech, server_mechs);
607         }
608
609         if (sm_auth_sasl(user, saslssf, saslmech ? saslmech : server_mechs,
610                          server) != RP_OK) {
611             sm_end(NOTOK);
612             return NOTOK;
613         }
614     }
615 #endif /* CYRUS_SASL */
616
617             if (onex)
618                 smtalk (SM_HELO, "ONEX");
619             if (watch)
620                 smtalk (SM_HELO, "VERB on");
621
622             return RP_OK;
623     }
624 }
625
626 static int
627 rclient (char *server, char *service)
628 {
629     int sd;
630     char response[BUFSIZ];
631
632     if ((sd = client (server, service, response, sizeof(response),
633                       sm_debug)) != NOTOK)
634         return sd;
635
636     sm_ierror ("%s", response);
637     return NOTOK;
638 }
639
640 int
641 sm_winit (int mode, char *from)
642 {
643     char *smtpcom = NULL;
644
645     switch (mode) {
646         case S_MAIL:
647             smtpcom = "MAIL";
648             break;
649
650         case S_SEND:
651             smtpcom = "SEND";
652             break;
653
654         case S_SOML:
655             smtpcom = "SOML";
656             break;
657
658         case S_SAML:
659             smtpcom = "SAML";
660             break;
661
662         default:
663             /* Hopefully, we do not get here. */
664             break;
665     }
666
667     switch (smtalk (SM_MAIL, "%s FROM:<%s>", smtpcom, from)) {
668         case 250: 
669             sm_addrs = 0;
670             return RP_OK;
671
672         case 500: 
673         case 501: 
674         case 552: 
675             return RP_PARM;
676
677         default: 
678             return RP_RPLY;
679     }
680 }
681
682
683 int
684 sm_wadr (char *mbox, char *host, char *path)
685 {
686     switch (smtalk (SM_RCPT, host && *host ? "RCPT TO:<%s%s@%s>"
687                                            : "RCPT TO:<%s%s>",
688                              path ? path : "", mbox, host)) {
689         case 250: 
690         case 251: 
691             sm_addrs++;
692             return RP_OK;
693
694         case 451: 
695 #ifdef SENDMAILBUG
696             sm_addrs++;
697             return RP_OK;
698 #endif /* SENDMAILBUG */
699         case 421: 
700         case 450: 
701         case 452: 
702             return RP_NO;
703
704         case 500: 
705         case 501: 
706             return RP_PARM;
707
708         case 550: 
709         case 551: 
710         case 552: 
711         case 553: 
712             return RP_USER;
713
714         default: 
715             return RP_RPLY;
716     }
717 }
718
719
720 int
721 sm_waend (void)
722 {
723     switch (smtalk (SM_DATA, "DATA")) {
724         case 354: 
725             sm_nl = TRUE;
726             return RP_OK;
727
728         case 451: 
729 #ifdef SENDMAILBUG
730             sm_nl = TRUE;
731             return RP_OK;
732 #endif /* SENDMAILBUG */
733         case 421: 
734             return RP_NO;
735
736         case 500: 
737         case 501: 
738         case 503: 
739         case 554: 
740             return RP_NDEL;
741
742         default: 
743             return RP_RPLY;
744     }
745 }
746
747
748 int
749 sm_wtxt (char *buffer, int len)
750 {
751     int result;
752
753     sm_alarmed = 0;
754     alarm (SM_TEXT);
755     result = sm_wstream (buffer, len);
756     alarm (0);
757
758     return (result == NOTOK ? RP_BHST : RP_OK);
759 }
760
761
762 int
763 sm_wtend (void)
764 {
765     if (sm_wstream ((char *) NULL, 0) == NOTOK)
766         return RP_BHST;
767
768     switch (smtalk (SM_DOT + 3 * sm_addrs, ".")) {
769         case 250: 
770         case 251: 
771             return RP_OK;
772
773         case 451: 
774 #ifdef SENDMAILBUG
775             return RP_OK;
776 #endif /* SENDMAILBUG */
777         case 452: 
778         default: 
779             return RP_NO;
780
781         case 552: 
782         case 554: 
783             return RP_NDEL;
784     }
785 }
786
787
788 int
789 sm_end (int type)
790 {
791     int status;
792     struct smtp sm_note;
793
794     if (sm_mts == MTS_SENDMAIL) {
795         switch (sm_child) {
796             case NOTOK: 
797             case OK: 
798                 return RP_OK;
799
800             default: 
801                 break;
802         }
803     }
804
805     if (sm_rfp == NULL && sm_wfp == NULL)
806         return RP_OK;
807
808     switch (type) {
809         case OK: 
810             smtalk (SM_QUIT, "QUIT");
811             break;
812
813         case NOTOK: 
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 */
817         case DONE: 
818             if (smtalk (SM_RSET, "RSET") == 250 && type == DONE)
819                 return RP_OK;
820             if (sm_mts == MTS_SMTP)
821                 smtalk (SM_QUIT, "QUIT");
822             else {
823                 kill (sm_child, SIGKILL);
824                 discard (sm_rfp);
825                 discard (sm_wfp);
826             }
827             if (type == NOTOK) {
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);
831             }
832             break;
833     }
834
835 #ifdef TLS_SUPPORT
836     if (tls_active) {
837         BIO_ssl_shutdown(io);
838         BIO_free_all(io);
839     }
840 #endif /* TLS_SUPPORT */
841
842     if (sm_rfp != NULL) {
843         alarm (SM_CLOS);
844         fclose (sm_rfp);
845         alarm (0);
846     }
847     if (sm_wfp != NULL) {
848         alarm (SM_CLOS);
849         fclose (sm_wfp);
850         alarm (0);
851     }
852
853     if (sm_mts == MTS_SMTP) {
854         status = 0;
855 #ifdef CYRUS_SASL
856         if (conn) {
857             sasl_dispose(&conn);
858             if (sasl_outbuffer) {
859                 free(sasl_outbuffer);
860             }
861         }
862         if (sasl_inbuffer)
863             free(sasl_inbuffer);
864 #endif /* CYRUS_SASL */
865     } else {
866         status = pidwait (sm_child, OK);
867         sm_child = NOTOK;
868     }
869
870     sm_rfp = sm_wfp = NULL;
871     return (status ? RP_BHST : RP_OK);
872 }
873
874 #ifdef CYRUS_SASL
875 /*
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.
879  */
880 static int
881 sm_auth_sasl(char *user, int saslssf, char *mechlist, char *inhost)
882 {
883     int result, status;
884     unsigned int buflen, outlen;
885     char *buf, outbuf[BUFSIZ], host[NI_MAXHOST];
886     const char *chosen_mech;
887     sasl_security_properties_t secprops;
888     sasl_ssf_t *ssf;
889     int *outbufmax;
890
891     /*
892      * Initialize the callback contexts
893      */
894
895     if (user == NULL)
896         user = getusername();
897
898     callbacks[SM_SASL_N_CB_USER].context = user;
899     callbacks[SM_SASL_N_CB_AUTHNAME].context = user;
900
901     /*
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.
905      */
906
907     memset(host, 0, sizeof(host));
908
909     if (!inhost) {
910         struct sockaddr_storage sin;
911         socklen_t len = sizeof(sin);
912         int result;
913
914         if (getpeername(fileno(sm_wfp), (struct sockaddr *) &sin, &len) < 0) {
915             sm_ierror("getpeername on SMTP socket failed: %s",
916                       strerror(errno));
917             return NOTOK;
918         }
919
920         result = getnameinfo((struct sockaddr *) &sin, len, host, sizeof(host),
921                              NULL, 0, NI_NAMEREQD);
922         if (result != 0) {
923             sm_ierror("Unable to look up name of connected host: %s",
924                       gai_strerror(result));
925             return NOTOK;
926         }
927     } else {
928         strncpy(host, inhost, sizeof(host) - 1);
929     }
930
931     sasl_pw_context[0] = host;
932     sasl_pw_context[1] = user;
933
934     callbacks[SM_SASL_N_CB_PASS].context = sasl_pw_context;
935
936     result = sasl_client_init(callbacks);
937
938     if (result != SASL_OK) {
939         sm_ierror("SASL library initialization failed: %s",
940                   sasl_errstring(result, NULL, NULL));
941         return NOTOK;
942     }
943
944     result = sasl_client_new("smtp", host, NULL, NULL, NULL, 0, &conn);
945
946     if (result != SASL_OK) {
947         sm_ierror("SASL client initialization failed: %s",
948                   sasl_errstring(result, NULL, NULL));
949         return NOTOK;
950     }
951
952     /*
953      * Initialize the security properties.  But if TLS is active, then
954      * don't negotiate encryption here.
955      */
956
957     memset(&secprops, 0, sizeof(secprops));
958     secprops.maxbufsize = SASL_MAXRECVBUF;
959     secprops.max_ssf = tls_active ? 0 : (saslssf != -1 ? saslssf : UINT_MAX);
960
961     result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
962
963     if (result != SASL_OK) {
964         sm_ierror("SASL security property initialization failed: %s",
965                   sasl_errstring(result, NULL, NULL));
966         return NOTOK;
967     }
968
969     /*
970      * Start the actual protocol.  Feed the mech list into the library
971      * and get out a possible initial challenge
972      */
973
974     result = sasl_client_start(conn, mechlist, NULL, (const char **) &buf,
975                                &buflen, (const char **) &chosen_mech);
976
977     if (result != SASL_OK && result != SASL_CONTINUE) {
978         sm_ierror("SASL client start failed: %s", sasl_errdetail(conn));
979         return NOTOK;
980     }
981
982     /*
983      * If we got an initial challenge, send it as part of the AUTH
984      * command; otherwise, just send a plain AUTH command.
985      */
986
987     if (buflen) {
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));
992             return NOTOK;
993         }
994
995         status = smtalk(SM_AUTH, "AUTH %s %s", chosen_mech, outbuf);
996     } else
997         status = smtalk(SM_AUTH, "AUTH %s", chosen_mech);
998
999     /*
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
1002      * we're all done.
1003      */
1004
1005     while (result == SASL_CONTINUE) {
1006
1007         /*
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()).
1011          *
1012          * Otherwise, if we get a message that doesn't seem to be a
1013          * valid response, then abort
1014          */
1015
1016         if (status == 235)
1017             break;
1018         else if (status < 300 || status > 399)
1019             return RP_BHST;
1020         
1021         /*
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.
1025          */
1026         
1027         if (strcmp("=", sm_reply.text) == 0) {
1028             outlen = 0;
1029         } else {
1030             result = sasl_decode64(sm_reply.text, sm_reply.length,
1031                                    outbuf, sizeof(outbuf), &outlen);
1032         
1033             if (result != SASL_OK) {
1034                 smtalk(SM_AUTH, "*");
1035                 sm_ierror("SASL base64 decode failed: %s",
1036                           sasl_errstring(result, NULL, NULL));
1037                 return NOTOK;
1038             }
1039         }
1040
1041         result = sasl_client_step(conn, outbuf, outlen, NULL,
1042                                   (const char **) &buf, &buflen);
1043
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));
1048             return NOTOK;
1049         }
1050
1051         status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
1052
1053         if (status != SASL_OK) {
1054             smtalk(SM_AUTH, "*");
1055             sm_ierror("SASL base64 encode failed: %s",
1056                       sasl_errstring(status, NULL, NULL));
1057             return NOTOK;
1058         }
1059         
1060         status = smtalk(SM_AUTH, outbuf);
1061     }
1062
1063     /*
1064      * Make sure that we got the correct response
1065      */
1066
1067     if (status < 200 || status > 299)
1068         return RP_BHST;
1069
1070     /*
1071      * We _should_ have completed the authentication successfully.
1072      * Get a few properties from the authentication exchange.
1073      */
1074
1075     result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &outbufmax);
1076
1077     if (result != SASL_OK) {
1078         sm_ierror("Cannot retrieve SASL negotiated output buffer size: %s",
1079                   sasl_errstring(result, NULL, NULL));
1080         return NOTOK;
1081     }
1082
1083     maxoutbuf = *outbufmax;
1084
1085     result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
1086
1087     sasl_ssf = *ssf;
1088
1089     if (result != SASL_OK) {
1090         sm_ierror("Cannot retrieve SASL negotiated security strength "
1091                   "factor: %s", sasl_errstring(result, NULL, NULL));
1092         return NOTOK;
1093     }
1094
1095     if (sasl_ssf > 0) {
1096         sasl_outbuffer = malloc(maxoutbuf);
1097
1098         if (sasl_outbuffer == NULL) {
1099                 sm_ierror("Unable to allocate %d bytes for SASL output "
1100                           "buffer", maxoutbuf);
1101                 return NOTOK;
1102         }
1103         sasl_outbuflen = 0;
1104         sasl_inbuflen = 0;
1105         sasl_inptr = sasl_inbuffer;
1106     } else {
1107         sasl_outbuffer = NULL;
1108         /* Don't NULL out sasl_inbuffer because it could be used in
1109            sm_fgetc (). */
1110     }
1111
1112     sasl_complete = 1;
1113
1114     return RP_OK;
1115 }
1116
1117 /*
1118  * Our callback functions to feed data to the SASL library
1119  */
1120
1121 static int
1122 sm_get_user(void *context, int id, const char **result, unsigned *len)
1123 {
1124     char *user = (char *) context;
1125
1126     if (! result || ((id != SASL_CB_USER) && (id != SASL_CB_AUTHNAME)))
1127         return SASL_BADPARAM;
1128
1129     *result = user;
1130     if (len)
1131         *len = strlen(user);
1132
1133     return SASL_OK;
1134 }
1135
1136 static int
1137 sm_get_pass(sasl_conn_t *conn, void *context, int id,
1138             sasl_secret_t **psecret)
1139 {
1140     NMH_UNUSED (conn);
1141
1142     char **pw_context = (char **) context;
1143     char *pass = NULL;
1144     int len;
1145
1146     if (! psecret || id != SASL_CB_PASS)
1147         return SASL_BADPARAM;
1148
1149     ruserpass(pw_context[0], &(pw_context[1]), &pass);
1150
1151     len = strlen(pass);
1152
1153     *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
1154
1155     if (! *psecret) {
1156         free(pass);
1157         return SASL_NOMEM;
1158     }
1159
1160     (*psecret)->len = len;
1161     strcpy((char *) (*psecret)->data, pass);
1162 /*    free(pass); */
1163
1164     return SASL_OK;
1165 }
1166 #endif /* CYRUS_SASL */
1167
1168 static int
1169 sm_ierror (char *fmt, ...)
1170 {
1171     va_list ap;
1172
1173     va_start(ap, fmt);
1174     vsnprintf (sm_reply.text, sizeof(sm_reply.text), fmt, ap);
1175     va_end(ap);
1176
1177     sm_reply.length = strlen (sm_reply.text);
1178     sm_reply.code = NOTOK;
1179
1180     return RP_BHST;
1181 }
1182
1183 static int
1184 smtalk (int time, char *fmt, ...)
1185 {
1186     va_list ap;
1187     int result;
1188     char buffer[BUFSIZ];
1189
1190     va_start(ap, fmt);
1191     vsnprintf (buffer, sizeof(buffer), fmt, ap);
1192     va_end(ap);
1193
1194     if (sm_debug) {
1195         if (sasl_ssf)
1196                 printf("(sasl-encrypted) ");
1197         if (tls_active)
1198                 printf("(tls-encrypted) ");
1199         printf ("=> %s\n", buffer);
1200         fflush (stdout);
1201     }
1202
1203     sm_alarmed = 0;
1204     alarm ((unsigned) time);
1205     if ((result = sm_wrecord (buffer, strlen (buffer))) != NOTOK)
1206         result = smhear ();
1207     alarm (0);
1208
1209     return result;
1210 }
1211
1212
1213 /*
1214  * write the buffer to the open SMTP channel
1215  */
1216
1217 static int
1218 sm_wrecord (char *buffer, int len)
1219 {
1220     if (sm_wfp == NULL)
1221         return sm_werror ();
1222
1223     sm_fwrite (buffer, len);
1224     sm_fputs ("\r\n");
1225     sm_fflush ();
1226
1227     return (ferror (sm_wfp) ? sm_werror () : OK);
1228 }
1229
1230
1231 static int
1232 sm_wstream (char *buffer, int len)
1233 {
1234     char  *bp;
1235     static char lc = '\0';
1236
1237     if (sm_wfp == NULL)
1238         return sm_werror ();
1239
1240     if (buffer == NULL && len == 0) {
1241         if (lc != '\n')
1242             sm_fputs ("\r\n");
1243         lc = '\0';
1244         return (ferror (sm_wfp) ? sm_werror () : OK);
1245     }
1246
1247     for (bp = buffer; len > 0; bp++, len--) {
1248         switch (*bp) {
1249             case '\n': 
1250                 sm_nl = TRUE;
1251                 sm_fputc ('\r');
1252                 break;
1253
1254             case '.': 
1255                 if (sm_nl)
1256                     sm_fputc ('.');/* FALL THROUGH */
1257             default: 
1258                 sm_nl = FALSE;
1259         }
1260         sm_fputc (*bp);
1261         if (ferror (sm_wfp))
1262             return sm_werror ();
1263     }
1264
1265     if (bp > buffer)
1266         lc = *--bp;
1267     return (ferror (sm_wfp) ? sm_werror () : OK);
1268 }
1269
1270 /*
1271  * Write out to the network, but do buffering for SASL (if enabled)
1272  */
1273
1274 static int
1275 sm_fwrite(char *buffer, int len)
1276 {
1277 #ifdef CYRUS_SASL
1278     const char *output;
1279     unsigned int outputlen;
1280
1281     if (sasl_complete == 0 || sasl_ssf == 0) {
1282 #endif /* CYRUS_SASL */
1283 #ifdef TLS_SUPPORT
1284         if (tls_active) {
1285             int ret;
1286
1287             ret = BIO_write(io, buffer, len);
1288
1289             if (ret <= 0) {
1290                 sm_ierror("TLS error during write: %s",
1291                           ERR_error_string(ERR_get_error(), NULL));
1292                 return NOTOK;
1293             }
1294         } else
1295 #endif /* TLS_SUPPORT */
1296         fwrite(buffer, sizeof(*buffer), len, sm_wfp);
1297 #ifdef CYRUS_SASL
1298     } else {
1299         while (len >= maxoutbuf - sasl_outbuflen) {
1300             memcpy(sasl_outbuffer + sasl_outbuflen, buffer,
1301                    maxoutbuf - sasl_outbuflen);
1302             len -= maxoutbuf - sasl_outbuflen;
1303             sasl_outbuflen = 0;
1304
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));
1309                 return NOTOK;
1310             }
1311
1312             fwrite(output, sizeof(*output), outputlen, sm_wfp);
1313         }
1314
1315         if (len > 0) {
1316             memcpy(sasl_outbuffer + sasl_outbuflen, buffer, len);
1317             sasl_outbuflen += len;
1318         }
1319     }
1320 #endif /* CYRUS_SASL */
1321     return ferror(sm_wfp) ? NOTOK : RP_OK;
1322 }
1323
1324 /*
1325  * Convenience functions to replace occurences of fputs() and fputc()
1326  */
1327
1328 static int
1329 sm_fputs(char *buffer)
1330 {
1331     return sm_fwrite(buffer, strlen(buffer));
1332 }
1333
1334 static int
1335 sm_fputc(int c)
1336 {
1337     char h = c;
1338
1339     return sm_fwrite(&h, 1);
1340 }
1341
1342 /*
1343  * Flush out any pending data on the connection
1344  */
1345
1346 static void
1347 sm_fflush(void)
1348 {
1349 #ifdef CYRUS_SASL
1350     const char *output;
1351     unsigned int outputlen;
1352     int result;
1353
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));
1360             return;
1361         }
1362
1363         fwrite(output, sizeof(*output), outputlen, sm_wfp);
1364         sasl_outbuflen = 0;
1365     }
1366 #endif /* CYRUS_SASL */
1367
1368 #ifdef TLS_SUPPORT
1369     if (tls_active) {
1370         (void) BIO_flush(io);
1371     }
1372 #endif /* TLS_SUPPORT */
1373
1374     fflush(sm_wfp);
1375 }
1376
1377 static int
1378 sm_werror (void)
1379 {
1380     sm_reply.length =
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"));
1384
1385     return (sm_reply.code = NOTOK);
1386 }
1387
1388
1389 static int
1390 smhear (void)
1391 {
1392     int i, code, cont, bc = 0, rc, more;
1393     unsigned char *bp;
1394     char *rp;
1395     char **ehlo = NULL, buffer[BUFSIZ];
1396
1397     if (doingEHLO) {
1398         static int at_least_once = 0;
1399
1400         if (at_least_once) {
1401             char *ep;
1402
1403             for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1404                 ep = *ehlo;
1405                 free (ep);
1406             }
1407         } else {
1408             at_least_once = 1;
1409         }
1410
1411         ehlo = EHLOkeys;
1412         *ehlo = NULL;
1413     }
1414
1415 again: ;
1416
1417     sm_reply.length = 0;
1418     sm_reply.text[0] = 0;
1419     rp = sm_reply.text;
1420     rc = sizeof(sm_reply.text) - 1;
1421
1422     for (more = FALSE; sm_rrecord ((char *) (bp = (unsigned char *) buffer),
1423                                    &bc) != NOTOK ; ) {
1424         if (sm_debug) {
1425             if (sasl_ssf > 0)
1426                 printf("(sasl-decrypted) ");
1427             if (tls_active)
1428                 printf("(tls-decrypted) ");
1429             printf ("<= %s\n", buffer);
1430             fflush (stdout);
1431         }
1432
1433         if (doingEHLO
1434                 && strncmp (buffer, "250", sizeof("250") - 1) == 0
1435                 && (buffer[3] == '-' || doingEHLO == 2)
1436                 && buffer[4]) {
1437             if (doingEHLO == 2) {
1438                 if ((*ehlo = malloc ((size_t) (strlen (buffer + 4) + 1)))) {
1439                     strcpy (*ehlo++, buffer + 4);
1440                     *ehlo = NULL;
1441                     if (ehlo >= EHLOkeys + MAXEHLO)
1442                         doingEHLO = 0;
1443                 }
1444                 else
1445                     doingEHLO = 0;
1446             }
1447             else
1448                 doingEHLO = 2;
1449         }
1450
1451         for (; bc > 0 && (!isascii (*bp) || !isdigit (*bp)); bp++, bc--)
1452             continue;
1453
1454         cont = FALSE;
1455         code = atoi ((char *) bp);
1456         bp += 3, bc -= 3;
1457         for (; bc > 0 && isspace (*bp); bp++, bc--)
1458             continue;
1459         if (bc > 0 && *bp == '-') {
1460             cont = TRUE;
1461             bp++, bc--;
1462             for (; bc > 0 && isspace (*bp); bp++, bc--)
1463                 continue;
1464         }
1465
1466         if (more) {
1467             if (code != sm_reply.code || cont)
1468                 continue;
1469             more = FALSE;
1470         } else {
1471             sm_reply.code = code;
1472             more = cont;
1473             if (bc <= 0) {
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);
1478             }
1479         }
1480
1481         if ((i = min (bc, rc)) > 0) {
1482             memcpy (rp, bp, i);
1483             rp += i;
1484             rc -= i;
1485             i = strlen(sm_moreply);
1486             if (more && rc > i + 1) {
1487                 memcpy (rp, sm_moreply, i); /* safe because of check in if() */
1488                 rp += i;
1489                 rc -= i;
1490             }
1491         }
1492         if (more)
1493             continue;
1494         if (sm_reply.code < 100) {
1495             if (sm_verbose) {
1496                 printf ("%s\n", sm_reply.text);
1497                 fflush (stdout);
1498             }
1499             goto again;
1500         }
1501
1502         sm_reply.length = rp - sm_reply.text;
1503         sm_reply.text[sm_reply.length] = 0;
1504         return sm_reply.code;
1505     }
1506     return NOTOK;
1507 }
1508
1509
1510 static int
1511 sm_rrecord (char *buffer, int *len)
1512 {
1513     int retval;
1514
1515     if (sm_rfp == NULL)
1516         return sm_rerror(0);
1517
1518     buffer[*len = 0] = 0;
1519
1520     if ((retval = sm_fgets (buffer, BUFSIZ, sm_rfp)) != RP_OK)
1521         return retval;
1522     *len = strlen (buffer);
1523     /* *len should be >0 except on EOF, but check for safety's sake */
1524     if (*len == 0)
1525         return sm_rerror (RP_EOF);
1526     if (buffer[*len - 1] != '\n')
1527         while ((retval = sm_fgetc (sm_rfp)) != '\n' && retval != EOF &&
1528                retval != -2)
1529             continue;
1530     else
1531         if ((*len > 1) && (buffer[*len - 2] == '\r'))
1532             *len -= 1;
1533     *len -= 1;
1534     buffer[*len] = 0;
1535
1536     return OK;
1537 }
1538
1539 /*
1540  * Our version of fgets, which calls our private fgetc function
1541  */
1542
1543 static int
1544 sm_fgets(char *buffer, int size, FILE *f)
1545 {
1546     int c;
1547
1548      do {
1549         c = sm_fgetc(f);
1550
1551         if (c == EOF)
1552             return RP_EOF;
1553
1554         if (c == -2)
1555             return NOTOK;
1556
1557         *buffer++ = c;
1558      } while (size > 1 && c != '\n');
1559
1560      *buffer = '\0';
1561
1562      return RP_OK;
1563 }
1564
1565
1566 #if defined(CYRUS_SASL) || defined(TLS_SUPPORT)
1567 /*
1568  * Read from the network, but do SASL or TLS encryption
1569  */
1570
1571 static int
1572 sm_fgetc(FILE *f)
1573 {
1574     char tmpbuf[BUFSIZ], *retbuf;
1575     unsigned int retbufsize = 0;
1576     int cc, result;
1577
1578     /*
1579      * If we have leftover data, return it
1580      */
1581
1582     if (sasl_inbuflen) {
1583         sasl_inbuflen--;
1584         return (int) *sasl_inptr++;
1585     }
1586
1587     /*
1588      * If not, read from the network until we have some data to return
1589      */
1590
1591     while (retbufsize == 0) {
1592
1593 #ifdef TLS_SUPPORT
1594         if (tls_active) {
1595             cc = SSL_read(ssl, tmpbuf, sizeof(tmpbuf));
1596
1597             if (cc == 0) {
1598                 result = SSL_get_error(ssl, cc);
1599
1600                 if (result != SSL_ERROR_ZERO_RETURN) {
1601                     sm_ierror("TLS peer aborted connection");
1602                 }
1603
1604                 return EOF;
1605             }
1606
1607             if (cc < 0) {
1608                 sm_ierror("SSL_read failed: %s",
1609                           ERR_error_string(ERR_get_error(), NULL));
1610                 return -2;
1611             }
1612         } else
1613 #endif /* TLS_SUPPORT */
1614
1615         cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1616
1617         if (cc == 0)
1618             return EOF;
1619
1620         if (cc < 0) {
1621             sm_ierror("Unable to read from network: %s", strerror(errno));
1622             return -2;
1623         }
1624
1625         /*
1626          * Don't call sasl_decode unless sasl is complete and we have
1627          * encryption working
1628          */
1629
1630 #ifdef CYRUS_SASL
1631         if (sasl_complete == 0 || sasl_ssf == 0) {
1632             retbuf = tmpbuf;
1633             retbufsize = cc;
1634         } else {
1635             result = sasl_decode(conn, tmpbuf, cc, (const char **) &retbuf,
1636                                  &retbufsize);
1637
1638             if (result != SASL_OK) {
1639                 sm_ierror("Unable to decode SASL network data: %s",
1640                           sasl_errdetail(conn));
1641                 return -2;
1642             }
1643         }
1644 #else /* ! CYRUS_SASL */
1645         retbuf = tmpbuf;
1646         retbufsize = cc;
1647 #endif /* CYRUS_SASL */
1648     }
1649
1650     if (retbufsize > SASL_MAXRECVBUF) {
1651         sm_ierror("Received data (%d bytes) is larger than the buffer "
1652                   "size (%d bytes)", retbufsize, SASL_MAXRECVBUF);
1653         return -2;
1654     }
1655
1656     memcpy(sasl_inbuffer, retbuf, retbufsize);
1657     sasl_inptr = sasl_inbuffer + 1;
1658     sasl_inbuflen = retbufsize - 1;
1659
1660     return (int) sasl_inbuffer[0];
1661 }
1662 #endif /* CYRUS_SASL || TLS_SUPPORT */
1663
1664 static int
1665 sm_rerror (int rc)
1666 {
1667     if (sm_mts == MTS_SMTP)
1668         sm_reply.length =
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"));
1673     else
1674         sm_reply.length =
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"));
1679
1680     return (sm_reply.code = NOTOK);
1681 }
1682
1683
1684 static void
1685 alrmser (int i)
1686 {
1687     NMH_UNUSED (i);
1688
1689 #ifndef RELIABLE_SIGNALS
1690     SIGNAL (SIGALRM, alrmser);
1691 #endif
1692
1693     sm_alarmed++;
1694     if (sm_debug) {
1695         printf ("timed out...\n");
1696         fflush (stdout);
1697     }
1698 }
1699
1700
1701 char *
1702 rp_string (int code)
1703 {
1704     char *text;
1705     static char buffer[BUFSIZ];
1706
1707     switch (sm_reply.code != NOTOK ? code : NOTOK) {
1708         case RP_AOK:
1709             text = "AOK";
1710             break;
1711
1712         case RP_MOK:
1713             text = "MOK";
1714             break;
1715
1716         case RP_OK: 
1717             text = "OK";
1718             break;
1719
1720         case RP_RPLY: 
1721             text = "RPLY";
1722             break;
1723
1724         case RP_BHST: 
1725         default: 
1726             text = "BHST";
1727             snprintf (buffer, sizeof(buffer), "[%s] %s", text, sm_reply.text);
1728             return buffer;
1729
1730         case RP_PARM: 
1731             text = "PARM";
1732             break;
1733
1734         case RP_NO: 
1735             text = "NO";
1736             break;
1737
1738         case RP_USER: 
1739             text = "USER";
1740             break;
1741
1742         case RP_NDEL: 
1743             text = "NDEL";
1744             break;
1745     }
1746
1747     snprintf (buffer, sizeof(buffer), "[%s] %3d %s",
1748                 text, sm_reply.code, sm_reply.text);
1749     return buffer;
1750 }
1751
1752 static char *
1753 EHLOset (char *s)
1754 {
1755     size_t len;
1756     char *ep, **ehlo;
1757
1758     len = strlen (s);
1759
1760     for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1761         ep = *ehlo;
1762         if (strncmp (ep, s, len) == 0) {
1763             for (ep += len; *ep == ' '; ep++)
1764                 continue;
1765             return ep;
1766         }
1767     }
1768
1769     return 0;
1770 }