* mts/smtp/smtp.c: In sm_auth_sasl (), removed zeroing of
[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         sasl_inbuflen = 0;
907         sasl_inptr = sasl_inbuffer;
908     } else {
909         sasl_outbuffer = NULL;
910         /* Don't NULL out sasl_inbuffer because it could be used in
911            sm_fgetc (). */
912     }
913
914     sasl_complete = 1;
915
916     return RP_OK;
917 }
918
919 /*
920  * Our callback functions to feed data to the SASL library
921  */
922
923 static int
924 sm_get_user(void *context, int id, const char **result, unsigned *len)
925 {
926     char *user = (char *) context;
927
928     if (! result || ((id != SASL_CB_USER) && (id != SASL_CB_AUTHNAME)))
929         return SASL_BADPARAM;
930
931     *result = user;
932     if (len)
933         *len = strlen(user);
934
935     return SASL_OK;
936 }
937
938 static int
939 sm_get_pass(sasl_conn_t *conn, void *context, int id,
940             sasl_secret_t **psecret)
941 {
942     char **pw_context = (char **) context;
943     char *pass = NULL;
944     int len;
945
946     if (! psecret || id != SASL_CB_PASS)
947         return SASL_BADPARAM;
948
949     ruserpass(pw_context[0], &(pw_context[1]), &pass);
950
951     len = strlen(pass);
952
953     *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
954
955     if (! *psecret) {
956         free(pass);
957         return SASL_NOMEM;
958     }
959
960     (*psecret)->len = len;
961     strcpy((char *) (*psecret)->data, pass);
962 /*    free(pass); */
963
964     return SASL_OK;
965 }
966 #endif /* CYRUS_SASL */
967
968 static int
969 sm_ierror (char *fmt, ...)
970 {
971     va_list ap;
972
973     va_start(ap, fmt);
974     vsnprintf (sm_reply.text, sizeof(sm_reply.text), fmt, ap);
975     va_end(ap);
976
977     sm_reply.length = strlen (sm_reply.text);
978     sm_reply.code = NOTOK;
979
980     return RP_BHST;
981 }
982
983 static int
984 smtalk (int time, char *fmt, ...)
985 {
986     va_list ap;
987     int result;
988     char buffer[BUFSIZ];
989
990     va_start(ap, fmt);
991     vsnprintf (buffer, sizeof(buffer), fmt, ap);
992     va_end(ap);
993
994     if (sm_debug) {
995 #ifdef CYRUS_SASL
996         if (sasl_ssf)
997                 printf("(encrypted) ");
998 #endif /* CYRUS_SASL */
999         printf ("=> %s\n", buffer);
1000         fflush (stdout);
1001     }
1002
1003     sm_alarmed = 0;
1004     alarm ((unsigned) time);
1005     if ((result = sm_wrecord (buffer, strlen (buffer))) != NOTOK)
1006         result = smhear ();
1007     alarm (0);
1008
1009     return result;
1010 }
1011
1012
1013 /*
1014  * write the buffer to the open SMTP channel
1015  */
1016
1017 static int
1018 sm_wrecord (char *buffer, int len)
1019 {
1020     if (sm_wfp == NULL)
1021         return sm_werror ();
1022
1023     sm_fwrite (buffer, len);
1024     sm_fputs ("\r\n");
1025     sm_fflush ();
1026
1027     return (ferror (sm_wfp) ? sm_werror () : OK);
1028 }
1029
1030
1031 static int
1032 sm_wstream (char *buffer, int len)
1033 {
1034     char  *bp;
1035     static char lc = '\0';
1036
1037     if (sm_wfp == NULL)
1038         return sm_werror ();
1039
1040     if (buffer == NULL && len == 0) {
1041         if (lc != '\n')
1042             sm_fputs ("\r\n");
1043         lc = '\0';
1044         return (ferror (sm_wfp) ? sm_werror () : OK);
1045     }
1046
1047     for (bp = buffer; len > 0; bp++, len--) {
1048         switch (*bp) {
1049             case '\n': 
1050                 sm_nl = TRUE;
1051                 sm_fputc ('\r');
1052                 break;
1053
1054             case '.': 
1055                 if (sm_nl)
1056                     sm_fputc ('.');/* FALL THROUGH */
1057             default: 
1058                 sm_nl = FALSE;
1059         }
1060         sm_fputc (*bp);
1061         if (ferror (sm_wfp))
1062             return sm_werror ();
1063     }
1064
1065     if (bp > buffer)
1066         lc = *--bp;
1067     return (ferror (sm_wfp) ? sm_werror () : OK);
1068 }
1069
1070 /*
1071  * Write out to the network, but do buffering for SASL (if enabled)
1072  */
1073
1074 static int
1075 sm_fwrite(char *buffer, int len)
1076 {
1077 #ifdef CYRUS_SASL
1078     const char *output;
1079     unsigned int outputlen;
1080
1081     if (sasl_complete == 0 || sasl_ssf == 0)
1082 #endif /* CYRUS_SASL */
1083         fwrite(buffer, sizeof(*buffer), len, sm_wfp);
1084 #ifdef CYRUS_SASL
1085     else {
1086         while (len >= maxoutbuf - sasl_outbuflen) {
1087             memcpy(sasl_outbuffer + sasl_outbuflen, buffer,
1088                    maxoutbuf - sasl_outbuflen);
1089             len -= maxoutbuf - sasl_outbuflen;
1090             sasl_outbuflen = 0;
1091
1092             if (sasl_encode(conn, sasl_outbuffer, maxoutbuf,
1093                             &output, &outputlen) != SASL_OK) {
1094                 sm_ierror("Unable to SASL encode connection data: %s",
1095                           sasl_errdetail(conn));
1096                 return NOTOK;
1097             }
1098
1099             fwrite(output, sizeof(*output), outputlen, sm_wfp);
1100         }
1101
1102         if (len > 0) {
1103             memcpy(sasl_outbuffer + sasl_outbuflen, buffer, len);
1104             sasl_outbuflen += len;
1105         }
1106     }
1107 #endif /* CYRUS_SASL */
1108     return ferror(sm_wfp) ? NOTOK : RP_OK;
1109 }
1110
1111 /*
1112  * Convenience functions to replace occurences of fputs() and fputc()
1113  */
1114
1115 static int
1116 sm_fputs(char *buffer)
1117 {
1118     return sm_fwrite(buffer, strlen(buffer));
1119 }
1120
1121 static int
1122 sm_fputc(int c)
1123 {
1124     char h = c;
1125
1126     return sm_fwrite(&h, 1);
1127 }
1128
1129 /*
1130  * Flush out any pending data on the connection
1131  */
1132
1133 static void
1134 sm_fflush(void)
1135 {
1136 #ifdef CYRUS_SASL
1137     const char *output;
1138     unsigned int outputlen;
1139     int result;
1140
1141     if (sasl_complete == 1 && sasl_ssf > 0 && sasl_outbuflen > 0) {
1142         result = sasl_encode(conn, sasl_outbuffer, sasl_outbuflen,
1143                              &output, &outputlen);
1144         if (result != SASL_OK) {
1145             sm_ierror("Unable to SASL encode connection data: %s",
1146                       sasl_errdetail(conn));
1147             return;
1148         }
1149
1150         fwrite(output, sizeof(*output), outputlen, sm_wfp);
1151         sasl_outbuflen = 0;
1152     }
1153 #endif /* CYRUS_SASL */
1154
1155     fflush(sm_wfp);
1156 }
1157
1158 static int
1159 sm_werror (void)
1160 {
1161     sm_reply.length =
1162         strlen (strcpy (sm_reply.text, sm_wfp == NULL ? "no socket opened"
1163             : sm_alarmed ? "write to socket timed out"
1164             : "error writing to socket"));
1165
1166     return (sm_reply.code = NOTOK);
1167 }
1168
1169
1170 static int
1171 smhear (void)
1172 {
1173     int i, code, cont, bc, rc, more;
1174     unsigned char *bp;
1175     char *rp;
1176     char **ehlo, buffer[BUFSIZ];
1177
1178     if (doingEHLO) {
1179         static int at_least_once = 0;
1180
1181         if (at_least_once) {
1182             char *ep;
1183
1184             for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1185                 ep = *ehlo;
1186                 free (ep);
1187             }
1188         } else {
1189             at_least_once = 1;
1190         }
1191
1192         ehlo = EHLOkeys;
1193         *ehlo = NULL;
1194     }
1195
1196 again: ;
1197
1198     sm_reply.length = 0;
1199     sm_reply.text[0] = 0;
1200     rp = sm_reply.text;
1201     rc = sizeof(sm_reply.text) - 1;
1202
1203     for (more = FALSE; sm_rrecord ((char *) (bp = (unsigned char *) buffer),
1204                                    &bc) != NOTOK ; ) {
1205         if (sm_debug) {
1206 #ifdef CYRUS_SASL
1207             if (sasl_ssf > 0)
1208                 printf("(decrypted) ");
1209 #endif /* CYRUS_SASL */
1210             printf ("<= %s\n", buffer);
1211             fflush (stdout);
1212         }
1213
1214         if (doingEHLO
1215                 && strncmp (buffer, "250", sizeof("250") - 1) == 0
1216                 && (buffer[3] == '-' || doingEHLO == 2)
1217                 && buffer[4]) {
1218             if (doingEHLO == 2) {
1219                 if ((*ehlo = malloc ((size_t) (strlen (buffer + 4) + 1)))) {
1220                     strcpy (*ehlo++, buffer + 4);
1221                     *ehlo = NULL;
1222                     if (ehlo >= EHLOkeys + MAXEHLO)
1223                         doingEHLO = 0;
1224                 }
1225                 else
1226                     doingEHLO = 0;
1227             }
1228             else
1229                 doingEHLO = 2;
1230         }
1231
1232         for (; bc > 0 && (!isascii (*bp) || !isdigit (*bp)); bp++, bc--)
1233             continue;
1234
1235         cont = FALSE;
1236         code = atoi ((char *) bp);
1237         bp += 3, bc -= 3;
1238         for (; bc > 0 && isspace (*bp); bp++, bc--)
1239             continue;
1240         if (bc > 0 && *bp == '-') {
1241             cont = TRUE;
1242             bp++, bc--;
1243             for (; bc > 0 && isspace (*bp); bp++, bc--)
1244                 continue;
1245         }
1246
1247         if (more) {
1248             if (code != sm_reply.code || cont)
1249                 continue;
1250             more = FALSE;
1251         } else {
1252             sm_reply.code = code;
1253             more = cont;
1254             if (bc <= 0) {
1255                 /* can never fail to 0-terminate because of size of buffer vs fixed string */
1256                 strncpy (buffer, sm_noreply, sizeof(buffer));
1257                 bp = (unsigned char *) buffer;
1258                 bc = strlen (sm_noreply);
1259             }
1260         }
1261
1262         if ((i = min (bc, rc)) > 0) {
1263             memcpy (rp, bp, i);
1264             rp += i;
1265             rc -= i;
1266             i = strlen(sm_moreply);
1267             if (more && rc > i + 1) {
1268                 memcpy (rp, sm_moreply, i); /* safe because of check in if() */
1269                 rp += i;
1270                 rc -= i;
1271             }
1272         }
1273         if (more)
1274             continue;
1275         if (sm_reply.code < 100) {
1276             if (sm_verbose) {
1277                 printf ("%s\n", sm_reply.text);
1278                 fflush (stdout);
1279             }
1280             goto again;
1281         }
1282
1283         sm_reply.length = rp - sm_reply.text;
1284         sm_reply.text[sm_reply.length] = 0;
1285         return sm_reply.code;
1286     }
1287     return NOTOK;
1288 }
1289
1290
1291 static int
1292 sm_rrecord (char *buffer, int *len)
1293 {
1294     int retval;
1295
1296     if (sm_rfp == NULL)
1297         return sm_rerror(0);
1298
1299     buffer[*len = 0] = 0;
1300
1301     if ((retval = sm_fgets (buffer, BUFSIZ, sm_rfp)) != RP_OK)
1302         return retval;
1303     *len = strlen (buffer);
1304     /* *len should be >0 except on EOF, but check for safety's sake */
1305     if (*len == 0)
1306         return sm_rerror (RP_EOF);
1307     if (buffer[*len - 1] != '\n')
1308         while ((retval = sm_fgetc (sm_rfp)) != '\n' && retval != EOF &&
1309                retval != -2)
1310             continue;
1311     else
1312         if ((*len > 1) && (buffer[*len - 2] == '\r'))
1313             *len -= 1;
1314     *len -= 1;
1315     buffer[*len] = 0;
1316
1317     return OK;
1318 }
1319
1320 /*
1321  * Our version of fgets, which calls our private fgetc function
1322  */
1323
1324 static int
1325 sm_fgets(char *buffer, int size, FILE *f)
1326 {
1327     int c;
1328
1329      do {
1330         c = sm_fgetc(f);
1331
1332         if (c == EOF)
1333             return RP_EOF;
1334
1335         if (c == -2)
1336             return NOTOK;
1337
1338         *buffer++ = c;
1339      } while (size > 1 && c != '\n');
1340
1341      *buffer = '\0';
1342
1343      return RP_OK;
1344 }
1345
1346
1347 #ifdef CYRUS_SASL
1348 /*
1349  * Read from the network, but do SASL encryption
1350  */
1351
1352 static int
1353 sm_fgetc(FILE *f)
1354 {
1355     char tmpbuf[BUFSIZ], *retbuf;
1356     unsigned int retbufsize = 0;
1357     int cc, result;
1358
1359     /*
1360      * If we have leftover data, return it
1361      */
1362
1363     if (sasl_inbuflen) {
1364         sasl_inbuflen--;
1365         return (int) *sasl_inptr++;
1366     }
1367
1368     /*
1369      * If not, read from the network until we have some data to return
1370      */
1371
1372     while (retbufsize == 0) {
1373
1374         cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1375
1376         if (cc == 0)
1377             return EOF;
1378
1379         if (cc < 0) {
1380             sm_ierror("Unable to read from network: %s", strerror(errno));
1381             return -2;
1382         }
1383
1384         /*
1385          * Don't call sasl_decode unless sasl is complete and we have
1386          * encryption working
1387          */
1388
1389         if (sasl_complete == 0 || sasl_ssf == 0) {
1390             retbuf = tmpbuf;
1391             retbufsize = cc;
1392         } else {
1393             result = sasl_decode(conn, tmpbuf, cc, (const char **) &retbuf,
1394                                  &retbufsize);
1395
1396             if (result != SASL_OK) {
1397                 sm_ierror("Unable to decode SASL network data: %s",
1398                           sasl_errdetail(conn));
1399                 return -2;
1400             }
1401         }
1402     }
1403
1404     if (retbufsize > SASL_MAXRECVBUF) {
1405         sm_ierror("Received data (%d bytes) is larger than the buffer "
1406                   "size (%d bytes)", retbufsize, SASL_MAXRECVBUF);
1407         return -2;
1408     }
1409
1410     memcpy(sasl_inbuffer, retbuf, retbufsize);
1411     sasl_inptr = sasl_inbuffer + 1;
1412     sasl_inbuflen = retbufsize - 1;
1413
1414     return (int) sasl_inbuffer[0];
1415 }
1416 #endif /* CYRUS_SASL */
1417
1418 static int
1419 sm_rerror (int rc)
1420 {
1421     if (sm_mts == MTS_SMTP)
1422         sm_reply.length =
1423             strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no socket opened"
1424                 : sm_alarmed ? "read from socket timed out"
1425                 : rc == RP_EOF ? "premature end-of-file on socket"
1426                 : "error reading from socket"));
1427     else
1428         sm_reply.length =
1429             strlen (strcpy (sm_reply.text, sm_rfp == NULL ? "no pipe opened"
1430                 : sm_alarmed ? "read from pipe timed out"
1431                 : rc == RP_EOF ? "premature end-of-file on pipe"
1432                 : "error reading from pipe"));
1433
1434     return (sm_reply.code = NOTOK);
1435 }
1436
1437
1438 static RETSIGTYPE
1439 alrmser (int i)
1440 {
1441 #ifndef RELIABLE_SIGNALS
1442     SIGNAL (SIGALRM, alrmser);
1443 #endif
1444
1445     sm_alarmed++;
1446     if (sm_debug) {
1447         printf ("timed out...\n");
1448         fflush (stdout);
1449     }
1450 }
1451
1452
1453 char *
1454 rp_string (int code)
1455 {
1456     char *text;
1457     static char buffer[BUFSIZ];
1458
1459     switch (sm_reply.code != NOTOK ? code : NOTOK) {
1460         case RP_AOK:
1461             text = "AOK";
1462             break;
1463
1464         case RP_MOK:
1465             text = "MOK";
1466             break;
1467
1468         case RP_OK: 
1469             text = "OK";
1470             break;
1471
1472         case RP_RPLY: 
1473             text = "RPLY";
1474             break;
1475
1476         case RP_BHST: 
1477         default: 
1478             text = "BHST";
1479             snprintf (buffer, sizeof(buffer), "[%s] %s", text, sm_reply.text);
1480             return buffer;
1481
1482         case RP_PARM: 
1483             text = "PARM";
1484             break;
1485
1486         case RP_NO: 
1487             text = "NO";
1488             break;
1489
1490         case RP_USER: 
1491             text = "USER";
1492             break;
1493
1494         case RP_NDEL: 
1495             text = "NDEL";
1496             break;
1497     }
1498
1499     snprintf (buffer, sizeof(buffer), "[%s] %3d %s",
1500                 text, sm_reply.code, sm_reply.text);
1501     return buffer;
1502 }
1503
1504 static char *
1505 EHLOset (char *s)
1506 {
1507     size_t len;
1508     char *ep, **ehlo;
1509
1510     len = strlen (s);
1511
1512     for (ehlo = EHLOkeys; *ehlo; ehlo++) {
1513         ep = *ehlo;
1514         if (strncmp (ep, s, len) == 0) {
1515             for (ep += len; *ep == ' '; ep++)
1516                 continue;
1517             return ep;
1518         }
1519     }
1520
1521     return 0;
1522 }