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