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