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