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