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