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