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