2 * popsbr.c -- POP client subroutines
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
12 #if defined(NNTP) && !defined(PSHSBR)
16 #ifdef NNTP /* building pshsbr.o from popsbr.c */
20 #if !defined(NNTP) && defined(APOP)
25 # include <sasl/sasl.h>
26 # include <sasl/saslutil.h>
27 #endif /* CYRUS_SASL */
30 #include <h/signals.h>
35 #define TRMLEN (sizeof TRM - 1)
37 static int poprint = 0;
38 static int pophack = 0;
40 char response[BUFSIZ];
47 #if !defined(NNTP) && defined(MPOP)
48 # define command pop_command
49 # define multiline pop_multiline
53 # ifdef BPOP /* stupid */
54 static int xtnd_last = -1;
55 static int xtnd_first = 0;
56 static char xtnd_name[512]; /* INCREDIBLE HACK!! */
61 static sasl_conn_t *conn; /* SASL connection state */
62 static int sasl_complete = 0; /* Has sasl authentication succeeded? */
63 static int maxoutbuf; /* Maximum output buffer size */
64 static sasl_ssf_t sasl_ssf = 0; /* Security strength factor */
65 static int sasl_get_user(void *, int, const char **, unsigned *);
66 static int sasl_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
72 static sasl_callback_t callbacks[] = {
73 { SASL_CB_USER, sasl_get_user, NULL },
74 #define POP_SASL_CB_N_USER 0
75 { SASL_CB_PASS, sasl_get_pass, NULL },
76 #define POP_SASL_CB_N_PASS 1
77 { SASL_CB_LOG, NULL, NULL },
78 { SASL_CB_LIST_END, NULL, NULL },
80 #define SASL_BUFFER_SIZE 262144
82 #else /* CYRUS_SASL */
83 # define sasl_fgetc fgetc
84 #endif /* CYRUS_SASL */
89 #if !defined(NNTP) && defined(APOP)
90 static char *pop_auth (char *, char *);
93 #if defined(NNTP) || !defined(MPOP)
94 /* otherwise they are not static functions */
95 static int command(const char *, ...);
96 static int multiline(void);
100 static int pop_auth_sasl(char *, char *, char *);
101 static int sasl_fgetc(FILE *);
102 #endif /* CYRUS_SASL */
104 static int traverse (int (*)(char *), const char *, ...);
105 static int vcommand(const char *, va_list);
106 static int sasl_getline (char *, int, FILE *);
107 static int putline (char *, FILE *);
110 #if !defined(NNTP) && defined(APOP)
112 pop_auth (char *user, char *pass)
116 unsigned char *dp, *ep, digest[16];
118 static char buffer[BUFSIZ];
120 if ((cp = strchr (response, '<')) == NULL
121 || (lp = strchr (cp, '>')) == NULL) {
122 snprintf (buffer, sizeof(buffer), "APOP not available: %s", response);
123 strncpy (response, buffer, sizeof(response));
128 snprintf (buffer, sizeof(buffer), "%s%s", cp, pass);
130 MD5Init (&mdContext);
131 MD5Update (&mdContext, (unsigned char *) buffer,
132 (unsigned int) strlen (buffer));
133 MD5Final (digest, &mdContext);
136 buflen = sizeof(buffer);
138 snprintf (cp, buflen, "%s ", user);
143 for (ep = (dp = digest) + sizeof(digest) / sizeof(digest[0]); dp < ep; ) {
144 snprintf (cp, buflen, "%02x", *dp++ & 0xff);
152 #endif /* !NNTP && APOP */
156 * This function implements the AUTH command for various SASL mechanisms
158 * We do the whole SASL dialog here. If this completes, then we've
159 * authenticated successfully and have (possibly) negotiated a security
164 pop_auth_sasl(char *user, char *host, char *mech)
166 int result, status, sasl_capability = 0;
167 unsigned int buflen, outlen;
168 char server_mechs[256], *buf, outbuf[BUFSIZ];
169 const char *chosen_mech;
170 sasl_security_properties_t secprops;
171 struct pass_context p_context;
176 * First off, we're going to send the CAPA command to see if we can
177 * even support the AUTH command, and if we do, then we'll get a
178 * list of mechanisms the server supports. If we don't support
179 * the CAPA command, then it's unlikely that we will support
183 if (command("CAPA") == NOTOK) {
184 snprintf(response, sizeof(response),
185 "The POP CAPA command failed; POP server does not "
190 while ((status = multiline()) != DONE)
195 case DONE: /* Shouldn't be possible, but just in case */
198 if (strncasecmp(response, "SASL ", 5) == 0) {
200 * We've seen the SASL capability. Grab the mech list
203 strncpy(server_mechs, response + 5, sizeof(server_mechs));
208 if (!sasl_capability) {
209 snprintf(response, sizeof(response), "POP server does not support "
215 * If we received a preferred mechanism, see if the server supports it.
218 if (mech && stringdex(mech, server_mechs) == -1) {
219 snprintf(response, sizeof(response), "Requested SASL mech \"%s\" is "
220 "not in list of supported mechanisms:\n%s",
226 * Start the SASL process. First off, initialize the SASL library.
229 callbacks[POP_SASL_CB_N_USER].context = user;
230 p_context.user = user;
231 p_context.host = host;
232 callbacks[POP_SASL_CB_N_PASS].context = &p_context;
234 result = sasl_client_init(callbacks);
236 if (result != SASL_OK) {
237 snprintf(response, sizeof(response), "SASL library initialization "
238 "failed: %s", sasl_errstring(result, NULL, NULL));
242 result = sasl_client_new("pop", host, NULL, NULL, NULL, 0, &conn);
244 if (result != SASL_OK) {
245 snprintf(response, sizeof(response), "SASL client initialization "
246 "failed: %s", sasl_errstring(result, NULL, NULL));
251 * Initialize the security properties
254 memset(&secprops, 0, sizeof(secprops));
255 secprops.maxbufsize = SASL_BUFFER_SIZE;
256 secprops.max_ssf = UINT_MAX;
258 result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
260 if (result != SASL_OK) {
261 snprintf(response, sizeof(response), "SASL security property "
262 "initialization failed: %s", sasl_errdetail(conn));
267 * Start the actual protocol. Feed the mech list into the library
268 * and get out a possible initial challenge
271 result = sasl_client_start(conn,
272 (const char *) (mech ? mech : server_mechs),
273 NULL, (const char **) &buf,
274 &buflen, &chosen_mech);
276 if (result != SASL_OK && result != SASL_CONTINUE) {
277 snprintf(response, sizeof(response), "SASL client start failed: %s",
278 sasl_errdetail(conn));
283 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
284 if (status != SASL_OK) {
285 snprintf(response, sizeof(response), "SASL base64 encode "
286 "failed: %s", sasl_errstring(status, NULL, NULL));
290 status = command("AUTH %s %s", chosen_mech, outbuf);
292 status = command("AUTH %s", chosen_mech);
294 while (result == SASL_CONTINUE) {
299 * If we get a "+OK" prefix to our response, then we should
300 * exit out of this exchange now (because authenticated should
304 if (strncmp(response, "+OK", 3) == 0)
308 * Otherwise, make sure the server challenge is correctly formatted
311 if (strncmp(response, "+ ", 2) != 0) {
313 snprintf(response, sizeof(response),
314 "Malformed authentication message from server");
318 result = sasl_decode64(response + 2, strlen(response + 2),
319 outbuf, sizeof(outbuf), &outlen);
321 if (result != SASL_OK) {
323 snprintf(response, sizeof(response), "SASL base64 decode "
324 "failed: %s", sasl_errstring(result, NULL, NULL));
328 result = sasl_client_step(conn, outbuf, outlen, NULL,
329 (const char **) &buf, &buflen);
331 if (result != SASL_OK && result != SASL_CONTINUE) {
333 snprintf(response, sizeof(response), "SASL client negotiaton "
334 "failed: %s", sasl_errdetail(conn));
338 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
340 if (status != SASL_OK) {
342 snprintf(response, sizeof(response), "SASL base64 encode "
343 "failed: %s", sasl_errstring(status, NULL, NULL));
347 status = command(outbuf);
351 * If we didn't get a positive final response, then error out
352 * (that probably means we failed an authorization check).
359 * We _should_ be okay now. Get a few properties now that negotiation
363 result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &moutbuf);
365 if (result != SASL_OK) {
366 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
367 "output buffer size: %s", sasl_errdetail(conn));
371 maxoutbuf = *moutbuf;
373 result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
377 if (result != SASL_OK) {
378 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
379 "security strength factor: %s", sasl_errdetail(conn));
384 * Limit this to what we can deal with. Shouldn't matter much because
385 * this is only outgoing data (which should be small)
388 if (maxoutbuf == 0 || maxoutbuf > BUFSIZ)
397 * Callback to return the userid sent down via the user parameter
401 sasl_get_user(void *context, int id, const char **result, unsigned *len)
403 char *user = (char *) context;
405 if (! result || id != SASL_CB_USER)
406 return SASL_BADPARAM;
416 * Callback to return the password (we call ruserpass, which can get it
421 sasl_get_pass(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
423 struct pass_context *p_context = (struct pass_context *) context;
427 if (! psecret || id != SASL_CB_PASS)
428 return SASL_BADPARAM;
430 ruserpass(p_context->user, &(p_context->host), &pass);
434 *psecret = (sasl_secret_t *) mh_xmalloc(sizeof(sasl_secret_t) + len);
436 (*psecret)->len = len;
437 strcpy((char *) (*psecret)->data, pass);
441 #endif /* CYRUS_SASL */
445 * Split string containing proxy command into an array of arguments
446 * suitable for passing to exec. Returned array must be freed. Shouldn't
447 * be possible to call this with host set to NULL.
450 parse_proxy(char *proxy, char *host)
454 int hlen = strlen(host);
456 unsigned char *cur, *pro;
459 /* skip any initial space */
460 for (pro = (unsigned char *) proxy; isspace(*pro); pro++)
463 /* calculate required size for argument array */
464 for (cur = pro; *cur; cur++) {
465 if (isspace(*cur) && cur[1] && !isspace(cur[1]))
467 else if (*cur == '%' && cur[1] == 'h') {
470 } else if (!isspace(*cur))
474 /* put together list of arguments */
475 p = pargv = mh_xmalloc(pargc * sizeof(char *));
476 c = *pargv = mh_xmalloc(plen * sizeof(char));
477 for (cur = pro; *cur; cur++) {
478 if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
481 } else if (*cur == '%' && cur[1] == 'h') {
485 } else if (!isspace(*cur))
493 pop_init (char *host, char *user, char *pass, char *proxy, int snoop,
494 int rpop, int kpop, int sasl, char *mech)
502 if ((apop = rpop) < 0)
506 if (proxy && *proxy) {
508 int inpipe[2]; /* for reading from the server */
509 int outpipe[2]; /* for sending to the server */
511 /* first give up any root priviledges we may have for rpop */
524 dup2(outpipe[0],0); /* connect read end of connection */
525 dup2(inpipe[1], 1); /* connect write end of connection */
526 if(inpipe[0]>1) close(inpipe[0]);
527 if(inpipe[1]>1) close(inpipe[1]);
528 if(outpipe[0]>1) close(outpipe[0]);
529 if(outpipe[1]>1) close(outpipe[1]);
531 /* run the proxy command */
532 argv=parse_proxy(proxy, host);
533 execvp(argv[0],argv);
543 /* okay in the parent we do some stuff */
544 close(inpipe[1]); /* child uses this */
545 close(outpipe[0]); /* child uses this */
550 /* and write on fd2 */
558 snprintf (buffer, sizeof(buffer), "%s/%s", KPOP_PRINCIPAL, "kpop");
559 if ((fd1 = client (host, "tcp", buffer, 0, response, sizeof(response))) == NOTOK) {
563 snprintf (response, sizeof(response), "this version of nmh compiled without KPOP support");
567 if ((fd1 = client (host, POPSERVICE, response, sizeof(response), snoop)) == NOTOK) {
572 if ((fd1 = client (host, "nntp", response, sizeof(response), snoop)) == NOTOK)
576 if ((fd2 = dup (fd1)) == NOTOK) {
579 if ((s = strerror(errno)))
580 snprintf (response, sizeof(response),
581 "unable to dup connection descriptor: %s", s);
583 snprintf (response, sizeof(response),
584 "unable to dup connection descriptor: unknown error");
590 if (pop_set (fd1, fd2, snoop) == NOTOK)
592 if (pop_set (fd1, fd2, snoop, (char *)0) == NOTOK)
596 SIGNAL (SIGPIPE, SIG_IGN);
598 switch (sasl_getline (response, sizeof response, input)) {
601 fprintf (stderr, "<--- %s\n", response);
603 if (*response == '+') {
607 char *cp = pop_auth (user, pass);
609 if (cp && command ("APOP %s", cp) != NOTOK)
616 if (pop_auth_sasl(user, host, mech) != NOTOK)
619 # endif /* CYRUS_SASL */
620 if (command ("USER %s", user) != NOTOK
621 && command ("%s %s", rpop ? "RPOP" : (pophack++, "PASS"),
625 if (command ("USER %s", user) != NOTOK
626 && command ("PASS %s", pass) != NOTOK)
631 if (*response < CHAR_ERR) {
632 command ("MODE READER");
636 strncpy (buffer, response, sizeof(buffer));
638 strncpy (response, buffer, sizeof(response));
644 fprintf (stderr, "%s\n", response);
650 return NOTOK; /* NOTREACHED */
655 pop_set (int in, int out, int snoop, char *myname)
658 pop_set (int in, int out, int snoop)
663 if (myname && *myname) {
664 /* interface from bbc to msh */
665 strncpy (xtnd_name, myname, sizeof(xtnd_name));
669 if ((input = fdopen (in, "r")) == NULL
670 || (output = fdopen (out, "w")) == NULL) {
671 strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
687 pop_fd (char *in, int inlen, char *out, int outlen)
689 snprintf (in, inlen, "%d", fileno (input));
690 snprintf (out, outlen, "%d", fileno (output));
696 * Find out number of messages available
697 * and their total size.
701 pop_stat (int *nmsgs, int *nbytes)
708 if (command ("STAT") == NOTOK)
711 *nmsgs = *nbytes = 0;
712 sscanf (response, "+OK %d %d", nmsgs, nbytes);
715 if (xtnd_last < 0) { /* in msh, xtnd_name is set from myname */
716 if (command("GROUP %s", xtnd_name) == NOTOK)
719 ap = brkstring (response, " ", "\n"); /* "211 nart first last ggg" */
720 xtnd_first = atoi (ap[2]);
721 xtnd_last = atoi (ap[3]);
724 /* nmsgs is not the real nart, but an incredible simuation */
726 *nmsgs = xtnd_last - xtnd_first + 1; /* because of holes... */
729 *nbytes = xtnd_first; /* for subtracting offset in msh() */
737 pop_exists (int (*action)())
739 #ifdef XMSGS /* hacked into NNTP 1.5 */
740 if (traverse (action, "XMSGS %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last) == OK)
743 /* provided by INN 1.4 */
744 if (traverse (action, "LISTGROUP") == OK)
746 return traverse (action, "XHDR NONAME %d-%d", (targ_t) xtnd_first, (targ_t) xtnd_last);
753 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes, int *ids)
756 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
766 if (command ("LIST %d", msgno) == NOTOK)
771 sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
774 sscanf (response, "+OK %d %d", msgs, bytes);
777 if (command ("STAT %d", msgno) == NOTOK)
787 if (command ("LIST") == NOTOK)
790 for (i = 0; i < *nmsgs; i++)
791 switch (multiline ()) {
801 sscanf (response, "%d %d %d",
802 msgs++, bytes++, ids++);
805 sscanf (response, "%d %d", msgs++, bytes++);
809 switch (multiline ()) {
824 pop_retr (int msgno, int (*action)(char *))
827 return traverse (action, "RETR %d", (targ_t) msgno);
829 return traverse (action, "ARTICLE %d", (targ_t) msgno);
835 traverse (int (*action)(char *), const char *fmt, ...)
839 char buffer[sizeof(response)];
842 result = vcommand (fmt, ap);
847 strncpy (buffer, response, sizeof(buffer));
850 switch (multiline ()) {
855 strncpy (response, buffer, sizeof(response));
859 (*action) (response);
868 return command ("DELE %d", msgno);
875 return command ("NOOP");
879 #if defined(MPOP) && !defined(NNTP)
883 return command ("LAST");
891 return command ("RSET");
896 pop_top (int msgno, int lines, int (*action)(char *))
899 return traverse (action, "TOP %d %d", (targ_t) msgno, (targ_t) lines);
901 return traverse (action, "HEAD %d", (targ_t) msgno);
908 pop_xtnd (int (*action)(), char *fmt, ...)
920 /* needs to be fixed... va_end needs to be added */
921 snprintf (buffer, sizeof(buffer), "XTND %s", fmt);
922 result = traverse (action, buffer, a, b, c, d);
926 snprintf (buffer, sizeof(buffer), fmt, a, b, c, d);
927 ap = brkstring (buffer, " ", "\n"); /* a hack, i know... */
929 if (!mh_strcasecmp(ap[0], "x-bboards")) { /* XTND "X-BBOARDS group */
930 /* most of these parameters are meaningless under NNTP.
931 * bbc.c was modified to set AKA and LEADERS as appropriate,
932 * the rest are left blank.
936 if (!mh_strcasecmp (ap[0], "archive") && ap[1]) {
937 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
939 xtnd_first = 1; /* setup to fail in pop_stat */
942 if (!mh_strcasecmp (ap[0], "bboards")) {
944 if (ap[1]) { /* XTND "BBOARDS group" */
945 snprintf (xtnd_name, sizeof(xtnd_name), "%s", ap[1]); /* save the name */
946 if (command("GROUP %s", xtnd_name) == NOTOK)
949 /* action must ignore extra args */
950 strncpy (buffer, response, sizeof(buffer));
951 ap = brkstring (response, " ", "\n");/* "211 nart first last g" */
952 xtnd_first = atoi (ap[2]);
953 xtnd_last = atoi (ap[3]);
958 } else { /* XTND "BBOARDS" */
959 return traverse (action, "LIST", a, b, c, d);
962 return NOTOK; /* unknown XTND command */
973 i = command ("QUIT");
986 #endif /* CYRUS_SASL */
994 #if !defined(MPOP) || defined(NNTP)
998 command(const char *fmt, ...)
1004 result = vcommand(fmt, ap);
1012 vcommand (const char *fmt, va_list ap)
1014 char *cp, buffer[BUFSIZ];
1016 vsnprintf (buffer, sizeof(buffer), fmt, ap);
1020 fprintf(stderr, "(encrypted) ");
1021 #endif /* CYRUS_SASL */
1023 if ((cp = strchr (buffer, ' ')))
1025 fprintf (stderr, "---> %s ********\n", buffer);
1031 fprintf (stderr, "---> %s\n", buffer);
1034 if (putline (buffer, output) == NOTOK)
1038 if (poprint && sasl_ssf)
1039 fprintf(stderr, "(decrypted) ");
1040 #endif /* CYRUS_SASL */
1042 switch (sasl_getline (response, sizeof response, input)) {
1045 fprintf (stderr, "<--- %s\n", response);
1047 return (*response == '+' ? OK : NOTOK);
1049 return (*response < CHAR_ERR ? OK : NOTOK);
1055 fprintf (stderr, "%s\n", response);
1059 return NOTOK; /* NOTREACHED */
1063 #if defined(MPOP) && !defined(NNTP)
1071 char buffer[BUFSIZ + TRMLEN];
1073 if (sasl_getline (buffer, sizeof buffer, input) != OK)
1079 fprintf(stderr, "(decrypted) ");
1080 #endif /* CYRUS_SASL */
1081 fprintf (stderr, "<--- %s\n", response);
1084 if (strncmp (buffer, TRM, TRMLEN) == 0) {
1085 if (buffer[TRMLEN] == 0)
1088 strncpy (response, buffer + TRMLEN, sizeof(response));
1091 strncpy (response, buffer, sizeof(response));
1097 * Note that these functions have been modified to deal with layer encryption
1102 sasl_getline (char *s, int n, FILE *iop)
1108 while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2)
1109 if ((*p++ = c) == '\n')
1113 if (ferror (iop) && c != EOF) {
1114 strncpy (response, "error on connection", sizeof(response));
1117 if (c == EOF && p == s) {
1118 strncpy (response, "connection closed by foreign host", sizeof(response));
1132 putline (char *s, FILE *iop)
1135 char outbuf[BUFSIZ], *buf;
1137 unsigned int buflen;
1139 if (!sasl_complete) {
1140 #endif /* CYRUS_SASL */
1141 fprintf (iop, "%s\r\n", s);
1145 * Build an output buffer, encrypt it using sasl_encode, and
1146 * squirt out the results.
1148 strncpy(outbuf, s, sizeof(outbuf) - 3);
1149 outbuf[sizeof(outbuf) - 3] = '\0'; /* Just in case */
1150 strcat(outbuf, "\r\n");
1152 result = sasl_encode(conn, outbuf, strlen(outbuf),
1153 (const char **) &buf, &buflen);
1155 if (result != SASL_OK) {
1156 snprintf(response, sizeof(response), "SASL encoding error: %s",
1157 sasl_errdetail(conn));
1161 fwrite(buf, buflen, 1, iop);
1163 #endif /* CYRUS_SASL */
1167 strncpy (response, "lost connection", sizeof(response));
1176 * Okay, our little fgetc replacement. Hopefully this is a little more
1177 * efficient than the last one.
1182 static unsigned char *buffer = NULL, *ptr;
1183 static int size = 0;
1185 unsigned int retbufsize = 0;
1187 char *retbuf, tmpbuf[SASL_BUFFER_SIZE];
1190 * If we have some leftover data, return that
1195 return (int) *ptr++;
1199 * Otherwise, fill our buffer until we have some data to return.
1202 while (retbufsize == 0) {
1204 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
1210 snprintf(response, sizeof(response), "Error during read from "
1211 "network: %s", strerror(errno));
1216 * We're not allowed to call sasl_decode until sasl_complete is
1217 * true, so we do these gyrations ...
1220 if (!sasl_complete) {
1227 result = sasl_decode(conn, tmpbuf, cc,
1228 (const char **) &retbuf, &retbufsize);
1230 if (result != SASL_OK) {
1231 snprintf(response, sizeof(response), "Error during SASL "
1232 "decoding: %s", sasl_errdetail(conn));
1238 if (retbufsize > size) {
1239 buffer = mh_xrealloc(buffer, retbufsize);
1243 memcpy(buffer, retbuf, retbufsize);
1245 cnt = retbufsize - 1;
1247 return (int) buffer[0];
1249 #endif /* CYRUS_SASL */