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