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