2d03efdc1a4bda5106354fc04251d863dcee66d6
[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     if (! psecret || id != SASL_CB_PASS)
351         return SASL_BADPARAM;
352
353     ruserpass(p_context->user, &(p_context->host), &pass);
354
355     len = strlen(pass);
356
357     *psecret = (sasl_secret_t *) mh_xmalloc(sizeof(sasl_secret_t) + len);
358
359     (*psecret)->len = len;
360     strcpy((char *) (*psecret)->data, pass);
361
362     return SASL_OK;
363 }
364 #endif /* CYRUS_SASL */
365
366
367 /*
368  * Split string containing proxy command into an array of arguments
369  * suitable for passing to exec. Returned array must be freed. Shouldn't
370  * be possible to call this with host set to NULL.
371  */
372 char **
373 parse_proxy(char *proxy, char *host)
374 {
375     char **pargv, **p;
376     int pargc = 2;
377     int hlen = strlen(host);
378     int plen = 1;
379     unsigned char *cur, *pro;
380     char *c;
381     
382     /* skip any initial space */
383     for (pro = (unsigned char *) proxy; isspace(*pro); pro++)
384         continue;
385     
386     /* calculate required size for argument array */
387     for (cur = pro; *cur; cur++) {
388         if (isspace(*cur) && cur[1] && !isspace(cur[1]))
389             plen++, pargc++;
390         else if (*cur == '%' && cur[1] == 'h') {
391             plen += hlen;
392             cur++;
393         } else if (!isspace(*cur))
394             plen++;
395     }
396
397    /* put together list of arguments */
398     p = pargv = mh_xmalloc(pargc * sizeof(char *));
399     c = *pargv = mh_xmalloc(plen * sizeof(char));
400     for (cur = pro; *cur; cur++) {
401         if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
402             *c++ = '\0';
403             *++p = c;
404         } else if (*cur == '%' && cur[1] == 'h') {
405             strcpy (c, host);
406             c += hlen;
407             cur++;
408         } else if (!isspace(*cur))
409             *c++ = *cur;
410     }
411     *++p = NULL;
412     return pargv;
413 }
414
415 int
416 pop_init (char *host, char *port, char *user, char *pass, char *proxy,
417           int snoop, int sasl, char *mech)
418 {
419     int fd1, fd2;
420     char buffer[BUFSIZ];
421
422     if (proxy && *proxy) {
423        int pid;
424        int inpipe[2];     /* for reading from the server */
425        int outpipe[2];    /* for sending to the server */
426
427        /* first give up any root priviledges we may have for rpop */
428        setuid(getuid());
429
430        pipe(inpipe);
431        pipe(outpipe);
432
433        pid=fork();
434        if (pid==0) {
435            char **argv;
436            
437            /* in child */
438            close(0);  
439            close(1);
440            dup2(outpipe[0],0);  /* connect read end of connection */
441            dup2(inpipe[1], 1);  /* connect write end of connection */
442            if(inpipe[0]>1) close(inpipe[0]);
443            if(inpipe[1]>1) close(inpipe[1]);
444            if(outpipe[0]>1) close(outpipe[0]);
445            if(outpipe[1]>1) close(outpipe[1]);
446
447            /* run the proxy command */
448            argv=parse_proxy(proxy, host);
449            execvp(argv[0],argv);
450
451            perror(argv[0]);
452            close(0);
453            close(1);
454            free(*argv);
455            free(argv);
456            exit(10);
457        }
458
459        /* okay in the parent we do some stuff */
460        close(inpipe[1]);  /* child uses this */
461        close(outpipe[0]); /* child uses this */
462
463        /* we read on fd1 */
464        fd1=inpipe[0];
465        /* and write on fd2 */
466        fd2=outpipe[1];
467
468     } else {
469
470         if ((fd1 = client (host, port ? port : "pop3", response,
471                            sizeof(response), snoop)) == NOTOK) {
472             return NOTOK;
473         }
474
475         if ((fd2 = dup (fd1)) == NOTOK) {
476             char *s;
477
478             if ((s = strerror(errno)))
479                 snprintf (response, sizeof(response),
480                     "unable to dup connection descriptor: %s", s);
481             else
482                 snprintf (response, sizeof(response),
483                     "unable to dup connection descriptor: unknown error");
484             close (fd1);
485             return NOTOK;
486         }
487     }
488     if (pop_set (fd1, fd2, snoop) == NOTOK)
489         return NOTOK;
490
491     SIGNAL (SIGPIPE, SIG_IGN);
492
493     switch (sasl_getline (response, sizeof response, input)) {
494         case OK: 
495             if (poprint)
496                 fprintf (stderr, "<--- %s\n", response);
497             if (*response == '+') {
498 #  ifdef CYRUS_SASL
499                 if (sasl) {
500                     if (pop_auth_sasl(user, host, mech) != NOTOK)
501                         return OK;
502                 } else
503 #  endif /* CYRUS_SASL */
504                 if (command ("USER %s", user) != NOTOK
505                     && command ("%s %s", (pophack++, "PASS"),
506                                         pass) != NOTOK)
507                 return OK;
508             }
509             strncpy (buffer, response, sizeof(buffer));
510             command ("QUIT");
511             strncpy (response, buffer, sizeof(response));
512                                 /* and fall */
513
514         case NOTOK: 
515         case DONE: 
516             if (poprint)            
517                 fprintf (stderr, "%s\n", response);
518             fclose (input);
519             fclose (output);
520             return NOTOK;
521     }
522
523     return NOTOK;       /* NOTREACHED */
524 }
525
526 int
527 pop_set (int in, int out, int snoop)
528 {
529
530     if ((input = fdopen (in, "r")) == NULL
531             || (output = fdopen (out, "w")) == NULL) {
532         strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
533         if (input)
534             fclose (input);
535         else
536             close (in);
537         close (out);
538         return NOTOK;
539     }
540
541     poprint = snoop;
542
543     return OK;
544 }
545
546
547 int
548 pop_fd (char *in, int inlen, char *out, int outlen)
549 {
550     snprintf (in, inlen, "%d", fileno (input));
551     snprintf (out, outlen, "%d", fileno (output));
552     return OK;
553 }
554
555
556 /*
557  * Find out number of messages available
558  * and their total size.
559  */
560
561 int
562 pop_stat (int *nmsgs, int *nbytes)
563 {
564
565     if (command ("STAT") == NOTOK)
566         return NOTOK;
567
568     *nmsgs = *nbytes = 0;
569     sscanf (response, "+OK %d %d", nmsgs, nbytes);
570
571     return OK;
572 }
573
574
575 int
576 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
577 {
578     int i;
579     int *ids = NULL;
580
581     if (msgno) {
582         if (command ("LIST %d", msgno) == NOTOK)
583             return NOTOK;
584         *msgs = *bytes = 0;
585         if (ids) {
586             *ids = 0;
587             sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
588         }
589         else
590             sscanf (response, "+OK %d %d", msgs, bytes);
591         return OK;
592     }
593
594     if (command ("LIST") == NOTOK)
595         return NOTOK;
596
597     for (i = 0; i < *nmsgs; i++)
598         switch (multiline ()) {
599             case NOTOK: 
600                 return NOTOK;
601             case DONE: 
602                 *nmsgs = ++i;
603                 return OK;
604             case OK: 
605                 *msgs = *bytes = 0;
606                 if (ids) {
607                     *ids = 0;
608                     sscanf (response, "%d %d %d",
609                             msgs++, bytes++, ids++);
610                 }
611                 else
612                     sscanf (response, "%d %d", msgs++, bytes++);
613                 break;
614         }
615     for (;;)
616         switch (multiline ()) {
617             case NOTOK: 
618                 return NOTOK;
619             case DONE: 
620                 return OK;
621             case OK: 
622                 break;
623         }
624 }
625
626
627 int
628 pop_retr (int msgno, int (*action)(char *))
629 {
630     return traverse (action, "RETR %d", msgno);
631 }
632
633
634 static int
635 traverse (int (*action)(char *), const char *fmt, ...)
636 {
637     int result;
638     va_list ap;
639     char buffer[sizeof(response)];
640
641     va_start(ap, fmt);
642     result = vcommand (fmt, ap);
643     va_end(ap);
644
645     if (result == NOTOK)
646         return NOTOK;
647     strncpy (buffer, response, sizeof(buffer));
648
649     for (;;)
650         switch (multiline ()) {
651             case NOTOK: 
652                 return NOTOK;
653
654             case DONE: 
655                 strncpy (response, buffer, sizeof(response));
656                 return OK;
657
658             case OK: 
659                 (*action) (response);
660                 break;
661         }
662 }
663
664
665 int
666 pop_dele (int msgno)
667 {
668     return command ("DELE %d", msgno);
669 }
670
671
672 int
673 pop_noop (void)
674 {
675     return command ("NOOP");
676 }
677
678
679 int
680 pop_rset (void)
681 {
682     return command ("RSET");
683 }
684
685
686 int
687 pop_top (int msgno, int lines, int (*action)(char *))
688 {
689     return traverse (action, "TOP %d %d", msgno, lines);
690 }
691
692
693 int
694 pop_quit (void)
695 {
696     int i;
697
698     i = command ("QUIT");
699     pop_done ();
700
701     return i;
702 }
703
704
705 int
706 pop_done (void)
707 {
708 #ifdef CYRUS_SASL
709     if (conn)
710         sasl_dispose(&conn);
711 #endif /* CYRUS_SASL */
712     fclose (input);
713     fclose (output);
714
715     return OK;
716 }
717
718
719 int
720 command(const char *fmt, ...)
721 {
722     va_list ap;
723     int result;
724
725     va_start(ap, fmt);
726     result = vcommand(fmt, ap);
727     va_end(ap);
728
729     return result;
730 }
731
732
733 static int
734 vcommand (const char *fmt, va_list ap)
735 {
736     char *cp, buffer[BUFSIZ];
737
738     vsnprintf (buffer, sizeof(buffer), fmt, ap);
739     if (poprint) {
740 #ifdef CYRUS_SASL
741         if (sasl_ssf)
742             fprintf(stderr, "(encrypted) ");
743 #endif /* CYRUS_SASL */
744         if (pophack) {
745             if ((cp = strchr (buffer, ' ')))
746                 *cp = 0;
747             fprintf (stderr, "---> %s ********\n", buffer);
748             if (cp)
749                 *cp = ' ';
750             pophack = 0;
751         }
752         else
753             fprintf (stderr, "---> %s\n", buffer);
754     }
755
756     if (putline (buffer, output) == NOTOK)
757         return NOTOK;
758
759 #ifdef CYRUS_SASL
760     if (poprint && sasl_ssf)
761         fprintf(stderr, "(decrypted) ");
762 #endif /* CYRUS_SASL */
763
764     switch (sasl_getline (response, sizeof response, input)) {
765         case OK: 
766             if (poprint)
767                 fprintf (stderr, "<--- %s\n", response);
768             return (*response == '+' ? OK : NOTOK);
769
770         case NOTOK: 
771         case DONE: 
772             if (poprint)            
773                 fprintf (stderr, "%s\n", response);
774             return NOTOK;
775     }
776
777     return NOTOK;       /* NOTREACHED */
778 }
779
780
781 int
782 multiline (void)
783 {
784     char buffer[BUFSIZ + TRMLEN];
785
786     if (sasl_getline (buffer, sizeof buffer, input) != OK)
787         return NOTOK;
788 #ifdef DEBUG
789     if (poprint) {
790 #ifdef CYRUS_SASL
791         if (sasl_ssf)
792             fprintf(stderr, "(decrypted) ");
793 #endif /* CYRUS_SASL */
794         fprintf (stderr, "<--- %s\n", response);
795     }
796 #endif /* DEBUG */
797     if (strncmp (buffer, TRM, TRMLEN) == 0) {
798         if (buffer[TRMLEN] == 0)
799             return DONE;
800         else
801             strncpy (response, buffer + TRMLEN, sizeof(response));
802     }
803     else
804         strncpy (response, buffer, sizeof(response));
805
806     return OK;
807 }
808
809 /*
810  * Note that these functions have been modified to deal with layer encryption
811  * in the SASL case
812  */
813
814 static int
815 sasl_getline (char *s, int n, FILE *iop)
816 {
817     int c = -2;
818     char *p;
819
820     p = s;
821     while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2) 
822         if ((*p++ = c) == '\n')
823             break;
824     if (c == -2)
825         return NOTOK;
826     if (ferror (iop) && c != EOF) {
827         strncpy (response, "error on connection", sizeof(response));
828         return NOTOK;
829     }
830     if (c == EOF && p == s) {
831         strncpy (response, "connection closed by foreign host", sizeof(response));
832         return DONE;
833     }
834     *p = 0;
835     if (*--p == '\n')
836         *p = 0;
837     if (*--p == '\r')
838         *p = 0;
839
840     return OK;
841 }
842
843
844 static int
845 putline (char *s, FILE *iop)
846 {
847 #ifdef CYRUS_SASL
848     char outbuf[BUFSIZ], *buf;
849     int result;
850     unsigned int buflen;
851
852     if (!sasl_complete) {
853 #endif /* CYRUS_SASL */
854         fprintf (iop, "%s\r\n", s);
855 #ifdef CYRUS_SASL
856     } else {
857         /*
858          * Build an output buffer, encrypt it using sasl_encode, and
859          * squirt out the results.
860          */
861         strncpy(outbuf, s, sizeof(outbuf) - 3);
862         outbuf[sizeof(outbuf) - 3] = '\0';   /* Just in case */
863         strcat(outbuf, "\r\n");
864
865         result = sasl_encode(conn, outbuf, strlen(outbuf),
866                              (const char **) &buf, &buflen);
867
868         if (result != SASL_OK) {
869             snprintf(response, sizeof(response), "SASL encoding error: %s",
870                      sasl_errdetail(conn));
871             return NOTOK;
872         }
873
874         fwrite(buf, buflen, 1, iop);
875     }
876 #endif /* CYRUS_SASL */
877
878     fflush (iop);
879     if (ferror (iop)) {
880         strncpy (response, "lost connection", sizeof(response));
881         return NOTOK;
882     }
883
884     return OK;
885 }
886
887 #ifdef CYRUS_SASL
888 /*
889  * Okay, our little fgetc replacement.  Hopefully this is a little more
890  * efficient than the last one.
891  */
892 static int
893 sasl_fgetc(FILE *f)
894 {
895     static unsigned char *buffer = NULL, *ptr;
896     static int size = 0;
897     static int cnt = 0;
898     unsigned int retbufsize = 0;
899     int cc, result;
900     char *retbuf, tmpbuf[SASL_BUFFER_SIZE];
901
902     /*
903      * If we have some leftover data, return that
904      */
905
906     if (cnt) {
907         cnt--;
908         return (int) *ptr++;
909     }
910
911     /*
912      * Otherwise, fill our buffer until we have some data to return.
913      */
914
915     while (retbufsize == 0) {
916
917         cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
918
919         if (cc == 0)
920             return EOF;
921
922         if (cc < 0) {
923             snprintf(response, sizeof(response), "Error during read from "
924                      "network: %s", strerror(errno));
925             return -2;
926         }
927
928         /*
929          * We're not allowed to call sasl_decode until sasl_complete is
930          * true, so we do these gyrations ...
931          */
932         
933         if (!sasl_complete) {
934
935             retbuf = tmpbuf;
936             retbufsize = cc;
937
938         } else {
939
940             result = sasl_decode(conn, tmpbuf, cc,
941                                  (const char **) &retbuf, &retbufsize);
942
943             if (result != SASL_OK) {
944                 snprintf(response, sizeof(response), "Error during SASL "
945                          "decoding: %s", sasl_errdetail(conn));
946                 return -2;
947             }
948         }
949     }
950
951     if (retbufsize > size) {
952         buffer = mh_xrealloc(buffer, retbufsize);
953         size = retbufsize;
954     }
955
956     memcpy(buffer, retbuf, retbufsize);
957     ptr = buffer + 1;
958     cnt = retbufsize - 1;
959
960     return (int) buffer[0];
961 }
962 #endif /* CYRUS_SASL */