2 * popsbr.c -- POP client subroutines
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.
13 extern int client(char *args, char *protocol, char *service, int rproto,
14 char *response, int len_response);
16 #if defined(NNTP) && !defined(PSHSBR)
20 #ifdef NNTP /* building pshsbr.o from popsbr.c */
24 #if !defined(NNTP) && defined(APOP)
30 # include <saslutil.h>
31 #endif /* CYRUS_SASL */
34 #include <h/signals.h>
39 #define TRMLEN (sizeof TRM - 1)
41 static int poprint = 0;
42 static int pophack = 0;
44 char response[BUFSIZ];
51 #if !defined(NNTP) && defined(MPOP)
52 # define command pop_command
53 # define multiline pop_multiline
57 # ifdef BPOP /* stupid */
58 static int xtnd_last = -1;
59 static int xtnd_first = 0;
60 static char xtnd_name[512]; /* INCREDIBLE HACK!! */
65 static sasl_conn_t *conn; /* SASL connection state */
66 static int sasl_complete = 0; /* Has sasl authentication succeeded? */
67 static int maxoutbuf; /* Maximum output buffer size */
68 static sasl_ssf_t sasl_ssf = 0; /* Security strength factor */
69 static int sasl_get_user(void *, int, const char **, unsigned *);
70 static int sasl_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
76 static sasl_callback_t callbacks[] = {
77 { SASL_CB_USER, sasl_get_user, NULL },
78 #define POP_SASL_CB_N_USER 0
79 { SASL_CB_PASS, sasl_get_pass, NULL },
80 #define POP_SASL_CB_N_PASS 1
81 { SASL_CB_LOG, NULL, NULL },
82 { SASL_CB_LIST_END, NULL, NULL },
84 #else /* CYRUS_SASL */
85 # define sasl_fgetc fgetc
86 #endif /* CYRUS_SASL */
91 #if !defined(NNTP) && defined(APOP)
92 static char *pop_auth (char *, char *);
95 #if defined(NNTP) || !defined(MPOP)
96 /* otherwise they are not static functions */
97 static int command(const char *, ...);
98 static int multiline(void);
102 static int pop_auth_sasl(char *, char *, char *);
103 static int sasl_fgetc(FILE *);
104 #endif /* CYRUS_SASL */
106 static int traverse (int (*)(), const char *, ...);
107 static int vcommand(const char *, va_list);
108 static int getline (char *, int, FILE *);
109 static int putline (char *, FILE *);
112 #if !defined(NNTP) && defined(APOP)
114 pop_auth (char *user, char *pass)
118 unsigned char *dp, *ep, digest[16];
120 static char buffer[BUFSIZ];
122 if ((cp = strchr (response, '<')) == NULL
123 || (lp = strchr (cp, '>')) == NULL) {
124 snprintf (buffer, sizeof(buffer), "APOP not available: %s", response);
125 strncpy (response, buffer, sizeof(response));
130 snprintf (buffer, sizeof(buffer), "%s%s", cp, pass);
132 MD5Init (&mdContext);
133 MD5Update (&mdContext, (unsigned char *) buffer,
134 (unsigned int) strlen (buffer));
135 MD5Final (digest, &mdContext);
138 buflen = sizeof(buffer);
140 snprintf (cp, buflen, "%s ", user);
145 for (ep = (dp = digest) + sizeof(digest) / sizeof(digest[0]); dp < ep; ) {
146 snprintf (cp, buflen, "%02x", *dp++ & 0xff);
154 #endif /* !NNTP && APOP */
158 * This function implements the AUTH command for various SASL mechanisms
160 * We do the whole SASL dialog here. If this completes, then we've
161 * authenticated successfully and have (possibly) negotiated a security
166 pop_auth_sasl(char *user, char *host, char *mech)
168 int result, status, sasl_capability = 0;
169 unsigned int buflen, outlen;
170 char server_mechs[256], *buf, outbuf[BUFSIZ];
171 const char *chosen_mech;
172 sasl_security_properties_t secprops;
173 struct pass_context p_context;
178 * First off, we're going to send the CAPA command to see if we can
179 * even support the AUTH command, and if we do, then we'll get a
180 * list of mechanisms the server supports. If we don't support
181 * the CAPA command, then it's unlikely that we will support
185 if (command("CAPA") == NOTOK) {
186 snprintf(response, sizeof(response),
187 "The POP CAPA command failed; POP server does not "
192 while ((status = multiline()) != DONE)
197 case DONE: /* Shouldn't be possible, but just in case */
200 if (strncasecmp(response, "SASL ", 5) == 0) {
202 * We've seen the SASL capability. Grab the mech list
205 strncpy(server_mechs, response + 5, sizeof(server_mechs));
210 if (!sasl_capability) {
211 snprintf(response, sizeof(response), "POP server does not support "
217 * If we received a preferred mechanism, see if the server supports it.
220 if (mech && stringdex(mech, server_mechs) == -1) {
221 snprintf(response, sizeof(response), "Requested SASL mech \"%s\" is "
222 "not in list of supported mechanisms:\n%s",
228 * Start the SASL process. First off, initialize the SASL library.
231 callbacks[POP_SASL_CB_N_USER].context = user;
232 p_context.user = user;
233 p_context.host = host;
234 callbacks[POP_SASL_CB_N_PASS].context = &p_context;
236 result = sasl_client_init(callbacks);
238 if (result != SASL_OK) {
239 snprintf(response, sizeof(response), "SASL library initialization "
240 "failed: %s", sasl_errstring(result, NULL, NULL));
244 result = sasl_client_new("pop", host, NULL, NULL, NULL, 0, &conn);
246 if (result != SASL_OK) {
247 snprintf(response, sizeof(response), "SASL client initialization "
248 "failed: %s", sasl_errstring(result, NULL, NULL));
253 * Initialize the security properties
256 memset(&secprops, 0, sizeof(secprops));
257 secprops.maxbufsize = BUFSIZ;
258 secprops.max_ssf = UINT_MAX;
260 result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
262 if (result != SASL_OK) {
263 snprintf(response, sizeof(response), "SASL security property "
264 "initialization failed: %s", sasl_errdetail(conn));
269 * Start the actual protocol. Feed the mech list into the library
270 * and get out a possible initial challenge
273 result = sasl_client_start(conn,
274 (const char *) (mech ? mech : server_mechs),
275 NULL, (const char **) &buf,
276 &buflen, &chosen_mech);
278 if (result != SASL_OK && result != SASL_CONTINUE) {
279 snprintf(response, sizeof(response), "SASL client start failed: %s",
280 sasl_errdetail(conn));
285 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
286 if (status != SASL_OK) {
287 snprintf(response, sizeof(response), "SASL base64 encode "
288 "failed: %s", sasl_errstring(status, NULL, NULL));
292 status = command("AUTH %s %s", chosen_mech, outbuf);
294 status = command("AUTH %s", chosen_mech);
296 while (result == SASL_CONTINUE) {
301 * If we get a "+OK" prefix to our response, then we should
302 * exit out of this exchange now (because authenticated should
306 if (strncmp(response, "+OK", 3) == 0)
310 * Otherwise, make sure the server challenge is correctly formatted
313 if (strncmp(response, "+ ", 2) != 0) {
315 snprintf(response, sizeof(response),
316 "Malformed authentication message from server");
320 result = sasl_decode64(response + 2, strlen(response + 2),
321 outbuf, sizeof(outbuf), &outlen);
323 if (result != SASL_OK) {
325 snprintf(response, sizeof(response), "SASL base64 decode "
326 "failed: %s", sasl_errstring(result, NULL, NULL));
330 result = sasl_client_step(conn, outbuf, outlen, NULL,
331 (const char **) &buf, &buflen);
333 if (result != SASL_OK && result != SASL_CONTINUE) {
335 snprintf(response, sizeof(response), "SASL client negotiaton "
336 "failed: %s", sasl_errdetail(conn));
340 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
342 if (status != SASL_OK) {
344 snprintf(response, sizeof(response), "SASL base64 encode "
345 "failed: %s", sasl_errstring(status, NULL, NULL));
349 status = command(outbuf);
353 * If we didn't get a positive final response, then error out
354 * (that probably means we failed an authorization check).
361 * We _should_ be okay now. Get a few properties now that negotiation
365 result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &moutbuf);
367 if (result != SASL_OK) {
368 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
369 "output buffer size: %s", sasl_errdetail(conn));
373 maxoutbuf = *moutbuf;
375 result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
379 if (result != SASL_OK) {
380 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
381 "security strength factor: %s", sasl_errdetail(conn));
386 * Limit this to what we can deal with.
389 if (maxoutbuf == 0 || maxoutbuf > BUFSIZ)
398 * Callback to return the userid sent down via the user parameter
402 sasl_get_user(void *context, int id, const char **result, unsigned *len)
404 char *user = (char *) context;
406 if (! result || id != SASL_CB_USER)
407 return SASL_BADPARAM;
417 * Callback to return the password (we call ruserpass, which can get it
422 sasl_get_pass(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
424 struct pass_context *p_context = (struct pass_context *) context;
428 if (! psecret || id != SASL_CB_PASS)
429 return SASL_BADPARAM;
431 ruserpass(p_context->user, &(p_context->host), &pass);
435 *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
440 (*psecret)->len = len;
441 strcpy((char *) (*psecret)->data, pass);
445 #endif /* CYRUS_SASL */
449 * Split string containing proxy command into an array of arguments
450 * suitable for passing to exec. Returned array must be freed. Shouldn't
451 * be possible to call this with host set to NULL.
454 parse_proxy(char *proxy, char *host)
458 int hlen = strlen(host);
463 /* skip any initial space */
464 for (pro = proxy; isspace(*pro); pro++)
467 /* calculate required size for argument array */
468 for (cur = pro; *cur; cur++) {
469 if (isspace(*cur) && cur[1] && !isspace(cur[1]))
471 else if (*cur == '%' && cur[1] == 'h') {
474 } else if (!isspace(*cur))
478 /* put together list of arguments */
479 p = pargv = malloc(pargc * sizeof(char *));
480 c = *pargv = malloc(plen * sizeof(char));
481 for (cur = pro; *cur; cur++) {
482 if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
485 } else if (*cur == '%' && cur[1] == 'h') {
489 } else if (!isspace(*cur))
497 pop_init (char *host, char *user, char *pass, char *proxy, int snoop,
498 int rpop, int kpop, int sasl, char *mech)
503 if (proxy && *proxy) {
505 int inpipe[2]; /* for reading from the server */
506 int outpipe[2]; /* for sending to the server */
508 /* first give up any root priviledges we may have for rpop */
521 dup2(outpipe[0],0); /* connect read end of connection */
522 dup2(inpipe[1], 1); /* connect write end of connection */
523 if(inpipe[0]>1) close(inpipe[0]);
524 if(inpipe[1]>1) close(inpipe[1]);
525 if(outpipe[0]>1) close(outpipe[0]);
526 if(outpipe[1]>1) close(outpipe[1]);
528 /* run the proxy command */
529 argv=parse_proxy(proxy, host);
530 execvp(argv[0],argv);
540 /* okay in the parent we do some stuff */
541 close(inpipe[1]); /* child uses this */
542 close(outpipe[0]); /* child uses this */
547 /* and write on fd2 */
555 if ((apop = rpop) < 0)
562 snprintf (buffer, sizeof(buffer), "%s/%s", KPOP_PRINCIPAL, "kpop");
563 if ((fd1 = client (host, "tcp", buffer, 0, response, sizeof(response))) == NOTOK) {
568 if ((fd1 = client (host, "tcp", POPSERVICE, rpop, response, sizeof(response))) == NOTOK) {
575 if ((fd1 = client (host, "tcp", "nntp", rpop, response, sizeof(response))) == NOTOK)
579 if ((fd2 = dup (fd1)) == NOTOK) {
582 if ((s = strerror(errno)))
583 snprintf (response, sizeof(response),
584 "unable to dup connection descriptor: %s", s);
586 snprintf (response, sizeof(response),
587 "unable to dup connection descriptor: unknown error");
593 if (pop_set (fd1, fd2, snoop) == NOTOK)
595 if (pop_set (fd1, fd2, snoop, (char *)0) == NOTOK)
599 SIGNAL (SIGPIPE, SIG_IGN);
601 switch (getline (response, sizeof response, input)) {
604 fprintf (stderr, "<--- %s\n", response);
606 if (*response == '+') {
610 char *cp = pop_auth (user, pass);
612 if (cp && command ("APOP %s", cp) != NOTOK)
619 if (pop_auth_sasl(user, host, mech) != NOTOK)
622 # endif /* CYRUS_SASL */
623 if (command ("USER %s", user) != NOTOK
624 && command ("%s %s", rpop ? "RPOP" : (pophack++, "PASS"),
628 if (command ("USER %s", user) != NOTOK
629 && command ("PASS %s", pass) != NOTOK)
634 if (*response < CHAR_ERR) {
635 command ("MODE READER");
639 strncpy (buffer, response, sizeof(buffer));
641 strncpy (response, buffer, sizeof(response));
647 fprintf (stderr, "%s\n", response);
653 return NOTOK; /* NOTREACHED */
658 pop_set (int in, int out, int snoop, char *myname)
661 pop_set (int in, int out, int snoop)
666 if (myname && *myname) {
667 /* interface from bbc to msh */
668 strncpy (xtnd_name, myname, sizeof(xtnd_name));
672 if ((input = fdopen (in, "r")) == NULL
673 || (output = fdopen (out, "w")) == NULL) {
674 strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
690 pop_fd (char *in, int inlen, char *out, int outlen)
692 snprintf (in, inlen, "%d", fileno (input));
693 snprintf (out, outlen, "%d", fileno (output));
699 * Find out number of messages available
700 * and their total size.
704 pop_stat (int *nmsgs, int *nbytes)
711 if (command ("STAT") == NOTOK)
714 *nmsgs = *nbytes = 0;
715 sscanf (response, "+OK %d %d", nmsgs, nbytes);
718 if (xtnd_last < 0) { /* in msh, xtnd_name is set from myname */
719 if (command("GROUP %s", xtnd_name) == NOTOK)
722 ap = brkstring (response, " ", "\n"); /* "211 nart first last ggg" */
723 xtnd_first = atoi (ap[2]);
724 xtnd_last = atoi (ap[3]);
727 /* nmsgs is not the real nart, but an incredible simuation */
729 *nmsgs = xtnd_last - xtnd_first + 1; /* because of holes... */
732 *nbytes = xtnd_first; /* for subtracting offset in msh() */
740 pop_exists (int (*action)())
742 #ifdef XMSGS /* hacked into NNTP 1.5 */
743 if (traverse (action, "XMSGS %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last) == OK)
746 /* provided by INN 1.4 */
747 if (traverse (action, "LISTGROUP") == OK)
749 return traverse (action, "XHDR NONAME %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last);
756 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes, int *ids)
759 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
769 if (command ("LIST %d", msgno) == NOTOK)
774 sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
777 sscanf (response, "+OK %d %d", msgs, bytes);
780 if (command ("STAT %d", msgno) == NOTOK)
790 if (command ("LIST") == NOTOK)
793 for (i = 0; i < *nmsgs; i++)
794 switch (multiline ()) {
804 sscanf (response, "%d %d %d",
805 msgs++, bytes++, ids++);
808 sscanf (response, "%d %d", msgs++, bytes++);
812 switch (multiline ()) {
827 pop_retr (int msgno, int (*action)())
830 return traverse (action, "RETR %d", (targ_t) msgno);
832 return traverse (action, "ARTICLE %d", (targ_t) msgno);
838 traverse (int (*action)(), const char *fmt, ...)
842 char buffer[sizeof(response)];
845 result = vcommand (fmt, ap);
850 strncpy (buffer, response, sizeof(buffer));
853 switch (multiline ()) {
858 strncpy (response, buffer, sizeof(response));
862 (*action) (response);
871 return command ("DELE %d", msgno);
878 return command ("NOOP");
882 #if defined(MPOP) && !defined(NNTP)
886 return command ("LAST");
894 return command ("RSET");
899 pop_top (int msgno, int lines, int (*action)())
902 return traverse (action, "TOP %d %d", (targ_t) msgno, (targ_t) lines);
904 return traverse (action, "HEAD %d", (targ_t) msgno);
911 pop_xtnd (int (*action)(), char *fmt, ...)
923 /* needs to be fixed... va_end needs to be added */
924 snprintf (buffer, sizeof(buffer), "XTND %s", fmt);
925 result = traverse (action, buffer, a, b, c, d);
929 snprintf (buffer, sizeof(buffer), fmt, a, b, c, d);
930 ap = brkstring (buffer, " ", "\n"); /* a hack, i know... */
932 if (!strcasecmp(ap[0], "x-bboards")) { /* XTND "X-BBOARDS group */
933 /* most of these parameters are meaningless under NNTP.
934 * bbc.c was modified to set AKA and LEADERS as appropriate,
935 * the rest are left blank.
939 if (!strcasecmp (ap[0], "archive") && ap[1]) {
940 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
942 xtnd_first = 1; /* setup to fail in pop_stat */
945 if (!strcasecmp (ap[0], "bboards")) {
947 if (ap[1]) { /* XTND "BBOARDS group" */
948 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
949 if (command("GROUP %s", xtnd_name) == NOTOK)
952 /* action must ignore extra args */
953 strncpy (buffer, response, sizeof(buffer));
954 ap = brkstring (response, " ", "\n");/* "211 nart first last g" */
955 xtnd_first = atoi (ap[2]);
956 xtnd_last = atoi (ap[3]);
961 } else { /* XTND "BBOARDS" */
962 return traverse (action, "LIST", a, b, c, d);
965 return NOTOK; /* unknown XTND command */
976 i = command ("QUIT");
989 #endif /* CYRUS_SASL */
997 #if !defined(MPOP) || defined(NNTP)
1001 command(const char *fmt, ...)
1007 result = vcommand(fmt, ap);
1015 vcommand (const char *fmt, va_list ap)
1017 char *cp, buffer[BUFSIZ];
1019 vsnprintf (buffer, sizeof(buffer), fmt, ap);
1023 fprintf(stderr, "(encrypted) ");
1024 #endif /* CYRUS_SASL */
1026 if ((cp = strchr (buffer, ' ')))
1028 fprintf (stderr, "---> %s ********\n", buffer);
1034 fprintf (stderr, "---> %s\n", buffer);
1037 if (putline (buffer, output) == NOTOK)
1041 if (poprint && sasl_ssf)
1042 fprintf(stderr, "(decrypted) ");
1043 #endif /* CYRUS_SASL */
1045 switch (getline (response, sizeof response, input)) {
1048 fprintf (stderr, "<--- %s\n", response);
1050 return (*response == '+' ? OK : NOTOK);
1052 return (*response < CHAR_ERR ? OK : NOTOK);
1058 fprintf (stderr, "%s\n", response);
1062 return NOTOK; /* NOTREACHED */
1066 #if defined(MPOP) && !defined(NNTP)
1074 char buffer[BUFSIZ + TRMLEN];
1076 if (getline (buffer, sizeof buffer, input) != OK)
1082 fprintf(stderr, "(decrypted) ");
1083 #endif /* CYRUS_SASL */
1084 fprintf (stderr, "<--- %s\n", response);
1087 if (strncmp (buffer, TRM, TRMLEN) == 0) {
1088 if (buffer[TRMLEN] == 0)
1091 strncpy (response, buffer + TRMLEN, sizeof(response));
1094 strncpy (response, buffer, sizeof(response));
1100 * Note that these functions have been modified to deal with layer encryption
1105 getline (char *s, int n, FILE *iop)
1111 while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2)
1112 if ((*p++ = c) == '\n')
1116 if (ferror (iop) && c != EOF) {
1117 strncpy (response, "error on connection", sizeof(response));
1120 if (c == EOF && p == s) {
1121 strncpy (response, "connection closed by foreign host", sizeof(response));
1135 putline (char *s, FILE *iop)
1138 char outbuf[BUFSIZ], *buf;
1140 unsigned int buflen;
1142 if (!sasl_complete) {
1143 #endif /* CYRUS_SASL */
1144 fprintf (iop, "%s\r\n", s);
1148 * Build an output buffer, encrypt it using sasl_encode, and
1149 * squirt out the results.
1151 strncpy(outbuf, s, sizeof(outbuf) - 3);
1152 outbuf[sizeof(outbuf) - 3] = '\0'; /* Just in case */
1153 strcat(outbuf, "\r\n");
1155 result = sasl_encode(conn, outbuf, strlen(outbuf),
1156 (const char **) &buf, &buflen);
1158 if (result != SASL_OK) {
1159 snprintf(response, sizeof(response), "SASL encoding error: %s",
1160 sasl_errdetail(conn));
1164 fwrite(buf, buflen, 1, iop);
1166 #endif /* CYRUS_SASL */
1170 strncpy (response, "lost connection", sizeof(response));
1179 * Okay, our little fgetc replacement. Hopefully this is a little more
1180 * efficient than the last one.
1185 static unsigned char *buffer = NULL, *ptr;
1186 static int size = 0;
1188 unsigned int retbufsize = 0;
1190 char *retbuf, tmpbuf[BUFSIZ];
1193 * If we have some leftover data, return that
1198 return (int) *ptr++;
1202 * Otherwise, fill our buffer until we have some data to return.
1205 while (retbufsize == 0) {
1207 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1213 snprintf(response, sizeof(response), "Error during read from "
1214 "network: %s", strerror(errno));
1219 * We're not allowed to call sasl_decode until sasl_complete is
1220 * true, so we do these gyrations ...
1223 if (!sasl_complete) {
1230 result = sasl_decode(conn, tmpbuf, cc,
1231 (const char **) &retbuf, &retbufsize);
1233 if (result != SASL_OK) {
1234 snprintf(response, sizeof(response), "Error during SASL "
1235 "decoding: %s", sasl_errdetail(conn));
1241 if (retbufsize > size) {
1242 buffer = realloc(buffer, retbufsize);
1244 snprintf(response, sizeof(response), "Error during realloc in "
1245 "read routine: %s", strerror(errno));
1251 memcpy(buffer, retbuf, retbufsize);
1253 cnt = retbufsize - 1;
1255 return (int) buffer[0];
1257 #endif /* CYRUS_SASL */