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