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