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.
13 # include <sasl/sasl.h>
14 # include <sasl/saslutil.h>
15 #endif /* CYRUS_SASL */
18 #include <h/signals.h>
23 #define TRMLEN (sizeof TRM - 1)
25 static int poprint = 0;
26 static int pophack = 0;
28 char response[BUFSIZ];
34 static sasl_conn_t *conn; /* SASL connection state */
35 static int sasl_complete = 0; /* Has sasl authentication succeeded? */
36 static int maxoutbuf; /* Maximum output buffer size */
37 static sasl_ssf_t sasl_ssf = 0; /* Security strength factor */
38 static int sasl_get_user(void *, int, const char **, unsigned *);
39 static int sasl_get_pass(sasl_conn_t *, void *, int, sasl_secret_t **);
45 static sasl_callback_t callbacks[] = {
46 { SASL_CB_USER, sasl_get_user, NULL },
47 #define POP_SASL_CB_N_USER 0
48 { SASL_CB_PASS, sasl_get_pass, NULL },
49 #define POP_SASL_CB_N_PASS 1
50 { SASL_CB_LOG, NULL, NULL },
51 { SASL_CB_LIST_END, NULL, NULL },
53 #define SASL_BUFFER_SIZE 262144
55 #else /* CYRUS_SASL */
56 # define sasl_fgetc fgetc
57 #endif /* CYRUS_SASL */
63 static int command(const char *, ...);
64 static int multiline(void);
67 static int pop_auth_sasl(char *, char *, char *);
68 static int sasl_fgetc(FILE *);
69 #endif /* CYRUS_SASL */
71 static int traverse (int (*)(char *), const char *, ...);
72 static int vcommand(const char *, va_list);
73 static int sasl_getline (char *, int, FILE *);
74 static int putline (char *, FILE *);
79 * This function implements the AUTH command for various SASL mechanisms
81 * We do the whole SASL dialog here. If this completes, then we've
82 * authenticated successfully and have (possibly) negotiated a security
87 pop_auth_sasl(char *user, char *host, char *mech)
89 int result, status, sasl_capability = 0;
90 unsigned int buflen, outlen;
91 char server_mechs[256], *buf, outbuf[BUFSIZ];
92 const char *chosen_mech;
93 sasl_security_properties_t secprops;
94 struct pass_context p_context;
99 * First off, we're going to send the CAPA command to see if we can
100 * even support the AUTH command, and if we do, then we'll get a
101 * list of mechanisms the server supports. If we don't support
102 * the CAPA command, then it's unlikely that we will support
106 if (command("CAPA") == NOTOK) {
107 snprintf(response, sizeof(response),
108 "The POP CAPA command failed; POP server does not "
113 while ((status = multiline()) != DONE)
118 case DONE: /* Shouldn't be possible, but just in case */
121 if (strncasecmp(response, "SASL ", 5) == 0) {
123 * We've seen the SASL capability. Grab the mech list
126 strncpy(server_mechs, response + 5, sizeof(server_mechs));
131 if (!sasl_capability) {
132 snprintf(response, sizeof(response), "POP server does not support "
138 * If we received a preferred mechanism, see if the server supports it.
141 if (mech && stringdex(mech, server_mechs) == -1) {
142 snprintf(response, sizeof(response), "Requested SASL mech \"%s\" is "
143 "not in list of supported mechanisms:\n%s",
149 * Start the SASL process. First off, initialize the SASL library.
152 callbacks[POP_SASL_CB_N_USER].context = user;
153 p_context.user = user;
154 p_context.host = host;
155 callbacks[POP_SASL_CB_N_PASS].context = &p_context;
157 result = sasl_client_init(callbacks);
159 if (result != SASL_OK) {
160 snprintf(response, sizeof(response), "SASL library initialization "
161 "failed: %s", sasl_errstring(result, NULL, NULL));
165 result = sasl_client_new("pop", host, NULL, NULL, NULL, 0, &conn);
167 if (result != SASL_OK) {
168 snprintf(response, sizeof(response), "SASL client initialization "
169 "failed: %s", sasl_errstring(result, NULL, NULL));
174 * Initialize the security properties
177 memset(&secprops, 0, sizeof(secprops));
178 secprops.maxbufsize = SASL_BUFFER_SIZE;
179 secprops.max_ssf = UINT_MAX;
181 result = sasl_setprop(conn, SASL_SEC_PROPS, &secprops);
183 if (result != SASL_OK) {
184 snprintf(response, sizeof(response), "SASL security property "
185 "initialization failed: %s", sasl_errdetail(conn));
190 * Start the actual protocol. Feed the mech list into the library
191 * and get out a possible initial challenge
194 result = sasl_client_start(conn,
195 (const char *) (mech ? mech : server_mechs),
196 NULL, (const char **) &buf,
197 &buflen, &chosen_mech);
199 if (result != SASL_OK && result != SASL_CONTINUE) {
200 snprintf(response, sizeof(response), "SASL client start failed: %s",
201 sasl_errdetail(conn));
206 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
207 if (status != SASL_OK) {
208 snprintf(response, sizeof(response), "SASL base64 encode "
209 "failed: %s", sasl_errstring(status, NULL, NULL));
213 status = command("AUTH %s %s", chosen_mech, outbuf);
215 status = command("AUTH %s", chosen_mech);
217 while (result == SASL_CONTINUE) {
222 * If we get a "+OK" prefix to our response, then we should
223 * exit out of this exchange now (because authenticated should
227 if (strncmp(response, "+OK", 3) == 0)
231 * Otherwise, make sure the server challenge is correctly formatted
234 if (strncmp(response, "+ ", 2) != 0) {
236 snprintf(response, sizeof(response),
237 "Malformed authentication message from server");
241 result = sasl_decode64(response + 2, strlen(response + 2),
242 outbuf, sizeof(outbuf), &outlen);
244 if (result != SASL_OK) {
246 snprintf(response, sizeof(response), "SASL base64 decode "
247 "failed: %s", sasl_errstring(result, NULL, NULL));
251 result = sasl_client_step(conn, outbuf, outlen, NULL,
252 (const char **) &buf, &buflen);
254 if (result != SASL_OK && result != SASL_CONTINUE) {
256 snprintf(response, sizeof(response), "SASL client negotiaton "
257 "failed: %s", sasl_errdetail(conn));
261 status = sasl_encode64(buf, buflen, outbuf, sizeof(outbuf), NULL);
263 if (status != SASL_OK) {
265 snprintf(response, sizeof(response), "SASL base64 encode "
266 "failed: %s", sasl_errstring(status, NULL, NULL));
270 status = command(outbuf);
274 * If we didn't get a positive final response, then error out
275 * (that probably means we failed an authorization check).
282 * We _should_ be okay now. Get a few properties now that negotiation
286 result = sasl_getprop(conn, SASL_MAXOUTBUF, (const void **) &moutbuf);
288 if (result != SASL_OK) {
289 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
290 "output buffer size: %s", sasl_errdetail(conn));
294 maxoutbuf = *moutbuf;
296 result = sasl_getprop(conn, SASL_SSF, (const void **) &ssf);
300 if (result != SASL_OK) {
301 snprintf(response, sizeof(response), "Cannot retrieve SASL negotiated "
302 "security strength factor: %s", sasl_errdetail(conn));
307 * Limit this to what we can deal with. Shouldn't matter much because
308 * this is only outgoing data (which should be small)
311 if (maxoutbuf == 0 || maxoutbuf > BUFSIZ)
320 * Callback to return the userid sent down via the user parameter
324 sasl_get_user(void *context, int id, const char **result, unsigned *len)
326 char *user = (char *) context;
328 if (! result || id != SASL_CB_USER)
329 return SASL_BADPARAM;
339 * Callback to return the password (we call ruserpass, which can get it
344 sasl_get_pass(sasl_conn_t *conn, void *context, int id, sasl_secret_t **psecret)
348 struct pass_context *p_context = (struct pass_context *) context;
352 if (! psecret || id != SASL_CB_PASS)
353 return SASL_BADPARAM;
355 ruserpass(p_context->user, &(p_context->host), &pass);
359 *psecret = (sasl_secret_t *) mh_xmalloc(sizeof(sasl_secret_t) + len);
361 (*psecret)->len = len;
362 strcpy((char *) (*psecret)->data, pass);
366 #endif /* CYRUS_SASL */
370 * Split string containing proxy command into an array of arguments
371 * suitable for passing to exec. Returned array must be freed. Shouldn't
372 * be possible to call this with host set to NULL.
375 parse_proxy(char *proxy, char *host)
379 int hlen = strlen(host);
381 unsigned char *cur, *pro;
384 /* skip any initial space */
385 for (pro = (unsigned char *) proxy; isspace(*pro); pro++)
388 /* calculate required size for argument array */
389 for (cur = pro; *cur; cur++) {
390 if (isspace(*cur) && cur[1] && !isspace(cur[1]))
392 else if (*cur == '%' && cur[1] == 'h') {
395 } else if (!isspace(*cur))
399 /* put together list of arguments */
400 p = pargv = mh_xmalloc(pargc * sizeof(char *));
401 c = *pargv = mh_xmalloc(plen * sizeof(char));
402 for (cur = pro; *cur; cur++) {
403 if (isspace(*cur) && cur[1] && !isspace(cur[1])) {
406 } else if (*cur == '%' && cur[1] == 'h') {
410 } else if (!isspace(*cur))
418 pop_init (char *host, char *port, char *user, char *pass, char *proxy,
419 int snoop, int sasl, char *mech)
424 #endif /* ! CYRUS_SASL */
429 if (proxy && *proxy) {
431 int inpipe[2]; /* for reading from the server */
432 int outpipe[2]; /* for sending to the server */
434 /* first give up any root priviledges we may have for rpop */
447 dup2(outpipe[0],0); /* connect read end of connection */
448 dup2(inpipe[1], 1); /* connect write end of connection */
449 if(inpipe[0]>1) close(inpipe[0]);
450 if(inpipe[1]>1) close(inpipe[1]);
451 if(outpipe[0]>1) close(outpipe[0]);
452 if(outpipe[1]>1) close(outpipe[1]);
454 /* run the proxy command */
455 argv=parse_proxy(proxy, host);
456 execvp(argv[0],argv);
466 /* okay in the parent we do some stuff */
467 close(inpipe[1]); /* child uses this */
468 close(outpipe[0]); /* child uses this */
472 /* and write on fd2 */
477 if ((fd1 = client (host, port ? port : "pop3", response,
478 sizeof(response), snoop)) == NOTOK) {
482 if ((fd2 = dup (fd1)) == NOTOK) {
485 if ((s = strerror(errno)))
486 snprintf (response, sizeof(response),
487 "unable to dup connection descriptor: %s", s);
489 snprintf (response, sizeof(response),
490 "unable to dup connection descriptor: unknown error");
495 if (pop_set (fd1, fd2, snoop) == NOTOK)
498 SIGNAL (SIGPIPE, SIG_IGN);
500 switch (sasl_getline (response, sizeof response, input)) {
503 fprintf (stderr, "<--- %s\n", response);
504 if (*response == '+') {
507 if (pop_auth_sasl(user, host, mech) != NOTOK)
510 # endif /* CYRUS_SASL */
511 if (command ("USER %s", user) != NOTOK
512 && command ("%s %s", (pophack++, "PASS"),
516 strncpy (buffer, response, sizeof(buffer));
518 strncpy (response, buffer, sizeof(response));
524 fprintf (stderr, "%s\n", response);
530 return NOTOK; /* NOTREACHED */
534 pop_set (int in, int out, int snoop)
537 if ((input = fdopen (in, "r")) == NULL
538 || (output = fdopen (out, "w")) == NULL) {
539 strncpy (response, "fdopen failed on connection descriptor", sizeof(response));
555 pop_fd (char *in, int inlen, char *out, int outlen)
557 snprintf (in, inlen, "%d", fileno (input));
558 snprintf (out, outlen, "%d", fileno (output));
564 * Find out number of messages available
565 * and their total size.
569 pop_stat (int *nmsgs, int *nbytes)
572 if (command ("STAT") == NOTOK)
575 *nmsgs = *nbytes = 0;
576 sscanf (response, "+OK %d %d", nmsgs, nbytes);
583 pop_list (int msgno, int *nmsgs, int *msgs, int *bytes)
589 if (command ("LIST %d", msgno) == NOTOK)
594 sscanf (response, "+OK %d %d %d", msgs, bytes, ids);
597 sscanf (response, "+OK %d %d", msgs, bytes);
601 if (command ("LIST") == NOTOK)
604 for (i = 0; i < *nmsgs; i++)
605 switch (multiline ()) {
615 sscanf (response, "%d %d %d",
616 msgs++, bytes++, ids++);
619 sscanf (response, "%d %d", msgs++, bytes++);
623 switch (multiline ()) {
635 pop_retr (int msgno, int (*action)(char *))
637 return traverse (action, "RETR %d", msgno);
642 traverse (int (*action)(char *), const char *fmt, ...)
646 char buffer[sizeof(response)];
649 result = vcommand (fmt, ap);
654 strncpy (buffer, response, sizeof(buffer));
657 switch (multiline ()) {
662 strncpy (response, buffer, sizeof(response));
666 (*action) (response);
675 return command ("DELE %d", msgno);
682 return command ("NOOP");
689 return command ("RSET");
694 pop_top (int msgno, int lines, int (*action)(char *))
696 return traverse (action, "TOP %d %d", msgno, lines);
705 i = command ("QUIT");
718 #endif /* CYRUS_SASL */
727 command(const char *fmt, ...)
733 result = vcommand(fmt, ap);
741 vcommand (const char *fmt, va_list ap)
743 char *cp, buffer[BUFSIZ];
745 vsnprintf (buffer, sizeof(buffer), fmt, ap);
749 fprintf(stderr, "(encrypted) ");
750 #endif /* CYRUS_SASL */
752 if ((cp = strchr (buffer, ' ')))
754 fprintf (stderr, "---> %s ********\n", buffer);
760 fprintf (stderr, "---> %s\n", buffer);
763 if (putline (buffer, output) == NOTOK)
767 if (poprint && sasl_ssf)
768 fprintf(stderr, "(decrypted) ");
769 #endif /* CYRUS_SASL */
771 switch (sasl_getline (response, sizeof response, input)) {
774 fprintf (stderr, "<--- %s\n", response);
775 return (*response == '+' ? OK : NOTOK);
780 fprintf (stderr, "%s\n", response);
784 return NOTOK; /* NOTREACHED */
791 char buffer[BUFSIZ + TRMLEN];
793 if (sasl_getline (buffer, sizeof buffer, input) != OK)
799 fprintf(stderr, "(decrypted) ");
800 #endif /* CYRUS_SASL */
801 fprintf (stderr, "<--- %s\n", response);
804 if (strncmp (buffer, TRM, TRMLEN) == 0) {
805 if (buffer[TRMLEN] == 0)
808 strncpy (response, buffer + TRMLEN, sizeof(response));
811 strncpy (response, buffer, sizeof(response));
817 * Note that these functions have been modified to deal with layer encryption
822 sasl_getline (char *s, int n, FILE *iop)
828 while (--n > 0 && (c = sasl_fgetc (iop)) != EOF && c != -2)
829 if ((*p++ = c) == '\n')
833 if (ferror (iop) && c != EOF) {
834 strncpy (response, "error on connection", sizeof(response));
837 if (c == EOF && p == s) {
838 strncpy (response, "connection closed by foreign host", sizeof(response));
852 putline (char *s, FILE *iop)
855 char outbuf[BUFSIZ], *buf;
859 if (!sasl_complete) {
860 #endif /* CYRUS_SASL */
861 fprintf (iop, "%s\r\n", s);
865 * Build an output buffer, encrypt it using sasl_encode, and
866 * squirt out the results.
868 strncpy(outbuf, s, sizeof(outbuf) - 3);
869 outbuf[sizeof(outbuf) - 3] = '\0'; /* Just in case */
870 strcat(outbuf, "\r\n");
872 result = sasl_encode(conn, outbuf, strlen(outbuf),
873 (const char **) &buf, &buflen);
875 if (result != SASL_OK) {
876 snprintf(response, sizeof(response), "SASL encoding error: %s",
877 sasl_errdetail(conn));
881 fwrite(buf, buflen, 1, iop);
883 #endif /* CYRUS_SASL */
887 strncpy (response, "lost connection", sizeof(response));
896 * Okay, our little fgetc replacement. Hopefully this is a little more
897 * efficient than the last one.
902 static unsigned char *buffer = NULL, *ptr;
903 static unsigned int size = 0;
905 unsigned int retbufsize = 0;
907 char *retbuf, tmpbuf[SASL_BUFFER_SIZE];
910 * If we have some leftover data, return that
919 * Otherwise, fill our buffer until we have some data to return.
922 while (retbufsize == 0) {
924 cc = read(fileno(f), tmpbuf, sizeof(tmpbuf));
930 snprintf(response, sizeof(response), "Error during read from "
931 "network: %s", strerror(errno));
936 * We're not allowed to call sasl_decode until sasl_complete is
937 * true, so we do these gyrations ...
940 if (!sasl_complete) {
947 result = sasl_decode(conn, tmpbuf, cc,
948 (const char **) &retbuf, &retbufsize);
950 if (result != SASL_OK) {
951 snprintf(response, sizeof(response), "Error during SASL "
952 "decoding: %s", sasl_errdetail(conn));
958 if (retbufsize > size) {
959 buffer = mh_xrealloc(buffer, retbufsize);
963 memcpy(buffer, retbuf, retbufsize);
965 cnt = retbufsize - 1;
967 return (int) buffer[0];
969 #endif /* CYRUS_SASL */