github.com/afumu/libc@v0.0.6/musl/src/network/lookup_name.c (about)

     1  #include <sys/socket.h>
     2  #include <netinet/in.h>
     3  #include <netdb.h>
     4  #include <net/if.h>
     5  #include <arpa/inet.h>
     6  #include <ctype.h>
     7  #include <stdlib.h>
     8  #include <string.h>
     9  #include <fcntl.h>
    10  #include <unistd.h>
    11  #include <pthread.h>
    12  #include <errno.h>
    13  #include <resolv.h>
    14  #include "lookup.h"
    15  #include "stdio_impl.h"
    16  #include "syscall.h"
    17  
    18  static int is_valid_hostname(const char *host)
    19  {
    20  	const unsigned char *s;
    21  	//TODO if (strnlen(host, 255)-1 >= 254 || mbstowcs(0, host, 0) == -1) return 0;
    22  	if (strnlen(host, 255)-1 >= 254) return 0;
    23  	for (s=(void *)host; *s>=0x80 || *s=='.' || *s=='-' || isalnum(*s); s++);
    24  	return !*s;
    25  }
    26  
    27  struct address zero_struct_address;
    28  
    29  static int name_from_null(struct address buf[static 2], const char *name, int family, int flags)
    30  {
    31  	int cnt = 0;
    32  	if (name) return 0;
    33  	if (flags & AI_PASSIVE) {
    34  		//TODO if (family != AF_INET6)
    35  		//TODO 	buf[cnt++] = (struct address){ .family = AF_INET };
    36  		if (family != AF_INET6) {
    37  			struct address x = zero_struct_address;
    38  			x.family = AF_INET;
    39  			buf[cnt++] = x;
    40  		}
    41  		//TODO if (family != AF_INET)
    42  		//TODO 	buf[cnt++] = (struct address){ .family = AF_INET6 };
    43  		if (family != AF_INET) {
    44  			struct address x = zero_struct_address;
    45  			x.family = AF_INET6;
    46  			buf[cnt++] = x;
    47  		}
    48  	} else {
    49  		abort(); //TODO-
    50  	// 	if (family != AF_INET6)
    51  	// 		buf[cnt++] = (struct address){ .family = AF_INET, .addr = { 127,0,0,1 } };
    52  	// 	if (family != AF_INET)
    53  	// 		buf[cnt++] = (struct address){ .family = AF_INET6, .addr = { [15] = 1 } };
    54  	}
    55  	return cnt;
    56  }
    57  
    58  static int name_from_numeric(struct address buf[static 1], const char *name, int family)
    59  {
    60  	return __lookup_ipliteral(buf, name, family);
    61  }
    62  
    63  static int name_from_hosts(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
    64  {
    65  	char line[512];
    66  	size_t l = strlen(name);
    67  	int cnt = 0, badfam = 0;
    68  	unsigned char _buf[1032];
    69  	//TODO FILE _f, *f = __fopen_rb_ca("/etc/hosts", &_f, _buf, sizeof _buf);
    70  	FILE _f, *f = fopen("/etc/hosts", "rb");
    71  	if (!f) switch (errno) {
    72  	case ENOENT:
    73  	case ENOTDIR:
    74  	case EACCES:
    75  		return 0;
    76  	default:
    77  		return EAI_SYSTEM;
    78  	}
    79  	while (fgets(line, sizeof line, f) && cnt < MAXADDRS) {
    80  		char *p, *z;
    81  
    82  		if ((p=strchr(line, '#'))) *p++='\n', *p=0;
    83  		for(p=line+1; (p=strstr(p, name)) &&
    84  			(!isspace(p[-1]) || !isspace(p[l])); p++);
    85  		if (!p) continue;
    86  
    87  		/* Isolate IP address to parse */
    88  		for (p=line; *p && !isspace(*p); p++);
    89  		*p++ = 0;
    90  		switch (name_from_numeric(buf+cnt, line, family)) {
    91  		case 1:
    92  			cnt++;
    93  			break;
    94  		case 0:
    95  			continue;
    96  		default:
    97  			badfam = EAI_NONAME;
    98  			continue;
    99  		}
   100  
   101  		/* Extract first name as canonical name */
   102  		for (; *p && isspace(*p); p++);
   103  		for (z=p; *z && !isspace(*z); z++);
   104  		*z = 0;
   105  		if (is_valid_hostname(p)) memcpy(canon, p, z-p+1);
   106  	}
   107  	//TODO __fclose_ca(f);
   108  	fclose(f);
   109  	return cnt ? cnt : badfam;
   110  }
   111  
   112  struct dpc_ctx {
   113  	struct address *addrs;
   114  	char *canon;
   115  	int cnt;
   116  };
   117  
   118  #define RR_A 1
   119  #define RR_CNAME 5
   120  #define RR_AAAA 28
   121  
   122  static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
   123  {
   124  	abort(); //TODO-
   125  	// char tmp[256];
   126  	// struct dpc_ctx *ctx = c;
   127  	// if (ctx->cnt >= MAXADDRS) return -1;
   128  	// switch (rr) {
   129  	// case RR_A:
   130  	// 	if (len != 4) return -1;
   131  	// 	ctx->addrs[ctx->cnt].family = AF_INET;
   132  	// 	ctx->addrs[ctx->cnt].scopeid = 0;
   133  	// 	memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
   134  	// 	break;
   135  	// case RR_AAAA:
   136  	// 	if (len != 16) return -1;
   137  	// 	ctx->addrs[ctx->cnt].family = AF_INET6;
   138  	// 	ctx->addrs[ctx->cnt].scopeid = 0;
   139  	// 	memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
   140  	// 	break;
   141  	// case RR_CNAME:
   142  	// 	if (__dn_expand(packet, (const unsigned char *)packet + 512,
   143  	// 	    data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
   144  	// 		strcpy(ctx->canon, tmp);
   145  	// 	break;
   146  	// }
   147  	// return 0;
   148  }
   149  
   150  static int name_from_dns(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, const struct resolvconf *conf)
   151  {
   152  	abort(); //TODO-
   153  	// unsigned char qbuf[2][280], abuf[2][512];
   154  	// const unsigned char *qp[2] = { qbuf[0], qbuf[1] };
   155  	// unsigned char *ap[2] = { abuf[0], abuf[1] };
   156  	// int qlens[2], alens[2];
   157  	// int i, nq = 0;
   158  	// struct dpc_ctx ctx = { .addrs = buf, .canon = canon };
   159  	// static const struct { int af; int rr; } afrr[2] = {
   160  	// 	{ .af = AF_INET6, .rr = RR_A },
   161  	// 	{ .af = AF_INET, .rr = RR_AAAA },
   162  	// };
   163  
   164  	// for (i=0; i<2; i++) {
   165  	// 	if (family != afrr[i].af) {
   166  	// 		qlens[nq] = __res_mkquery(0, name, 1, afrr[i].rr,
   167  	// 			0, 0, 0, qbuf[nq], sizeof *qbuf);
   168  	// 		if (qlens[nq] == -1)
   169  	// 			return EAI_NONAME;
   170  	// 		qbuf[nq][3] = 0; /* don't need AD flag */
   171  	// 		nq++;
   172  	// 	}
   173  	// }
   174  
   175  	// if (__res_msend_rc(nq, qp, qlens, ap, alens, sizeof *abuf, conf) < 0)
   176  	// 	return EAI_SYSTEM;
   177  
   178  	// for (i=0; i<nq; i++) {
   179  	// 	if (alens[i] < 4 || (abuf[i][3] & 15) == 2) return EAI_AGAIN;
   180  	// 	if ((abuf[i][3] & 15) == 3) return 0;
   181  	// 	if ((abuf[i][3] & 15) != 0) return EAI_FAIL;
   182  	// }
   183  
   184  	// for (i=0; i<nq; i++)
   185  	// 	__dns_parse(abuf[i], alens[i], dns_parse_callback, &ctx);
   186  
   187  	// if (ctx.cnt) return ctx.cnt;
   188  	// return EAI_NONAME;
   189  }
   190  
   191  static int name_from_dns_search(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
   192  {
   193  	return -1; //TODO-
   194  	abort(); //TODO-
   195  	// char search[256];
   196  	// struct resolvconf conf;
   197  	// size_t l, dots;
   198  	// char *p, *z;
   199  
   200  	// if (__get_resolv_conf(&conf, search, sizeof search) < 0) return -1;
   201  
   202  	// /* Count dots, suppress search when >=ndots or name ends in
   203  	//  * a dot, which is an explicit request for global scope. */
   204  	// for (dots=l=0; name[l]; l++) if (name[l]=='.') dots++;
   205  	// if (dots >= conf.ndots || name[l-1]=='.') *search = 0;
   206  
   207  	// /* Strip final dot for canon, fail if multiple trailing dots. */
   208  	// if (name[l-1]=='.') l--;
   209  	// if (!l || name[l-1]=='.') return EAI_NONAME;
   210  
   211  	// /* This can never happen; the caller already checked length. */
   212  	// if (l >= 256) return EAI_NONAME;
   213  
   214  	// /* Name with search domain appended is setup in canon[]. This both
   215  	//  * provides the desired default canonical name (if the requested
   216  	//  * name is not a CNAME record) and serves as a buffer for passing
   217  	//  * the full requested name to name_from_dns. */
   218  	// memcpy(canon, name, l);
   219  	// canon[l] = '.';
   220  
   221  	// for (p=search; *p; p=z) {
   222  	// 	for (; isspace(*p); p++);
   223  	// 	for (z=p; *z && !isspace(*z); z++);
   224  	// 	if (z==p) break;
   225  	// 	if (z-p < 256 - l - 1) {
   226  	// 		memcpy(canon+l+1, p, z-p);
   227  	// 		canon[z-p+1+l] = 0;
   228  	// 		int cnt = name_from_dns(buf, canon, canon, family, &conf);
   229  	// 		if (cnt) return cnt;
   230  	// 	}
   231  	// }
   232  
   233  	// canon[l] = 0;
   234  	// return name_from_dns(buf, canon, name, family, &conf);
   235  }
   236  
   237  static const struct policy {
   238  	unsigned char addr[16];
   239  	unsigned char len, mask;
   240  	unsigned char prec, label;
   241  } defpolicy[] = {
   242  	{ "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1", 15, 0xff, 50, 0 },
   243  	{ "\0\0\0\0\0\0\0\0\0\0\xff\xff", 11, 0xff, 35, 4 },
   244  	{ "\x20\2", 1, 0xff, 30, 2 },
   245  	{ "\x20\1", 3, 0xff, 5, 5 },
   246  	{ "\xfc", 0, 0xfe, 3, 13 },
   247  #if 0
   248  	/* These are deprecated and/or returned to the address
   249  	 * pool, so despite the RFC, treating them as special
   250  	 * is probably wrong. */
   251  	{ "", 11, 0xff, 1, 3 },
   252  	{ "\xfe\xc0", 1, 0xc0, 1, 11 },
   253  	{ "\x3f\xfe", 1, 0xff, 1, 12 },
   254  #endif
   255  	/* Last rule must match all addresses to stop loop. */
   256  	{ "", 0, 0, 40, 1 },
   257  };
   258  
   259  static const struct policy *policyof(const struct in6_addr *a)
   260  {
   261  	int i;
   262  	for (i=0; ; i++) {
   263  		if (memcmp(a->s6_addr, defpolicy[i].addr, defpolicy[i].len))
   264  			continue;
   265  		if ((a->s6_addr[defpolicy[i].len] & defpolicy[i].mask)
   266  		    != defpolicy[i].addr[defpolicy[i].len])
   267  			continue;
   268  		return defpolicy+i;
   269  	}
   270  }
   271  
   272  static int labelof(const struct in6_addr *a)
   273  {
   274  	return policyof(a)->label;
   275  }
   276  
   277  static int scopeof(const struct in6_addr *a)
   278  {
   279  	if (IN6_IS_ADDR_MULTICAST(a)) return a->s6_addr[1] & 15;
   280  	if (IN6_IS_ADDR_LINKLOCAL(a)) return 2;
   281  	if (IN6_IS_ADDR_LOOPBACK(a)) return 2;
   282  	if (IN6_IS_ADDR_SITELOCAL(a)) return 5;
   283  	return 14;
   284  }
   285  
   286  static int prefixmatch(const struct in6_addr *s, const struct in6_addr *d)
   287  {
   288  	/* FIXME: The common prefix length should be limited to no greater
   289  	 * than the nominal length of the prefix portion of the source
   290  	 * address. However the definition of the source prefix length is
   291  	 * not clear and thus this limiting is not yet implemented. */
   292  	unsigned i;
   293  	for (i=0; i<128 && !((s->s6_addr[i/8]^d->s6_addr[i/8])&(128>>(i%8))); i++);
   294  	return i;
   295  }
   296  
   297  #define DAS_USABLE              0x40000000
   298  #define DAS_MATCHINGSCOPE       0x20000000
   299  #define DAS_MATCHINGLABEL       0x10000000
   300  #define DAS_PREC_SHIFT          20
   301  #define DAS_SCOPE_SHIFT         16
   302  #define DAS_PREFIX_SHIFT        8
   303  #define DAS_ORDER_SHIFT         0
   304  
   305  static int addrcmp(const void *_a, const void *_b)
   306  {
   307  	const struct address *a = _a, *b = _b;
   308  	return b->sortkey - a->sortkey;
   309  }
   310  
   311  int __lookup_name(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, int flags)
   312  {
   313  	int cnt = 0, i, j;
   314  
   315  	*canon = 0;
   316  	if (name) {
   317  		/* reject empty name and check len so it fits into temp bufs */
   318  		size_t l = strnlen(name, 255);
   319  		if (l-1 >= 254)
   320  			return EAI_NONAME;
   321  		memcpy(canon, name, l+1);
   322  	}
   323  
   324  	/* Procedurally, a request for v6 addresses with the v4-mapped
   325  	 * flag set is like a request for unspecified family, followed
   326  	 * by filtering of the results. */
   327  	if (flags & AI_V4MAPPED) {
   328  		if (family == AF_INET6) family = AF_UNSPEC;
   329  		else flags -= AI_V4MAPPED;
   330  	}
   331  
   332  	/* Try each backend until there's at least one result. */
   333  	cnt = name_from_null(buf, name, family, flags);
   334  	if (!cnt) cnt = name_from_numeric(buf, name, family);
   335  	if (!cnt && !(flags & AI_NUMERICHOST)) {
   336  		cnt = name_from_hosts(buf, canon, name, family);
   337  		if (!cnt) cnt = name_from_dns_search(buf, canon, name, family);
   338  	}
   339  	if (cnt<=0) return cnt ? cnt : EAI_NONAME;
   340  
   341  	/* Filter/transform results for v4-mapped lookup, if requested. */
   342  	if (flags & AI_V4MAPPED) {
   343  		abort(); //TODO-
   344  	// 	if (!(flags & AI_ALL)) {
   345  	// 		/* If any v6 results exist, remove v4 results. */
   346  	// 		for (i=0; i<cnt && buf[i].family != AF_INET6; i++);
   347  	// 		if (i<cnt) {
   348  	// 			for (j=0; i<cnt; i++) {
   349  	// 				if (buf[i].family == AF_INET6)
   350  	// 					buf[j++] = buf[i];
   351  	// 			}
   352  	// 			cnt = i = j;
   353  	// 		}
   354  	// 	}
   355  	// 	/* Translate any remaining v4 results to v6 */
   356  	// 	for (i=0; i<cnt; i++) {
   357  	// 		if (buf[i].family != AF_INET) continue;
   358  	// 		memcpy(buf[i].addr+12, buf[i].addr, 4);
   359  	// 		memcpy(buf[i].addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
   360  	// 		buf[i].family = AF_INET6;
   361  	// 	}
   362  	}
   363  
   364  	/* No further processing is needed if there are fewer than 2
   365  	 * results or if there are only IPv4 results. */
   366  	if (cnt<2 || family==AF_INET) return cnt;
   367  	for (i=0; i<cnt; i++) if (buf[i].family != AF_INET) break;
   368  	if (i==cnt) return cnt;
   369  
   370  	int cs;
   371  	//TODO pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
   372  
   373  	/* The following implements a subset of RFC 3484/6724 destination
   374  	 * address selection by generating a single 31-bit sort key for
   375  	 * each address. Rules 3, 4, and 7 are omitted for having
   376  	 * excessive runtime and code size cost and dubious benefit.
   377  	 * So far the label/precedence table cannot be customized. */
   378  	for (i=0; i<cnt; i++) {
   379  		int family = buf[i].family;
   380  		int key = 0;
   381  		struct sockaddr_in6 sa6 = { 0 }, da6 = {
   382  			.sin6_family = AF_INET6,
   383  			.sin6_scope_id = buf[i].scopeid,
   384  			.sin6_port = 65535
   385  		};
   386  		struct sockaddr_in sa4 = { 0 }, da4 = {
   387  			.sin_family = AF_INET,
   388  			.sin_port = 65535
   389  		};
   390  		void *sa, *da;
   391  		socklen_t salen, dalen;
   392  		if (family == AF_INET6) {
   393  			memcpy(da6.sin6_addr.s6_addr, buf[i].addr, 16);
   394  			da = &da6; dalen = sizeof da6;
   395  			sa = &sa6; salen = sizeof sa6;
   396  		} else {
   397  			memcpy(sa6.sin6_addr.s6_addr,
   398  				"\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
   399  			memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
   400  			memcpy(da6.sin6_addr.s6_addr,
   401  				"\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
   402  			memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
   403  			memcpy(&da4.sin_addr, buf[i].addr, 4);
   404  			da = &da4; dalen = sizeof da4;
   405  			sa = &sa4; salen = sizeof sa4;
   406  		}
   407  		const struct policy *dpolicy = policyof(&da6.sin6_addr);
   408  		int dscope = scopeof(&da6.sin6_addr);
   409  		int dlabel = dpolicy->label;
   410  		int dprec = dpolicy->prec;
   411  		int prefixlen = 0;
   412  		int fd = socket(family, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP);
   413  		if (fd >= 0) {
   414  			if (!connect(fd, da, dalen)) {
   415  				key |= DAS_USABLE;
   416  				if (!getsockname(fd, sa, &salen)) {
   417  					if (family == AF_INET) memcpy(
   418  						sa6.sin6_addr.s6_addr+12,
   419  						&sa4.sin_addr, 4);
   420  					if (dscope == scopeof(&sa6.sin6_addr))
   421  						key |= DAS_MATCHINGSCOPE;
   422  					if (dlabel == labelof(&sa6.sin6_addr))
   423  						key |= DAS_MATCHINGLABEL;
   424  					prefixlen = prefixmatch(&sa6.sin6_addr,
   425  						&da6.sin6_addr);
   426  				}
   427  			}
   428  			close(fd);
   429  		}
   430  		key |= dprec << DAS_PREC_SHIFT;
   431  		key |= (15-dscope) << DAS_SCOPE_SHIFT;
   432  		key |= prefixlen << DAS_PREFIX_SHIFT;
   433  		key |= (MAXADDRS-i) << DAS_ORDER_SHIFT;
   434  		buf[i].sortkey = key;
   435  	}
   436  	qsort(buf, cnt, sizeof *buf, addrcmp);
   437  
   438  	//TODO pthread_setcancelstate(cs, 0);
   439  
   440  	return cnt;
   441  }