Ensure reproducable environment..
[s-mailx.git] / urlcrecry.c
blob65158a51b2f1a8b71c72c396a992505424c8d5b6
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ URL parsing, credential handling and crypto hooks.
3 *@ .netrc parser quite loosely based upon NetBSD usr.bin/ftp/
4 *@ $NetBSD: ruserpass.c,v 1.33 2007/04/17 05:52:04 lukem Exp $
6 * Copyright (c) 2014 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
8 * Permission to use, copy, modify, and/or distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #undef n_FILE
21 #define n_FILE urlcrecry
23 #ifndef HAVE_AMALGAMATION
24 # include "nail.h"
25 #endif
27 #ifdef HAVE_NETRC
28 /* NetBSD usr.bin/ftp/ruserpass.c uses 100 bytes for that, we need four
29 * concurrently (dummy, host, user, pass), so make it a KB */
30 # define NRC_TOKEN_MAXLEN (1024 / 4)
32 enum nrc_token {
33 NRC_ERROR = -1,
34 NRC_NONE = 0,
35 NRC_DEFAULT,
36 NRC_LOGIN,
37 NRC_PASSWORD,
38 NRC_ACCOUNT,
39 NRC_MACDEF,
40 NRC_MACHINE,
41 NRC_INPUT
44 struct nrc_node {
45 struct nrc_node *nrc_next;
46 struct nrc_node *nrc_result; /* In match phase, former possible one */
47 ui32_t nrc_mlen; /* Length of machine name */
48 ui32_t nrc_ulen; /* Length of user name */
49 ui32_t nrc_plen; /* Length of password */
50 char nrc_dat[VFIELD_SIZE(sizeof(ui32_t))];
52 # define NRC_NODE_ERR ((struct nrc_node*)-1)
54 static struct nrc_node *_nrc_list;
55 #endif /* HAVE_NETRC */
57 /* Find the last @ before a slash
58 * TODO Casts off the const but this is ok here; obsolete function! */
59 #ifdef HAVE_SOCKETS /* temporary (we'll have file://..) */
60 static char * _url_last_at_before_slash(char const *sp);
61 #endif
63 #ifdef HAVE_NETRC
64 /* Initialize .netrc cache */
65 static void _nrc_init(void);
66 static enum nrc_token __nrc_token(FILE *fi, char buffer[NRC_TOKEN_MAXLEN],
67 bool_t *nl_last);
69 /* We shall lookup a machine in .netrc says ok_blook(netrc_lookup).
70 * only_pass is true then the lookup is for the password only, otherwise we
71 * look for a user (and add password only if we have an exact machine match) */
72 static bool_t _nrc_lookup(struct url *urlp, bool_t only_pass);
74 /* 0=no match; 1=exact match; -1=wildcard match */
75 static int __nrc_host_match(struct nrc_node const *nrc,
76 struct url const *urlp);
77 static bool_t __nrc_find_user(struct url *urlp,
78 struct nrc_node const *nrc);
79 static bool_t __nrc_find_pass(struct url *urlp, bool_t user_match,
80 struct nrc_node const *nrc);
81 #endif /* HAVE_NETRC */
83 /* The password can also be gained through external agents TODO v15-compat */
84 #ifdef HAVE_AGENT
85 static bool_t _agent_shell_lookup(struct url *urlp, char const *comm);
86 #endif
88 #ifdef HAVE_SOCKETS
89 static char *
90 _url_last_at_before_slash(char const *sp)
92 char const *cp;
93 char c;
94 NYD2_ENTER;
96 for (cp = sp; (c = *cp) != '\0'; ++cp)
97 if (c == '/')
98 break;
99 while (cp > sp && *--cp != '@')
101 if (*cp != '@')
102 cp = NULL;
103 NYD2_LEAVE;
104 return UNCONST(cp);
106 #endif
108 #ifdef HAVE_NETRC
109 static void
110 _nrc_init(void)
112 struct n_sigman sm;
113 char buffer[NRC_TOKEN_MAXLEN], host[NRC_TOKEN_MAXLEN],
114 user[NRC_TOKEN_MAXLEN], pass[NRC_TOKEN_MAXLEN], *netrc_load;
115 struct stat sb;
116 FILE *fi;
117 enum nrc_token t;
118 bool_t ispipe, seen_default, nl_last;
119 struct nrc_node *ntail, *nhead, *nrc;
120 NYD_ENTER;
122 UNINIT(ntail, NULL);
123 nhead = NULL;
124 nrc = NRC_NODE_ERR;
125 ispipe = FAL0;
126 fi = NULL;
128 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL) {
129 case 0:
130 break;
131 default:
132 goto jleave;
135 if ((netrc_load = ok_vlook(netrc_pipe)) != NULL) {
136 ispipe = TRU1;
137 if ((fi = Popen(netrc_load, "r", ok_vlook(SHELL), NULL, COMMAND_FD_NULL)
138 ) == NULL) {
139 n_perr(netrc_load, 0);
140 goto j_leave;
142 } else {
143 if ((netrc_load = file_expand(ok_vlook(NETRC))) == NULL)
144 goto j_leave;
146 if ((fi = Fopen(netrc_load, "r")) == NULL) {
147 n_err(_("Cannot open \"%s\"\n"), netrc_load);
148 goto j_leave;
151 /* Be simple and apply rigid (permission) check(s) */
152 if (fstat(fileno(fi), &sb) == -1 || !S_ISREG(sb.st_mode) ||
153 (sb.st_mode & (S_IRWXG | S_IRWXO))) {
154 n_err(_("Not a regular file, or accessible by non-user: \"%s\"\n"),
155 netrc_load);
156 goto jleave;
160 seen_default = FAL0;
161 nl_last = TRU1;
162 jnext:
163 switch((t = __nrc_token(fi, buffer, &nl_last))) {
164 case NRC_NONE:
165 break;
166 default: /* Doesn't happen (but on error?), keep CC happy */
167 case NRC_DEFAULT:
168 jdef:
169 /* We ignore the default entry (require an exact host match), and we also
170 * ignore anything after such an entry (faulty syntax) */
171 seen_default = TRU1;
172 /* FALLTHRU */
173 case NRC_MACHINE:
174 jm_h:
175 /* Normalize HOST to lowercase */
176 *host = '\0';
177 if (!seen_default && (t = __nrc_token(fi, host, &nl_last)) != NRC_INPUT)
178 goto jerr;
179 else {
180 char *cp;
181 for (cp = host; *cp != '\0'; ++cp)
182 *cp = lowerconv(*cp);
185 *user = *pass = '\0';
186 while ((t = __nrc_token(fi, buffer, &nl_last)) != NRC_NONE &&
187 t != NRC_MACHINE && t != NRC_DEFAULT) {
188 switch(t) {
189 case NRC_LOGIN:
190 if ((t = __nrc_token(fi, user, &nl_last)) != NRC_INPUT)
191 goto jerr;
192 break;
193 case NRC_PASSWORD:
194 if ((t = __nrc_token(fi, pass, &nl_last)) != NRC_INPUT)
195 goto jerr;
196 break;
197 case NRC_ACCOUNT:
198 if ((t = __nrc_token(fi, buffer, &nl_last)) != NRC_INPUT)
199 goto jerr;
200 break;
201 case NRC_MACDEF:
202 if ((t = __nrc_token(fi, buffer, &nl_last)) != NRC_INPUT)
203 goto jerr;
204 else {
205 int i = 0, c;
206 while ((c = getc(fi)) != EOF)
207 if (c == '\n') { /* xxx */
208 /* Don't care about comments here, since we parse until
209 * we've seen two successive newline characters */
210 if (i)
211 break;
212 i = 1;
213 } else
214 i = 0;
216 break;
217 default:
218 case NRC_ERROR:
219 goto jerr;
223 if (!seen_default && (*user != '\0' || *pass != '\0')) {
224 size_t hl = strlen(host), ul = strlen(user), pl = strlen(pass);
225 struct nrc_node *nx = smalloc(sizeof(*nx) -
226 VFIELD_SIZEOF(struct nrc_node, nrc_dat) + hl +1 + ul +1 + pl +1);
228 if (nhead != NULL)
229 ntail->nrc_next = nx;
230 else
231 nhead = nx;
232 ntail = nx;
233 nx->nrc_next = NULL;
234 nx->nrc_mlen = hl;
235 nx->nrc_ulen = ul;
236 nx->nrc_plen = pl;
237 memcpy(nx->nrc_dat, host, ++hl);
238 memcpy(nx->nrc_dat + hl, user, ++ul);
239 memcpy(nx->nrc_dat + hl + ul, pass, ++pl);
241 if (t == NRC_MACHINE)
242 goto jm_h;
243 if (t == NRC_DEFAULT)
244 goto jdef;
245 if (t != NRC_NONE)
246 goto jnext;
247 break;
248 case NRC_ERROR:
249 jerr:
250 if (options & OPT_D_V)
251 n_err(_("Errors occurred while parsing \"%s\"\n"), netrc_load);
252 assert(nrc == NRC_NODE_ERR);
253 goto jleave;
256 if (nhead != NULL)
257 nrc = nhead;
258 n_sigman_cleanup_ping(&sm);
259 jleave:
260 if (fi != NULL) {
261 if (ispipe)
262 Pclose(fi, TRU1);
263 else
264 Fclose(fi);
266 if (nrc == NRC_NODE_ERR)
267 while (nhead != NULL) {
268 ntail = nhead;
269 nhead = nhead->nrc_next;
270 free(ntail);
272 j_leave:
273 _nrc_list = nrc;
274 NYD_LEAVE;
275 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
278 static enum nrc_token
279 __nrc_token(FILE *fi, char buffer[NRC_TOKEN_MAXLEN], bool_t *nl_last)
281 int c;
282 char *cp;
283 enum nrc_token rv;
284 NYD2_ENTER;
286 rv = NRC_NONE;
287 for (;;) {
288 bool_t seen_nl;
290 c = EOF;
291 if (feof(fi) || ferror(fi))
292 goto jleave;
294 for (seen_nl = *nl_last; (c = getc(fi)) != EOF && whitechar(c);)
295 seen_nl |= (c == '\n');
297 if (c == EOF)
298 goto jleave;
299 /* fetchmail and derived parsers support comments */
300 if ((*nl_last = seen_nl) && c == '#') {
301 while ((c = getc(fi)) != EOF && c != '\n')
303 continue;
305 break;
308 cp = buffer;
309 /* Is it a quoted token? At least IBM syntax also supports ' quotes */
310 if (c == '"' || c == '\'') {
311 int quotec = c;
313 /* Not requiring the closing QM is (Net)BSD syntax */
314 while ((c = getc(fi)) != EOF && c != quotec) {
315 /* Backslash escaping the next character is (Net)BSD syntax */
316 if (c == '\\')
317 if ((c = getc(fi)) == EOF)
318 break;
319 *cp++ = c;
320 if (PTRCMP(cp, ==, buffer + NRC_TOKEN_MAXLEN)) {
321 rv = NRC_ERROR;
322 goto jleave;
325 } else {
326 *cp++ = c;
327 while ((c = getc(fi)) != EOF && !whitechar(c)) {
328 /* Backslash escaping the next character is (Net)BSD syntax */
329 if (c == '\\' && (c = getc(fi)) == EOF)
330 break;
331 *cp++ = c;
332 if (PTRCMP(cp, ==, buffer + NRC_TOKEN_MAXLEN)) {
333 rv = NRC_ERROR;
334 goto jleave;
337 *nl_last = (c == '\n');
339 *cp = '\0';
341 if (*buffer == '\0')
342 do {/*rv = NRC_NONE*/} while (0);
343 else if (!strcmp(buffer, "default"))
344 rv = NRC_DEFAULT;
345 else if (!strcmp(buffer, "login"))
346 rv = NRC_LOGIN;
347 else if (!strcmp(buffer, "password") || !strcmp(buffer, "passwd"))
348 rv = NRC_PASSWORD;
349 else if (!strcmp(buffer, "account"))
350 rv = NRC_ACCOUNT;
351 else if (!strcmp(buffer, "macdef"))
352 rv = NRC_MACDEF;
353 else if (!strcmp(buffer, "machine"))
354 rv = NRC_MACHINE;
355 else
356 rv = NRC_INPUT;
357 jleave:
358 if (c == EOF && !feof(fi))
359 rv = NRC_ERROR;
360 NYD2_LEAVE;
361 return rv;
364 static bool_t
365 _nrc_lookup(struct url *urlp, bool_t only_pass)
367 struct nrc_node *nrc, *nrc_wild, *nrc_exact;
368 bool_t rv = FAL0;
369 NYD_ENTER;
371 assert(!only_pass || urlp->url_user.s != NULL);
372 assert(only_pass || urlp->url_user.s == NULL);
374 if (_nrc_list == NULL)
375 _nrc_init();
376 if (_nrc_list == NRC_NODE_ERR)
377 goto jleave;
379 nrc_wild = nrc_exact = NULL;
380 for (nrc = _nrc_list; nrc != NULL; nrc = nrc->nrc_next)
381 switch (__nrc_host_match(nrc, urlp)) {
382 case 1:
383 nrc->nrc_result = nrc_exact;
384 nrc_exact = nrc;
385 continue;
386 case -1:
387 nrc->nrc_result = nrc_wild;
388 nrc_wild = nrc;
389 /* FALLTHRU */
390 case 0:
391 continue;
394 if (!only_pass && urlp->url_user.s == NULL) {
395 /* Must be an unambiguous entry of its kind */
396 if (nrc_exact != NULL && nrc_exact->nrc_result != NULL)
397 goto jleave;
398 if (__nrc_find_user(urlp, nrc_exact))
399 goto j_user;
401 if (nrc_wild != NULL && nrc_wild->nrc_result != NULL)
402 goto jleave;
403 if (!__nrc_find_user(urlp, nrc_wild))
404 goto jleave;
405 j_user:
409 if (__nrc_find_pass(urlp, TRU1, nrc_exact) ||
410 __nrc_find_pass(urlp, TRU1, nrc_wild) ||
411 /* Do not try to find a password without exact user match unless we've
412 * been called during credential lookup, a.k.a. the second time */
413 !only_pass ||
414 __nrc_find_pass(urlp, FAL0, nrc_exact) ||
415 __nrc_find_pass(urlp, FAL0, nrc_wild))
416 rv = TRU1;
417 jleave:
418 NYD_LEAVE;
419 return rv;
422 static int
423 __nrc_host_match(struct nrc_node const *nrc, struct url const *urlp)
425 char const *d2, *d1;
426 size_t l2, l1;
427 int rv = 0;
428 NYD2_ENTER;
430 /* Find a matching machine -- entries are all lowercase normalized */
431 if (nrc->nrc_mlen == urlp->url_host.l) {
432 if (LIKELY(!memcmp(nrc->nrc_dat, urlp->url_host.s, urlp->url_host.l)))
433 rv = 1;
434 goto jleave;
437 /* Cannot be an exact match, but maybe the .netrc machine starts with
438 * a "*." glob, which we recognize as an extension, meaning "skip
439 * a single subdomain, then match the rest" */
440 d1 = nrc->nrc_dat + 2;
441 l1 = nrc->nrc_mlen;
442 if (l1 <= 2 || d1[-1] != '.' || d1[-2] != '*')
443 goto jleave;
444 l1 -= 2;
446 /* Brute skipping over one subdomain, no RFC 1035 or RFC 1122 checks;
447 * in fact this even succeeds for ".host.com", but - why care, here? */
448 d2 = urlp->url_host.s;
449 l2 = urlp->url_host.l;
450 while (l2 > 0) {
451 --l2;
452 if (*d2++ == '.')
453 break;
456 if (l2 == l1 && !memcmp(d1, d2, l1))
457 /* This matches, but we won't use it directly but watch out for an
458 * exact match first! */
459 rv = -1;
460 jleave:
461 NYD2_LEAVE;
462 return rv;
465 static bool_t
466 __nrc_find_user(struct url *urlp, struct nrc_node const *nrc)
468 NYD2_ENTER;
470 for (; nrc != NULL; nrc = nrc->nrc_result)
471 if (nrc->nrc_ulen > 0) {
472 /* Fake it was part of URL otherwise XXX */
473 urlp->url_had_user = TRU1;
474 /* That buffer will be duplicated by url_parse() in this case! */
475 urlp->url_user.s = UNCONST(nrc->nrc_dat + nrc->nrc_mlen +1);
476 urlp->url_user.l = nrc->nrc_ulen;
477 break;
480 NYD2_LEAVE;
481 return (nrc != NULL);
484 static bool_t
485 __nrc_find_pass(struct url *urlp, bool_t user_match, struct nrc_node const *nrc)
487 NYD2_ENTER;
489 for (; nrc != NULL; nrc = nrc->nrc_result) {
490 bool_t um = (nrc->nrc_ulen == urlp->url_user.l &&
491 !memcmp(nrc->nrc_dat + nrc->nrc_mlen +1, urlp->url_user.s,
492 urlp->url_user.l));
494 if (user_match) {
495 if (!um)
496 continue;
497 } else if (!um && nrc->nrc_ulen > 0)
498 continue;
499 if (nrc->nrc_plen == 0)
500 continue;
502 /* We are responsible for duplicating this buffer! */
503 urlp->url_pass.s = savestrbuf(nrc->nrc_dat + nrc->nrc_mlen +1 +
504 nrc->nrc_ulen + 1, (urlp->url_pass.l = nrc->nrc_plen));
505 break;
508 NYD2_LEAVE;
509 return (nrc != NULL);
511 #endif /* HAVE_NETRC */
513 #ifdef HAVE_AGENT
514 static bool_t
515 _agent_shell_lookup(struct url *urlp, char const *comm) /* TODO v15-compat */
517 char buf[128];
518 char const *env_addon[8];
519 struct str s;
520 FILE *pbuf;
521 union {char const *cp; int c; sighandler_type sht;} u;
522 size_t cl, l;
523 bool_t rv = FAL0;
524 NYD2_ENTER;
526 env_addon[0] = str_concat_csvl(&s, AGENT_USER, "=", urlp->url_user.s,
527 NULL)->s;
528 env_addon[1] = str_concat_csvl(&s, AGENT_USER_ENC, "=", urlp->url_user_enc.s,
529 NULL)->s;
530 env_addon[2] = str_concat_csvl(&s, AGENT_HOST, "=", urlp->url_host.s,
531 NULL)->s;
532 env_addon[3] = str_concat_csvl(&s, AGENT_HOST_PORT, "=", urlp->url_h_p.s,
533 NULL)->s;
535 env_addon[4] = str_concat_csvl(&s, NAILENV_TMPDIR, "=", tempdir, NULL)->s;
536 env_addon[5] = str_concat_csvl(&s, "TMPDIR", "=", tempdir, NULL)->s;
538 env_addon[6] = NULL;
540 if ((pbuf = Popen(comm, "r", ok_vlook(SHELL), env_addon, -1)) == NULL) {
541 n_err(_("*agent-shell-lookup* startup failed (\"%s\")\n"), comm);
542 goto jleave;
545 for (s.s = NULL, s.l = cl = l = 0; (u.c = getc(pbuf)) != EOF; ++cl) {
546 if (u.c == '\n') /* xxx */
547 continue;
548 buf[l++] = u.c;
549 if (l == sizeof(buf) - 1) {
550 n_str_add_buf(&s, buf, l);
551 l = 0;
554 if (l > 0)
555 n_str_add_buf(&s, buf, l);
557 if (!Pclose(pbuf, TRU1)) {
558 n_err(_("*agent-shell-lookup* execution failure (\"%s\")\n"), comm);
559 goto jleave;
562 /* We are responsible for duplicating this buffer! */
563 if (s.s != NULL)
564 urlp->url_pass.s = savestrbuf(s.s, urlp->url_pass.l = s.l);
565 else if (cl > 0)
566 urlp->url_pass.s = UNCONST(""), urlp->url_pass.l = 0;
567 rv = TRU1;
568 jleave:
569 if (s.s != NULL)
570 free(s.s);
571 NYD2_LEAVE;
572 return rv;
574 #endif /* HAVE_AGENT */
576 FL char *
577 (urlxenc)(char const *cp, bool_t ispath SALLOC_DEBUG_ARGS)
579 char *n, *np, c1;
580 NYD2_ENTER;
582 np = n = (salloc)(strlen(cp) * 3 +1 SALLOC_DEBUG_ARGSCALL);
584 for (; (c1 = *cp) != '\0'; ++cp) {
585 /* (RFC 1738) RFC 3986, 2.3 Unreserved Characters:
586 * ALPHA / DIGIT / "-" / "." / "_" / "~"
587 * However add a special is[file]path mode for file-system friendliness */
588 if (alnumchar(c1) || c1 == '_')
589 *np++ = c1;
590 else if (!ispath) {
591 if (c1 != '-' && c1 != '.' && c1 != '~')
592 goto jesc;
593 *np++ = c1;
594 } else if (PTRCMP(np, >, n) && (*cp == '-' || *cp == '.')) /* XXX imap */
595 *np++ = c1;
596 else {
597 jesc:
598 np[0] = '%';
599 n_c_to_hex_base16(np + 1, c1);
600 np += 3;
603 *np = '\0';
604 NYD2_LEAVE;
605 return n;
608 FL char *
609 (urlxdec)(char const *cp SALLOC_DEBUG_ARGS)
611 char *n, *np;
612 si32_t c;
613 NYD2_ENTER;
615 np = n = (salloc)(strlen(cp) +1 SALLOC_DEBUG_ARGSCALL);
617 while ((c = (uc_i)*cp++) != '\0') {
618 if (c == '%' && cp[0] != '\0' && cp[1] != '\0') {
619 si32_t o = c;
620 if (LIKELY((c = n_c_from_hex_base16(cp)) >= '\0'))
621 cp += 2;
622 else
623 c = o;
625 *np++ = (char)c;
627 *np = '\0';
628 NYD2_LEAVE;
629 return n;
632 #ifdef HAVE_SOCKETS /* Note: not indented for that -- later: file:// etc.! */
633 FL char const *
634 url_servbyname(struct url const *urlp, ui16_t *irv_or_null)
636 static struct {
637 char const name[14];
638 char const port[8];
639 ui16_t portno;
640 } const tbl[] = {
641 { "smtp", "25", 25},
642 { "submission", "587", 587},
643 { "smtps", "465", 465},
644 { "pop3", "110", 110},
645 { "pop3s", "995", 995},
646 { "imap", "143", 143},
647 { "imaps", "993", 993}
649 char const *rv;
650 size_t i;
651 NYD_ENTER;
653 for (rv = NULL, i = 0; i < NELEM(tbl); ++i)
654 if (!asccasecmp(tbl[i].name, urlp->url_proto)) {
655 rv = tbl[i].port;
656 if (irv_or_null != NULL)
657 *irv_or_null = tbl[i].portno;
658 break;
660 NYD_LEAVE;
661 return rv;
664 FL bool_t
665 url_parse(struct url *urlp, enum cproto cproto, char const *data)
667 #if defined HAVE_SMTP && defined HAVE_POP3
668 # define __ALLPROTO
669 #endif
670 #if defined HAVE_SMTP || defined HAVE_POP3
671 # define __ANYPROTO
672 char *cp, *x;
673 #endif
674 bool_t rv = FAL0;
675 NYD_ENTER;
676 UNUSED(data);
678 memset(urlp, 0, sizeof *urlp);
679 urlp->url_input = data;
680 urlp->url_cproto = cproto;
682 /* Network protocol */
683 #define _protox(X,Y) \
684 urlp->url_portno = Y;\
685 memcpy(urlp->url_proto, X "://", sizeof(X "://"));\
686 urlp->url_proto[sizeof(X) -1] = '\0';\
687 urlp->url_proto_len = sizeof(X) -1;\
688 urlp->url_proto_xlen = sizeof(X "://") -1
689 #define __if(X,Y,Z) \
690 if (!ascncasecmp(data, X "://", sizeof(X "://") -1)) {\
691 _protox(X, Y);\
692 data += sizeof(X "://") -1;\
693 do { Z; } while (0);\
694 goto juser;\
696 #define _if(X,Y) __if(X, Y, (void)0)
697 #ifdef HAVE_SSL
698 # define _ifs(X,Y) __if(X, Y, urlp->url_needs_tls = TRU1)
699 #else
700 # define _ifs(X,Y) goto jeproto;
701 #endif
703 switch (cproto) {
704 case CPROTO_SMTP:
705 #ifdef HAVE_SMTP
706 _if ("smtp", 25)
707 _if ("submission", 587)
708 _ifs ("smtps", 465)
709 _protox("smtp", 25);
710 break;
711 #else
712 goto jeproto;
713 #endif
714 case CPROTO_POP3:
715 #ifdef HAVE_POP3
716 _if ("pop3", 110)
717 _ifs ("pop3s", 995)
718 _protox("pop3", 110);
719 break;
720 #else
721 goto jeproto;
722 #endif
723 #if 0
724 case CPROTO_IMAP:
725 _if ("imap", 143)
726 _ifs ("imaps", 993)
727 _protox("imap", 143);
728 break;
729 goto jeproto;
730 #endif
733 #undef _ifs
734 #undef _if
735 #undef __if
736 #undef _protox
738 if (strstr(data, "://") != NULL) {
739 #if !defined __ALLPROTO || !defined HAVE_SSL
740 jeproto:
741 #endif
742 n_err(_("URL \"proto://\" prefix invalid: \"%s\"\n"), urlp->url_input);
743 goto jleave;
745 #ifdef __ANYPROTO
747 /* User and password, I */
748 juser:
749 if ((cp = _url_last_at_before_slash(data)) != NULL) {
750 size_t l = PTR2SIZE(cp - data);
751 char const *d = data;
752 char *ub = ac_alloc(l +1);
754 urlp->url_had_user = TRU1;
755 data = cp + 1;
757 /* And also have a password? */
758 if ((cp = memchr(d, ':', l)) != NULL) {
759 size_t i = PTR2SIZE(cp - d);
761 l -= i + 1;
762 memcpy(ub, cp + 1, l);
763 ub[l] = '\0';
764 urlp->url_pass.l = strlen(urlp->url_pass.s = urlxdec(ub));
766 if (strcmp(ub, urlxenc(urlp->url_pass.s, FAL0))) {
767 n_err(_("String is not properly URL percent encoded: \"%s\"\n"),
768 ub);
769 goto jleave;
771 l = i;
774 memcpy(ub, d, l);
775 ub[l] = '\0';
776 urlp->url_user.l = strlen(urlp->url_user.s = urlxdec(ub));
777 urlp->url_user_enc.l = strlen(
778 urlp->url_user_enc.s = urlxenc(urlp->url_user.s, FAL0));
780 if (urlp->url_user_enc.l != l || memcmp(urlp->url_user_enc.s, ub, l)) {
781 n_err(_("String is not properly URL percent encoded: \"%s\"\n"), ub);
782 goto jleave;
785 ac_free(ub);
788 /* Servername and port -- and possible path suffix */
789 if ((cp = strchr(data, ':')) != NULL) { /* TODO URL parse, IPv6 support */
790 char *eptr;
791 long l;
793 urlp->url_port = x = savestr(x = cp + 1);
794 if ((x = strchr(x, '/')) != NULL)
795 *x = '\0';
796 l = strtol(urlp->url_port, &eptr, 10);
797 if (*eptr != '\0' || l <= 0 || UICMP(32, l, >=, 0xFFFFu)) {
798 n_err(_("URL with invalid port number: \"%s\"\n"), urlp->url_input);
799 goto jleave;
801 urlp->url_portno = (ui16_t)l;
802 } else {
803 if ((x = strchr(data, '/')) != NULL)
804 data = savestrbuf(data, PTR2SIZE(x - data));
805 cp = UNCONST(data + strlen(data));
808 /* A (non-empty) path may only occur with IMAP */
809 if (x != NULL && x[1] != '\0') {
810 #if 0
811 if (cproto != CPROTO_IMAP) {
812 #endif
813 n_err(_("URL protocol doesn't support paths: \"%s\"\n"),
814 urlp->url_input);
815 goto jleave;
816 #if 0
818 urlp->url_path.l = strlen(++x);
819 urlp->url_path.s = savestrbuf(x, urlp->url_path.l);
820 #endif
823 urlp->url_host.s = savestrbuf(data, urlp->url_host.l = PTR2SIZE(cp - data));
824 { size_t i;
825 for (cp = urlp->url_host.s, i = urlp->url_host.l; i != 0; ++cp, --i)
826 *cp = lowerconv(*cp);
829 /* .url_h_p: HOST:PORT */
830 { size_t i;
831 struct str *s = &urlp->url_h_p;
833 s->s = salloc(urlp->url_host.l + 1 + sizeof("65536")-1 +1);
834 memcpy(s->s, urlp->url_host.s, i = urlp->url_host.l);
835 if (urlp->url_port != NULL) {
836 size_t j = strlen(urlp->url_port);
837 s->s[i++] = ':';
838 memcpy(s->s + i, urlp->url_port, j);
839 i += j;
841 s->s[i] = '\0';
842 s->l = i;
845 /* User, II
846 * If there was no user in the URL, do we have *user-HOST* or *user*? */
847 if (!urlp->url_had_user) {
848 if ((urlp->url_user.s = xok_vlook(user, urlp, OXM_PLAIN | OXM_H_P))
849 == NULL) {
850 /* No, check wether .netrc lookup is desired */
851 # ifdef HAVE_NETRC
852 if (!ok_blook(v15_compat) ||
853 !xok_blook(netrc_lookup, urlp, OXM_PLAIN | OXM_H_P) ||
854 !_nrc_lookup(urlp, FAL0))
855 # endif
856 urlp->url_user.s = UNCONST(myname);
859 urlp->url_user.l = strlen(urlp->url_user.s);
860 urlp->url_user.s = savestrbuf(urlp->url_user.s, urlp->url_user.l);
861 urlp->url_user_enc.l = strlen(
862 urlp->url_user_enc.s = urlxenc(urlp->url_user.s, FAL0));
865 /* And then there are a lot of prebuild string combinations TODO do lazy */
867 /* .url_u_h: .url_user@.url_host
868 * For SMTP we apply ridiculously complicated *v15-compat* plus
869 * *smtp-hostname* / *hostname* dependent rules */
870 { struct str h, *s;
871 size_t i;
873 if (cproto == CPROTO_SMTP && ok_blook(v15_compat) &&
874 (cp = ok_vlook(smtp_hostname)) != NULL) {
875 if (*cp == '\0')
876 cp = nodename(1);
877 h.s = savestrbuf(cp, h.l = strlen(cp));
878 } else
879 h = urlp->url_host;
881 s = &urlp->url_u_h;
882 i = urlp->url_user.l;
884 s->s = salloc(i + 1 + h.l +1);
885 if (i > 0) {
886 memcpy(s->s, urlp->url_user.s, i);
887 s->s[i++] = '@';
889 memcpy(s->s + i, h.s, h.l +1);
890 i += h.l;
891 s->l = i;
894 /* .url_u_h_p: .url_user@.url_host[:.url_port] */
895 { struct str *s = &urlp->url_u_h_p;
896 size_t i = urlp->url_user.l;
898 s->s = salloc(i + 1 + urlp->url_h_p.l +1);
899 if (i > 0) {
900 memcpy(s->s, urlp->url_user.s, i);
901 s->s[i++] = '@';
903 memcpy(s->s + i, urlp->url_h_p.s, urlp->url_h_p.l +1);
904 i += urlp->url_h_p.l;
905 s->l = i;
908 /* .url_eu_h_p: .url_user_enc@.url_host[:.url_port] */
909 { struct str *s = &urlp->url_eu_h_p;
910 size_t i = urlp->url_user_enc.l;
912 s->s = salloc(i + 1 + urlp->url_h_p.l +1);
913 if (i > 0) {
914 memcpy(s->s, urlp->url_user_enc.s, i);
915 s->s[i++] = '@';
917 memcpy(s->s + i, urlp->url_h_p.s, urlp->url_h_p.l +1);
918 i += urlp->url_h_p.l;
919 s->l = i;
922 /* .url_p_u_h_p: .url_proto://.url_u_h_p */
923 { size_t i;
924 char *ud = salloc((i = urlp->url_proto_xlen + urlp->url_u_h_p.l) +1);
926 urlp->url_proto[urlp->url_proto_len] = ':';
927 memcpy(sstpcpy(ud, urlp->url_proto), urlp->url_u_h_p.s,
928 urlp->url_u_h_p.l +1);
929 urlp->url_proto[urlp->url_proto_len] = '\0';
931 urlp->url_p_u_h_p = ud;
934 /* .url_p_eu_h_p, .url_p_eu_h_p_p: .url_proto://.url_eu_h_p[/.url_path] */
935 { size_t i;
936 char *ud = salloc((i = urlp->url_proto_xlen + urlp->url_eu_h_p.l) +
937 1 + urlp->url_path.l +1);
939 urlp->url_proto[urlp->url_proto_len] = ':';
940 memcpy(sstpcpy(ud, urlp->url_proto), urlp->url_eu_h_p.s,
941 urlp->url_eu_h_p.l +1);
942 urlp->url_proto[urlp->url_proto_len] = '\0';
944 if (urlp->url_path.l == 0)
945 urlp->url_p_eu_h_p = urlp->url_p_eu_h_p_p = ud;
946 else {
947 urlp->url_p_eu_h_p = savestrbuf(ud, i);
948 urlp->url_p_eu_h_p_p = ud;
949 ud += i;
950 *ud++ = '/';
951 memcpy(ud, urlp->url_path.s, urlp->url_path.l +1);
955 rv = TRU1;
956 #endif /* __ANYPROTO */
957 jleave:
958 NYD_LEAVE;
959 return rv;
960 #undef __ANYPROTO
961 #undef __ALLPROTO
964 FL bool_t
965 ccred_lookup_old(struct ccred *ccp, enum cproto cproto, char const *addr)
967 char const *pname, *pxstr, *authdef;
968 size_t pxlen, addrlen, i;
969 char *vbuf, *s;
970 ui8_t authmask;
971 enum {NONE=0, WANT_PASS=1<<0, REQ_PASS=1<<1, WANT_USER=1<<2, REQ_USER=1<<3}
972 ware = NONE;
973 bool_t addr_is_nuser = FAL0; /* XXX v15.0 legacy! v15_compat */
974 NYD_ENTER;
976 memset(ccp, 0, sizeof *ccp);
978 switch (cproto) {
979 default:
980 case CPROTO_SMTP:
981 pname = "SMTP";
982 pxstr = "smtp-auth";
983 pxlen = sizeof("smtp-auth") -1;
984 authmask = AUTHTYPE_NONE | AUTHTYPE_PLAIN | AUTHTYPE_LOGIN |
985 AUTHTYPE_CRAM_MD5 | AUTHTYPE_GSSAPI;
986 authdef = "none";
987 addr_is_nuser = TRU1;
988 break;
989 case CPROTO_POP3:
990 pname = "POP3";
991 pxstr = "pop3-auth";
992 pxlen = sizeof("pop3-auth") -1;
993 authmask = AUTHTYPE_PLAIN;
994 authdef = "plain";
995 break;
998 ccp->cc_cproto = cproto;
999 addrlen = strlen(addr);
1000 vbuf = ac_alloc(pxlen + addrlen + sizeof("-password-")-1 +1);
1001 memcpy(vbuf, pxstr, pxlen);
1003 /* Authentication type */
1004 vbuf[pxlen] = '-';
1005 memcpy(vbuf + pxlen + 1, addr, addrlen +1);
1006 if ((s = vok_vlook(vbuf)) == NULL) {
1007 vbuf[pxlen] = '\0';
1008 if ((s = vok_vlook(vbuf)) == NULL)
1009 s = UNCONST(authdef);
1012 if (!asccasecmp(s, "none")) {
1013 ccp->cc_auth = "NONE";
1014 ccp->cc_authtype = AUTHTYPE_NONE;
1015 /*ware = NONE;*/
1016 } else if (!asccasecmp(s, "plain")) {
1017 ccp->cc_auth = "PLAIN";
1018 ccp->cc_authtype = AUTHTYPE_PLAIN;
1019 ware = REQ_PASS | REQ_USER;
1020 } else if (!asccasecmp(s, "login")) {
1021 ccp->cc_auth = "LOGIN";
1022 ccp->cc_authtype = AUTHTYPE_LOGIN;
1023 ware = REQ_PASS | REQ_USER;
1024 } else if (!asccasecmp(s, "cram-md5")) {
1025 ccp->cc_auth = "CRAM-MD5";
1026 ccp->cc_authtype = AUTHTYPE_CRAM_MD5;
1027 ware = REQ_PASS | REQ_USER;
1028 } else if (!asccasecmp(s, "gssapi")) {
1029 ccp->cc_auth = "GSS-API";
1030 ccp->cc_authtype = AUTHTYPE_GSSAPI;
1031 ware = REQ_USER;
1032 } /* no else */
1034 /* Verify method */
1035 if (!(ccp->cc_authtype & authmask)) {
1036 n_err(_("Unsupported %s authentication method: %s\n"), pname, s);
1037 ccp = NULL;
1038 goto jleave;
1040 # ifndef HAVE_MD5
1041 if (ccp->cc_authtype == AUTHTYPE_CRAM_MD5) {
1042 n_err(_("No CRAM-MD5 support compiled in\n"));
1043 ccp = NULL;
1044 goto jleave;
1046 # endif
1047 # ifndef HAVE_GSSAPI
1048 if (ccp->cc_authtype == AUTHTYPE_GSSAPI) {
1049 n_err(_("No GSS-API support compiled in\n"));
1050 ccp = NULL;
1051 goto jleave;
1053 # endif
1055 /* User name */
1056 if (!(ware & (WANT_USER | REQ_USER)))
1057 goto jpass;
1059 if (!addr_is_nuser) {
1060 if ((s = _url_last_at_before_slash(addr)) != NULL) {
1061 ccp->cc_user.s = urlxdec(savestrbuf(addr, PTR2SIZE(s - addr)));
1062 ccp->cc_user.l = strlen(ccp->cc_user.s);
1063 } else if (ware & REQ_USER)
1064 goto jgetuser;
1065 goto jpass;
1068 memcpy(vbuf + pxlen, "-user-", i = sizeof("-user-") -1);
1069 i += pxlen;
1070 memcpy(vbuf + i, addr, addrlen +1);
1071 if ((s = vok_vlook(vbuf)) == NULL) {
1072 vbuf[--i] = '\0';
1073 if ((s = vok_vlook(vbuf)) == NULL && (ware & REQ_USER)) {
1074 if ((s = getuser(NULL)) == NULL) {
1075 jgetuser: /* TODO v15.0: today we simply bail, but we should call getuser().
1076 * TODO even better: introduce "PROTO-user" and "PROTO-pass" and
1077 * TODO check that first, then! change control flow, grow vbuf */
1078 n_err(_("A user is necessary for %s authentication\n"), pname);
1079 ccp = NULL;
1080 goto jleave;
1084 ccp->cc_user.l = strlen(ccp->cc_user.s = savestr(s));
1086 /* Password */
1087 jpass:
1088 if (!(ware & (WANT_PASS | REQ_PASS)))
1089 goto jleave;
1091 if (!addr_is_nuser) {
1092 memcpy(vbuf, "password-", i = sizeof("password-") -1);
1093 } else {
1094 memcpy(vbuf + pxlen, "-password-", i = sizeof("-password-") -1);
1095 i += pxlen;
1097 memcpy(vbuf + i, addr, addrlen +1);
1098 if ((s = vok_vlook(vbuf)) == NULL) {
1099 vbuf[--i] = '\0';
1100 if ((!addr_is_nuser || (s = vok_vlook(vbuf)) == NULL) &&
1101 (ware & REQ_PASS)) {
1102 if ((s = getpassword(NULL)) == NULL) {
1103 n_err(_("A password is necessary for %s authentication\n"),
1104 pname);
1105 ccp = NULL;
1106 goto jleave;
1110 if (s != NULL)
1111 ccp->cc_pass.l = strlen(ccp->cc_pass.s = savestr(s));
1113 jleave:
1114 ac_free(vbuf);
1115 if (ccp != NULL && (options & OPT_D_VV))
1116 n_err(_("Credentials: host \"%s\", user \"%s\", pass \"%s\"\n"),
1117 addr, (ccp->cc_user.s != NULL ? ccp->cc_user.s : ""),
1118 (ccp->cc_pass.s != NULL ? ccp->cc_pass.s : ""));
1119 NYD_LEAVE;
1120 return (ccp != NULL);
1123 FL bool_t
1124 ccred_lookup(struct ccred *ccp, struct url *urlp)
1126 char const *pstr, *authdef;
1127 char *s;
1128 enum okeys authokey;
1129 ui8_t authmask;
1130 enum {NONE=0, WANT_PASS=1<<0, REQ_PASS=1<<1, WANT_USER=1<<2, REQ_USER=1<<3}
1131 ware = NONE;
1132 NYD_ENTER;
1134 memset(ccp, 0, sizeof *ccp);
1135 ccp->cc_user = urlp->url_user;
1137 switch ((ccp->cc_cproto = urlp->url_cproto)) {
1138 default:
1139 case CPROTO_SMTP:
1140 pstr = "smtp";
1141 authokey = ok_v_smtp_auth;
1142 authmask = AUTHTYPE_NONE | AUTHTYPE_PLAIN | AUTHTYPE_LOGIN |
1143 AUTHTYPE_CRAM_MD5 | AUTHTYPE_GSSAPI;
1144 authdef = "plain";
1145 break;
1146 case CPROTO_POP3:
1147 pstr = "pop3";
1148 authokey = ok_v_pop3_auth;
1149 authmask = AUTHTYPE_PLAIN;
1150 authdef = "plain";
1151 break;
1154 /* Authentication type */
1155 if ((s = xok_VLOOK(authokey, urlp, OXM_ALL)) == NULL)
1156 s = UNCONST(authdef);
1158 if (!asccasecmp(s, "none")) {
1159 ccp->cc_auth = "NONE";
1160 ccp->cc_authtype = AUTHTYPE_NONE;
1161 /*ware = NONE;*/
1162 } else if (!asccasecmp(s, "plain")) {
1163 ccp->cc_auth = "PLAIN";
1164 ccp->cc_authtype = AUTHTYPE_PLAIN;
1165 ware = REQ_PASS | REQ_USER;
1166 } else if (!asccasecmp(s, "login")) {
1167 ccp->cc_auth = "LOGIN";
1168 ccp->cc_authtype = AUTHTYPE_LOGIN;
1169 ware = REQ_PASS | REQ_USER;
1170 } else if (!asccasecmp(s, "cram-md5")) {
1171 ccp->cc_auth = "CRAM-MD5";
1172 ccp->cc_authtype = AUTHTYPE_CRAM_MD5;
1173 ware = REQ_PASS | REQ_USER;
1174 } else if (!asccasecmp(s, "gssapi")) {
1175 ccp->cc_auth = "GSS-API";
1176 ccp->cc_authtype = AUTHTYPE_GSSAPI;
1177 ware = REQ_USER;
1178 } /* no else */
1180 /* Verify method */
1181 if (!(ccp->cc_authtype & authmask)) {
1182 n_err(_("Unsupported %s authentication method: %s\n"), pstr, s);
1183 ccp = NULL;
1184 goto jleave;
1186 # ifndef HAVE_MD5
1187 if (ccp->cc_authtype == AUTHTYPE_CRAM_MD5) {
1188 n_err(_("No CRAM-MD5 support compiled in\n"));
1189 ccp = NULL;
1190 goto jleave;
1192 # endif
1193 # ifndef HAVE_GSSAPI
1194 if (ccp->cc_authtype == AUTHTYPE_GSSAPI) {
1195 n_err(_("No GSS-API support compiled in\n"));
1196 ccp = NULL;
1197 goto jleave;
1199 # endif
1201 /* Password */
1202 ccp->cc_pass = urlp->url_pass;
1203 if (ccp->cc_pass.s != NULL)
1204 goto jleave;
1206 if ((s = xok_vlook(password, urlp, OXM_ALL)) != NULL)
1207 goto js2pass;
1208 # ifdef HAVE_AGENT /* TODO v15-compat obsolete */
1209 if ((s = xok_vlook(agent_shell_lookup, urlp, OXM_ALL)) != NULL) {
1210 OBSOLETE(_("*agent-shell-lookup* will vanish. Please use encrypted "
1211 "~/.netrc (via *netrc-pipe*), or simply `source' an encrypted file"));
1212 if (!_agent_shell_lookup(urlp, s)) {
1213 ccp = NULL;
1214 goto jleave;
1215 } else if (urlp->url_pass.s != NULL) {
1216 ccp->cc_pass = urlp->url_pass;
1217 goto jleave;
1220 # endif
1221 # ifdef HAVE_NETRC
1222 if (xok_blook(netrc_lookup, urlp, OXM_ALL) && _nrc_lookup(urlp, TRU1)) {
1223 ccp->cc_pass = urlp->url_pass;
1224 goto jleave;
1226 # endif
1227 if (ware & REQ_PASS) {
1228 if ((s = getpassword(NULL)) != NULL)
1229 js2pass:
1230 ccp->cc_pass.l = strlen(ccp->cc_pass.s = savestr(s));
1231 else {
1232 n_err(_("A password is necessary for %s authentication\n"), pstr);
1233 ccp = NULL;
1237 jleave:
1238 if (ccp != NULL && (options & OPT_D_VV))
1239 n_err(_("Credentials: host \"%s\", user \"%s\", pass \"%s\"\n"),
1240 urlp->url_h_p.s, (ccp->cc_user.s != NULL ? ccp->cc_user.s : ""),
1241 (ccp->cc_pass.s != NULL ? ccp->cc_pass.s : ""));
1242 NYD_LEAVE;
1243 return (ccp != NULL);
1245 #endif /* HAVE_SOCKETS */
1247 #ifdef HAVE_NETRC
1248 FL int
1249 c_netrc(void *v)
1251 char **argv = v;
1252 struct nrc_node *nrc;
1253 bool_t load_only;
1254 NYD_ENTER;
1256 load_only = FAL0;
1257 if (*argv == NULL)
1258 goto jlist;
1259 if (argv[1] != NULL)
1260 goto jerr;
1261 if (!asccasecmp(*argv, "show"))
1262 goto jlist;
1263 load_only = TRU1;
1264 if (!asccasecmp(*argv, "load"))
1265 goto jlist;
1266 if (!asccasecmp(*argv, "clear"))
1267 goto jclear;
1268 jerr:
1269 n_err(_("Synopsis: netrc: (<show> or) <clear> the .netrc cache\n"));
1270 v = NULL;
1271 jleave:
1272 NYD_LEAVE;
1273 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
1275 jlist: {
1276 FILE *fp;
1277 size_t l;
1279 if (_nrc_list == NULL)
1280 _nrc_init();
1281 if (_nrc_list == NRC_NODE_ERR) {
1282 n_err(_("Interpolate what file?\n"));
1283 v = NULL;
1284 goto jleave;
1286 if (load_only)
1287 goto jleave;
1289 if ((fp = Ftmp(NULL, "netrc", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL) {
1290 n_perr(_("tmpfile"), 0);
1291 v = NULL;
1292 goto jleave;
1295 for (l = 0, nrc = _nrc_list; nrc != NULL; ++l, nrc = nrc->nrc_next) {
1296 fprintf(fp, _("machine %s "), nrc->nrc_dat);
1297 if (nrc->nrc_ulen > 0)
1298 fprintf(fp, _("login \"%s\" "),
1299 string_quote(nrc->nrc_dat + nrc->nrc_mlen +1));
1300 if (nrc->nrc_plen > 0)
1301 fprintf(fp, _("password \"%s\"\n"),
1302 string_quote(nrc->nrc_dat + nrc->nrc_mlen +1 + nrc->nrc_ulen +1));
1303 else
1304 putc('\n', fp);
1307 page_or_print(fp, l);
1308 Fclose(fp);
1310 goto jleave;
1312 jclear:
1313 if (_nrc_list == NRC_NODE_ERR)
1314 _nrc_list = NULL;
1315 while ((nrc = _nrc_list) != NULL) {
1316 _nrc_list = nrc->nrc_next;
1317 free(nrc);
1319 goto jleave;
1321 #endif /* HAVE_NETRC */
1323 #ifdef HAVE_MD5
1324 FL char *
1325 md5tohex(char hex[MD5TOHEX_SIZE], void const *vp)
1327 char const *cp = vp;
1328 size_t i, j;
1329 NYD_ENTER;
1331 for (i = 0; i < MD5TOHEX_SIZE / 2; ++i) {
1332 j = i << 1;
1333 # define __hex(n) ((n) > 9 ? (n) - 10 + 'a' : (n) + '0')
1334 hex[j] = __hex((cp[i] & 0xF0) >> 4);
1335 hex[++j] = __hex(cp[i] & 0x0F);
1336 # undef __hex
1338 NYD_LEAVE;
1339 return hex;
1342 FL char *
1343 cram_md5_string(struct str const *user, struct str const *pass,
1344 char const *b64)
1346 struct str in, out;
1347 char digest[16], *cp;
1348 NYD_ENTER;
1350 out.s = NULL;
1351 in.s = UNCONST(b64);
1352 in.l = strlen(in.s);
1353 b64_decode(&out, &in, NULL);
1354 assert(out.s != NULL);
1356 hmac_md5((uc_i*)out.s, out.l, (uc_i*)pass->s, pass->l, digest);
1357 free(out.s);
1358 cp = md5tohex(salloc(MD5TOHEX_SIZE +1), digest);
1360 in.l = user->l + MD5TOHEX_SIZE +1;
1361 in.s = ac_alloc(user->l + 1 + MD5TOHEX_SIZE +1);
1362 memcpy(in.s, user->s, user->l);
1363 in.s[user->l] = ' ';
1364 memcpy(in.s + user->l + 1, cp, MD5TOHEX_SIZE);
1365 b64_encode(&out, &in, B64_SALLOC | B64_CRLF);
1366 ac_free(in.s);
1367 NYD_LEAVE;
1368 return out.s;
1371 FL void
1372 hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len,
1373 void *digest)
1376 * This code is taken from
1378 * Network Working Group H. Krawczyk
1379 * Request for Comments: 2104 IBM
1380 * Category: Informational M. Bellare
1381 * UCSD
1382 * R. Canetti
1383 * IBM
1384 * February 1997
1387 * HMAC: Keyed-Hashing for Message Authentication
1389 md5_ctx context;
1390 unsigned char k_ipad[65]; /* inner padding - key XORd with ipad */
1391 unsigned char k_opad[65]; /* outer padding - key XORd with opad */
1392 unsigned char tk[16];
1393 int i;
1394 NYD_ENTER;
1396 /* if key is longer than 64 bytes reset it to key=MD5(key) */
1397 if (key_len > 64) {
1398 md5_ctx tctx;
1400 md5_init(&tctx);
1401 md5_update(&tctx, key, key_len);
1402 md5_final(tk, &tctx);
1404 key = tk;
1405 key_len = 16;
1408 /* the HMAC_MD5 transform looks like:
1410 * MD5(K XOR opad, MD5(K XOR ipad, text))
1412 * where K is an n byte key
1413 * ipad is the byte 0x36 repeated 64 times
1414 * opad is the byte 0x5c repeated 64 times
1415 * and text is the data being protected */
1417 /* start out by storing key in pads */
1418 memset(k_ipad, 0, sizeof k_ipad);
1419 memset(k_opad, 0, sizeof k_opad);
1420 memcpy(k_ipad, key, key_len);
1421 memcpy(k_opad, key, key_len);
1423 /* XOR key with ipad and opad values */
1424 for (i=0; i<64; i++) {
1425 k_ipad[i] ^= 0x36;
1426 k_opad[i] ^= 0x5c;
1429 /* perform inner MD5 */
1430 md5_init(&context); /* init context for 1st pass */
1431 md5_update(&context, k_ipad, 64); /* start with inner pad */
1432 md5_update(&context, text, text_len); /* then text of datagram */
1433 md5_final(digest, &context); /* finish up 1st pass */
1435 /* perform outer MD5 */
1436 md5_init(&context); /* init context for 2nd pass */
1437 md5_update(&context, k_opad, 64); /* start with outer pad */
1438 md5_update(&context, digest, 16); /* then results of 1st hash */
1439 md5_final(digest, &context); /* finish up 2nd pass */
1440 NYD_LEAVE;
1442 #endif /* HAVE_MD5 */
1444 /* s-it-mode */