c566264d3f0f7ea40ee0dbe7bd53583d5d2d5a6f
[mmh] / uip / popsbr.c
1 /*
2  * popsbr.c -- POP client subroutines
3  *
4  * This code is Copyright (c) 2002, by the authors of nmh.  See the
5  * COPYRIGHT file in the root directory of the nmh distribution for
6  * complete copyright information.
7  */
8
9 #include <h/mh.h>
10 #include <h/utils.h>
11
12 #ifdef CYRUS_SASL
13 # include <sasl/sasl.h>
14 # include <sasl/saslutil.h>
15 #endif /* CYRUS_SASL */
16
17 #include <h/popsbr.h>
18 #include <h/signals.h>
19 #include <signal.h>
20 #include <errno.h>
21
22 #define TRM     "."
23 #define TRMLEN  (sizeof TRM - 1)
24
25 static int poprint = 0;
26 static int pophack = 0;
27
28 char response[BUFSIZ];
29
30 static FILE *input;
31 static FILE *output;
32
33 #ifdef CYRUS_SASL
34 static sasl_conn_t *conn;       /* SASL connection state */
35 static int sasl_complete = 0;   /* Has sasl authentication succeeded? */
36 static int maxoutbuf;           /* Maximum output buffer size */
37 static sasl_ssf_t sasl_ssf = 0; /* Security strength factor */
38 static int sasl_get_user(void *, int, const char **, unsigned *);
39 static int sasl_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
40 struct pass_context {
41     char *user;
42     char *host;
43 };
44
45 static sasl_callback_t callbacks[] = {
46     { SASL_CB_USER, sasl_get_user, NULL },
47 #define POP_SASL_CB_N_USER 0
48     { SASL_CB_PASS, sasl_get_pass, NULL },
49 #define POP_SASL_CB_N_PASS 1
50     { SASL_CB_LOG, NULL, NULL },
51     { SASL_CB_LIST_END, NULL, NULL },
52
53 #define SASL_BUFFER_SIZE 262144
54 };
55 #else /* CYRUS_SASL */
56 # define sasl_fgetc fgetc
57 #endif /* CYRUS_SASL */
58
59 /*
60  * static prototypes
61  */
62
63 static int command(const char *, ...);
64 static int multiline(void);
65
66 #ifdef CYRUS_SASL
67 static int pop_auth_sasl(char *, char *, char *);
68 static int sasl_fgetc(FILE *);
69 #endif /* CYRUS_SASL */
70
71 static int traverse (int (*)(char *), const char *, ...);
72 static int vcommand(const char *, va_list);
73 static int sasl_getline (char *, int, FILE *);
74 static int putline (char *, FILE *);
75
76
77 #ifdef CYRUS_SASL
78 /*
79  * This function implements the AUTH command for various SASL mechanisms
80  *
81  * We do the whole SASL dialog here.  If this completes, then we've
82  * authenticated successfully and have (possibly) negotiated a security
83  * layer.
84  */
85
86 int
87 pop_auth_sasl(char *user, char *host, char *mech)
88 {
89     int result, status, sasl_capability = 0;
90     unsigned int buflen, outlen;
91     char server_mechs[256], *buf, outbuf[BUFSIZ];
92     const char *chosen_mech;
93     sasl_security_properties_t secprops;
94     struct pass_context p_context;
95     sasl_ssf_t *ssf;
96     int *moutbuf;
97
98     /*
99      * First off, we're going to send the CAPA command to see if we can
100      * even support the AUTH command, and if we do, then we'll get a
101      * list of mechanisms the server supports.  If we don't support
102      * the CAPA command, then it's unlikely that we will support
103      * SASL
104      */
105
106     if (command("CAPA") == NOTOK) {
107         snprintf(response, sizeof(response),
108                  "The POP CAPA command failed; POP server does not "
109                  "support SASL");
110         return NOTOK;
111     }
112
113     while ((status = multiline()) != DONE)
114         switch (status) {
115         case NOTOK:
116             return NOTOK;
117             break;
118         case DONE:      /* Shouldn't be possible, but just in case */
119             break;
120         case OK:
121             if (strncasecmp(response, "SASL ", 5) == 0) {
122                 /*
123                  * We've seen the SASL capability.  Grab the mech list
124                  */
125                 sasl_capability++;
126                 strncpy(server_mechs, response + 5, sizeof(server_mechs));
127             }
128             break;
129         }
130
131     if (!sasl_capability) {
132         snprintf(response, sizeof(response), "POP server does not support "
133                  "SASL");
134         return NOTOK;
135     }
136
137     /*
138      * If we received a preferred mechanism, see if the server supports it.
139      */
140
141     if (mech && stringdex(mech, server_mechs) == -1) {
142         snprintf(response, sizeof(response), "Requested SASL mech \"%s\" is "
143                  "not in list of supported mechanisms:\n%s",
144                  mech, server_mechs);
145         return NOTOK;
146     }
147
148     /*
149      * Start the SASL process.  First off, initialize the SASL library.
150      */
151
152     callbacks[POP_SASL_CB_N_USER].context = user;
153     p_context.user = user;
154     p_context.host = host;
155     callbacks[POP_SASL_CB_N_PASS].context = &p_context;
156
157     result = sasl_client_init(callbacks);
158
159     if (result != SASL_OK) {
160         snprintf(response, sizeof(response), "SASL library initialization "
161                  "failed: %s", sasl_errstring(result, NULL, NULL));
162         return NOTOK;
163     }
164
165     result = sasl_client_new("pop", host, NULL, NULL, NULL, 0, &conn);
166
167     if (result != SASL_OK) {
168         snprintf(response, sizeof(response), "SASL client initialization "
169                  "failed: %s", sasl_errstring(result, NULL, NULL));
170         return NOTOK;
171     }
172
173     /*
174      * Initialize the security properties
175      */
176
177     memset(&secprops, 0, sizeof(secprops));
178     secprops.maxbufsize = SASL_BUFFER_SIZE;
179     secprops.max_ssf = UINT_MAX;
180
181     result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
182
183     if (result != SASL_OK) {
184         snprintf(response, sizeof(response), "SASL security property "
185                  "initialization failed: %s", sasl_errdetail(conn));
186         return NOTOK;
187     }
188
189     /*
190      * Start the actual protocol.  Feed the mech list into the library
191      * and get out a possible initial challenge
192      */
193
194     result = sasl_client_start(conn,
195                                (const char *) (mech ? mech : server_mechs),
196                                NULL, (const char **) &buf,
197                                &buflen, &chosen_mech);
198
199     if (result != SASL_OK && result != SASL_CONTINUE) {
200         snprintf(response, sizeof(response), "SASL client start failed: %s",
201                  sasl_errdetail(conn));
202         return NOTOK;
203     }
204
205     if (buflen) {
206         status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
207         if (status != SASL_OK) {
208             snprintf(response, sizeof(response), "SASL base64 encode "
209                      "failed: %s", sasl_errstring(status, NULL, NULL));
210             return NOTOK;
211         }
212
213         status = command("AUTH %s %s", chosen_mech, outbuf);
214     } else
215         status = command("AUTH %s", chosen_mech);
216
217     while (result == SASL_CONTINUE) {
218         if (status == NOTOK)
219             return NOTOK;
220         
221         /*
222          * If we get a "+OK" prefix to our response, then we should
223          * exit out of this exchange now (because authenticated should
224          * have succeeded)
225          */
226         
227         if (strncmp(response, "+OK", 3) == 0)
228             break;
229         
230         /*
231          * Otherwise, make sure the server challenge is correctly formatted
232          */
233         
234         if (strncmp(response, "+ ", 2) != 0) {
235             command("*");
236             snprintf(response, sizeof(response),
237                      "Malformed authentication message from server");
238             return NOTOK;
239         }
240
241         result = sasl_decode64(response + 2, strlen(response + 2),
242                                outbuf, sizeof(outbuf), &outlen);
243         
244         if (result != SASL_OK) {
245             command("*");
246             snprintf(response, sizeof(response), "SASL base64 decode "
247                      "failed: %s", sasl_errstring(result, NULL, NULL));
248             return NOTOK;
249         }
250
251         result = sasl_client_step(conn, outbuf, outlen, NULL,
252                                   (const char **) &buf, &buflen);
253
254         if (result != SASL_OK && result != SASL_CONTINUE) {
255             command("*");
256             snprintf(response, sizeof(response), "SASL client negotiaton "
257                      "failed: %s", sasl_errdetail(conn));
258             return NOTOK;
259         }
260
261         status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
262
263         if (status != SASL_OK) {
264             command("*");
265             snprintf(response, sizeof(response), "SASL base64 encode "
266                      "failed: %s", sasl_errstring(status, NULL, NULL));
267             return NOTOK;
268         }
269
270         status = command(outbuf);
271     }
272
273     /*
274      * If we didn't get a positive final response, then error out
275      * (that probably means we failed an authorization check).
276      */
277
278     if (status != OK)
279         return NOTOK;
280
281     /*
282      * We _should_ be okay now.  Get a few properties now that negotiation
283      * has completed.
284      */
285
286     result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &moutbuf);
287
288     if (result != SASL_OK) {
289         snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
290                  "output buffer size: %s", sasl_errdetail(conn));
291         return NOTOK;
292     }
293
294     maxoutbuf = *moutbuf;
295
296     result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
297
298     sasl_ssf = *ssf;
299
300     if (result != SASL_OK) {
301         snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
302                  "security strength factor: %s", sasl_errdetail(conn));
303         return NOTOK;
304     }
305
306     /*
307      * Limit this to what we can deal with.  Shouldn't matter much because
308      * this is only outgoing data (which should be small)
309      */
310
311     if (maxoutbuf == 0 || maxoutbuf > BUFSIZ)
312         maxoutbuf = BUFSIZ;
313
314     sasl_complete = 1;
315
316     return status;
317 }
318
319 /*
320  * Callback to return the userid sent down via the user parameter
321  */
322
323 static int
324 sasl_get_user(void *context, int id, const char **result, unsigned *len)
325 {
326     char *user = (char *) context;
327
328     if (! result || id != SASL_CB_USER)
329         return SASL_BADPARAM;
330
331     *result = user;
332     if (len)
333         *len = strlen(user);
334
335     return SASL_OK;
336 }
337
338 /*
339  * Callback to return the password (we call ruserpass, which can get it
340  * out of the .netrc
341  */
342
343 static int
344 sasl_get_pass(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
345 {
346     struct pass_context *p_context = (struct pass_context *) context;
347     char *pass = NULL;
348     int len;
349
350     NMH_UNUSED (conn);
351
352     if (! psecret || id != SASL_CB_PASS)
353         return SASL_BADPARAM;
354
355     ruserpass(p_context->user, &(p_context->host), &pass);
356
357     len = strlen(pass);
358
359     *psecret = (sasl_secret_t *) mh_xmalloc(sizeof(sasl_secret_t) + len);
360
361     (*psecret)->len = len;
362     strcpy((char *) (*psecret)->data, pass);
363
364     return SASL_OK;
365 }
366 #endif /* CYRUS_SASL */
367
368
369 /*
370  * Split string containing proxy command into an array of arguments
371  * suitable for passing to exec. Returned array must be freed. Shouldn't
372  * be possible to call this with host set to NULL.
373  */
374 char **
375 parse_proxy(char *proxy, char *host)
376 {
377     char **pargv, **p;
378     int pargc = 2;
379     int hlen = strlen(host);
380     int plen = 1;
381     unsigned char *cur, *pro;
382     char *c;
383     
384     /* skip any initial space */
385     for (pro = (unsigned char *) proxy; isspace(*pro); pro++)
386         continue;
387     
388     /* calculate required size for argument array */
389     for (cur = pro; *cur; cur++) {
390         if (isspace(*cur) && cur[1] && !isspace(cur[1]))
391             plen++, pargc++;
392         else if (*cur == '%' && cur[1] == 'h') {
393             plen += hlen;
394             cur++;
395         } else if (!isspace(*cur))
396             plen++;
397     }
398
399    /* put together list of arguments */
400     p = pargv = mh_xmalloc(pargc * sizeof(char *));
401     c = *pargv = mh_xmalloc(plen * sizeof(char));
402     for (cur = pro; *cur; cur++) {
403         if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
404             *c++ = '\0';
405             *++p = c;
406         } else if (*cur == '%' && cur[1] == 'h') {
407             strcpy (c, host);
408             c += hlen;
409             cur++;
410         } else if (!isspace(*cur))
411             *c++ = *cur;
412     }
413     *++p = NULL;
414     return pargv;
415 }
416
417 int
418 pop_init (char *host, char *port, char *user, char *pass, char *proxy,
419           int snoop, int sasl, char *mech)
420 {
421     int fd1, fd2;
422     char buffer[BUFSIZ];
423 #ifndef CYRUS_SASL
424     NMH_UNUSED (sasl);
425     NMH_UNUSED (mech);
426 #endif /* ! CYRUS_SASL */
427
428     if (proxy && *proxy) {
429        int pid;
430        int inpipe[2];     /* for reading from the server */
431        int outpipe[2];    /* for sending to the server */
432
433        /* first give up any root priviledges we may have for rpop */
434        setuid(getuid());
435
436        pipe(inpipe);
437        pipe(outpipe);
438
439        pid=fork();
440        if (pid==0) {
441            char **argv;
442            
443            /* in child */
444            close(0);  
445            close(1);
446            dup2(outpipe[0],0);  /* connect read end of connection */
447            dup2(inpipe[1], 1);  /* connect write end of connection */
448            if(inpipe[0]>1) close(inpipe[0]);
449            if(inpipe[1]>1) close(inpipe[1]);
450            if(outpipe[0]>1) close(outpipe[0]);
451            if(outpipe[1]>1) close(outpipe[1]);
452
453            /* run the proxy command */
454            argv=parse_proxy(proxy, host);
455            execvp(argv[0],argv);
456
457            perror(argv[0]);
458            close(0);
459            close(1);
460            free(*argv);
461            free(argv);
462            exit(10);
463        }
464
465        /* okay in the parent we do some stuff */
466        close(inpipe[1]);  /* child uses this */
467        close(outpipe[0]); /* child uses this */
468
469        /* we read on fd1 */
470        fd1=inpipe[0];
471        /* and write on fd2 */
472        fd2=outpipe[1];
473
474     } else {
475
476         if ((fd1 = client (host, port ? port : "pop3", response,
477                            sizeof(response), snoop)) == NOTOK) {
478             return NOTOK;
479         }
480
481         if ((fd2 = dup (fd1)) == NOTOK) {
482             char *s;
483
484             if ((s = strerror(errno)))
485                 snprintf (response, sizeof(response),
486                     "unable to dup connection descriptor: %s", s);
487             else
488                 snprintf (response, sizeof(response),
489                     "unable to dup connection descriptor: unknown error");
490             close (fd1);
491             return NOTOK;
492         }
493     }
494     if (pop_set (fd1, fd2, snoop) == NOTOK)
495         return NOTOK;
496
497     SIGNAL (SIGPIPE, SIG_IGN);
498
499     switch (sasl_getline (response, sizeof response, input)) {
500         case OK: 
501             if (poprint)
502                 fprintf (stderr, "<--- %s\n", response);
503             if (*response == '+') {
504 #  ifdef CYRUS_SASL
505                 if (sasl) {
506                     if (pop_auth_sasl(user, host, mech) != NOTOK)
507                         return OK;
508                 } else
509 #  endif /* CYRUS_SASL */
510                 if (command ("USER %s", user) != NOTOK
511                     && command ("%s %s", (pophack++, "PASS"),
512                                         pass) != NOTOK)
513                 return OK;
514             }
515             strncpy (buffer, response, sizeof(buffer));
516             command ("QUIT");
517             strncpy (response, buffer, sizeof(response));
518                                 /* and fall */
519
520         case NOTOK: 
521         case DONE: 
522             if (poprint)            
523                 fprintf (stderr, "%s\n", response);
524             fclose (input);
525             fclose (output);
526             return NOTOK;
527     }
528
529     return NOTOK;       /* NOTREACHED */
530 }
531
532 int
533 pop_set (int in, int out, int snoop)
534 {
535
536     if ((input = fdopen (in, "r")) == NULL
537             || (output = fdopen (out, "w")) == NULL) {
538         strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
539         if (input)
540             fclose (input);
541         else
542             close (in);
543         close (out);
544         return NOTOK;
545     }
546
547     poprint = snoop;
548
549     return OK;
550 }
551
552
553 int
554 pop_fd (char *in, int inlen, char *out, int outlen)
555 {
556     snprintf (in, inlen, "%d", fileno (input));
557     snprintf (out, outlen, "%d", fileno (output));
558     return OK;
559 }
560
561
562 /*
563  * Find out number of messages available
564  * and their total size.
565  */
566
567 int
568 pop_stat (int *nmsgs, int *nbytes)
569 {
570
571     if (command ("STAT") == NOTOK)
572         return NOTOK;
573
574     *nmsgs = *nbytes = 0;
575     sscanf (response, "+OK %d %d", nmsgs, nbytes);
576
577     return OK;
578 }
579
580
581 int
582 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
583 {
584     int i;
585     int *ids = NULL;
586
587     if (msgno) {
588         if (command ("LIST %d", msgno) == NOTOK)
589             return NOTOK;
590         *msgs = *bytes = 0;
591         if (ids) {
592             *ids = 0;
593             sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
594         }
595         else
596             sscanf (response, "+OK %d %d", msgs, bytes);
597         return OK;
598     }
599
600     if (command ("LIST") == NOTOK)
601         return NOTOK;
602
603     for (i = 0; i < *nmsgs; i++)
604         switch (multiline ()) {
605             case NOTOK: 
606                 return NOTOK;
607             case DONE: 
608                 *nmsgs = ++i;
609                 return OK;
610             case OK: 
611                 *msgs = *bytes = 0;
612                 if (ids) {
613                     *ids = 0;
614                     sscanf (response, "%d %d %d",
615                             msgs++, bytes++, ids++);
616                 }
617                 else
618                     sscanf (response, "%d %d", msgs++, bytes++);
619                 break;
620         }
621     for (;;)
622         switch (multiline ()) {
623             case NOTOK: 
624                 return NOTOK;
625             case DONE: 
626                 return OK;
627             case OK: 
628                 break;
629         }
630 }
631
632
633 int
634 pop_retr (int msgno, int (*action)(char *))
635 {
636     return traverse (action, "RETR %d", msgno);
637 }
638
639
640 static int
641 traverse (int (*action)(char *), const char *fmt, ...)
642 {
643     int result;
644     va_list ap;
645     char buffer[sizeof(response)];
646
647     va_start(ap, fmt);
648     result = vcommand (fmt, ap);
649     va_end(ap);
650
651     if (result == NOTOK)
652         return NOTOK;
653     strncpy (buffer, response, sizeof(buffer));
654
655     for (;;)
656         switch (multiline ()) {
657             case NOTOK: 
658                 return NOTOK;
659
660             case DONE: 
661                 strncpy (response, buffer, sizeof(response));
662                 return OK;
663
664             case OK: 
665                 (*action) (response);
666                 break;
667         }
668 }
669
670
671 int
672 pop_dele (int msgno)
673 {
674     return command ("DELE %d", msgno);
675 }
676
677
678 int
679 pop_noop (void)
680 {
681     return command ("NOOP");
682 }
683
684
685 int
686 pop_rset (void)
687 {
688     return command ("RSET");
689 }
690
691
692 int
693 pop_top (int msgno, int lines, int (*action)(char *))
694 {
695     return traverse (action, "TOP %d %d", msgno, lines);
696 }
697
698
699 int
700 pop_quit (void)
701 {
702     int i;
703
704     i = command ("QUIT");
705     pop_done ();
706
707     return i;
708 }
709
710
711 int
712 pop_done (void)
713 {
714 #ifdef CYRUS_SASL
715     if (conn)
716         sasl_dispose(&conn);
717 #endif /* CYRUS_SASL */
718     fclose (input);
719     fclose (output);
720
721     return OK;
722 }
723
724
725 int
726 command(const char *fmt, ...)
727 {
728     va_list ap;
729     int result;
730
731     va_start(ap, fmt);
732     result = vcommand(fmt, ap);
733     va_end(ap);
734
735     return result;
736 }
737
738
739 static int
740 vcommand (const char *fmt, va_list ap)
741 {
742     char *cp, buffer[BUFSIZ];
743
744     vsnprintf (buffer, sizeof(buffer), fmt, ap);
745     if (poprint) {
746 #ifdef CYRUS_SASL
747         if (sasl_ssf)
748             fprintf(stderr, "(encrypted) ");
749 #endif /* CYRUS_SASL */
750         if (pophack) {
751             if ((cp = strchr (buffer, ' ')))
752                 *cp = 0;
753             fprintf (stderr, "---> %s ********\n", buffer);
754             if (cp)
755                 *cp = ' ';
756             pophack = 0;
757         }
758         else
759             fprintf (stderr, "---> %s\n", buffer);
760     }
761
762     if (putline (buffer, output) == NOTOK)
763         return NOTOK;
764
765 #ifdef CYRUS_SASL
766     if (poprint && sasl_ssf)
767         fprintf(stderr, "(decrypted) ");
768 #endif /* CYRUS_SASL */
769
770     switch (sasl_getline (response, sizeof response, input)) {
771         case OK: 
772             if (poprint)
773                 fprintf (stderr, "<--- %s\n", response);
774             return (*response == '+' ? OK : NOTOK);
775
776         case NOTOK: 
777         case DONE: 
778             if (poprint)            
779                 fprintf (stderr, "%s\n", response);
780             return NOTOK;
781     }
782
783     return NOTOK;       /* NOTREACHED */
784 }
785
786
787 int
788 multiline (void)
789 {
790     char buffer[BUFSIZ + TRMLEN];
791
792     if (sasl_getline (buffer, sizeof buffer, input) != OK)
793         return NOTOK;
794 #ifdef DEBUG
795     if (poprint) {
796 #ifdef CYRUS_SASL
797         if (sasl_ssf)
798             fprintf(stderr, "(decrypted) ");
799 #endif /* CYRUS_SASL */
800         fprintf (stderr, "<--- %s\n", response);
801     }
802 #endif /* DEBUG */
803     if (strncmp (buffer, TRM, TRMLEN) == 0) {
804         if (buffer[TRMLEN] == 0)
805             return DONE;
806         else
807             strncpy (response, buffer + TRMLEN, sizeof(response));
808     }
809     else
810         strncpy (response, buffer, sizeof(response));
811
812     return OK;
813 }
814
815 /*
816  * Note that these functions have been modified to deal with layer encryption
817  * in the SASL case
818  */
819
820 static int
821 sasl_getline (char *s, int n, FILE *iop)
822 {
823     int c = -2;
824     char *p;
825
826     p = s;
827     while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2) 
828         if ((*p++ = c) == '\n')
829             break;
830     if (c == -2)
831         return NOTOK;
832     if (ferror (iop) && c != EOF) {
833         strncpy (response, "error on connection", sizeof(response));
834         return NOTOK;
835     }
836     if (c == EOF && p == s) {
837         strncpy (response, "connection closed by foreign host", sizeof(response));
838         return DONE;
839     }
840     *p = 0;
841     if (*--p == '\n')
842         *p = 0;
843     if (*--p == '\r')
844         *p = 0;
845
846     return OK;
847 }
848
849
850 static int
851 putline (char *s, FILE *iop)
852 {
853 #ifdef CYRUS_SASL
854     char outbuf[BUFSIZ], *buf;
855     int result;
856     unsigned int buflen;
857
858     if (!sasl_complete) {
859 #endif /* CYRUS_SASL */
860         fprintf (iop, "%s\r\n", s);
861 #ifdef CYRUS_SASL
862     } else {
863         /*
864          * Build an output buffer, encrypt it using sasl_encode, and
865          * squirt out the results.
866          */
867         strncpy(outbuf, s, sizeof(outbuf) - 3);
868         outbuf[sizeof(outbuf) - 3] = '\0';   /* Just in case */
869         strcat(outbuf, "\r\n");
870
871         result = sasl_encode(conn, outbuf, strlen(outbuf),
872                              (const char **) &buf, &buflen);
873
874         if (result != SASL_OK) {
875             snprintf(response, sizeof(response), "SASL encoding error: %s",
876                      sasl_errdetail(conn));
877             return NOTOK;
878         }
879
880         fwrite(buf, buflen, 1, iop);
881     }
882 #endif /* CYRUS_SASL */
883
884     fflush (iop);
885     if (ferror (iop)) {
886         strncpy (response, "lost connection", sizeof(response));
887         return NOTOK;
888     }
889
890     return OK;
891 }
892
893 #ifdef CYRUS_SASL
894 /*
895  * Okay, our little fgetc replacement.  Hopefully this is a little more
896  * efficient than the last one.
897  */
898 static int
899 sasl_fgetc(FILE *f)
900 {
901     static unsigned char *buffer = NULL, *ptr;
902     static unsigned int size = 0;
903     static int cnt = 0;
904     unsigned int retbufsize = 0;
905     int cc, result;
906     char *retbuf, tmpbuf[SASL_BUFFER_SIZE];
907
908     /*
909      * If we have some leftover data, return that
910      */
911
912     if (cnt) {
913         cnt--;
914         return (int) *ptr++;
915     }
916
917     /*
918      * Otherwise, fill our buffer until we have some data to return.
919      */
920
921     while (retbufsize == 0) {
922
923         cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
924
925         if (cc == 0)
926             return EOF;
927
928         if (cc < 0) {
929             snprintf(response, sizeof(response), "Error during read from "
930                      "network: %s", strerror(errno));
931             return -2;
932         }
933
934         /*
935          * We're not allowed to call sasl_decode until sasl_complete is
936          * true, so we do these gyrations ...
937          */
938         
939         if (!sasl_complete) {
940
941             retbuf = tmpbuf;
942             retbufsize = cc;
943
944         } else {
945
946             result = sasl_decode(conn, tmpbuf, cc,
947                                  (const char **) &retbuf, &retbufsize);
948
949             if (result != SASL_OK) {
950                 snprintf(response, sizeof(response), "Error during SASL "
951                          "decoding: %s", sasl_errdetail(conn));
952                 return -2;
953             }
954         }
955     }
956
957     if (retbufsize > size) {
958         buffer = mh_xrealloc(buffer, retbufsize);
959         size = retbufsize;
960     }
961
962     memcpy(buffer, retbuf, retbufsize);
963     ptr = buffer + 1;
964     cnt = retbufsize - 1;
965
966     return (int) buffer[0];
967 }
968 #endif /* CYRUS_SASL */