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