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