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)
29 # include <sasl/sasl.h>
30 # include <sasl/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)
506 if ((apop = rpop) < 0)
510 if (proxy && *proxy) {
512 int inpipe[2]; /* for reading from the server */
513 int outpipe[2]; /* for sending to the server */
515 /* first give up any root priviledges we may have for rpop */
528 dup2(outpipe[0],0); /* connect read end of connection */
529 dup2(inpipe[1], 1); /* connect write end of connection */
530 if(inpipe[0]>1) close(inpipe[0]);
531 if(inpipe[1]>1) close(inpipe[1]);
532 if(outpipe[0]>1) close(outpipe[0]);
533 if(outpipe[1]>1) close(outpipe[1]);
535 /* run the proxy command */
536 argv=parse_proxy(proxy, host);
537 execvp(argv[0],argv);
547 /* okay in the parent we do some stuff */
548 close(inpipe[1]); /* child uses this */
549 close(outpipe[0]); /* child uses this */
554 /* and write on fd2 */
562 snprintf (buffer, sizeof(buffer), "%s/%s", KPOP_PRINCIPAL, "kpop");
563 if ((fd1 = client (host, "tcp", buffer, 0, response, sizeof(response))) == NOTOK) {
567 snprintf (response, sizeof(response), "this version of nmh compiled without KPOP support");
571 if ((fd1 = client (host, "tcp", POPSERVICE, rpop, response, sizeof(response))) == NOTOK) {
576 if ((fd1 = client (host, "tcp", "nntp", rpop, response, sizeof(response))) == NOTOK)
580 if ((fd2 = dup (fd1)) == NOTOK) {
583 if ((s = strerror(errno)))
584 snprintf (response, sizeof(response),
585 "unable to dup connection descriptor: %s", s);
587 snprintf (response, sizeof(response),
588 "unable to dup connection descriptor: unknown error");
594 if (pop_set (fd1, fd2, snoop) == NOTOK)
596 if (pop_set (fd1, fd2, snoop, (char *)0) == NOTOK)
600 SIGNAL (SIGPIPE, SIG_IGN);
602 switch (getline (response, sizeof response, input)) {
605 fprintf (stderr, "<--- %s\n", response);
607 if (*response == '+') {
611 char *cp = pop_auth (user, pass);
613 if (cp && command ("APOP %s", cp) != NOTOK)
620 if (pop_auth_sasl(user, host, mech) != NOTOK)
623 # endif /* CYRUS_SASL */
624 if (command ("USER %s", user) != NOTOK
625 && command ("%s %s", rpop ? "RPOP" : (pophack++, "PASS"),
629 if (command ("USER %s", user) != NOTOK
630 && command ("PASS %s", pass) != NOTOK)
635 if (*response < CHAR_ERR) {
636 command ("MODE READER");
640 strncpy (buffer, response, sizeof(buffer));
642 strncpy (response, buffer, sizeof(response));
648 fprintf (stderr, "%s\n", response);
654 return NOTOK; /* NOTREACHED */
659 pop_set (int in, int out, int snoop, char *myname)
662 pop_set (int in, int out, int snoop)
667 if (myname && *myname) {
668 /* interface from bbc to msh */
669 strncpy (xtnd_name, myname, sizeof(xtnd_name));
673 if ((input = fdopen (in, "r")) == NULL
674 || (output = fdopen (out, "w")) == NULL) {
675 strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
691 pop_fd (char *in, int inlen, char *out, int outlen)
693 snprintf (in, inlen, "%d", fileno (input));
694 snprintf (out, outlen, "%d", fileno (output));
700 * Find out number of messages available
701 * and their total size.
705 pop_stat (int *nmsgs, int *nbytes)
712 if (command ("STAT") == NOTOK)
715 *nmsgs = *nbytes = 0;
716 sscanf (response, "+OK %d %d", nmsgs, nbytes);
719 if (xtnd_last < 0) { /* in msh, xtnd_name is set from myname */
720 if (command("GROUP %s", xtnd_name) == NOTOK)
723 ap = brkstring (response, " ", "\n"); /* "211 nart first last ggg" */
724 xtnd_first = atoi (ap[2]);
725 xtnd_last = atoi (ap[3]);
728 /* nmsgs is not the real nart, but an incredible simuation */
730 *nmsgs = xtnd_last - xtnd_first + 1; /* because of holes... */
733 *nbytes = xtnd_first; /* for subtracting offset in msh() */
741 pop_exists (int (*action)())
743 #ifdef XMSGS /* hacked into NNTP 1.5 */
744 if (traverse (action, "XMSGS %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last) == OK)
747 /* provided by INN 1.4 */
748 if (traverse (action, "LISTGROUP") == OK)
750 return traverse (action, "XHDR NONAME %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last);
757 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes, int *ids)
760 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
770 if (command ("LIST %d", msgno) == NOTOK)
775 sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
778 sscanf (response, "+OK %d %d", msgs, bytes);
781 if (command ("STAT %d", msgno) == NOTOK)
791 if (command ("LIST") == NOTOK)
794 for (i = 0; i < *nmsgs; i++)
795 switch (multiline ()) {
805 sscanf (response, "%d %d %d",
806 msgs++, bytes++, ids++);
809 sscanf (response, "%d %d", msgs++, bytes++);
813 switch (multiline ()) {
828 pop_retr (int msgno, int (*action)())
831 return traverse (action, "RETR %d", (targ_t) msgno);
833 return traverse (action, "ARTICLE %d", (targ_t) msgno);
839 traverse (int (*action)(), const char *fmt, ...)
843 char buffer[sizeof(response)];
846 result = vcommand (fmt, ap);
851 strncpy (buffer, response, sizeof(buffer));
854 switch (multiline ()) {
859 strncpy (response, buffer, sizeof(response));
863 (*action) (response);
872 return command ("DELE %d", msgno);
879 return command ("NOOP");
883 #if defined(MPOP) && !defined(NNTP)
887 return command ("LAST");
895 return command ("RSET");
900 pop_top (int msgno, int lines, int (*action)())
903 return traverse (action, "TOP %d %d", (targ_t) msgno, (targ_t) lines);
905 return traverse (action, "HEAD %d", (targ_t) msgno);
912 pop_xtnd (int (*action)(), char *fmt, ...)
924 /* needs to be fixed... va_end needs to be added */
925 snprintf (buffer, sizeof(buffer), "XTND %s", fmt);
926 result = traverse (action, buffer, a, b, c, d);
930 snprintf (buffer, sizeof(buffer), fmt, a, b, c, d);
931 ap = brkstring (buffer, " ", "\n"); /* a hack, i know... */
933 if (!strcasecmp(ap[0], "x-bboards")) { /* XTND "X-BBOARDS group */
934 /* most of these parameters are meaningless under NNTP.
935 * bbc.c was modified to set AKA and LEADERS as appropriate,
936 * the rest are left blank.
940 if (!strcasecmp (ap[0], "archive") && ap[1]) {
941 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
943 xtnd_first = 1; /* setup to fail in pop_stat */
946 if (!strcasecmp (ap[0], "bboards")) {
948 if (ap[1]) { /* XTND "BBOARDS group" */
949 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
950 if (command("GROUP %s", xtnd_name) == NOTOK)
953 /* action must ignore extra args */
954 strncpy (buffer, response, sizeof(buffer));
955 ap = brkstring (response, " ", "\n");/* "211 nart first last g" */
956 xtnd_first = atoi (ap[2]);
957 xtnd_last = atoi (ap[3]);
962 } else { /* XTND "BBOARDS" */
963 return traverse (action, "LIST", a, b, c, d);
966 return NOTOK; /* unknown XTND command */
977 i = command ("QUIT");
990 #endif /* CYRUS_SASL */
998 #if !defined(MPOP) || defined(NNTP)
1002 command(const char *fmt, ...)
1008 result = vcommand(fmt, ap);
1016 vcommand (const char *fmt, va_list ap)
1018 char *cp, buffer[BUFSIZ];
1020 vsnprintf (buffer, sizeof(buffer), fmt, ap);
1024 fprintf(stderr, "(encrypted) ");
1025 #endif /* CYRUS_SASL */
1027 if ((cp = strchr (buffer, ' ')))
1029 fprintf (stderr, "---> %s ********\n", buffer);
1035 fprintf (stderr, "---> %s\n", buffer);
1038 if (putline (buffer, output) == NOTOK)
1042 if (poprint && sasl_ssf)
1043 fprintf(stderr, "(decrypted) ");
1044 #endif /* CYRUS_SASL */
1046 switch (getline (response, sizeof response, input)) {
1049 fprintf (stderr, "<--- %s\n", response);
1051 return (*response == '+' ? OK : NOTOK);
1053 return (*response < CHAR_ERR ? OK : NOTOK);
1059 fprintf (stderr, "%s\n", response);
1063 return NOTOK; /* NOTREACHED */
1067 #if defined(MPOP) && !defined(NNTP)
1075 char buffer[BUFSIZ + TRMLEN];
1077 if (getline (buffer, sizeof buffer, input) != OK)
1083 fprintf(stderr, "(decrypted) ");
1084 #endif /* CYRUS_SASL */
1085 fprintf (stderr, "<--- %s\n", response);
1088 if (strncmp (buffer, TRM, TRMLEN) == 0) {
1089 if (buffer[TRMLEN] == 0)
1092 strncpy (response, buffer + TRMLEN, sizeof(response));
1095 strncpy (response, buffer, sizeof(response));
1101 * Note that these functions have been modified to deal with layer encryption
1106 getline (char *s, int n, FILE *iop)
1112 while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2)
1113 if ((*p++ = c) == '\n')
1117 if (ferror (iop) && c != EOF) {
1118 strncpy (response, "error on connection", sizeof(response));
1121 if (c == EOF && p == s) {
1122 strncpy (response, "connection closed by foreign host", sizeof(response));
1136 putline (char *s, FILE *iop)
1139 char outbuf[BUFSIZ], *buf;
1141 unsigned int buflen;
1143 if (!sasl_complete) {
1144 #endif /* CYRUS_SASL */
1145 fprintf (iop, "%s\r\n", s);
1149 * Build an output buffer, encrypt it using sasl_encode, and
1150 * squirt out the results.
1152 strncpy(outbuf, s, sizeof(outbuf) - 3);
1153 outbuf[sizeof(outbuf) - 3] = '\0'; /* Just in case */
1154 strcat(outbuf, "\r\n");
1156 result = sasl_encode(conn, outbuf, strlen(outbuf),
1157 (const char **) &buf, &buflen);
1159 if (result != SASL_OK) {
1160 snprintf(response, sizeof(response), "SASL encoding error: %s",
1161 sasl_errdetail(conn));
1165 fwrite(buf, buflen, 1, iop);
1167 #endif /* CYRUS_SASL */
1171 strncpy (response, "lost connection", sizeof(response));
1180 * Okay, our little fgetc replacement. Hopefully this is a little more
1181 * efficient than the last one.
1186 static unsigned char *buffer = NULL, *ptr;
1187 static int size = 0;
1189 unsigned int retbufsize = 0;
1191 char *retbuf, tmpbuf[BUFSIZ];
1194 * If we have some leftover data, return that
1199 return (int) *ptr++;
1203 * Otherwise, fill our buffer until we have some data to return.
1206 while (retbufsize == 0) {
1208 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1214 snprintf(response, sizeof(response), "Error during read from "
1215 "network: %s", strerror(errno));
1220 * We're not allowed to call sasl_decode until sasl_complete is
1221 * true, so we do these gyrations ...
1224 if (!sasl_complete) {
1231 result = sasl_decode(conn, tmpbuf, cc,
1232 (const char **) &retbuf, &retbufsize);
1234 if (result != SASL_OK) {
1235 snprintf(response, sizeof(response), "Error during SASL "
1236 "decoding: %s", sasl_errdetail(conn));
1242 if (retbufsize > size) {
1243 buffer = realloc(buffer, retbufsize);
1245 snprintf(response, sizeof(response), "Error during realloc in "
1246 "read routine: %s", strerror(errno));
1252 memcpy(buffer, retbuf, retbufsize);
1254 cnt = retbufsize - 1;
1256 return (int) buffer[0];
1258 #endif /* CYRUS_SASL */