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