fail when kpop connection attempted without KPOP support compiled in
[mmh] / uip / popsbr.c
1 /*
2  * popsbr.c -- POP client subroutines
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
13 extern int  client(char *args, char *protocol, char *service, int rproto,
14                    char *response, int len_response);
15
16 #if defined(NNTP) && !defined(PSHSBR)
17 # undef NNTP
18 #endif
19
20 #ifdef NNTP                     /* building pshsbr.o from popsbr.c */
21 # include <h/nntp.h>
22 #endif /* NNTP */
23
24 #if !defined(NNTP) && defined(APOP)
25 # include <h/md5.h>
26 #endif
27
28 #ifdef CYRUS_SASL
29 # include <sasl/sasl.h>
30 # include <sasl/saslutil.h>
31 #endif /* CYRUS_SASL */
32
33 #include <h/popsbr.h>
34 #include <h/signals.h>
35 #include <signal.h>
36 #include <errno.h>
37
38 #define TRM     "."
39 #define TRMLEN  (sizeof TRM - 1)
40
41 static int poprint = 0;
42 static int pophack = 0;
43
44 char response[BUFSIZ];
45
46 static FILE *input;
47 static FILE *output;
48
49 #define targ_t char *
50
51 #if !defined(NNTP) && defined(MPOP)
52 # define command pop_command
53 # define multiline pop_multiline
54 #endif
55
56 #ifdef NNTP
57 # ifdef BPOP    /* stupid */
58 static int xtnd_last = -1;
59 static int xtnd_first = 0;
60 static char xtnd_name[512];     /* INCREDIBLE HACK!! */
61 # endif
62 #endif /* NNTP */
63
64 #ifdef CYRUS_SASL
65 static sasl_conn_t *conn;       /* SASL connection state */
66 static int sasl_complete = 0;   /* Has sasl authentication succeeded? */
67 static int maxoutbuf;           /* Maximum output buffer size */
68 static sasl_ssf_t sasl_ssf = 0; /* Security strength factor */
69 static int sasl_get_user(void *, int, const char **, unsigned *);
70 static int sasl_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
71 struct pass_context {
72     char *user;
73     char *host;
74 };
75
76 static sasl_callback_t callbacks[] = {
77     { SASL_CB_USER, sasl_get_user, NULL },
78 #define POP_SASL_CB_N_USER 0
79     { SASL_CB_PASS, sasl_get_pass, NULL },
80 #define POP_SASL_CB_N_PASS 1
81     { SASL_CB_LOG, NULL, NULL },
82     { SASL_CB_LIST_END, NULL, NULL },
83 };
84 #else /* CYRUS_SASL */
85 # define sasl_fgetc fgetc
86 #endif /* CYRUS_SASL */
87
88 /*
89  * static prototypes
90  */
91 #if !defined(NNTP) && defined(APOP)
92 static char *pop_auth (char *, char *);
93 #endif
94
95 #if defined(NNTP) || !defined(MPOP)
96 /* otherwise they are not static functions */
97 static int command(const char *, ...);
98 static int multiline(void);
99 #endif
100
101 #ifdef CYRUS_SASL
102 static int pop_auth_sasl(char *, char *, char *);
103 static int sasl_fgetc(FILE *);
104 #endif /* CYRUS_SASL */
105
106 static int traverse (int (*)(), const char *, ...);
107 static int vcommand(const char *, va_list);
108 static int getline (char *, int, FILE *);
109 static int putline (char *, FILE *);
110
111
112 #if !defined(NNTP) && defined(APOP)
113 static char *
114 pop_auth (char *user, char *pass)
115 {
116     int len, buflen;
117     char *cp, *lp;
118     unsigned char *dp, *ep, digest[16];
119     MD5_CTX mdContext;
120     static char buffer[BUFSIZ];
121
122     if ((cp = strchr (response, '<')) == NULL
123             || (lp = strchr (cp, '>')) == NULL) {
124         snprintf (buffer, sizeof(buffer), "APOP not available: %s", response);
125         strncpy (response, buffer, sizeof(response));
126         return NULL;
127     }
128
129     *(++lp) = '\0';
130     snprintf (buffer, sizeof(buffer), "%s%s", cp, pass);
131
132     MD5Init (&mdContext);
133     MD5Update (&mdContext, (unsigned char *) buffer,
134                (unsigned int) strlen (buffer));
135     MD5Final (digest, &mdContext);
136
137     cp = buffer;
138     buflen = sizeof(buffer);
139
140     snprintf (cp, buflen, "%s ", user);
141     len = strlen (cp);
142     cp += len;
143     buflen -= len;
144
145     for (ep = (dp = digest) + sizeof(digest) / sizeof(digest[0]); dp < ep; ) {
146         snprintf (cp, buflen, "%02x", *dp++ & 0xff);
147         cp += 2;
148         buflen -= 2;
149     }
150     *cp = '\0';
151
152     return buffer;
153 }
154 #endif  /* !NNTP && APOP */
155
156 #ifdef CYRUS_SASL
157 /*
158  * This function implements the AUTH command for various SASL mechanisms
159  *
160  * We do the whole SASL dialog here.  If this completes, then we've
161  * authenticated successfully and have (possibly) negotiated a security
162  * layer.
163  */
164
165 int
166 pop_auth_sasl(char *user, char *host, char *mech)
167 {
168     int result, status, sasl_capability = 0;
169     unsigned int buflen, outlen;
170     char server_mechs[256], *buf, outbuf[BUFSIZ];
171     const char *chosen_mech;
172     sasl_security_properties_t secprops;
173     struct pass_context p_context;
174     sasl_ssf_t *ssf;
175     int *moutbuf;
176
177     /*
178      * First off, we're going to send the CAPA command to see if we can
179      * even support the AUTH command, and if we do, then we'll get a
180      * list of mechanisms the server supports.  If we don't support
181      * the CAPA command, then it's unlikely that we will support
182      * SASL
183      */
184
185     if (command("CAPA") == NOTOK) {
186         snprintf(response, sizeof(response),
187                  "The POP CAPA command failed; POP server does not "
188                  "support SASL");
189         return NOTOK;
190     }
191
192     while ((status = multiline()) != DONE)
193         switch (status) {
194         case NOTOK:
195             return NOTOK;
196             break;
197         case DONE:      /* Shouldn't be possible, but just in case */
198             break;
199         case OK:
200             if (strncasecmp(response, "SASL ", 5) == 0) {
201                 /*
202                  * We've seen the SASL capability.  Grab the mech list
203                  */
204                 sasl_capability++;
205                 strncpy(server_mechs, response + 5, sizeof(server_mechs));
206             }
207             break;
208         }
209
210     if (!sasl_capability) {
211         snprintf(response, sizeof(response), "POP server does not support "
212                  "SASL");
213         return NOTOK;
214     }
215
216     /*
217      * If we received a preferred mechanism, see if the server supports it.
218      */
219
220     if (mech && stringdex(mech, server_mechs) == -1) {
221         snprintf(response, sizeof(response), "Requested SASL mech \"%s\" is "
222                  "not in list of supported mechanisms:\n%s",
223                  mech, server_mechs);
224         return NOTOK;
225     }
226
227     /*
228      * Start the SASL process.  First off, initialize the SASL library.
229      */
230
231     callbacks[POP_SASL_CB_N_USER].context = user;
232     p_context.user = user;
233     p_context.host = host;
234     callbacks[POP_SASL_CB_N_PASS].context = &p_context;
235
236     result = sasl_client_init(callbacks);
237
238     if (result != SASL_OK) {
239         snprintf(response, sizeof(response), "SASL library initialization "
240                  "failed: %s", sasl_errstring(result, NULL, NULL));
241         return NOTOK;
242     }
243
244     result = sasl_client_new("pop", host, NULL, NULL, NULL, 0, &conn);
245
246     if (result != SASL_OK) {
247         snprintf(response, sizeof(response), "SASL client initialization "
248                  "failed: %s", sasl_errstring(result, NULL, NULL));
249         return NOTOK;
250     }
251
252     /*
253      * Initialize the security properties
254      */
255
256     memset(&secprops, 0, sizeof(secprops));
257     secprops.maxbufsize = BUFSIZ;
258     secprops.max_ssf = UINT_MAX;
259
260     result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
261
262     if (result != SASL_OK) {
263         snprintf(response, sizeof(response), "SASL security property "
264                  "initialization failed: %s", sasl_errdetail(conn));
265         return NOTOK;
266     }
267
268     /*
269      * Start the actual protocol.  Feed the mech list into the library
270      * and get out a possible initial challenge
271      */
272
273     result = sasl_client_start(conn,
274                                (const char *) (mech ? mech : server_mechs),
275                                NULL, (const char **) &buf,
276                                &buflen, &chosen_mech);
277
278     if (result != SASL_OK && result != SASL_CONTINUE) {
279         snprintf(response, sizeof(response), "SASL client start failed: %s",
280                  sasl_errdetail(conn));
281         return NOTOK;
282     }
283
284     if (buflen) {
285         status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
286         if (status != SASL_OK) {
287             snprintf(response, sizeof(response), "SASL base64 encode "
288                      "failed: %s", sasl_errstring(status, NULL, NULL));
289             return NOTOK;
290         }
291
292         status = command("AUTH %s %s", chosen_mech, outbuf);
293     } else
294         status = command("AUTH %s", chosen_mech);
295
296     while (result == SASL_CONTINUE) {
297         if (status == NOTOK)
298             return NOTOK;
299         
300         /*
301          * If we get a "+OK" prefix to our response, then we should
302          * exit out of this exchange now (because authenticated should
303          * have succeeded)
304          */
305         
306         if (strncmp(response, "+OK", 3) == 0)
307             break;
308         
309         /*
310          * Otherwise, make sure the server challenge is correctly formatted
311          */
312         
313         if (strncmp(response, "+ ", 2) != 0) {
314             command("*");
315             snprintf(response, sizeof(response),
316                      "Malformed authentication message from server");
317             return NOTOK;
318         }
319
320         result = sasl_decode64(response + 2, strlen(response + 2),
321                                outbuf, sizeof(outbuf), &outlen);
322         
323         if (result != SASL_OK) {
324             command("*");
325             snprintf(response, sizeof(response), "SASL base64 decode "
326                      "failed: %s", sasl_errstring(result, NULL, NULL));
327             return NOTOK;
328         }
329
330         result = sasl_client_step(conn, outbuf, outlen, NULL,
331                                   (const char **) &buf, &buflen);
332
333         if (result != SASL_OK && result != SASL_CONTINUE) {
334             command("*");
335             snprintf(response, sizeof(response), "SASL client negotiaton "
336                      "failed: %s", sasl_errdetail(conn));
337             return NOTOK;
338         }
339
340         status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
341
342         if (status != SASL_OK) {
343             command("*");
344             snprintf(response, sizeof(response), "SASL base64 encode "
345                      "failed: %s", sasl_errstring(status, NULL, NULL));
346             return NOTOK;
347         }
348
349         status = command(outbuf);
350     }
351
352     /*
353      * If we didn't get a positive final response, then error out
354      * (that probably means we failed an authorization check).
355      */
356
357     if (status != OK)
358         return NOTOK;
359
360     /*
361      * We _should_ be okay now.  Get a few properties now that negotiation
362      * has completed.
363      */
364
365     result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &moutbuf);
366
367     if (result != SASL_OK) {
368         snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
369                  "output buffer size: %s", sasl_errdetail(conn));
370         return NOTOK;
371     }
372
373     maxoutbuf = *moutbuf;
374
375     result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
376
377     sasl_ssf = *ssf;
378
379     if (result != SASL_OK) {
380         snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
381                  "security strength factor: %s", sasl_errdetail(conn));
382         return NOTOK;
383     }
384
385     /*
386      * Limit this to what we can deal with.
387      */
388
389     if (maxoutbuf == 0 || maxoutbuf > BUFSIZ)
390         maxoutbuf = BUFSIZ;
391
392     sasl_complete = 1;
393
394     return status;
395 }
396
397 /*
398  * Callback to return the userid sent down via the user parameter
399  */
400
401 static int
402 sasl_get_user(void *context, int id, const char **result, unsigned *len)
403 {
404     char *user = (char *) context;
405
406     if (! result || id != SASL_CB_USER)
407         return SASL_BADPARAM;
408
409     *result = user;
410     if (len)
411         *len = strlen(user);
412
413     return SASL_OK;
414 }
415
416 /*
417  * Callback to return the password (we call ruserpass, which can get it
418  * out of the .netrc
419  */
420
421 static int
422 sasl_get_pass(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
423 {
424     struct pass_context *p_context = (struct pass_context *) context;
425     char *pass = NULL;
426     int len;
427
428     if (! psecret || id != SASL_CB_PASS)
429         return SASL_BADPARAM;
430
431     ruserpass(p_context->user, &(p_context->host), &pass);
432
433     len = strlen(pass);
434
435     *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
436
437     if (! *psecret)
438         return SASL_NOMEM;
439
440     (*psecret)->len = len;
441     strcpy((char *) (*psecret)->data, pass);
442
443     return SASL_OK;
444 }
445 #endif /* CYRUS_SASL */
446
447
448 /*
449  * Split string containing proxy command into an array of arguments
450  * suitable for passing to exec. Returned array must be freed. Shouldn't
451  * be possible to call this with host set to NULL.
452  */
453 char **
454 parse_proxy(char *proxy, char *host)
455 {
456     char **pargv, **p;
457     int pargc = 2;
458     int hlen = strlen(host);
459     int plen = 1;
460     char *cur, *pro;
461     char *c;
462     
463     /* skip any initial space */
464     for (pro = proxy; isspace(*pro); pro++)
465         continue;
466     
467     /* calculate required size for argument array */
468     for (cur = pro; *cur; cur++) {
469         if (isspace(*cur) && cur[1] && !isspace(cur[1]))
470             plen++, pargc++;
471         else if (*cur == '%' && cur[1] == 'h') {
472             plen += hlen;
473             cur++;
474         } else if (!isspace(*cur))
475             plen++;
476     }
477
478    /* put together list of arguments */
479     p = pargv = malloc(pargc * sizeof(char *));
480     c = *pargv = malloc(plen * sizeof(char));
481     for (cur = pro; *cur; cur++) {
482         if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
483             *c++ = '\0';
484             *++p = c;
485         } else if (*cur == '%' && cur[1] == 'h') {
486             strcpy (c, host);
487             c += hlen;
488             cur++;
489         } else if (!isspace(*cur))
490             *c++ = *cur;
491     }
492     *++p = NULL;
493     return pargv;
494 }
495
496 int
497 pop_init (char *host, char *user, char *pass, char *proxy, int snoop,
498           int rpop, int kpop, int sasl, char *mech)
499 {
500     int fd1, fd2;
501     char buffer[BUFSIZ];
502
503     if (proxy && *proxy) {
504        int pid;
505        int inpipe[2];     /* for reading from the server */
506        int outpipe[2];    /* for sending to the server */
507
508        /* first give up any root priviledges we may have for rpop */
509        setuid(getuid());
510
511        pipe(inpipe);
512        pipe(outpipe);
513
514        pid=fork();
515        if (pid==0) {
516            char **argv;
517            
518            /* in child */
519            close(0);  
520            close(1);
521            dup2(outpipe[0],0);  /* connect read end of connection */
522            dup2(inpipe[1], 1);  /* connect write end of connection */
523            if(inpipe[0]>1) close(inpipe[0]);
524            if(inpipe[1]>1) close(inpipe[1]);
525            if(outpipe[0]>1) close(outpipe[0]);
526            if(outpipe[1]>1) close(outpipe[1]);
527
528            /* run the proxy command */
529            argv=parse_proxy(proxy, host);
530            execvp(argv[0],argv);
531
532            perror(argv[0]);
533            close(0);
534            close(1);
535            free(*argv);
536            free(argv);
537            exit(10);
538        }
539
540        /* okay in the parent we do some stuff */
541        close(inpipe[1]);  /* child uses this */
542        close(outpipe[0]); /* child uses this */
543
544        /* we read on fd1 */
545        fd1=inpipe[0];
546
547        /* and write on fd2 */
548        fd2=outpipe[1];
549
550     } else {
551
552 #ifdef APOP
553         int apop;
554
555         if ((apop = rpop) < 0)
556             rpop = 0;
557 #endif
558
559 #ifndef NNTP
560         if ( kpop ) {
561 # ifdef KPOP
562             snprintf (buffer, sizeof(buffer), "%s/%s", KPOP_PRINCIPAL, "kpop");
563             if ((fd1 = client (host, "tcp", buffer, 0, response, sizeof(response))) == NOTOK) {
564                 return NOTOK;
565             }
566 # else  /* KPOP */
567             snprintf (response, sizeof(response), "this version of nmh compiled without KPOP support");
568             return NOTOK;
569 # endif /* KPOP */
570         } else {
571             if ((fd1 = client (host, "tcp", POPSERVICE, rpop, response, sizeof(response))) == NOTOK) {
572                 return NOTOK;
573             }
574         }
575 #else   /* NNTP */
576         if ((fd1 = client (host, "tcp", "nntp", rpop, response, sizeof(response))) == NOTOK)
577             return NOTOK;
578 #endif
579
580         if ((fd2 = dup (fd1)) == NOTOK) {
581             char *s;
582
583             if ((s = strerror(errno)))
584                 snprintf (response, sizeof(response),
585                     "unable to dup connection descriptor: %s", s);
586             else
587                 snprintf (response, sizeof(response),
588                     "unable to dup connection descriptor: unknown error");
589             close (fd1);
590             return NOTOK;
591         }
592     }
593 #ifndef NNTP
594     if (pop_set (fd1, fd2, snoop) == NOTOK)
595 #else   /* NNTP */
596     if (pop_set (fd1, fd2, snoop, (char *)0) == NOTOK)
597 #endif  /* NNTP */
598         return NOTOK;
599
600     SIGNAL (SIGPIPE, SIG_IGN);
601
602     switch (getline (response, sizeof response, input)) {
603         case OK: 
604             if (poprint)
605                 fprintf (stderr, "<--- %s\n", response);
606 #ifndef NNTP
607             if (*response == '+') {
608 # ifndef KPOP
609 #  ifdef APOP
610                 if (apop < 0) {
611                     char *cp = pop_auth (user, pass);
612
613                     if (cp && command ("APOP %s", cp) != NOTOK)
614                         return OK;
615                 }
616                 else
617 #  endif /* APOP */
618 #  ifdef CYRUS_SASL
619                 if (sasl) {
620                     if (pop_auth_sasl(user, host, mech) != NOTOK)
621                         return OK;
622                 } else
623 #  endif /* CYRUS_SASL */
624                 if (command ("USER %s", user) != NOTOK
625                     && command ("%s %s", rpop ? "RPOP" : (pophack++, "PASS"),
626                                         pass) != NOTOK)
627                 return OK;
628 # else /* KPOP */
629                 if (command ("USER %s", user) != NOTOK
630                     && command ("PASS %s", pass) != NOTOK)
631                 return OK;
632 # endif
633             }
634 #else /* NNTP */
635             if (*response < CHAR_ERR) {
636                 command ("MODE READER");
637                 return OK;
638             }
639 #endif
640             strncpy (buffer, response, sizeof(buffer));
641             command ("QUIT");
642             strncpy (response, buffer, sizeof(response));
643                                 /* and fall */
644
645         case NOTOK: 
646         case DONE: 
647             if (poprint)            
648                 fprintf (stderr, "%s\n", response);
649             fclose (input);
650             fclose (output);
651             return NOTOK;
652     }
653
654     return NOTOK;       /* NOTREACHED */
655 }
656
657 #ifdef NNTP
658 int
659 pop_set (int in, int out, int snoop, char *myname)
660 #else
661 int
662 pop_set (int in, int out, int snoop)
663 #endif
664 {
665
666 #ifdef NNTP
667     if (myname && *myname) {
668         /* interface from bbc to msh */
669         strncpy (xtnd_name, myname, sizeof(xtnd_name));
670     }
671 #endif  /* NNTP */
672
673     if ((input = fdopen (in, "r")) == NULL
674             || (output = fdopen (out, "w")) == NULL) {
675         strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
676         if (input)
677             fclose (input);
678         else
679             close (in);
680         close (out);
681         return NOTOK;
682     }
683
684     poprint = snoop;
685
686     return OK;
687 }
688
689
690 int
691 pop_fd (char *in, int inlen, char *out, int outlen)
692 {
693     snprintf (in, inlen, "%d", fileno (input));
694     snprintf (out, outlen, "%d", fileno (output));
695     return OK;
696 }
697
698
699 /*
700  * Find out number of messages available
701  * and their total size.
702  */
703
704 int
705 pop_stat (int *nmsgs, int *nbytes)
706 {
707 #ifdef NNTP
708     char **ap;
709 #endif /* NNTP */
710
711 #ifndef NNTP
712     if (command ("STAT") == NOTOK)
713         return NOTOK;
714
715     *nmsgs = *nbytes = 0;
716     sscanf (response, "+OK %d %d", nmsgs, nbytes);
717
718 #else /* NNTP */
719     if (xtnd_last < 0) {        /* in msh, xtnd_name is set from myname */
720         if (command("GROUP %s", xtnd_name) == NOTOK)
721             return NOTOK;
722
723         ap = brkstring (response, " ", "\n"); /* "211 nart first last ggg" */
724         xtnd_first = atoi (ap[2]);
725         xtnd_last  = atoi (ap[3]);
726     }
727
728     /* nmsgs is not the real nart, but an incredible simuation */
729     if (xtnd_last > 0)
730         *nmsgs = xtnd_last - xtnd_first + 1;    /* because of holes... */
731     else
732         *nmsgs = 0;
733     *nbytes = xtnd_first;       /* for subtracting offset in msh() */
734 #endif /* NNTP */
735
736     return OK;
737 }
738
739 #ifdef NNTP
740 int
741 pop_exists (int (*action)())
742 {
743 #ifdef XMSGS            /* hacked into NNTP 1.5 */
744     if (traverse (action, "XMSGS %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last) == OK)
745         return OK;
746 #endif
747     /* provided by INN 1.4 */
748     if (traverse (action, "LISTGROUP") == OK)
749         return OK;
750     return traverse (action, "XHDR NONAME %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last);
751 }
752 #endif  /* NNTP */
753
754
755 #ifdef BPOP
756 int
757 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes, int *ids)
758 #else
759 int
760 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
761 #endif
762 {
763     int i;
764 #ifndef BPOP
765     int *ids = NULL;
766 #endif
767
768     if (msgno) {
769 #ifndef NNTP
770         if (command ("LIST %d", msgno) == NOTOK)
771             return NOTOK;
772         *msgs = *bytes = 0;
773         if (ids) {
774             *ids = 0;
775             sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
776         }
777         else
778             sscanf (response, "+OK %d %d", msgs, bytes);
779 #else /* NNTP */
780         *msgs = *bytes = 0;
781         if (command ("STAT %d", msgno) == NOTOK) 
782             return NOTOK;
783         if (ids) {
784             *ids = msgno;
785         }
786 #endif /* NNTP */
787         return OK;
788     }
789
790 #ifndef NNTP
791     if (command ("LIST") == NOTOK)
792         return NOTOK;
793
794     for (i = 0; i < *nmsgs; i++)
795         switch (multiline ()) {
796             case NOTOK: 
797                 return NOTOK;
798             case DONE: 
799                 *nmsgs = ++i;
800                 return OK;
801             case OK: 
802                 *msgs = *bytes = 0;
803                 if (ids) {
804                     *ids = 0;
805                     sscanf (response, "%d %d %d",
806                             msgs++, bytes++, ids++);
807                 }
808                 else
809                     sscanf (response, "%d %d", msgs++, bytes++);
810                 break;
811         }
812     for (;;)
813         switch (multiline ()) {
814             case NOTOK: 
815                 return NOTOK;
816             case DONE: 
817                 return OK;
818             case OK: 
819                 break;
820         }
821 #else /* NNTP */
822     return NOTOK;
823 #endif /* NNTP */
824 }
825
826
827 int
828 pop_retr (int msgno, int (*action)())
829 {
830 #ifndef NNTP
831     return traverse (action, "RETR %d", (targ_t) msgno);
832 #else /* NNTP */
833     return traverse (action, "ARTICLE %d", (targ_t) msgno);
834 #endif /* NNTP */
835 }
836
837
838 static int
839 traverse (int (*action)(), const char *fmt, ...)
840 {
841     int result;
842     va_list ap;
843     char buffer[sizeof(response)];
844
845     va_start(ap, fmt);
846     result = vcommand (fmt, ap);
847     va_end(ap);
848
849     if (result == NOTOK)
850         return NOTOK;
851     strncpy (buffer, response, sizeof(buffer));
852
853     for (;;)
854         switch (multiline ()) {
855             case NOTOK: 
856                 return NOTOK;
857
858             case DONE: 
859                 strncpy (response, buffer, sizeof(response));
860                 return OK;
861
862             case OK: 
863                 (*action) (response);
864                 break;
865         }
866 }
867
868
869 int
870 pop_dele (int msgno)
871 {
872     return command ("DELE %d", msgno);
873 }
874
875
876 int
877 pop_noop (void)
878 {
879     return command ("NOOP");
880 }
881
882
883 #if defined(MPOP) && !defined(NNTP)
884 int
885 pop_last (void)
886 {
887     return command ("LAST");
888 }
889 #endif
890
891
892 int
893 pop_rset (void)
894 {
895     return command ("RSET");
896 }
897
898
899 int
900 pop_top (int msgno, int lines, int (*action)())
901 {
902 #ifndef NNTP
903     return traverse (action, "TOP %d %d", (targ_t) msgno, (targ_t) lines);
904 #else   /* NNTP */
905     return traverse (action, "HEAD %d", (targ_t) msgno);
906 #endif /* NNTP */
907 }
908
909
910 #ifdef BPOP
911 int
912 pop_xtnd (int (*action)(), char *fmt, ...)
913 {
914     int result;
915     va_list ap;
916     char buffer[BUFSIZ];
917
918 #ifdef NNTP
919     char **ap;
920 #endif
921
922     va_start(ap, fmt);
923 #ifndef NNTP
924     /* needs to be fixed... va_end needs to be added */
925     snprintf (buffer, sizeof(buffer), "XTND %s", fmt);
926     result = traverse (action, buffer, a, b, c, d);
927     va_end(ap);
928     return result;
929 #else /* NNTP */
930     snprintf (buffer, sizeof(buffer), fmt, a, b, c, d);
931     ap = brkstring (buffer, " ", "\n"); /* a hack, i know... */
932
933     if (!strcasecmp(ap[0], "x-bboards")) {      /* XTND "X-BBOARDS group */
934         /* most of these parameters are meaningless under NNTP. 
935          * bbc.c was modified to set AKA and LEADERS as appropriate,
936          * the rest are left blank.
937          */
938         return OK;
939     }
940     if (!strcasecmp (ap[0], "archive") && ap[1]) {
941         snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]);   /* save the name */
942         xtnd_last = 0;
943         xtnd_first = 1;         /* setup to fail in pop_stat */
944         return OK;
945     }
946     if (!strcasecmp (ap[0], "bboards")) {
947
948         if (ap[1]) {                    /* XTND "BBOARDS group" */
949             snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]);       /* save the name */
950             if (command("GROUP %s", xtnd_name) == NOTOK)
951                 return NOTOK;
952
953             /* action must ignore extra args */
954             strncpy (buffer, response, sizeof(buffer));
955             ap = brkstring (response, " ", "\n");/* "211 nart first last g" */
956             xtnd_first = atoi (ap[2]);
957             xtnd_last  = atoi (ap[3]);
958
959             (*action) (buffer);         
960             return OK;
961
962         } else {                /* XTND "BBOARDS" */
963             return traverse (action, "LIST", a, b, c, d);
964         }
965     }
966     return NOTOK;       /* unknown XTND command */
967 #endif /* NNTP */
968 }
969 #endif /* BPOP */
970
971
972 int
973 pop_quit (void)
974 {
975     int i;
976
977     i = command ("QUIT");
978     pop_done ();
979
980     return i;
981 }
982
983
984 int
985 pop_done (void)
986 {
987 #ifdef CYRUS_SASL
988     if (conn)
989         sasl_dispose(&conn);
990 #endif /* CYRUS_SASL */
991     fclose (input);
992     fclose (output);
993
994     return OK;
995 }
996
997
998 #if !defined(MPOP) || defined(NNTP)
999 static
1000 #endif
1001 int
1002 command(const char *fmt, ...)
1003 {
1004     va_list ap;
1005     int result;
1006
1007     va_start(ap, fmt);
1008     result = vcommand(fmt, ap);
1009     va_end(ap);
1010
1011     return result;
1012 }
1013
1014
1015 static int
1016 vcommand (const char *fmt, va_list ap)
1017 {
1018     char *cp, buffer[BUFSIZ];
1019
1020     vsnprintf (buffer, sizeof(buffer), fmt, ap);
1021     if (poprint) {
1022 #ifdef CYRUS_SASL
1023         if (sasl_ssf)
1024             fprintf(stderr, "(encrypted) ");
1025 #endif /* CYRUS_SASL */
1026         if (pophack) {
1027             if ((cp = strchr (buffer, ' ')))
1028                 *cp = 0;
1029             fprintf (stderr, "---> %s ********\n", buffer);
1030             if (cp)
1031                 *cp = ' ';
1032             pophack = 0;
1033         }
1034         else
1035             fprintf (stderr, "---> %s\n", buffer);
1036     }
1037
1038     if (putline (buffer, output) == NOTOK)
1039         return NOTOK;
1040
1041 #ifdef CYRUS_SASL
1042     if (poprint && sasl_ssf)
1043         fprintf(stderr, "(decrypted) ");
1044 #endif /* CYRUS_SASL */
1045
1046     switch (getline (response, sizeof response, input)) {
1047         case OK: 
1048             if (poprint)
1049                 fprintf (stderr, "<--- %s\n", response);
1050 #ifndef NNTP
1051             return (*response == '+' ? OK : NOTOK);
1052 #else   /* NNTP */
1053             return (*response < CHAR_ERR ? OK : NOTOK);
1054 #endif  /* NNTP */
1055
1056         case NOTOK: 
1057         case DONE: 
1058             if (poprint)            
1059                 fprintf (stderr, "%s\n", response);
1060             return NOTOK;
1061     }
1062
1063     return NOTOK;       /* NOTREACHED */
1064 }
1065
1066
1067 #if defined(MPOP) && !defined(NNTP)
1068 int
1069 multiline (void)
1070 #else
1071 static int
1072 multiline (void)
1073 #endif
1074 {
1075     char buffer[BUFSIZ + TRMLEN];
1076
1077     if (getline (buffer, sizeof buffer, input) != OK)
1078         return NOTOK;
1079 #ifdef DEBUG
1080     if (poprint) {
1081 #ifdef CYRUS_SASL
1082         if (sasl_ssf)
1083             fprintf(stderr, "(decrypted) ");
1084 #endif /* CYRUS_SASL */
1085         fprintf (stderr, "<--- %s\n", response);
1086     }
1087 #endif /* DEBUG */
1088     if (strncmp (buffer, TRM, TRMLEN) == 0) {
1089         if (buffer[TRMLEN] == 0)
1090             return DONE;
1091         else
1092             strncpy (response, buffer + TRMLEN, sizeof(response));
1093     }
1094     else
1095         strncpy (response, buffer, sizeof(response));
1096
1097     return OK;
1098 }
1099
1100 /*
1101  * Note that these functions have been modified to deal with layer encryption
1102  * in the SASL case
1103  */
1104
1105 static int
1106 getline (char *s, int n, FILE *iop)
1107 {
1108     int c;
1109     char *p;
1110
1111     p = s;
1112     while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2) 
1113         if ((*p++ = c) == '\n')
1114             break;
1115     if (c == -2)
1116         return NOTOK;
1117     if (ferror (iop) && c != EOF) {
1118         strncpy (response, "error on connection", sizeof(response));
1119         return NOTOK;
1120     }
1121     if (c == EOF && p == s) {
1122         strncpy (response, "connection closed by foreign host", sizeof(response));
1123         return DONE;
1124     }
1125     *p = 0;
1126     if (*--p == '\n')
1127         *p = 0;
1128     if (*--p == '\r')
1129         *p = 0;
1130
1131     return OK;
1132 }
1133
1134
1135 static int
1136 putline (char *s, FILE *iop)
1137 {
1138 #ifdef CYRUS_SASL
1139     char outbuf[BUFSIZ], *buf;
1140     int result;
1141     unsigned int buflen;
1142
1143     if (!sasl_complete) {
1144 #endif /* CYRUS_SASL */
1145         fprintf (iop, "%s\r\n", s);
1146 #ifdef CYRUS_SASL
1147     } else {
1148         /*
1149          * Build an output buffer, encrypt it using sasl_encode, and
1150          * squirt out the results.
1151          */
1152         strncpy(outbuf, s, sizeof(outbuf) - 3);
1153         outbuf[sizeof(outbuf) - 3] = '\0';   /* Just in case */
1154         strcat(outbuf, "\r\n");
1155
1156         result = sasl_encode(conn, outbuf, strlen(outbuf),
1157                              (const char **) &buf, &buflen);
1158
1159         if (result != SASL_OK) {
1160             snprintf(response, sizeof(response), "SASL encoding error: %s",
1161                      sasl_errdetail(conn));
1162             return NOTOK;
1163         }
1164
1165         fwrite(buf, buflen, 1, iop);
1166     }
1167 #endif /* CYRUS_SASL */
1168
1169     fflush (iop);
1170     if (ferror (iop)) {
1171         strncpy (response, "lost connection", sizeof(response));
1172         return NOTOK;
1173     }
1174
1175     return OK;
1176 }
1177
1178 #ifdef CYRUS_SASL
1179 /*
1180  * Okay, our little fgetc replacement.  Hopefully this is a little more
1181  * efficient than the last one.
1182  */
1183 static int
1184 sasl_fgetc(FILE *f)
1185 {
1186     static unsigned char *buffer = NULL, *ptr;
1187     static int size = 0;
1188     static int cnt = 0;
1189     unsigned int retbufsize = 0;
1190     int cc, result;
1191     char *retbuf, tmpbuf[BUFSIZ];
1192
1193     /*
1194      * If we have some leftover data, return that
1195      */
1196
1197     if (cnt) {
1198         cnt--;
1199         return (int) *ptr++;
1200     }
1201
1202     /*
1203      * Otherwise, fill our buffer until we have some data to return.
1204      */
1205
1206     while (retbufsize == 0) {
1207
1208         cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1209
1210         if (cc == 0)
1211             return EOF;
1212
1213         if (cc < 0) {
1214             snprintf(response, sizeof(response), "Error during read from "
1215                      "network: %s", strerror(errno));
1216             return -2;
1217         }
1218
1219         /*
1220          * We're not allowed to call sasl_decode until sasl_complete is
1221          * true, so we do these gyrations ...
1222          */
1223         
1224         if (!sasl_complete) {
1225
1226             retbuf = tmpbuf;
1227             retbufsize = cc;
1228
1229         } else {
1230
1231             result = sasl_decode(conn, tmpbuf, cc,
1232                                  (const char **) &retbuf, &retbufsize);
1233
1234             if (result != SASL_OK) {
1235                 snprintf(response, sizeof(response), "Error during SASL "
1236                          "decoding: %s", sasl_errdetail(conn));
1237                 return -2;
1238             }
1239         }
1240     }
1241
1242     if (retbufsize > size) {
1243         buffer = realloc(buffer, retbufsize);
1244         if (!buffer) {
1245             snprintf(response, sizeof(response), "Error during realloc in "
1246                      "read routine: %s", strerror(errno));
1247             return -2;
1248         }
1249         size = retbufsize;
1250     }
1251
1252     memcpy(buffer, retbuf, retbufsize);
1253     ptr = buffer + 1;
1254     cnt = retbufsize - 1;
1255
1256     return (int) buffer[0];
1257 }
1258 #endif /* CYRUS_SASL */