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