Use DNS implementation from Musl Libc

Now that our socket system call polyfills are good enough to support
Musl's DNS library we should be using that rather than the barebones
domain name system implementation we rolled on our own. There's many
benefits to making this change. So many, that I myself wouldn't feel
qualified to enumerate them all. The Musl DNS code had to be changed
in order to support Windows of course, which looks very solid so far
This commit is contained in:
Justine Tunney 2023-12-28 22:58:17 -08:00
parent 1a28e35c62
commit 43fe5956ad
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
146 changed files with 2646 additions and 7190 deletions

View file

@ -198,9 +198,9 @@ include third_party/nsync/mem/BUILD.mk # │ You can now use stdio
include libc/proc/BUILD.mk # │ You can now use threads
include libc/dlopen/BUILD.mk # │ You can now use processes
include libc/thread/BUILD.mk # │ You can finally call malloc()
include tool/hello/BUILD.mk # │
include third_party/zlib/BUILD.mk # │
include libc/stdio/BUILD.mk # │
include tool/hello/BUILD.mk # │
include libc/time/BUILD.mk # │
include net/BUILD.mk # │
include third_party/vqsort/BUILD.mk # │
@ -213,9 +213,8 @@ include third_party/intel/BUILD.mk # │
include third_party/aarch64/BUILD.mk # │
include libc/BUILD.mk #─┘
include libc/sock/BUILD.mk #─┐
include libc/dns/BUILD.mk # ├──ONLINE RUNTIME
include net/http/BUILD.mk # │ You can communicate with the network
include third_party/musl/BUILD.mk # │
include net/http/BUILD.mk # ├──ONLINE RUNTIME
include third_party/musl/BUILD.mk # │ You can communicate with the network
include libc/x/BUILD.mk # │
include dsp/scale/BUILD.mk # │
include dsp/mpeg/BUILD.mk # │
@ -297,7 +296,6 @@ include test/libc/calls/BUILD.mk
include test/libc/x/BUILD.mk
include test/libc/xed/BUILD.mk
include test/libc/fmt/BUILD.mk
include test/libc/dns/BUILD.mk
include test/libc/time/BUILD.mk
include test/libc/proc/BUILD.mk
include test/libc/stdio/BUILD.mk
@ -373,7 +371,6 @@ loc: o/$(MODE)/tool/build/summy.com
COSMOPOLITAN_OBJECTS = \
TOOL_ARGS \
NET_HTTP \
LIBC_DNS \
LIBC_SOCK \
LIBC_NT_WS2_32 \
LIBC_NT_IPHLPAPI \
@ -424,7 +421,6 @@ COSMOPOLITAN_H_PKGS = \
APE \
LIBC \
LIBC_CALLS \
LIBC_DNS \
LIBC_ELF \
LIBC_FMT \
LIBC_DLOPEN \

View file

@ -3,8 +3,6 @@
#include "dsp/mpeg/mpeg.h"
COSMOPOLITAN_C_START_
struct FILE;
enum plm_buffer_mode {
PLM_BUFFER_MODE_FILE,
PLM_BUFFER_MODE_FIXED_MEM,
@ -17,7 +15,7 @@ typedef struct plm_buffer_t {
unsigned length;
int free_when_done;
int close_when_done;
struct FILE *fh;
FILE *fh;
plm_buffer_load_callback load_callback;
void *load_callback_user_data;
unsigned char *bytes;

View file

@ -1,9 +1,8 @@
#ifndef COSMOPOLITAN_DSP_MPEG_MPEG_H_
#define COSMOPOLITAN_DSP_MPEG_MPEG_H_
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
struct FILE;
typedef struct plm_t plm_t;
typedef struct plm_buffer_t plm_buffer_t;
typedef struct plm_demux_t plm_demux_t;
@ -112,7 +111,7 @@ plm_t *plm_create_with_filename(const char *filename);
* to let plmpeg call fclose() on the handle when plm_destroy() is
* called.
*/
plm_t *plm_create_with_file(struct FILE *fh, int close_when_done);
plm_t *plm_create_with_file(FILE *fh, int close_when_done);
/**
* Create a plmpeg instance with pointer to memory as source. This assumes the
@ -257,7 +256,7 @@ plm_buffer_t *plm_buffer_create_with_filename(const char *filename);
* to let plmpeg call fclose() on the handle when plm_destroy() is
* called.
*/
plm_buffer_t *plm_buffer_create_with_file(struct FILE *fh, int close_when_done);
plm_buffer_t *plm_buffer_create_with_file(FILE *fh, int close_when_done);
/**
* Create a buffer instance with a pointer to memory as source. This assumes

View file

@ -5,7 +5,6 @@
COSMOPOLITAN_C_START_
struct FILE;
struct termios;
struct TtyIdent {

View file

@ -44,7 +44,6 @@ EXAMPLES_DIRECTDEPS = \
DSP_TTY \
LIBC_CALLS \
LIBC_DLOPEN \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_IRQ \

View file

@ -8,7 +8,6 @@
*/
#endif
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/fmt/conv.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
@ -26,6 +25,7 @@
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "third_party/getopt/getopt.internal.h"
#include "third_party/musl/netdb.h"
/**
* @fileoverview netcat clone
@ -60,9 +60,7 @@ int main(int argc, char *argv[]) {
halfclose = false;
break;
case 'h':
fputs("Usage: ", stdout);
fputs(argv[0], stdout);
fputs(" [-hH] IP PORT\n", stdout);
tinyprint(1, "Usage: ", argv[0], " [-hH] IP PORT\n", NULL);
exit(0);
default:
fprintf(stderr, "bad option %d\n", opt);
@ -76,17 +74,9 @@ int main(int argc, char *argv[]) {
host = argv[optind + 0];
port = argv[optind + 1];
switch ((rc = getaddrinfo(host, port, &hint, &ai))) {
case EAI_SUCCESS:
break;
case EAI_SYSTEM:
perror("getaddrinfo");
exit(1);
default:
fputs("EAI_", stderr);
fputs(gai_strerror(rc), stderr);
fputs("\n", stderr);
exit(1);
if ((rc = getaddrinfo(host, port, &hint, &ai))) {
tinyprint(2, host, ": ", gai_strerror(rc), "\n", NULL);
exit(1);
}
if ((sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
@ -95,12 +85,12 @@ int main(int argc, char *argv[]) {
}
if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) == -1) {
perror("setsockopt(SO_LINGER)");
perror("SO_LINGER");
exit(1);
}
if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
perror("connect");
perror(host);
exit(1);
}

View file

@ -30,12 +30,13 @@
*/
#include "libc/calls/calls.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/log/bsd.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ex.h"
@ -44,6 +45,7 @@
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/sock.h"
#include "third_party/getopt/getopt.internal.h"
#include "third_party/musl/netdb.h"
// clang-format off
asm(".ident\t\"\\n\\n\

View file

@ -276,7 +276,6 @@ LIBC_FILES := $(wildcard libc/*)
o/$(MODE)/libc: o/$(MODE)/libc/calls \
o/$(MODE)/libc/crt \
o/$(MODE)/libc/dlopen \
o/$(MODE)/libc/dns \
o/$(MODE)/libc/elf \
o/$(MODE)/libc/fmt \
o/$(MODE)/libc/intrin \

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Copyright 2023 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
@ -16,11 +16,13 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/calls/sysdir.internal.h"
#include "libc/dce.h"
// error number global for gethostbyname*(), gethostbyaddr*(), etc.
static _Thread_local int __h_errno;
errno_t *__h_errno_location(void) {
return &__h_errno;
const char *GetHostsTxtPath(char *path, size_t size) {
if (!IsWindows()) {
return "/etc/hosts";
} else {
return GetSystemDirectoryPath(path, "drivers\\etc\\hosts", size);
}
}

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Copyright 2023 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
@ -16,18 +16,13 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/mem/mem.h"
#include "libc/calls/sysdir.internal.h"
#include "libc/dce.h"
/**
* Frees addresses returned by getaddrinfo().
*/
void freeaddrinfo(struct addrinfo *ai) {
struct addrinfo *next;
while (ai) {
/* we assume ai_addr and ai_canonname are shoehorned */
next = ai->ai_next;
free(ai);
ai = next;
const char *GetProtocolsTxtPath(char *buf, size_t size) {
if (!IsWindows()) {
return "/etc/protocols";
} else {
return GetSystemDirectoryPath(buf, "drivers\\etc\\protocol", size);
}
}

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Copyright 2023 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
@ -16,22 +16,13 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/calls/sysdir.internal.h"
#include "libc/dce.h"
/**
* Turns `h_errno` value into string.
*/
const char *hstrerror(int err) {
switch (err) {
case HOST_NOT_FOUND:
return "HOST_NOT_FOUND";
case TRY_AGAIN:
return "TRY_AGAIN";
case NO_RECOVERY:
return "NO_RECOVERY";
case NO_DATA:
return "NO_DATA";
default:
return "UNKNOWN";
const char *GetServicesTxtPath(char *path, size_t size) {
if (!IsWindows()) {
return "/etc/services";
} else {
return GetSystemDirectoryPath(path, "drivers\\etc\\services", size);
}
}

View file

@ -16,19 +16,16 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/nt/systeminfo.h"
#include "libc/str/str.h"
// e.g. GetSystemDirectoryPath(buf, size, "FOO") → "C:\WINDOWS\SYSTEM32\FOO"
textwindows char *GetSystemDirectoryPath(char *buf, size_t size,
const char *path) {
// e.g. GetSystemDirectoryPath(buf, "FOO", size) → "C:\WINDOWS\SYSTEM32\FOO"
textwindows char *GetSystemDirectoryPath(char *buf, const char *path,
size_t size) {
uint32_t syslen = GetSystemDirectoryA(buf, size);
size_t pathlen = strlen(path);
if (syslen && syslen + pathlen + 1 < size) {
if (buf[syslen] == '\\') {
--syslen;
}
if (buf[syslen] == '\\') --syslen;
memcpy(buf + syslen, path, pathlen + 1);
return buf;
} else {

View file

@ -0,0 +1,11 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_SYSDIR_H_
#define COSMOPOLITAN_LIBC_CALLS_SYSDIR_H_
COSMOPOLITAN_C_START_
const char *GetHostsTxtPath(char *, size_t);
const char *GetServicesTxtPath(char *, size_t);
const char *GetProtocolsTxtPath(char *, size_t);
char *GetSystemDirectoryPath(char *, const char *, size_t);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_CALLS_SYSDIR_H_ */

View file

@ -1,59 +0,0 @@
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐
#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘
PKGS += LIBC_DNS
LIBC_DNS_ARTIFACTS += LIBC_DNS_A
LIBC_DNS = $(LIBC_DNS_A_DEPS) $(LIBC_DNS_A)
LIBC_DNS_A = o/$(MODE)/libc/dns/dns.a
LIBC_DNS_A_FILES := $(wildcard libc/dns/*)
LIBC_DNS_A_HDRS = $(filter %.h,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS_C = $(filter %.c,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS_S = $(filter %.S,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS = \
$(LIBC_DNS_A_SRCS_S) \
$(LIBC_DNS_A_SRCS_C)
LIBC_DNS_A_OBJS = \
$(LIBC_DNS_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(LIBC_DNS_A_SRCS_C:%.c=o/$(MODE)/%.o)
LIBC_DNS_A_CHECKS = \
$(LIBC_DNS_A).pkg \
$(LIBC_DNS_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_DNS_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT_ADVAPI32 \
LIBC_NT_KERNEL32 \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
LIBC_STR \
LIBC_SYSV
LIBC_DNS_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_DNS_A_DIRECTDEPS),$($(x))))
$(LIBC_DNS_A): libc/dns/ \
$(LIBC_DNS_A).pkg \
$(LIBC_DNS_A_OBJS)
$(LIBC_DNS_A).pkg: \
$(LIBC_DNS_A_OBJS) \
$(foreach x,$(LIBC_DNS_A_DIRECTDEPS),$($(x)_A).pkg)
LIBC_DNS_LIBS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)))
LIBC_DNS_SRCS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_SRCS))
LIBC_DNS_HDRS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_HDRS))
LIBC_DNS_CHECKS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_CHECKS))
LIBC_DNS_OBJS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_OBJS))
$(LIBC_DNS_OBJS): $(BUILD_FILES) libc/dns/BUILD.mk
.PHONY: o/$(MODE)/libc/dns
o/$(MODE)/libc/dns: $(LIBC_DNS_CHECKS)

View file

@ -1,77 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
forceinline void FindDnsLabel(const char *A, size_t *i, size_t *n) {
while (*i) {
if (A[*i - 1] == '.') {
if (*i == *n) {
--(*n);
} else {
break;
}
}
--(*i);
}
}
/**
* Compares DNS hostnames in reverse lexicographical asciibetical order.
* @return <0, 0, or >0
* @see test/libc/dns/comparednsnames_test.c (the code that matters)
*/
int CompareDnsNames(const char *A, const char *B) {
int res;
bool first;
size_t n, m, i, j;
if (A == B) return 0;
n = strlen(A);
m = strlen(B);
if (!n || !m || ((A[n - 1] == '.') ^ (B[m - 1] == '.'))) {
if (n && m && A[n - 1] == '.' && strchr(B, '.')) {
--m;
} else if (n && m && B[m - 1] == '.' && strchr(A, '.')) {
--n;
} else {
return A[n ? n - 1 : 0] - B[m ? m - 1 : 0];
}
}
i = n;
j = m;
first = true;
for (;;) {
FindDnsLabel(A, &i, &n);
FindDnsLabel(B, &j, &m);
if (first) {
first = false;
if (!i && j) return 1;
if (!j && i) return -1;
}
if ((res = strncasecmp(&A[i], &B[j], MIN(n - i + 1, m - j + 1)))) {
return res;
}
if (!i || !j) {
return i - j;
}
n = i;
m = j;
}
}

View file

@ -1,19 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#define COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#include "libc/sock/sock.h"
#define DNS_TYPE_A 1
#define DNS_TYPE_NS 2
#define DNS_TYPE_CNAME 5
#define DNS_TYPE_SOA 6
#define DNS_TYPE_PTR 12
#define DNS_TYPE_MX 15
#define DNS_TYPE_TXT 16
#define DNS_CLASS_IN 1
#define kMinSockaddr4Size \
(offsetof(struct sockaddr_in, sin_addr) + sizeof(struct in_addr))
#endif /* COSMOPOLITAN_LIBC_DNS_CONSTS_H_ */

View file

@ -1,79 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_DNS_H_
#define COSMOPOLITAN_LIBC_DNS_DNS_H_
#include "libc/dns/resolvconf.h"
#include "libc/sock/struct/sockaddr.h"
#define DNS_PORT 53
#define DNS_NAME_MAX 253
#define DNS_LABEL_MAX 63
#define EAI_SUCCESS 0
#define EAI_BADFLAGS -1
#define EAI_NONAME -2
#define EAI_AGAIN -3
#define EAI_FAIL -4
#define EAI_NODATA -5
#define EAI_FAMILY -6
#define EAI_SOCKTYPE -7
#define EAI_SERVICE -8
#define EAI_ADDRFAMILY -9
#define EAI_MEMORY -10
#define EAI_OVERFLOW -12
#define EAI_SYSTEM -11
#define EAI_ALLDONE -103
#define EAI_CANCELED -101
#define EAI_IDN_ENCODE -105
#define EAI_INPROGRESS -100
#define EAI_INTR -104
#define EAI_NOTCANCELED -102
/* AI_* conforms to NT ABI */
#define AI_PASSIVE 1
#define AI_CANONNAME 2
#define AI_NUMERICHOST 4
#define AI_NUMERICSERV 8
#define AI_ALL 0x0100
#define AI_ADDRCONFIG 0x0400
#define AI_V4MAPPED 0x0800
#define NI_NUMERICSCOPE 0
#define NI_NUMERICHOST 1
#define NI_NUMERICSERV 2
#define NI_NOFQDN 4
#define NI_NAMEREQD 8
#define NI_DGRAM 16
#define NI_MAXSERV 32
#define NI_MAXHOST 1025
COSMOPOLITAN_C_START_
struct addrinfo {
int32_t ai_flags; /* AI_XXX */
int32_t ai_family; /* AF_INET */
int32_t ai_socktype; /* SOCK_XXX */
int32_t ai_protocol; /* IPPROTO_XXX */
uint32_t ai_addrlen;
union {
struct sockaddr *ai_addr;
struct sockaddr_in *ai_addr4;
};
char *ai_canonname /*[DNS_NAME_MAX + 1]*/;
struct addrinfo *ai_next;
};
int getaddrinfo(const char *, const char *, const struct addrinfo *,
struct addrinfo **);
void freeaddrinfo(struct addrinfo *);
int getnameinfo(const struct sockaddr *, uint32_t, char *, uint32_t, char *,
uint32_t, int);
const char *gai_strerror(int);
int CompareDnsNames(const char *, const char *) paramsnonnull();
int PascalifyDnsName(uint8_t *, size_t, const char *) paramsnonnull();
int ResolveDns(const struct ResolvConf *, int, const char *, struct sockaddr *,
uint32_t) paramsnonnull();
int ResolveDnsReverse(const struct ResolvConf *, int, const char *, char *,
size_t) paramsnonnull();
struct addrinfo *newaddrinfo(uint16_t);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_DNS_H_ */

View file

@ -1,57 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dnsheader.h"
#include "libc/serialize.h"
#include "libc/sysv/errfuns.h"
/**
* Serializes DNS message h to wire.
*
* @return number of bytes written (always 12) or -1 w/ errno
* @see pascalifydnsname()
*/
void SerializeDnsHeader(uint8_t p[restrict 12], const struct DnsHeader *h) {
p[0x0] = h->id >> 8;
p[0x1] = h->id;
p[0x2] = h->bf1;
p[0x3] = h->bf2;
p[0x4] = h->qdcount >> 8;
p[0x5] = h->qdcount;
p[0x6] = h->ancount >> 8;
p[0x7] = h->ancount;
p[0x8] = h->nscount >> 8;
p[0x9] = h->nscount;
p[0xa] = h->arcount >> 8;
p[0xb] = h->arcount;
}
/**
* Serializes DNS message h to wire.
*
* @return number of bytes read (always 12) or -1 w/ errno
*/
void DeserializeDnsHeader(struct DnsHeader *h, const uint8_t p[restrict 12]) {
h->id = READ16BE(p);
h->bf1 = p[2];
h->bf2 = p[3];
h->qdcount = READ16BE(p + 4);
h->ancount = READ16BE(p + 6);
h->nscount = READ16BE(p + 8);
h->arcount = READ16BE(p + 10);
}

View file

@ -1,19 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_
#define COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_
COSMOPOLITAN_C_START_
struct DnsHeader {
uint16_t id; /* transaction id */
uint8_t bf1; /* bit field 1 */
uint8_t bf2; /* bit field 2 */
uint16_t qdcount; /* question count */
uint16_t ancount; /* answer count */
uint16_t nscount; /* nameserver count */
uint16_t arcount; /* additional record count */
};
void SerializeDnsHeader(uint8_t[restrict 12], const struct DnsHeader *);
void DeserializeDnsHeader(struct DnsHeader *, const uint8_t[restrict 12]);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_ */

View file

@ -1,14 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_DNSQUESTION_H_
#define COSMOPOLITAN_LIBC_DNS_DNSQUESTION_H_
COSMOPOLITAN_C_START_
struct DnsQuestion {
const char *qname;
uint16_t qtype;
uint16_t qclass;
};
int SerializeDnsQuestion(uint8_t *, size_t, const struct DnsQuestion *);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_DNSQUESTION_H_ */

View file

@ -1,73 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_ENT_H_
#define COSMOPOLITAN_LIBC_DNS_ENT_H_
#include "libc/dns/dns.h"
#define HOST_NOT_FOUND 1
#define TRY_AGAIN 2
#define NO_RECOVERY 3
#define NO_DATA 4
#define NO_ADDRESS NO_DATA
COSMOPOLITAN_C_START_
struct netent {
char *n_name; /* official network name */
char **n_aliases; /* alias list */
int n_addrtype; /* net address type */
uint32_t n_net; /* network number */
};
struct protoent {
char *p_name; /* official protocol name */
char **p_aliases; /* alias list */
int p_proto; /* protocol number */
};
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#define h_addr h_addr_list[0]
struct servent {
char *s_name; /* official service name */
char **s_aliases; /* alias list */
int s_port; /* port number (in network byte order) */
char *s_proto; /* protocol to use */
};
#define h_errno (*__h_errno_location())
errno_t *__h_errno_location(void) dontthrow pureconst;
void herror(const char *);
const char *hstrerror(int);
struct netent *getnetent(void);
struct netent *getnetbyname(const char *);
struct netent *getnetbyaddr(uint32_t, int);
void setnetent(int);
void endnetent(void);
struct protoent *getprotoent(void);
struct protoent *getprotobyname(const char *);
struct protoent *getprotobynumber(int);
void setprotoent(int);
void endprotoent(void);
struct hostent *gethostent(void);
struct hostent *gethostbyname(const char *);
struct hostent *gethostbyaddr(const void *, uint32_t, int);
void sethostent(int);
void endhostent(void);
struct servent *getservent(void);
struct servent *getservbyname(const char *, const char *);
struct servent *getservbyport(int, const char *);
void setservent(int);
void endservent(void);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_ENT_H_ */

View file

@ -1,67 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
/**
* Turns getaddrinfo() return code into string.
*/
const char *gai_strerror(int code) {
switch (code) {
case EAI_ADDRFAMILY:
return "ADDRFAMILY";
case EAI_AGAIN:
return "AGAIN";
case EAI_ALLDONE:
return "ALLDONE";
case EAI_BADFLAGS:
return "BADFLAGS";
case EAI_CANCELED:
return "CANCELED";
case EAI_FAIL:
return "FAIL";
case EAI_FAMILY:
return "FAMILY";
case EAI_IDN_ENCODE:
return "ENCODE";
case EAI_INPROGRESS:
return "INPROGRESS";
case EAI_INTR:
return "INTR";
case EAI_MEMORY:
return "MEMORY";
case EAI_NODATA:
return "NODATA";
case EAI_NONAME:
return "NONAME";
case EAI_NOTCANCELED:
return "NOTCANCELED";
case EAI_OVERFLOW:
return "OVERFLOW";
case EAI_SERVICE:
return "SERVICE";
case EAI_SOCKTYPE:
return "SOCKTYPE";
case EAI_SUCCESS:
return "SUCCESS";
case EAI_SYSTEM:
return "SYSTEM";
default:
return "???";
}
}

View file

@ -1,116 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/resolvconf.h"
#include "libc/dns/servicestxt.h"
#include "libc/fmt/conv.h"
#include "libc/macros.internal.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
/**
* Resolves address for internet name.
*
* @param name is either an ip string or a utf-8 hostname
* @param service is the port number as a string
* @param hints may be passed to specialize behavior (optional)
* @param res receives a pointer that must be freed with freeaddrinfo(),
* and won't be modified if non-zero is returned
* @return 0 on success or EAI_xxx value
*/
int getaddrinfo(const char *name, const char *service,
const struct addrinfo *hints, struct addrinfo **res) {
char *eptr;
int rc, port;
char proto[32];
const char *canon;
struct addrinfo *ai;
port = 0;
if (!name && !service) {
return EAI_NONAME;
}
if (!name && hints && (hints->ai_flags & AI_CANONNAME)) {
return EAI_BADFLAGS;
}
if (service && ((port = strtol(service, &eptr, 10)), *eptr)) {
if (hints && hints->ai_socktype == SOCK_STREAM) {
strcpy(proto, "tcp");
} else if (hints && hints->ai_socktype == SOCK_DGRAM) {
strcpy(proto, "udp");
} else { // ai_socktype == 0
strcpy(proto, "");
}
if ((port = LookupServicesByName(service, proto, sizeof(proto), NULL, 0,
NULL)) == -1) {
return EAI_NONAME;
}
}
if (!(ai = newaddrinfo(port))) {
return EAI_MEMORY;
}
if (service) {
// if service isn't specified, port is left uninitialized
ai->ai_addr4->sin_port = htons(port);
}
if (hints) {
ai->ai_socktype = hints->ai_socktype;
ai->ai_protocol = hints->ai_protocol;
}
if (!name) {
ai->ai_addr4->sin_addr.s_addr =
(hints && (hints->ai_flags & AI_PASSIVE) == AI_PASSIVE)
? htonl(INADDR_ANY)
: htonl(INADDR_LOOPBACK);
*res = ai;
return 0;
}
if (inet_pton(AF_INET, name, &ai->ai_addr4->sin_addr.s_addr) == 1) {
*res = ai;
return 0;
} else if (hints && (hints->ai_flags & AI_NUMERICHOST) == AI_NUMERICHOST) {
freeaddrinfo(ai);
return EAI_NONAME;
} else if (ResolveHostsTxt(GetHostsTxt(), AF_INET, name, ai->ai_addr,
sizeof(ai->ai_addr4), &canon) > 0) {
strlcpy(ai->ai_canonname, canon, DNS_NAME_MAX + 1);
*res = ai;
return 0;
} else {
rc = ResolveDns(GetResolvConf(), AF_INET, name, ai->ai_addr,
sizeof(ai->ai_addr4));
if (rc > 0) {
*res = ai;
return 0;
}
freeaddrinfo(ai);
if (rc == 0) {
return EAI_NONAME;
} else {
return EAI_SYSTEM;
}
}
}

View file

@ -1,58 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/mem/mem.h"
#include "libc/sysv/consts/af.h"
struct hostent *gethostbyaddr(const void *s_addr, uint32_t len, int type) {
static struct hostent *ptr1, he1;
static char h_name[DNS_NAME_MAX + 1];
static char *h_aliases[1];
static char *h_addr_list[2];
static char h_addr_list0[4];
struct sockaddr_in addr;
if (!ptr1) {
he1.h_name = h_name;
he1.h_aliases = h_aliases;
he1.h_aliases[0] = NULL;
he1.h_addrtype = AF_INET;
he1.h_length = 4;
he1.h_addr_list = h_addr_list;
he1.h_addr_list[0] = h_addr_list0;
he1.h_addr_list[1] = NULL;
ptr1 = &he1;
}
if (type != AF_INET || len != sizeof(uint32_t)) return NULL;
addr.sin_family = AF_INET;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(uint32_t *)(s_addr);
if (getnameinfo((struct sockaddr *)&addr, sizeof(addr), ptr1->h_name,
DNS_NAME_MAX, NULL, 0, 0))
return NULL;
*((uint32_t *)ptr1->h_addr_list[0]) = (addr.sin_addr.s_addr);
return ptr1;
}

View file

@ -1,70 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
struct hostent *gethostbyname(const char *name) {
static struct hostent *ptr0, he0;
static char h_name[DNS_NAME_MAX + 1];
static char *h_aliases[1];
static char *h_addr_list[2];
static char h_addr_list0[4];
struct addrinfo *result = NULL;
if (!ptr0) {
he0.h_name = h_name;
he0.h_aliases = h_aliases;
he0.h_aliases[0] = NULL;
he0.h_addrtype = AF_INET;
he0.h_length = 4;
he0.h_addr_list = h_addr_list;
he0.h_addr_list[0] = h_addr_list0;
he0.h_addr_list[1] = NULL;
ptr0 = &he0;
}
if (getaddrinfo(name, NULL, NULL, &result) || result == NULL) {
return NULL;
}
/* if getaddrinfo is successful, result->ai_canonname is non-NULL,
* (see newaddrinfo) but the string can still be empty */
strlcpy(ptr0->h_name, *result->ai_canonname ? result->ai_canonname : name,
sizeof(h_name));
*((uint32_t *)ptr0->h_addr_list[0]) = result->ai_addr4->sin_addr.s_addr;
/* TODO: if result has ai_next, fit multiple entries for h_addr_list */
freeaddrinfo(result);
return ptr0;
}

View file

@ -1,94 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/cxxabi.h"
#include "libc/dce.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/servicestxt.h"
#include "libc/intrin/pushpop.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/thread/thread.h"
static struct HostsTxt *g_hoststxt;
static struct HostsTxtInitialStaticMemory {
struct HostsTxt ht;
pthread_mutex_t lock;
struct HostsTxtEntry entries[8];
char strings[64];
} g_hoststxt_init;
static const char *GetHostsTxtPath(char *path, size_t size) {
if (!IsWindows()) {
return "/etc/hosts";
} else {
return GetSystemDirectoryPath(path, size, "drivers\\etc\\hosts");
}
}
/**
* Returns hosts.txt map.
*
* @note yoinking realloc() ensures there's no size limits
*/
const struct HostsTxt *GetHostsTxt(void) {
FILE *f;
char pathbuf[256];
struct HostsTxtInitialStaticMemory *init;
init = &g_hoststxt_init;
pthread_mutex_lock(&init->lock);
if (!g_hoststxt) {
g_hoststxt = &init->ht;
init->ht.entries.n = pushpop(ARRAYLEN(init->entries));
init->ht.entries.p = init->entries;
init->ht.strings.n = pushpop(ARRAYLEN(init->strings));
init->ht.strings.p = init->strings;
__cxa_atexit((void *)FreeHostsTxt, &g_hoststxt, NULL);
if ((f = fopen(GetHostsTxtPath(pathbuf, sizeof(pathbuf)), "r"))) {
if (ParseHostsTxt(g_hoststxt, f) == -1) {
/* TODO(jart): Elevate robustness. */
}
fclose(f);
}
}
pthread_mutex_unlock(&init->lock);
return g_hoststxt;
}
/**
* Frees HOSTS.TXT data structure populated by ParseHostsTxt().
*/
void FreeHostsTxt(struct HostsTxt **ht) {
if (*ht) {
if ((*ht)->entries.p != g_hoststxt_init.entries) {
free((*ht)->entries.p);
}
if ((*ht)->strings.p != g_hoststxt_init.strings) {
free((*ht)->strings.p);
}
if (*ht != &g_hoststxt_init.ht) {
free(*ht);
}
*ht = 0;
}
}

View file

@ -1,115 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/resolvconf.h"
#include "libc/dns/servicestxt.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/errfuns.h"
/**
* Resolves name/service for socket address.
*
* @param addr
* @param addrlen
* @param name
* @param namelen
* @param service
* @param servicelen
* @param flags
*
* @return 0 on success or EAI_xxx value
*/
int getnameinfo(const struct sockaddr *addr, uint32_t addrlen, char *name,
uint32_t namelen, char *service, uint32_t servicelen,
int flags) {
char *p, rdomain[1 + sizeof "255.255.255.255.in-addr.arpa"];
char info[NI_MAXHOST + 1];
int port;
uint8_t *ip;
unsigned int valid_flags;
valid_flags =
(NI_NAMEREQD | NI_NUMERICHOST | NI_NUMERICSERV | NI_NOFQDN | NI_DGRAM);
if (flags & ~(valid_flags)) return EAI_BADFLAGS;
if (!name && !service) return EAI_NONAME;
if (addr->sa_family != AF_INET || addrlen < sizeof(struct sockaddr_in))
return EAI_FAMILY;
ip = (uint8_t *)&(((struct sockaddr_in *)addr)->sin_addr);
p = rdomain;
p = FormatUint32(p, ip[3]), *p++ = '.';
p = FormatUint32(p, ip[2]), *p++ = '.';
p = FormatUint32(p, ip[1]), *p++ = '.';
p = FormatUint32(p, ip[0]), stpcpy(p, ".in-addr.arpa");
info[0] = '\0';
if (name != NULL && namelen != 0) {
if ((flags & NI_NUMERICHOST) && (flags & NI_NAMEREQD)) return EAI_NONAME;
if ((flags & NI_NUMERICHOST) &&
inet_ntop(AF_INET, ip, info, sizeof(info)) == NULL)
return EAI_SYSTEM;
else if (!info[0] && ResolveHostsReverse(GetHostsTxt(), AF_INET, ip, info,
sizeof(info)) < 0)
return EAI_SYSTEM;
else if (!info[0] && ResolveDnsReverse(GetResolvConf(), AF_INET, rdomain,
info, sizeof(info)) < 0)
return EAI_SYSTEM;
else if (!info[0] && (flags & NI_NAMEREQD))
return EAI_NONAME;
else if (!info[0] && inet_ntop(AF_INET, ip, info, sizeof(info)) == NULL)
return EAI_SYSTEM;
if (strlen(info) + 1 > namelen) return EAI_OVERFLOW;
strcpy(name, info);
}
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
info[0] = '\0';
if (service != NULL && servicelen != 0) {
if ((flags & NI_NUMERICSERV) ||
LookupServicesByPort(port, ((flags & NI_DGRAM) ? "udp" : "tcp"), 4,
info, sizeof(info), NULL) == -1) {
FormatInt32(info, port);
}
if (strlen(info) + 1 > servicelen) {
return EAI_OVERFLOW;
}
strcpy(service, info);
}
return 0;
}

View file

@ -1,93 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dns/dns.h"
#include "libc/dns/resolvconf.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/nt/enum/keyaccess.h"
#include "libc/nt/enum/reggetvalueflags.h"
#include "libc/nt/registry.h"
#include "libc/nt/runtime.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
/**
* Extracts DNS nameserver IPs from Windows Registry.
*
* @param resolv points to a ResolvConf object, which should be zero
* initialized by the caller; or if it already contains items,
* this function will append
* @return number of nameservers appended, or -1 w/ errno
*/
textwindows int GetNtNameServers(struct ResolvConf *resolv) {
int rc;
char value8[128];
int64_t hkInterfaces;
char *state, *addr, *tmp;
struct sockaddr_in nameserver;
char16_t value[128], uuid[64];
uint32_t i, keycount, valuebytes, uuidlen;
keycount = 0;
hkInterfaces = kNtInvalidHandleValue;
if (!RegOpenKeyEx(
kNtHkeyLocalMachine,
u"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces",
0, kNtKeyRead, &hkInterfaces) &&
!RegQueryInfoKey(hkInterfaces, 0, 0, 0, &keycount, 0, 0, 0, 0, 0, 0, 0)) {
nameserver.sin_family = AF_INET;
nameserver.sin_port = htons(DNS_PORT);
rc = 0;
for (i = 0; i < keycount; ++i) {
uuidlen = sizeof(uuid);
if (!RegEnumKeyEx(hkInterfaces, i, uuid, &uuidlen, 0, 0, 0, 0) &&
((!RegGetValue(hkInterfaces, uuid, u"DhcpIpAddress",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)) ||
(!RegGetValue(hkInterfaces, uuid, u"IpAddress",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t))) &&
((!RegGetValue(hkInterfaces, uuid, u"DhcpNameServer",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)) ||
(!RegGetValue(hkInterfaces, uuid, u"NameServer",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)))) {
tprecode16to8(value8, sizeof(value8), value);
tmp = value8;
while ((addr = strtok_r(tmp, ", ", &state))) {
if (inet_pton(AF_INET, addr, &nameserver.sin_addr.s_addr) == 1) {
if (append(&resolv->nameservers, &nameserver) != -1) ++rc;
}
tmp = NULL;
}
}
}
} else {
rc = __winerr();
}
RegCloseKey(hkInterfaces);
return rc;
}

View file

@ -1,37 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/prototxt.h"
#include "libc/dns/servicestxt.h"
const char *GetProtocolsTxtPath(char *buf, size_t size) {
if (!IsWindows()) {
return "/etc/protocols";
} else {
return GetSystemDirectoryPath(buf, size, "drivers\\etc\\protocol");
}
}

View file

@ -1,36 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/servicestxt.h"
const char *GetServicesTxtPath(char *path, size_t size) {
if (!IsWindows()) {
return "/etc/services";
} else {
return GetSystemDirectoryPath(path, size, "drivers\\etc\\services");
}
}

View file

@ -1,46 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/dns/prototxt.h"
#include "libc/mem/mem.h"
struct protoent *getprotobyname(const char *name) {
static struct protoent *ptr0, pe0;
static char p_name[DNS_NAME_MAX + 1];
if (!ptr0) {
pe0.p_name = p_name;
if (!(pe0.p_aliases = calloc(1, sizeof(char *)))) return NULL;
pe0.p_proto = -1;
ptr0 = &pe0;
}
ptr0->p_proto = LookupProtoByName(name, ptr0->p_name, DNS_NAME_MAX, NULL);
if (ptr0->p_proto == -1) return NULL;
return ptr0;
}

View file

@ -1,47 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/dns/prototxt.h"
#include "libc/mem/mem.h"
struct protoent *getprotobynumber(int proto) {
static struct protoent *ptr1, pe1;
static char p_name[DNS_NAME_MAX + 1];
if (!ptr1) {
pe1.p_name = p_name;
if (!(pe1.p_aliases = calloc(1, sizeof(char *)))) return NULL;
pe1.p_proto = -1;
ptr1 = &pe1;
}
if (LookupProtoByNumber(proto, ptr1->p_name, DNS_NAME_MAX, NULL) == -1)
return NULL;
ptr1->p_proto = proto;
return ptr1;
}

View file

@ -1,83 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/cxxabi.h"
#include "libc/dce.h"
#include "libc/dns/resolvconf.h"
#include "libc/intrin/pushpop.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/stdio.h"
#include "libc/thread/thread.h"
static struct ResolvConf *g_resolvconf;
static struct ResolvConfInitialStaticMemory {
struct ResolvConf rv;
pthread_mutex_t lock;
struct sockaddr_in nameservers[3];
} g_resolvconf_init;
/**
* Returns singleton with DNS server address.
*/
const struct ResolvConf *GetResolvConf(void) {
int rc;
FILE *f;
struct ResolvConfInitialStaticMemory *init;
init = &g_resolvconf_init;
pthread_mutex_lock(&init->lock);
if (!g_resolvconf) {
g_resolvconf = &init->rv;
pushmov(&init->rv.nameservers.n, ARRAYLEN(init->nameservers));
init->rv.nameservers.p = init->nameservers;
__cxa_atexit((void *)FreeResolvConf, &g_resolvconf, NULL);
if (!IsWindows()) {
if ((f = fopen("/etc/resolv.conf", "r"))) {
rc = ParseResolvConf(g_resolvconf, f);
} else {
rc = -1;
}
fclose(f);
} else {
rc = GetNtNameServers(g_resolvconf);
}
if (rc == -1 && !IsTiny()) {
/* TODO(jart): Elevate robustness. */
}
}
pthread_mutex_unlock(&init->lock);
return g_resolvconf;
}
/**
* Frees resolv.conf data structure populated by ParseResolvConf().
*/
void FreeResolvConf(struct ResolvConf **rvp) {
if (*rvp) {
if ((*rvp)->nameservers.p != g_resolvconf_init.nameservers) {
free((*rvp)->nameservers.p);
}
if (*rvp != &g_resolvconf_init.rv) {
free(*rvp);
}
*rvp = 0;
}
}

View file

@ -1,55 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/dns/servicestxt.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
struct servent *getservbyname(const char *name, const char *proto) {
static struct servent *ptr0, se0;
static char s_name[DNS_NAME_MAX + 1];
static char localproto[DNS_NAME_MAX + 1];
int p;
if (!ptr0) {
se0.s_name = s_name;
if (!(se0.s_aliases = calloc(1, sizeof(char *)))) return NULL;
se0.s_port = 0;
se0.s_proto = localproto;
ptr0 = &se0;
}
if (proto) {
strlcpy(localproto, proto, sizeof(localproto));
} else {
*localproto = 0;
}
p = LookupServicesByName(name, ptr0->s_proto, DNS_NAME_MAX, ptr0->s_name,
DNS_NAME_MAX, NULL);
if (p == -1) return NULL;
ptr0->s_port = htons(p);
return ptr0;
}

View file

@ -1,56 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/dns/servicestxt.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
struct servent *getservbyport(int port, const char *proto) {
static struct servent *ptr1, se1;
static char s_name[DNS_NAME_MAX + 1];
static char localproto[DNS_NAME_MAX + 1];
if (!ptr1) {
se1.s_name = s_name;
if (!(se1.s_aliases = calloc(1, sizeof(char *)))) return NULL;
se1.s_port = 0;
se1.s_proto = localproto;
ptr1 = &se1;
}
if (proto) {
if (!memccpy(localproto, proto, '\0', DNS_NAME_MAX)) {
return NULL;
}
} else {
*localproto = 0;
}
if (LookupServicesByPort(ntohs(port), ptr1->s_proto, DNS_NAME_MAX,
ptr1->s_name, DNS_NAME_MAX, NULL) == -1) {
return NULL;
}
ptr1->s_port = port;
return ptr1;
}

View file

@ -1,36 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
#include "libc/stdio/stdio.h"
/**
* Prints `h_errno` description to stderr.
* @see perror()
*/
void herror(const char *s) {
fprintf(stderr, "%s%s%s\n", s ? s : "", s ? ": " : "", hstrerror(h_errno));
}

View file

@ -1,37 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
struct hostent *gethostent(void) {
return NULL;
}
void sethostent(int stayopen) {
}
void endhostent(void) {
}

View file

@ -1,38 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_
#define COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
struct HostsTxtEntry {
uint8_t ip[4]; /* inet_ntop(AF_INET, he->ip, buf, size) */
uint32_t name; /* &ht->strings.p[he->name] */
uint32_t canon; /* &ht->strings.p[he->canon] */
};
struct HostsTxtEntries {
size_t i, n;
struct HostsTxtEntry *p;
};
struct HostsTxtStrings {
size_t i, n;
char *p;
};
struct HostsTxt {
struct HostsTxtEntries entries;
struct HostsTxtStrings strings;
};
const struct HostsTxt *GetHostsTxt(void) returnsnonnull;
void FreeHostsTxt(struct HostsTxt **) paramsnonnull();
int ParseHostsTxt(struct HostsTxt *, FILE *) paramsnonnull();
int ResolveHostsTxt(const struct HostsTxt *, int, const char *,
struct sockaddr *, uint32_t, const char **)
paramsnonnull((1, 3));
int ResolveHostsReverse(const struct HostsTxt *, int, const uint8_t *, char *,
size_t) paramsnonnull((1, 3));
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_ */

View file

@ -1,101 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/prototxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/protocols to find number for a given name.
*
* @param protoname is a NULL-terminated string
* @param buf is a buffer to store the official name of the protocol
* @param bufsize is the size of buf
* @param filepath is the location of protocols file
* (if NULL, uses /etc/protocols)
* @return -1 on error, or
* positive protocol number
*
* @note aliases are read from file for comparison, but not returned.
* @see LookupProtoByNumber
*/
int LookupProtoByName(const char *protoname, char *buf, size_t bufsize,
const char *filepath) {
FILE *f;
char *line;
size_t linesize;
const char *path;
int found, result;
char pathbuf[256];
char *name, *number, *alias, *comment, *tok;
if (!(path = filepath)) {
path =
!IsWindows()
? "/etc/protocols"
: firstnonnull(GetProtocolsTxtPath(pathbuf, sizeof(pathbuf)), path);
}
if (bufsize == 0 || !(f = fopen(path, "r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
result = -1;
while (found == 0 && getline(&line, &linesize, f) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
number = strtok_r(NULL, "/ \t\r\n\v", &tok);
if (name && number) {
alias = name;
while (alias && strcasecmp(alias, protoname)) {
alias = strtok_r(NULL, " \t\r\n\v", &tok);
}
if (alias) { /* alias matched with protoname */
if (!memccpy(buf, name, '\0', bufsize)) {
if (bufsize) {
*buf = 0;
}
break;
}
result = atoi(number);
found = 1;
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return result;
}

View file

@ -1,90 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/prototxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/protocols to find name for a given number.
*
* The format of /etc/protocols is like this:
*
* # comment
* # NAME PROTOCOL ALIASES
* ip 0 IP
* icmp 1 ICMP
*
* @param protonum is the protocol number
* @param buf is a buffer to store the official name of the protocol
* @param bufsize is the size of buf
* @param path is the location of the protocols file, which may be NULL
* to use the system-wide default
* @return 0 on success, -1 on error
* @note aliases are not read from the file.
*/
int LookupProtoByNumber(const int protonum, char *buf, size_t bufsize,
const char *path) {
FILE *f;
int found;
char *line;
size_t linesize;
char pathbuf[256];
char *name, *number, *comment, *tok;
if (!bufsize ||
!(f = fopen(path ? path : GetProtocolsTxtPath(pathbuf, sizeof(pathbuf)),
"r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
number = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && number && protonum == atoi(number)) {
if (!memccpy(buf, name, '\0', bufsize)) {
strcpy(buf, "");
break;
}
found = 1;
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
fclose(f);
return -1;
}
fclose(f);
if (!found) return -1;
return 0;
}

View file

@ -1,107 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/servicestxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/services to find port for a given name.
*
* @param servname is a NULL-terminated string
* @param servproto is a NULL-terminated string (eg "tcp", "udp")
* (if servproto is an empty string,
* if is filled with the first matching
* protocol)
* @param servprotolen the size of servproto
* @param buf is a buffer to store the official name of the service
* (if NULL, the official name is not stored)
* @param bufsize is the size of buf
* @param path is the location of services file
* (if NULL, uses /etc/services)
* @return -1 on error, or positive port number
* @note aliases are read from file for comparison, but not returned.
* @see LookupServicesByPort
*/
int LookupServicesByName(const char *servname, char *servproto,
size_t servprotolen, char *buf, size_t bufsize,
const char *path) {
FILE *f;
char *line;
size_t linesize;
char pathbuf[256];
int found, result;
char *name, *port, *proto, *alias, *comment, *tok;
if (servprotolen == 0 ||
!(f = fopen(path ? path : GetServicesTxtPath(pathbuf, sizeof(pathbuf)),
"r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
result = -1;
if (bufsize) strcpy(buf, "");
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
port = strtok_r(NULL, "/ \t\r\n\v", &tok);
proto = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && port && proto) {
alias = name;
while (alias && strcasecmp(alias, servname) != 0)
alias = strtok_r(NULL, " \t\r\n\v", &tok);
if (alias) /* alias matched with servname */
{
if (!servproto[0] || strncasecmp(proto, servproto, servprotolen) == 0) {
if (!servproto[0] && !memccpy(servproto, proto, '\0', servprotolen)) {
strcpy(servproto, "");
break;
}
if (bufsize && !memccpy(buf, name, '\0', bufsize)) {
*buf = 0;
break;
}
result = atoi(port);
found = 1;
}
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return result;
}

View file

@ -1,107 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/dns/servicestxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/services to find name for a given port.
*
* The format of /etc/services is like this:
*
* # comment
* # NAME PORT/PROTOCOL ALIASES
* ftp 21/tcp
* fsp 21/udp fspd
* ssh 22/tcp
*
* @param servport is the port number
* @param servproto is a NULL-terminated string (eg "tcp", "udp")
* (if servproto is an empty string,
* if is filled with the first matching
* protocol)
* @param servprotolen the size of servproto
* @param buf is a buffer to store the official name of the service
* @param bufsize is the size of buf
* @param path is the location of the services file, which may be NULL
* to use the system-wide default
* @return 0 on success, -1 on error
* @note aliases are not read from the file.
*/
int LookupServicesByPort(const int servport, char *servproto,
size_t servprotolen, char *buf, size_t bufsize,
const char *path) {
FILE *f;
int found;
char *line;
size_t linesize;
char pathbuf[256];
char *name, *port, *proto, *comment, *tok;
if (!servprotolen ||
!(f = fopen(path ? path : GetServicesTxtPath(pathbuf, sizeof(pathbuf)),
"r"))) {
return -1;
}
found = 0;
line = NULL;
linesize = 0;
if (bufsize) *buf = 0;
while (!found && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
port = strtok_r(NULL, "/ \t\r\n\v", &tok);
proto = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && port && proto && servport == atoi(port)) {
if (!servproto[0] || strncasecmp(proto, servproto, servprotolen) == 0) {
if (!servproto[0] && !memccpy(servproto, proto, '\0', servprotolen)) {
strcpy(servproto, "");
break;
}
if (!memccpy(buf, name, '\0', bufsize)) {
if (bufsize) {
*buf = 0;
}
break;
}
found = 1;
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return 0;
}

View file

@ -1,45 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
struct netent *getnetent(void) {
return NULL;
}
struct netent *getnetbyname(const char *name) {
return NULL;
}
struct netent *getnetbyaddr(uint32_t net, int type) {
return NULL;
}
void setnetent(int stayopen) {
}
void endnetent(void) {
}

View file

@ -1,39 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
#define SIZE sizeof(struct addrinfo)
#define ADDRLEN sizeof(struct sockaddr_in)
struct addrinfo *newaddrinfo(uint16_t port) {
struct addrinfo *ai;
if ((ai = calloc(1, SIZE + ADDRLEN + DNS_NAME_MAX + 1))) {
ai->ai_family = AF_INET;
ai->ai_addrlen = ADDRLEN;
ai->ai_addr4 = (struct sockaddr_in *)((char *)ai + SIZE);
ai->ai_addr4->sin_family = AF_INET;
ai->ai_addr4->sin_port = htons(port);
ai->ai_canonname = (char *)ai + SIZE + ADDRLEN;
}
return ai;
}

View file

@ -1,72 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/errno.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
/**
* Parses HOSTS.TXT contents.
*
* Hostnames were invented by Peggy Karp; her format looks like this:
*
* # this is a comment
* # IP CANON [ALT...]
* 203.0.113.1 lol.example. lol
* 203.0.113.2 cat.example. cat
*
* @param htp points to a HostsTxt object, which should be zero
* initialized by the caller; or if it already contains items,
* this function will append
* @param f is the file content; see fopen() and fmemopen()
* @return 0 on success, or -1 w/ errno
* @see hoststxtsort() which is the logical next step
*/
int ParseHostsTxt(struct HostsTxt *ht, FILE *f) {
char *line;
size_t linesize;
struct HostsTxtEntry entry;
char *addr, *name, *tok, *comment;
line = NULL;
linesize = 0;
while ((getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
if ((addr = strtok_r(line, " \t\r\n\v", &tok)) &&
inet_pton(AF_INET, addr, entry.ip) == 1) {
entry.canon = ht->strings.i;
while ((name = strtok_r(NULL, " \t\r\n\v", &tok))) {
entry.name = ht->strings.i;
concat(&ht->strings, name, strnlen(name, DNS_NAME_MAX) + 1);
append(&ht->entries, &entry);
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
return 0;
}

View file

@ -1,68 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/resolvconf.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
/**
* Parses /etc/resolv.conf file.
*
* The content of the file usually looks like this:
*
* nameserver 8.8.8.8
* nameserver 8.8.4.4
*
* @param resolv points to a ResolvConf object, which should be zero
* initialized by the caller; or if it already contains items,
* this function will append
* @param f is an open stream with file content
* @return number of nameservers appended, or -1 w/ errno
*/
int ParseResolvConf(struct ResolvConf *resolv, struct FILE *f) {
/* TODO(jart): options ndots:5 */
int rc;
char *line;
size_t linesize;
struct sockaddr_in nameserver;
char *directive, *value, *tok, *comment;
rc = 0;
line = 0;
linesize = 0;
nameserver.sin_family = AF_INET;
nameserver.sin_port = htons(DNS_PORT);
while (getline(&line, &linesize, f) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
if ((directive = strtok_r(line, " \t\r\n\v", &tok)) &&
(value = strtok_r(NULL, " \t\r\n\v", &tok))) {
if ((strcmp(directive, "nameserver") == 0 &&
inet_pton(AF_INET, value, &nameserver.sin_addr.s_addr) == 1)) {
if (append(&resolv->nameservers, &nameserver) != -1) ++rc;
}
}
}
free(line);
return rc | ferror(f);
}

View file

@ -1,58 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
/**
* Writes dotted hostname to DNS message wire.
*
* The wire format is basically a sequence of Pascal strings, for each
* label in the name. We only do enough validation to maintain protocol
* invariants.
*
* @param name is a dotted NUL-terminated hostname string
* @return bytes written (excluding NUL) or -1 w/ errno
*/
int PascalifyDnsName(uint8_t *buf, size_t size, const char *name) {
size_t i, j, k, namelen;
if ((namelen = strlen(name)) > DNS_NAME_MAX) return enametoolong();
i = 0;
if (size || namelen) {
if (namelen + 1 > size) return enospc();
buf[0] = '\0';
j = 0;
for (;;) {
for (k = 0; name[j + k] && name[j + k] != '.'; ++k) {
buf[i + k + 1] = name[j + k];
}
if (k) {
if (k > DNS_LABEL_MAX) return enametoolong();
buf[i] = k;
i += k + 1;
}
j += k + 1;
if (!name[j - 1]) {
break;
}
}
buf[i] = '\0';
}
return i;
}

View file

@ -1,37 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
struct protoent *getprotoent(void) {
return NULL;
}
void setprotoent(int stayopen) {
}
void endprotoent(void) {
}

View file

@ -1,17 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_
#define COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
const char *GetProtocolsTxtPath(char *, size_t);
int LookupProtoByNumber(const int, char *, size_t, const char *)
paramsnonnull((2));
int LookupProtoByName(const char *, char *, size_t, const char *)
paramsnonnull((1, 2));
/* TODO: implement like struct HostsTxt? */
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_ */

View file

@ -1,22 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_
#define COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
struct Nameservers {
size_t i, n;
struct sockaddr_in *p;
};
struct ResolvConf {
struct Nameservers nameservers;
};
const struct ResolvConf *GetResolvConf(void) returnsnonnull;
int ParseResolvConf(struct ResolvConf *, struct FILE *) paramsnonnull();
void FreeResolvConf(struct ResolvConf **) paramsnonnull();
int GetNtNameServers(struct ResolvConf *) paramsnonnull();
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_ */

View file

@ -1,113 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/dnsheader.h"
#include "libc/dns/dnsquestion.h"
#include "libc/dns/resolvconf.h"
#include "libc/serialize.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
#define kMsgMax 512
/**
* Queries Domain Name System for address associated with name.
*
* @param resolvconf can be GetResolvConf()
* @param af can be AF_INET, AF_UNSPEC
* @param name can be a local or fully-qualified hostname
* @param addr should point to a struct sockaddr_in; if this function
* succeeds, its sin_family and sin_addr fields will be modified
* @param addrsize is the byte size of addr
* @return number of matches found, or -1 w/ errno
* @error EAFNOSUPPORT. ENETDOWN, ENAMETOOLONG, EBADMSG
*/
int ResolveDns(const struct ResolvConf *resolvconf, int af, const char *name,
struct sockaddr *addr, uint32_t addrsize) {
int rc, fd, n;
struct DnsQuestion q;
struct DnsHeader h, h2;
struct sockaddr_in *a4;
uint8_t *p, *pe, msg[512];
uint16_t rtype, rclass, rdlength;
if (addrsize < kMinSockaddr4Size) return einval();
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
if (!resolvconf->nameservers.i) return 0;
bzero(&h, sizeof(h));
rc = ebadmsg();
h.id = _rand64();
h.bf1 = 1; /* recursion desired */
h.qdcount = 1;
q.qname = name;
q.qtype = DNS_TYPE_A;
q.qclass = DNS_CLASS_IN;
bzero(msg, sizeof(msg));
SerializeDnsHeader(msg, &h);
if ((n = SerializeDnsQuestion(msg + 12, 500, &q)) == -1) return -1;
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) return -1;
if (sendto(fd, msg, 12 + n, 0, (struct sockaddr *)resolvconf->nameservers.p,
sizeof(*resolvconf->nameservers.p)) == 12 + n &&
(n = read(fd, msg, 512)) >= 12) {
DeserializeDnsHeader(&h2, msg);
if (h2.id == h.id) {
rc = 0;
p = msg + 12;
pe = msg + n;
while (p < pe && h2.qdcount--) {
p += strnlen((char *)p, pe - p) + 1 + 4;
}
while (p < pe && h2.ancount--) {
if ((p[0] & 0xc0) == 0xc0) { /* name pointer */
p += 2;
} else {
p += strnlen((char *)p, pe - p) + 1;
}
if (p + 10 <= pe) {
rtype = READ16BE(p);
rclass = READ16BE(p + 2);
// ttl = READ32BE(p + 4);
rdlength = READ16BE(p + 8);
if (p + 10 + rdlength <= pe && rdlength == 4 &&
rclass == DNS_CLASS_IN && rtype == DNS_TYPE_A) {
rc = 1;
a4 = (struct sockaddr_in *)addr;
a4->sin_family = AF_INET;
memcpy(&a4->sin_addr.s_addr, p + 10, 4);
break;
}
p += 10 + rdlength;
}
}
}
}
close(fd);
return rc;
}

View file

@ -1,128 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/dnsheader.h"
#include "libc/dns/dnsquestion.h"
#include "libc/dns/resolvconf.h"
#include "libc/serialize.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/rand.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
#define kMsgMax 512
/**
* Performs reverse DNS lookup with IP address.
*
* @param resolvconf can be GetResolvConf()
* @param af can be AF_INET, AF_UNSPEC
* @param name is a reversed IP address string ending with .in-addr.arpa
* @param buf to store the obtained hostname if any
* @param bufsize is size of buf
* @return 0 on success, or -1 w/ errno
* @error EAFNOSUPPORT, ENETDOWN, ENAMETOOLONG, EBADMSG
*/
int ResolveDnsReverse(const struct ResolvConf *resolvconf, int af,
const char *name, char *buf, size_t bufsize) {
int rc, fd, n;
struct DnsQuestion q;
struct DnsHeader h, h2;
uint8_t *p, *pe, msg[512];
uint16_t rtype, rclass, rdlength;
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
if (!resolvconf->nameservers.i) return 0;
bzero(&h, sizeof(h));
rc = ebadmsg();
h.id = _rand64();
h.bf1 = 1; /* recursion desired */
h.qdcount = 1;
q.qname = name;
q.qtype = DNS_TYPE_PTR;
q.qclass = DNS_CLASS_IN;
bzero(msg, sizeof(msg));
SerializeDnsHeader(msg, &h);
if ((n = SerializeDnsQuestion(msg + 12, 500, &q)) == -1) return -1;
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) return -1;
if (sendto(fd, msg, 12 + n, 0, (struct sockaddr *)resolvconf->nameservers.p,
sizeof(*resolvconf->nameservers.p)) == 12 + n &&
(n = read(fd, msg, 512)) >= 12) {
DeserializeDnsHeader(&h2, msg);
if (h2.id == h.id) {
rc = 0;
if (h2.ancount) {
p = msg + 12;
pe = msg + n;
while (p < pe && h2.qdcount) {
p += strnlen((char *)p, pe - p) + 1 + 4;
h2.qdcount--;
}
if (p + 1 < pe) {
if ((p[0] & 0b11000000) == 0b11000000) { /* name pointer */
p += 2;
} else {
p += strnlen((char *)p, pe - p) + 1;
}
if (p + 2 + 2 + 4 + 2 < pe) {
rtype = READ16BE(p), p += 2;
rclass = READ16BE(p), p += 2;
/* ttl */ p += 4;
rdlength = READ16BE(p), p += 2;
if (p + rdlength <= pe && rtype == DNS_TYPE_PTR &&
rclass == DNS_CLASS_IN) {
if (strnlen((char *)p, pe - p) + 1 > bufsize)
rc = -1;
else {
/* domain name starts with a letter */
for (; !isalnum((char)(*p)) && p < pe; p++) rdlength--;
for (char *tmp = (char *)p; rdlength > 0 && *tmp != '\0';
tmp++) {
/* each label is alphanumeric or hyphen
* any other character is assumed separator */
if (!isalnum(*tmp) && *tmp != '-') *tmp = '.';
rdlength--;
}
strcpy(buf, (char *)p);
}
} else
rc = -1;
}
}
}
}
}
close(fd);
return rc;
}

View file

@ -1,52 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/serialize.h"
#include "libc/mem/alg.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Finds name associated with address in HOSTS.TXT table.
*
* @param ht can be GetHostsTxt()
* @param af can be AF_INET
* @param ip is IP address in binary (sin_addr)
* @param buf is buffer to store the name
* @param bufsize is length of buf
* @return 1 if found, 0 if not found, or -1 w/ errno
* @error EAFNOSUPPORT
*/
int ResolveHostsReverse(const struct HostsTxt *ht, int af, const uint8_t *ip,
char *buf, size_t bufsize) {
size_t i;
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
for (i = 0; i < ht->entries.i; ++i) {
if (READ32LE(ip) == READ32LE(ht->entries.p[i].ip)) {
if (memccpy(buf, ht->strings.p + ht->entries.p[i].name, 0, bufsize)) {
return 1;
}
}
}
return 0;
}

View file

@ -1,62 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/mem/alg.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Finds address associated with name in HOSTS.TXT table.
*
* @param ht can be GetHostsTxt()
* @param af can be AF_INET, AF_UNSPEC
* @param name can be a local or fully-qualified hostname
* @param addr should point to a struct sockaddr_in; if this function
* succeeds, its sin_family and sin_addr fields will be modified
* @param addrsize is the byte size of addr
* @param canon be used to return a pointer to the canonical name
* @return number of matches found, or -1 w/ errno
* @error EAFNOSUPPORT
*/
int ResolveHostsTxt(const struct HostsTxt *ht, int af, const char *name,
struct sockaddr *addr, uint32_t addrsize,
const char **canon) {
size_t i;
struct sockaddr_in *addr4;
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
for (i = 0; i < ht->entries.i; ++i) {
if (!CompareDnsNames(name, ht->strings.p + ht->entries.p[i].name)) {
if (addr) {
if (addrsize < kMinSockaddr4Size) return einval();
addr4 = (struct sockaddr_in *)addr;
addr4->sin_family = AF_INET;
memcpy(&addr4->sin_addr.s_addr, &ht->entries.p[i].ip[0], 4);
}
if (canon) {
*canon = ht->strings.p + ht->entries.p[i].canon;
}
return 1;
}
}
return 0;
}

View file

@ -1,59 +0,0 @@
NETWORK WORKING GROUP PEGGY KARP
REQUEST FOR COMMENTS #226 MITRE
NIC #7625 20 SEPT 71
CATEGORIES: D.3
UPDATES: NONE
OBSOLETES: NONE
STANDARDIZATION OF HOST MNEUMONICS
IN EACH TELNET IMPLEMENTATION, A LIST OF HOST NMEUMONICS IS PROVIDED
FOR THE USER TO INDICATE THE SERVING HOST DESIRED. CURRENTLY, EACH
SITE EMPLOYS THEIR OWN SPECIAL LIST. RATHER THAN REQUIRE THE USER TO
BE COGNIZANT OF THE IDIOSYNCRASIES OF EACH LIST, ESPECIALLY WHEN
CHAINED THROUGH SEVERAL HOSTS VIA TELNET, IT HAS BEEN RECOMMENDED THAT
STANDARD HOST DESIGNATORS BE ADOPTED.
THE FOLLOWING LIST OF SIX CHARACTER DESIGNATORS IS PROPOSED AS THE
STANDARD LIST. REGISTER ANY OBJECTIONS BY 3 OCTOBER TO P. KARP (703)
893-3500 X2391, X2318. AN OFFICIAL POLICY AND IMPLEMENTATION DATE WILL
BE SET ON 8 OCTOBER.
THE LIST:
HOST # DESIGNATOR
1 UCLA
65 UCLA36
2 SRIARC
66 SRIAI
3 UCSB
4 UTAH
6 MULTCS
70 MITDM
7 RAND
8 SDC
9 HARV
10 LNCTX2
74 LNC360
11 STAN
12 ILL
69 BBN
133 BBNB
144 AMES
145 MITRE
158 TIP
[ This RFC was put into machine readable form for entry ]
[ into the online RFC archives by BBN Corp. under the ]
[ direction of Alex McKenzie. 12/96 ]
[Page 1]

View file

@ -1,222 +0,0 @@
Network Working Group Peggy Karp
Request for Comments: #247 MITRE
NIC 7688 12 October 1971
Categories: Policy, Telnet
Related: #226, 236, 239, 233, 237
Obsoletes: #226
Proferred Set of Standard Host Names
In RFC #226, BBN's TENEX list of Host names was set up as a strawman
set of standard Host names. Comments received since then (an RFC
actually generated comments!!!) have influenced me to propose the
following general rules for forming Host names.
The Host names will be 8 characters in length. The general form is
<site> '-' <machine>
<site> will be at most 4 characters, formed as follows:
(a) Use the keyword in the site name, if not more than
four characters, e.g., NASA Ames, Case Western
Reserve. ---- ----
(b) Use the standard acronym, if not more than four
characters, e.g., UCLA, RADC, NBS.
(c) If a standard abbreviation exists, use it, e.g., Ill.
(d) If none of the above apply, use the first four letters
in the site name, e.g., Burr, Mitr, Harv.
(e) If none of the above is acceptable to the site, the
technical liaison should select the site mnemonic.
<machine> will be at most 4 characters of the form <mfg. #>
<designator>.
Examples of mfg. # are:
IBM 360 2 digit model number
IBM 370 3 digit model number
PDP 1 - 2 digit model number
Burroughs 4 digits
CDC 4 digits
etc.
[Page 1]
RFC #247
<designator> will be used when more than one machine of the same
type is located at a site (e.g., 2 PDP-10s at MIT, at SRI, and
at BBN).
Limiting <machine> to 4 characters does not permit distinctions
to be made between machines with 4 digit mfg. #s. I expect
the situation will be handled in an ad hoc manner by the NIC if
it arises.
TIPs are identified as 'TIP' rather than by '316'. If a Host
is not to be permanently addressable, the machine is identified
as 'TEST'.
A list of Host names, formed according to these rules, is
attached. Alternate Host names should be provided, as
suggested by Jon Postel (RFC #236). RFC's 206, 233, and
236 present lists with 4-character alternate names. The
Technical Liaison should select the alternate name for his
site and communicate the selection to the NIC.
The preceding rules and the attached list of Host names are
subject to the approval of the NWG. Hereafter, the list will
be generated and maintained by the NIC in cooperation with
the Technical Liaison at each site, as suggested in RFC #237.
Comments should be addressed to Dick Watson.
[ This RFC was put into machine readable form for entry ]
[ into the online RFC archives by BBN Corp. under the ]
[ direction of Alex McKenzie. 12/96 ]
[Page 2]
RFC #247
Attachment 1
NETWORK ADDRESS STANDARD NAME
--------------- -------------
1 UCLA-7
65 UCLA-91
2 SRI-10NI
66 SRI-10AI
3 UCSB-75
4 UTAH-10
5 BBN-516
69 BBN-10A
133 BBN-10B
6 MIT-645
70 MIT-10DM
134 MIT-10AI
7 RAND-65
71 RAND-10
8 SDC-75
9 HARV-10
73 HARV-1
137 HARV-11
10 LL-67
74 LL-TX2
138 LL-TSP
11 SAIL-10
12 ILL-11
76 ILL-6500
13 CASE-10
14 CMU-10
15 BURR-6500
79 BURR-TEST
16 AMES-67
144 AMES-TIP
145 MITR-TIP
18 RADC-645
146 RADC-TIP
19 NBS-11
147 NBS-TIP
148 ETAC-TIP
21 TINK-418
22 MCCL-418
23 USC-44
151 USC-TIP
152 GWC-TIP
25 NCAR-7600
153 NCAR-TIP
158 BBNX-TEST
[Page 3]
RFC #247
Attachment 2
An Implementation Scheme
If the standard Host names are formed according to the proposed
rules, the following implementation scheme, suggested by Steve
Crocker, can be used.
Map <site> into an 8-bit number, S and
map <machine> into an 8-bit number, M,
where
S + M = Network Address.
S and M can be selected such that specification of <site>
alone could cause a default to the "primary" Host at
the site. Note that this scheme depends on a unique
<site> designator for each IMP.
Some examples:
If the "primary" Host at UCLA is the 91, let
UCLA -> S = X'41'
7 -> M = X'40'
91 -> M = X'00'
then for
UCLA-7, S + M = X'01' = 1 base 10
UCLA-91,S + M = X'41' = 65 base 10
and
UCLA alone = X'41' = 65 base 10
If the primary Host at BBN is TENEX System A, let
BBN -> S = X'45'
516 -> M = X'40'
10A -> M = X'00'
10B -> M = X'C0'
then for
BBN-516, S + M = X'05' = 5 base 10
BBN-10A, S + M = X'45' = 69 base 10
BBN-10B, S + M = X'85' = 133 base 10
and
BBN alone = X'45' = 69 base 10
The primary Host for each IMP would be designated by the
site and such information disseminated by the NIC.
[Page 4]

File diff suppressed because it is too large Load diff

View file

@ -1,39 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/dnsquestion.h"
#include "libc/sysv/errfuns.h"
/**
* Serializes DNS question record to wire.
*
* @return number of bytes written
* @see pascalifydnsname()
*/
int SerializeDnsQuestion(uint8_t *buf, size_t size,
const struct DnsQuestion *dq) {
int wrote;
if ((wrote = PascalifyDnsName(buf, size, dq->qname)) == -1) return -1;
if (wrote + 1 + 4 > size) return enospc();
buf[wrote + 1] = dq->qtype >> 8;
buf[wrote + 2] = dq->qtype;
buf[wrote + 3] = dq->qclass >> 8;
buf[wrote + 4] = dq->qclass;
return wrote + 5;
}

View file

@ -1,37 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/ent.h"
struct servent *getservent(void) {
return NULL;
}
void setservent(int stayopen) {
}
void endservent(void) {
}

View file

@ -1,17 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_DNS_SERVICESTXT_H_
#define COSMOPOLITAN_LIBC_DNS_SERVICESTXT_H_
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
char *GetSystemDirectoryPath(char *, size_t, const char *);
int LookupServicesByPort(const int, char *, size_t, char *, size_t,
const char *) paramsnonnull((2, 4));
int LookupServicesByName(const char *, char *, size_t, char *, size_t,
const char *) paramsnonnull((1, 2));
const char *GetServicesTxtPath(char *, size_t);
/* TODO: implement like struct HostsTxt? */
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_DNS_SERVICESTXT_H_ */

View file

@ -1,8 +1,6 @@
#ifndef _NETDB_H
#define _NETDB_H
#include "libc/calls/weirdtypes.h"
#include "libc/dns/dns.h"
#include "libc/dns/ent.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/in6_pktinfo.h"
#include "libc/sock/struct/in_pktinfo.h"
@ -19,4 +17,5 @@
#include "libc/sysv/consts/mcast.h"
#include "libc/sysv/consts/pf.h"
#include "libc/sysv/consts/sock.h"
#include "third_party/musl/netdb.h"
#endif /* _NETDB_H */

View file

@ -1,7 +1,7 @@
#ifndef COSMOPOLITAN_LIBC_LOG_LOG_H_
#define COSMOPOLITAN_LIBC_LOG_LOG_H_
#ifdef _COSMO_SOURCE
#include "libc/stdio/stdio.h"
#ifdef _COSMO_SOURCE
#define kLogFatal 0
#define kLogError 1

View file

@ -26,7 +26,6 @@
#include "libc/calls/termios.h"
#include "libc/calls/ttydefaults.h"
#include "libc/dce.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/kprintf.h"

View file

@ -21,4 +21,9 @@
#define IN_LOOPBACKNET 127
/* clang-format off */
#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } }
#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } }
/* clang-format on */
#endif /* COSMOPOLITAN_LIBC_SYSV_CONSTS_INADDR_H_ */

View file

@ -3,7 +3,7 @@
#include "libc/stdio/stdio.h"
COSMOPOLITAN_C_START_
char *xgetline(struct FILE *) paramsnonnull() mallocesque;
char *xgetline(FILE *) paramsnonnull() mallocesque;
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_X_XGETLINE_H_ */

View file

@ -16,10 +16,11 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/str/str.h"
#include "net/http/http.h"
#define DNS_NAME_MAX 253
extern const char kHostChars[256]; // -_0-9A-Za-z
/**

View file

@ -4,7 +4,6 @@
.PHONY: o/$(MODE)/test/libc
o/$(MODE)/test/libc: \
o/$(MODE)/test/libc/calls \
o/$(MODE)/test/libc/dns \
o/$(MODE)/test/libc/fmt \
o/$(MODE)/test/libc/intrin \
o/$(MODE)/test/libc/log \

View file

@ -1,60 +0,0 @@
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐
#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘
PKGS += TEST_LIBC_DNS
TEST_LIBC_DNS_SRCS := $(wildcard test/libc/dns/*.c)
TEST_LIBC_DNS_SRCS_TEST = $(filter %_test.c,$(TEST_LIBC_DNS_SRCS))
TEST_LIBC_DNS_OBJS = \
$(TEST_LIBC_DNS_SRCS:%.c=o/$(MODE)/%.o)
TEST_LIBC_DNS_COMS = \
$(TEST_LIBC_DNS_SRCS:%.c=o/$(MODE)/%.com)
TEST_LIBC_DNS_BINS = \
$(TEST_LIBC_DNS_COMS) \
$(TEST_LIBC_DNS_COMS:%=%.dbg)
TEST_LIBC_DNS_TESTS = \
$(TEST_LIBC_DNS_SRCS_TEST:%.c=o/$(MODE)/%.com.ok)
TEST_LIBC_DNS_CHECKS = \
$(TEST_LIBC_DNS_SRCS_TEST:%.c=o/$(MODE)/%.com.runs)
TEST_LIBC_DNS_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
LIBC_STR \
LIBC_SYSV \
LIBC_TESTLIB \
LIBC_X
TEST_LIBC_DNS_DEPS := \
$(call uniq,$(foreach x,$(TEST_LIBC_DNS_DIRECTDEPS),$($(x))))
o/$(MODE)/test/libc/dns/dns.pkg: \
$(TEST_LIBC_DNS_OBJS) \
$(foreach x,$(TEST_LIBC_DNS_DIRECTDEPS),$($(x)_A).pkg)
o/$(MODE)/test/libc/dns/%.com.dbg: \
$(TEST_LIBC_DNS_DEPS) \
o/$(MODE)/test/libc/dns/%.o \
o/$(MODE)/test/libc/dns/dns.pkg \
$(LIBC_TESTMAIN) \
$(CRT) \
$(APE_NO_MODIFY_SELF)
@$(APELINK)
.PHONY: o/$(MODE)/test/libc/dns
o/$(MODE)/test/libc/dns: \
$(TEST_LIBC_DNS_BINS) \
$(TEST_LIBC_DNS_CHECKS)

View file

@ -1,110 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
void SetUpOnce(void) {
ASSERT_SYS(0, 0, pledge("stdio rpath", 0));
}
TEST(CompareDnsNames, testEmpty) {
char *A = strcpy(malloc(1), "");
char *B = strcpy(malloc(1), "");
EXPECT_EQ(CompareDnsNames(A, B), 0);
EXPECT_EQ(CompareDnsNames(A, A), 0);
free(B);
free(A);
}
TEST(CompareDnsNames, testDotless_caseInsensitiveBehavior) {
char *A = malloc(2);
char *B = malloc(2);
EXPECT_EQ(CompareDnsNames(strcpy(A, "a"), strcpy(B, "a")), 0);
EXPECT_EQ(CompareDnsNames(A, A), 0);
EXPECT_EQ(CompareDnsNames(strcpy(A, "a"), strcpy(B, "A")), 0);
EXPECT_EQ(CompareDnsNames(strcpy(A, "A"), strcpy(B, "a")), 0);
EXPECT_LT(CompareDnsNames(strcpy(A, "a"), strcpy(B, "b")), 0);
EXPECT_LT(CompareDnsNames(strcpy(A, "a"), strcpy(B, "B")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "d"), strcpy(B, "a")), 0);
free(B);
free(A);
}
TEST(CompareDnsNames, testMultiLabel_lexiReverse) {
char *A = malloc(16);
char *B = malloc(16);
EXPECT_EQ(CompareDnsNames(strcpy(A, "a.example"), strcpy(B, "a.example")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "b.example"), strcpy(B, "a.example")), 0);
EXPECT_LT(CompareDnsNames(strcpy(A, "b.example"), strcpy(B, "a.examplz")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "a.zxample"), strcpy(B, "a.examplz")), 0);
EXPECT_EQ(CompareDnsNames(strcpy(A, "c.a.example"), strcpy(B, "c.a.example")),
0);
EXPECT_GT(CompareDnsNames(strcpy(A, "d.a.example"), strcpy(B, "c.a.example")),
0);
EXPECT_LT(CompareDnsNames(strcpy(A, "cat.example"), strcpy(B, "lol.example")),
0);
free(B);
free(A);
}
TEST(CompareDnsNames, testTldDotQualifier_canBeEqualToDottedNames) {
char *A = malloc(16);
char *B = malloc(16);
EXPECT_EQ(
CompareDnsNames(strcpy(B, "aaa.example."), strcpy(A, "aaa.example")), 0);
free(B);
free(A);
}
TEST(CompareDnsNames, testFullyQualified_alwaysComesFirst) {
char *A = malloc(16);
char *B = malloc(16);
EXPECT_LT(CompareDnsNames(strcpy(B, "aaa.example."), strcpy(A, "zzz")), 0);
EXPECT_LT(CompareDnsNames(strcpy(B, "zzz.example."), strcpy(A, "aaa")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "zzz"), strcpy(B, "aaa.example.")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "aaa"), strcpy(B, "zzz.example.")), 0);
free(B);
free(A);
}
TEST(CompareDnsNames, testLikelySld_alwaysComesBeforeLocalName) {
char *A = malloc(16);
char *B = malloc(16);
EXPECT_LT(CompareDnsNames(strcpy(B, "z.e"), strcpy(A, "a")), 0);
EXPECT_LT(CompareDnsNames(strcpy(B, "aaa.example"), strcpy(A, "zzz")), 0);
EXPECT_LT(CompareDnsNames(strcpy(B, "zzz.example"), strcpy(A, "aaa")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "zzz"), strcpy(B, "aaa.example")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "aaa"), strcpy(B, "zzz.example")), 0);
free(B);
free(A);
}
TEST(CompareDnsNames, testLikelySubdomain_alwaysComesAfterSld) {
char *A = malloc(16);
char *B = malloc(16);
EXPECT_LT(CompareDnsNames(strcpy(B, "a.e"), strcpy(A, "z.a.e")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "z.a.e"), strcpy(B, "a.e")), 0);
EXPECT_LT(CompareDnsNames(strcpy(B, "b.e"), strcpy(A, "a.b.e")), 0);
EXPECT_GT(CompareDnsNames(strcpy(A, "a.b.e"), strcpy(B, "b.e")), 0);
free(B);
free(A);
}

View file

@ -1,47 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/dnsheader.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
TEST(SerializeDnsHeader, test) {
uint8_t buf[12];
struct DnsHeader header;
memset(&header, 0, sizeof(header));
header.id = 255;
header.bf1 = true;
header.qdcount = 1;
SerializeDnsHeader(buf, &header);
EXPECT_BINEQ(u" λ☺  ☺      ", buf);
}
TEST(SerializeDnsHeader, fuzzSymmetry) {
uint8_t buf[12];
struct DnsHeader in, out;
rngset(&in, sizeof(in), _rand64, -1);
rngset(&out, sizeof(out), _rand64, -1);
SerializeDnsHeader(buf, &in);
DeserializeDnsHeader(&out, buf);
ASSERT_EQ(0, memcmp(&in, &out, 12), "%#.*s\n\t%#.*s", 12, in, 12, buf);
}

View file

@ -1,46 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/dnsquestion.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "libc/testlib/testlib.h"
TEST(SerializeDnsQuestion, test) {
struct DnsQuestion dq;
char name[] = "foo.bar";
uint8_t buf[1 + 3 + 1 + 3 + 1 + 4];
dq.qname = name;
dq.qtype = 0x0201;
dq.qclass = 0x0102;
EXPECT_EQ(1 + 3 + 1 + 3 + 1 + 4,
SerializeDnsQuestion(buf, 1 + 3 + 1 + 3 + 1 + 4, &dq));
EXPECT_BINEQ(u"♥foo♥bar ☻☺☺☻", buf);
}
TEST(SerializeDnsQuestion, testNoSpace) {
struct DnsQuestion dq;
char name[] = "foo.bar";
uint8_t buf[1 + 3 + 1 + 3 + 1 + 3];
dq.qname = name;
dq.qtype = 0x0201;
dq.qclass = 0x0102;
EXPECT_EQ(-1, SerializeDnsQuestion(buf, 1 + 3 + 1 + 3 + 1 + 3, &dq));
EXPECT_EQ(ENOSPC, errno);
}

View file

@ -1,80 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/hoststxt.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/testlib/testlib.h"
static const char *parseip(unsigned char ip[4]) {
static char g_ipbuf[16];
return inet_ntop(AF_INET, ip, g_ipbuf, sizeof(g_ipbuf));
}
TEST(ParseHostsTxt, testEmpty) {
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(0, ht->entries.i);
FreeHostsTxt(&ht);
fclose(f);
}
TEST(ParseHostsTxt, testCorrectlyTokenizesAndSorts) {
const char kInput[] = "# this is a comment\n"
"# IP HOST1 HOST2\n"
"203.0.113.1 lol.example. lol\n"
"203.0.113.2 cat.example. cat\n";
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(1, fwrite(kInput, strlen(kInput), 1, f));
rewind(f);
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(4, ht->entries.i);
EXPECT_STREQ("lol.example.", &ht->strings.p[ht->entries.p[0].name]);
EXPECT_STREQ("lol.example.", &ht->strings.p[ht->entries.p[0].canon]);
EXPECT_STREQ("203.0.113.1", parseip(ht->entries.p[0].ip));
EXPECT_STREQ("lol", &ht->strings.p[ht->entries.p[1].name]);
EXPECT_STREQ("lol.example.", &ht->strings.p[ht->entries.p[1].canon]);
EXPECT_STREQ("203.0.113.1", parseip(ht->entries.p[1].ip));
EXPECT_STREQ("cat.example.", &ht->strings.p[ht->entries.p[2].name]);
EXPECT_STREQ("cat.example.", &ht->strings.p[ht->entries.p[2].canon]);
EXPECT_STREQ("203.0.113.2", parseip(ht->entries.p[2].ip));
EXPECT_STREQ("cat", &ht->strings.p[ht->entries.p[3].name]);
EXPECT_STREQ("cat.example.", &ht->strings.p[ht->entries.p[3].canon]);
EXPECT_STREQ("203.0.113.2", parseip(ht->entries.p[3].ip));
FreeHostsTxt(&ht);
fclose(f);
}
TEST(ParseHostsTxt, testIpv6_isIgnored) {
const char kInput[] = "::1 boop\n"
"203.0.113.2 cat # ignore me\n";
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen((void *)kInput, strlen(kInput), "r+");
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(1, ht->entries.i);
EXPECT_STREQ("cat", &ht->strings.p[ht->entries.p[0].name]);
EXPECT_STREQ("cat", &ht->strings.p[ht->entries.p[0].canon]);
EXPECT_STREQ("203.0.113.2", parseip(ht->entries.p[0].ip));
FreeHostsTxt(&ht);
fclose(f);
}

View file

@ -1,70 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/resolvconf.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/testlib/testlib.h"
static const char *FormatIp(struct sockaddr_in *ip) {
static char g_ipbuf[16];
return inet_ntop(ip->sin_family, &ip->sin_addr.s_addr, g_ipbuf, 16);
}
TEST(ParseResolvConf, testEmpty) {
struct ResolvConf *rv = calloc(1, sizeof(struct ResolvConf));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(0, ParseResolvConf(rv, f));
ASSERT_EQ(0, rv->nameservers.i);
FreeResolvConf(&rv);
fclose(f);
}
TEST(ParseResolvConf, testCorrectlyTokenizes) {
const char kInput[] = "# this is a comment\n"
"nameserver 203.0.113.2 \n"
" nameserver 203.0.113.1\n";
struct ResolvConf *rv = calloc(1, sizeof(struct ResolvConf));
FILE *f = fmemopen((void *)kInput, strlen(kInput), "r+");
ASSERT_EQ(2, ParseResolvConf(rv, f));
ASSERT_EQ(2, rv->nameservers.i);
EXPECT_EQ(AF_INET, rv->nameservers.p[0].sin_family);
EXPECT_EQ(DNS_PORT, ntohs(rv->nameservers.p[0].sin_port));
EXPECT_STREQ("203.0.113.2", FormatIp(&rv->nameservers.p[0]));
EXPECT_EQ(AF_INET, rv->nameservers.p[1].sin_family);
EXPECT_EQ(DNS_PORT, ntohs(rv->nameservers.p[1].sin_port));
EXPECT_STREQ("203.0.113.1", FormatIp(&rv->nameservers.p[1]));
FreeResolvConf(&rv);
fclose(f);
}
TEST(ParseResolvConf, testMulticastDnsThing_getsIgnored) {
const char kInput[] = "search local # boop\n";
struct ResolvConf *rv = calloc(1, sizeof(struct ResolvConf));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(strlen(kInput), fwrite(kInput, 1, strlen(kInput), f));
ASSERT_EQ(0, ParseResolvConf(rv, f));
ASSERT_EQ(0, rv->nameservers.i);
FreeResolvConf(&rv);
fclose(f);
}

View file

@ -1,79 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
TEST(PascalifyDnsName, testEmpty) {
uint8_t *buf = malloc(1);
char *name = strdup("");
EXPECT_EQ(0, PascalifyDnsName(buf, 1, name));
EXPECT_BINEQ(u" ", buf);
free(name);
free(buf);
}
TEST(PascalifyDnsName, testOneLabel) {
uint8_t *buf = malloc(1 + 3 + 1);
char *name = strdup("foo");
EXPECT_EQ(1 + 3, PascalifyDnsName(buf, 1 + 3 + 1, name));
EXPECT_BINEQ(u"♥foo ", buf);
free(name);
free(buf);
}
TEST(PascalifyDnsName, testTwoLabels) {
uint8_t *buf = malloc(1 + 3 + 1 + 3 + 1);
char *name = strdup("foo.bar");
EXPECT_EQ(1 + 3 + 1 + 3, PascalifyDnsName(buf, 1 + 3 + 1 + 3 + 1, name));
EXPECT_BINEQ(u"♥foo♥bar ", buf);
free(name);
free(buf);
}
TEST(PascalifyDnsName, testFqdnDot_isntIncluded) {
uint8_t *buf = malloc(1 + 3 + 1 + 3 + 1);
char *name = strdup("foo.bar.");
EXPECT_EQ(1 + 3 + 1 + 3, PascalifyDnsName(buf, 1 + 3 + 1 + 3 + 1, name));
EXPECT_BINEQ(u"♥foo♥bar ", buf);
free(name);
free(buf);
}
TEST(PascalifyDnsName, testTooLong) {
uint8_t *buf = malloc(1);
char *name = malloc(1000);
memset(name, '.', 999);
name[999] = '\0';
EXPECT_EQ(-1, PascalifyDnsName(buf, 1, name));
EXPECT_EQ(ENAMETOOLONG, errno);
free(name);
free(buf);
}
TEST(PascalifyDnsName, testNoSpace) {
uint8_t *buf = malloc(1);
char *name = strdup("foo");
EXPECT_EQ(-1, PascalifyDnsName(buf, 1, name));
EXPECT_EQ(ENOSPC, errno);
free(name);
free(buf);
}

View file

@ -1,78 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/prototxt.h"
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/dns/ent.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
void SetUpOnce(void) {
testlib_enable_tmp_setup_teardown();
}
void SetUp() {
int fd;
const char *sample = "\
# skip comment string\n\
rspf 73 RSPF CPHB \n\
ggp 3 GGP ";
ASSERT_NE(-1, (fd = creat("protocols", 0755)));
ASSERT_NE(-1, write(fd, sample, strlen(sample)));
ASSERT_NE(-1, close(fd));
}
TEST(LookupProtoByNumber, GetNameWhenNumberCorrect) {
char name[16]; /* sample has only names of length 3-4 */
strcpy(name, "");
ASSERT_EQ(-1, /*non-existent number */
LookupProtoByNumber(24, name, sizeof(name), "protocols"));
ASSERT_EQ(-1, /* sizeof(name) insufficient, memccpy failure */
LookupProtoByNumber(73, name, 1, "protocols"));
ASSERT_STREQ(name, ""); /* cleaned up after memccpy failed */
ASSERT_EQ(0, /* works with valid number */
LookupProtoByNumber(73, name, sizeof(name), "protocols"));
ASSERT_STREQ(name, "rspf"); /* official name written */
}
TEST(LookupProtoByName, GetNumberWhenNameOrAlias) {
char name[16]; /* sample has only names of length 3-4 */
strcpy(name, "");
ASSERT_EQ(-1, /* non-existent name or alias */
LookupProtoByName("tcp", name, sizeof(name), "protocols"));
ASSERT_EQ(-1, /* sizeof(name) insufficient, memccpy failure */
LookupProtoByName("ggp", name, 1, "protocols"));
ASSERT_STREQ(name, ""); /* cleaned up after memccpy failed */
ASSERT_EQ(3, /* works with valid name */
LookupProtoByName("ggp", name, sizeof(name), "protocols"));
ASSERT_STREQ(name, "ggp");
ASSERT_EQ(73, /* works with valid alias */
LookupProtoByName("CPHB", name, sizeof(name), "protocols"));
ASSERT_STREQ(name, "rspf"); /* official name written */
}

View file

@ -1,79 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/hoststxt.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/testlib/testlib.h"
TEST(ParseHostsTxt, testNotFound) {
const char kInput[] = "# this is a comment\n"
"# IP HOST1 HOST2\n"
"203.0.113.1 lol.example lol\n"
"203.0.113.2 cat.example cat\n";
char name[256];
uint8_t ip[4] = {127, 0, 113, 1};
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(1, fwrite(kInput, strlen(kInput), 1, f));
rewind(f);
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(4, ht->entries.i);
ASSERT_EQ(0, ResolveHostsReverse(ht, AF_INET, ip, name, sizeof(name)));
FreeHostsTxt(&ht);
fclose(f);
}
TEST(ParseHostsTxt, testFirstLookup) {
const char kInput[] = "# this is a comment\n"
"# IP HOST1 HOST2\n"
"203.0.113.1 lol.example lol\n"
"203.0.113.2 cat.example cat\n";
char name[256];
uint8_t ip[4] = {203, 0, 113, 1};
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(1, fwrite(kInput, strlen(kInput), 1, f));
rewind(f);
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(4, ht->entries.i);
ASSERT_EQ(1, ResolveHostsReverse(ht, AF_INET, ip, name, sizeof(name)));
EXPECT_STREQ("lol.example", name);
FreeHostsTxt(&ht);
fclose(f);
}
TEST(ParseHostsTxt, testSecondLookup) {
const char kInput[] = "# this is a comment\n"
"# IP HOST1 HOST2\n"
"203.0.113.1 lol.example lol\n"
"203.0.113.2 cat.example cat\n";
char name[256];
uint8_t ip[4] = {203, 0, 113, 2};
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen(NULL, BUFSIZ, "r+");
ASSERT_EQ(1, fwrite(kInput, strlen(kInput), 1, f));
rewind(f);
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(4, ht->entries.i);
ASSERT_EQ(1, ResolveHostsReverse(ht, AF_INET, ip, name, sizeof(name)));
EXPECT_STREQ("cat.example", name);
FreeHostsTxt(&ht);
fclose(f);
}

View file

@ -1,78 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/testlib/testlib.h"
static const char *EzIp4Lookup(const struct HostsTxt *ht, const char *name) {
struct sockaddr_in addr4;
if (ResolveHostsTxt(ht, AF_INET, name, (void *)&addr4,
sizeof(struct sockaddr_in), NULL) > 0) {
static char g_ipbuf[16];
return inet_ntop(AF_INET, &addr4.sin_addr, g_ipbuf, sizeof(g_ipbuf));
} else {
return NULL;
}
}
static const char *EzCanonicalize(const struct HostsTxt *ht, const char *name) {
const char *res;
return ResolveHostsTxt(ht, AF_INET, name, NULL, 0, &res) > 0 ? res : NULL;
}
static const char kInput[] = "127.0.0.1 localhost\n"
"203.0.113.1 lol.example. lol\n"
"203.0.113.2 cat.example. cat\n";
TEST(ResolveHostsTxt, testBasicLookups) {
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen((void *)kInput, strlen(kInput), "r+");
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(5, ht->entries.i);
EXPECT_STREQ("127.0.0.1", EzIp4Lookup(ht, "localhost"));
EXPECT_STREQ("203.0.113.1", EzIp4Lookup(ht, "lol"));
EXPECT_STREQ("203.0.113.1", EzIp4Lookup(ht, "lol.example"));
EXPECT_STREQ("203.0.113.1", EzIp4Lookup(ht, "lol.example."));
EXPECT_STREQ("203.0.113.2", EzIp4Lookup(ht, "cat"));
EXPECT_STREQ("203.0.113.2", EzIp4Lookup(ht, "cat.example."));
EXPECT_EQ(NULL, EzIp4Lookup(ht, "boop"));
FreeHostsTxt(&ht);
fclose(f);
}
TEST(ResolveHostsTxt, testCanonicalize) {
struct HostsTxt *ht = calloc(1, sizeof(struct HostsTxt));
FILE *f = fmemopen((void *)kInput, strlen(kInput), "r+");
ASSERT_EQ(0, ParseHostsTxt(ht, f));
ASSERT_EQ(5, ht->entries.i);
EXPECT_STREQ("localhost", EzCanonicalize(ht, "localhost"));
EXPECT_STREQ("lol.example.", EzCanonicalize(ht, "lol"));
EXPECT_STREQ("lol.example.", EzCanonicalize(ht, "lol.example"));
EXPECT_STREQ("lol.example.", EzCanonicalize(ht, "lol.example."));
EXPECT_STREQ("cat.example.", EzCanonicalize(ht, "cat"));
EXPECT_STREQ("cat.example.", EzCanonicalize(ht, "cat.example."));
EXPECT_EQ(NULL, EzCanonicalize(ht, "boop"));
FreeHostsTxt(&ht);
fclose(f);
}

View file

@ -1,184 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/dns/servicestxt.h"
#include "libc/calls/calls.h"
#include "libc/dns/dns.h"
#include "libc/dns/ent.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
void SetUpOnce(void) {
testlib_enable_tmp_setup_teardown();
}
void SetUp() {
int fd;
const char* sample = "\
# skip comment string\n\
chargen 19/tcp ttytst source\n\
chargen 19/udp ttytst source\n\
ssh 22/tcp # SSH Remote Login Protocol";
ASSERT_NE(-1, (fd = creat("services", 0755)));
ASSERT_NE(-1, write(fd, sample, strlen(sample)));
ASSERT_NE(-1, close(fd));
}
TEST(LookupServicesByPort, GetNameWhenPortCorrect) {
char name[8]; /* service names are of length 3 */
char eitherproto[8]; /* protocol names are of length 3 */
char proto1[] = "tcp";
char proto2[] = "udp";
char* localproto;
strcpy(eitherproto, "");
strcpy(name, "");
localproto = eitherproto;
ASSERT_EQ(-1, /* non existent port */
LookupServicesByPort(965, localproto, sizeof(eitherproto), name,
sizeof(name), "services"));
ASSERT_EQ('\0', localproto[0]);
localproto = eitherproto;
ASSERT_EQ(-1, /* port in network byte order */
LookupServicesByPort(htons(22), localproto, sizeof(eitherproto),
name, sizeof(name), "services"));
ASSERT_EQ('\0', localproto[0]);
localproto = proto2;
ASSERT_EQ(-1, /* port ok but wrong protocol */
LookupServicesByPort(22, localproto, sizeof(proto2), name,
sizeof(name), "services"));
ASSERT_STREQ(proto2, "udp");
localproto = proto1;
ASSERT_EQ(
-1, /* protocol is non-NULL/length must be nonzero */
LookupServicesByPort(22, localproto, 0, name, sizeof(name), "services"));
ASSERT_STREQ(proto1, "tcp");
localproto = proto1;
ASSERT_EQ(-1, /* sizeof(name) insufficient, memccpy failure */
LookupServicesByPort(22, localproto, sizeof(proto1), name, 1,
"services"));
ASSERT_STREQ(proto1, "tcp");
ASSERT_STREQ(name, ""); /* cleaned up after memccpy failed */
localproto = eitherproto;
ASSERT_EQ(
-1, /* sizeof(proto) insufficient, memccpy failure */
LookupServicesByPort(22, localproto, 1, name, sizeof(name), "services"));
ASSERT_STREQ(eitherproto, ""); /* cleaned up after memccpy failed */
localproto = proto1;
ASSERT_EQ(0, LookupServicesByPort(22, localproto, sizeof(proto1), name,
sizeof(name), "services"));
ASSERT_STREQ(name, "ssh");
ASSERT_STREQ(proto1, "tcp");
localproto = proto2;
ASSERT_EQ(0, LookupServicesByPort(19, localproto, sizeof(proto2), name,
sizeof(name), "services"));
ASSERT_STREQ(name, "chargen");
ASSERT_STREQ(proto2, "udp");
localproto = eitherproto;
ASSERT_EQ(0, /* pick first matching protocol */
LookupServicesByPort(19, localproto, sizeof(eitherproto), name,
sizeof(name), "services"));
ASSERT_STREQ(name, "chargen");
ASSERT_NE('\0', localproto[0]); /* buffer filled during the call */
ASSERT_STREQ(eitherproto, "tcp");
}
TEST(LookupServicesByName, GetPortWhenNameOrAlias) {
char name[8]; /* service names are of length 3 */
char eitherproto[8]; /* protocol names are of length 3 */
char proto1[] = "tcp";
char proto2[] = "udp";
char* localproto;
strcpy(eitherproto, "");
strcpy(name, "");
localproto = eitherproto;
ASSERT_EQ(-1, /* non-existent name */
LookupServicesByName("http", localproto, sizeof(eitherproto), name,
sizeof(name), "services"));
ASSERT_EQ('\0', localproto[0]);
localproto = proto2;
ASSERT_EQ(-1, /* name exists but wrong protocol */
LookupServicesByName("ssh", localproto, sizeof(proto2), name,
sizeof(name), "services"));
ASSERT_STREQ(proto2, "udp");
localproto = proto2;
ASSERT_EQ(-1, /* protocol is non-NULL/length must be nonzero */
LookupServicesByName("ssh", localproto, sizeof(proto2), name,
sizeof(name), "services"));
ASSERT_STREQ(proto2, "udp");
localproto = proto1;
ASSERT_EQ(-1, /* sizeof(name) insufficient, memccpy failure */
LookupServicesByName("ssh", localproto, sizeof(proto1), name, 1,
"services"));
ASSERT_STREQ(proto1, "tcp");
ASSERT_STREQ(name, ""); /* cleaned up after memccpy failed */
localproto = eitherproto;
ASSERT_EQ(-1, /* sizeof(proto) insufficient, memccpy failure */
LookupServicesByName("ssh", localproto, 1, name, sizeof(name),
"services"));
ASSERT_STREQ(eitherproto, ""); /* cleaned up after memccpy failed */
localproto = proto1;
ASSERT_EQ(22, LookupServicesByName("ssh", localproto, sizeof(proto1), name,
sizeof(name), "services"));
ASSERT_STREQ(name, "ssh"); /* official name written to buffer */
ASSERT_STREQ(proto1, "tcp");
localproto = proto2;
ASSERT_EQ(19, /* works if alias provided */
LookupServicesByName("ttytst", localproto, sizeof(proto2), name,
sizeof(name), "services"));
ASSERT_STREQ(name, "chargen"); /* official name written to buffer */
localproto = proto2;
ASSERT_EQ(19, /* can get port returned without official name */
LookupServicesByName("ttytst", localproto, sizeof(proto2), NULL, 0,
"services"));
localproto = eitherproto;
ASSERT_EQ(19, /* pick first matching protocol */
LookupServicesByName("source", localproto, sizeof(eitherproto),
name, sizeof(name), "services"));
ASSERT_STREQ(name, "chargen");
ASSERT_STREQ(localproto, "tcp");
}

View file

@ -18,7 +18,6 @@ THIRD_PARTY_BASH_BINS = \
THIRD_PARTY_BASH_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \

View file

@ -22,7 +22,6 @@ THIRD_PARTY_FINGER_A_DIRECTDEPS = \
LIBC_STDIO \
LIBC_STR \
LIBC_SYSV \
LIBC_DNS \
LIBC_SOCK \
LIBC_TIME \
THIRD_PARTY_MUSL \

View file

@ -34,13 +34,14 @@
* SUCH DAMAGE.
*/
#include "libc/calls/calls.h"
#include "libc/dns/ent.h"
#include "libc/errno.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "third_party/musl/netdb.h"
#include "third_party/finger/finger.h"
#ifndef lint

View file

@ -16,7 +16,6 @@ THIRD_PARTY_HIREDIS_A_OBJS = \
THIRD_PARTY_HIREDIS_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
@ -28,7 +27,8 @@ THIRD_PARTY_HIREDIS_A_DIRECTDEPS = \
LIBC_SYSV \
LIBC_TIME \
LIBC_X \
THIRD_PARTY_GDTOA
THIRD_PARTY_GDTOA \
THIRD_PARTY_MUSL
THIRD_PARTY_HIREDIS_A_DEPS := \
$(call uniq,$(foreach x,$(THIRD_PARTY_HIREDIS_A_DIRECTDEPS),$($(x))))

View file

@ -40,7 +40,6 @@
#include "libc/intrin/newbie.h"
#include "libc/sock/sock.h"
#include "libc/sock/select.h"
#include "libc/dns/dns.h"
#include "libc/sysv/consts/endian.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/flock.h"
@ -62,6 +61,8 @@
#include "libc/sysv/consts/tcp.h"
#include "libc/mem/alg.h"
#include "libc/str/str.h"
#include "libc/sock/struct/sockaddr.h"
#include "third_party/musl/netdb.h"
#include "libc/errno.h"
#include "libc/calls/calls.h"

View file

@ -40,7 +40,6 @@
#include "libc/calls/ucontext.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/itoa.h"
@ -115,6 +114,8 @@
#include "third_party/nsync/futex.internal.h"
#include "tool/net/luacheck.h"
#define DNS_NAME_MAX 253
/**
* @fileoverview UNIX system calls thinly wrapped for Lua
* @support Linux, Mac, Windows, FreeBSD, NetBSD, OpenBSD

View file

@ -18,7 +18,6 @@ THIRD_PARTY_MBEDTLS_A_CHECKS = \
THIRD_PARTY_MBEDTLS_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
@ -31,6 +30,7 @@ THIRD_PARTY_MBEDTLS_A_DIRECTDEPS = \
LIBC_TIME \
NET_HTTP \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_MUSL \
THIRD_PARTY_ZLIB
THIRD_PARTY_MBEDTLS_A_DEPS := \

View file

@ -19,7 +19,6 @@
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/sock/select.h"
#include "libc/sock/struct/sockaddr6.h"
@ -33,6 +32,8 @@
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "third_party/mbedtls/error.h"
#include "third_party/musl/netdb.h"
#include "libc/sock/sock.h"
#include "third_party/mbedtls/ssl.h"
#define IS_EINTR(ret) ((ret) == EINTR)

View file

@ -96,7 +96,6 @@ THIRD_PARTY_MBEDTLS_TEST_CHECKS = \
THIRD_PARTY_MBEDTLS_TEST_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
@ -112,7 +111,8 @@ THIRD_PARTY_MBEDTLS_TEST_DIRECTDEPS = \
LIBC_X \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_GDTOA \
THIRD_PARTY_MBEDTLS
THIRD_PARTY_MBEDTLS \
THIRD_PARTY_MUSL
THIRD_PARTY_MBEDTLS_TEST_DEPS := \
$(call uniq,$(foreach x,$(THIRD_PARTY_MBEDTLS_TEST_DIRECTDEPS),$($(x))))

View file

@ -48,6 +48,12 @@ $(THIRD_PARTY_MUSL_A).pkg: \
$(THIRD_PARTY_MUSL_A_OBJS) \
$(foreach x,$(THIRD_PARTY_MUSL_A_DIRECTDEPS),$($(x)_A).pkg)
o/$(MODE)/third_party/musl/getnameinfo.o \
o/$(MODE)/third_party/musl/lookup_name.o \
o/$(MODE)/third_party/musl/lookup_serv.o: \
private CFLAGS += \
-fportcosmo
# offer assurances about the stack safety of cosmo libc
$(THIRD_PARTY_MUSL_A_OBJS): private COPTS += -Wframe-larger-than=4096 -Walloca-larger-than=4096

View file

@ -28,15 +28,12 @@
#include "third_party/musl/resolv.h"
#include "libc/str/str.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
/* RFC 1035 message compression */
/* label start offsets of a compressed domain name s */
static int getoffs(short *offs, const unsigned char *base, const unsigned char *s)
static int getoffs(short *offs,
const unsigned char *base,
const unsigned char *s)
{
int i=0;
for (;;) {
@ -65,8 +62,12 @@ static int getlens(unsigned char *lens, const char *s, int l)
}
/* longest suffix match of an ascii domain with a compressed domain name dn */
static int match(int *offset, const unsigned char *base, const unsigned char *dn,
const char *end, const unsigned char *lens, int nlen)
static int match(int *offset,
const unsigned char *base,
const unsigned char *dn,
const char *end,
const unsigned char *lens,
int nlen)
{
int l, o, m=0;
short offs[128];
@ -86,7 +87,11 @@ static int match(int *offset, const unsigned char *base, const unsigned char *dn
}
}
int dn_comp(const char *src, unsigned char *dst, int space, unsigned char **dnptrs, unsigned char **lastdnptr)
int dn_comp(const char *src,
unsigned char *dst,
int space,
unsigned char **dnptrs,
unsigned char **lastdnptr)
{
int i, j, n, m=0, offset, bestlen=0, bestoff;
unsigned char lens[127];

View file

@ -27,12 +27,11 @@
*/
#include "third_party/musl/resolv.internal.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
int __dn_expand(const unsigned char *base, const unsigned char *end, const unsigned char *src, char *dest, int space)
int __dn_expand(const unsigned char *base,
const unsigned char *end,
const unsigned char *src,
char *dest,
int space)
{
const unsigned char *p = src;
char *dend, *dbegin = dest;

View file

@ -27,11 +27,6 @@
*/
#include "third_party/musl/resolv.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
int dn_skipname(const unsigned char *s, const unsigned char *end)
{
const unsigned char *p = s;

View file

Before

Width:  |  Height:  |  Size: 474 KiB

After

Width:  |  Height:  |  Size: 474 KiB

61
third_party/musl/dns_parse.c vendored Normal file
View file

@ -0,0 +1,61 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "third_party/musl/lookup.internal.h"
int __dns_parse(const unsigned char *r, int rlen,
int callback(void *, int, const void *, int, const void *, int),
void *ctx)
{
int qdcount, ancount;
const unsigned char *p;
int len;
if (rlen<12) return -1;
if ((r[3]&15)) return 0;
p = r+12;
qdcount = r[4]*256 + r[5];
ancount = r[6]*256 + r[7];
if (qdcount+ancount > 64) return -1;
while (qdcount--) {
while (p-r < rlen && *p-1U < 127) p++;
if (p>r+rlen-6)
return -1;
p += 5 + !!*p;
}
while (ancount--) {
while (p-r < rlen && *p-1U < 127) p++;
if (p>r+rlen-12)
return -1;
p += 1 + !!*p;
len = p[8]*256 + p[9];
if (len+10 > r+rlen-p) return -1;
if (callback(ctx, p[1], p+10, len, r, rlen) < 0) return -1;
p += 10 + len;
}
return 0;
}

49
third_party/musl/ent.c vendored Normal file
View file

@ -0,0 +1,49 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "third_party/musl/netdb.h"
void sethostent(int x)
{
}
struct hostent *gethostent()
{
return 0;
}
struct netent *getnetent()
{
return 0;
}
void endhostent(void)
{
}
__weak_reference(sethostent, setnetent);
__weak_reference(endhostent, endnetent);

View file

@ -1,5 +1,32 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/thread/thread.h"
#include "pwf.internal.h"
#include <pthread.h>
struct spwd *fgetspent(FILE *f)
{

47
third_party/musl/freeaddrinfo.c vendored Normal file
View file

@ -0,0 +1,47 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/intrin/atomic.h"
#include "libc/mem/mem.h"
#include "third_party/musl/lookup.internal.h"
#include "third_party/musl/netdb.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
void freeaddrinfo(struct addrinfo *p)
{
size_t cnt;
for (cnt=1; p->ai_next; cnt++, p=p->ai_next);
struct aibuf *b = (void *)((char *)p - offsetof(struct aibuf, ai));
b -= b->slot;
if (atomic_fetch_sub(&b->ref, cnt) == cnt) {
free(b);
}
}

56
third_party/musl/gai_strerror.c vendored Normal file
View file

@ -0,0 +1,56 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "third_party/musl/netdb.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
static const char msgs[] =
"Invalid flags\0"
"Name does not resolve\0"
"Try again\0"
"Non-recoverable error\0"
"Name has no usable address\0"
"Unrecognized address family or invalid length\0"
"Unrecognized socket type\0"
"Unrecognized service\0"
"Unknown error\0"
"Out of memory\0"
"System error\0"
"Overflow\0"
"\0Unknown error";
const char *gai_strerror(int ecode)
{
const char *s;
for (s=msgs, ecode++; ecode && *s; ecode++, s++) for (; *s; s++);
if (!*s) s++;
return s;
}

171
third_party/musl/getaddrinfo.c vendored Normal file
View file

@ -0,0 +1,171 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
#include "libc/thread/thread.h"
#include "third_party/musl/lookup.internal.h"
#include "libc/intrin/atomic.h"
#include "third_party/musl/netdb.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
int getaddrinfo(const char *host,
const char *serv,
const struct addrinfo *hint,
struct addrinfo **res)
{
struct service ports[MAXSERVS];
struct address addrs[MAXADDRS];
char canon[256], *outcanon;
int nservs, naddrs, nais, canon_len, i, j, k;
int family = AF_UNSPEC, flags = 0, proto = 0, socktype = 0;
int no_family = 0;
struct aibuf *out;
if (!host && !serv) return EAI_NONAME;
if (hint) {
family = hint->ai_family;
flags = hint->ai_flags;
proto = hint->ai_protocol;
socktype = hint->ai_socktype;
const int mask = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST |
AI_V4MAPPED | AI_ALL | AI_ADDRCONFIG | AI_NUMERICSERV;
if ((flags & mask) != flags)
return EAI_BADFLAGS;
if (family != AF_INET &&
family != AF_INET6 &&
family != AF_UNSPEC) {
return EAI_FAMILY;
}
}
if (flags & AI_ADDRCONFIG) {
/* Define the "an address is configured" condition for address
* families via ability to create a socket for the family plus
* routability of the loopback address for the family. */
const struct sockaddr_in lo4 = {
.sin_family = AF_INET, .sin_port = 65535,
.sin_addr.s_addr = __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
? 0x7f000001 : 0x0100007f
};
const struct sockaddr_in6 lo6 = {
.sin6_family = AF_INET6, .sin6_port = 65535,
.sin6_addr = IN6ADDR_LOOPBACK_INIT
};
int tf[2] = { AF_INET, AF_INET6 };
const void *ta[2] = { &lo4, &lo6 };
socklen_t tl[2] = { sizeof lo4, sizeof lo6 };
for (i=0; i<2; i++) {
if (family==tf[1-i]) continue;
int s = socket(tf[i], SOCK_CLOEXEC|SOCK_DGRAM,
IPPROTO_UDP);
if (s>=0) {
int cs;
pthread_setcancelstate(
PTHREAD_CANCEL_DISABLE, &cs);
int r = connect(s, ta[i], tl[i]);
int saved_errno = errno;
pthread_setcancelstate(cs, 0);
close(s);
if (!r) continue;
errno = saved_errno;
}
if (errno != EADDRNOTAVAIL &&
errno != EAFNOSUPPORT &&
errno != EHOSTUNREACH &&
errno != ENETDOWN &&
errno != ENETUNREACH) {
return EAI_SYSTEM;
}
if (family == tf[i]) no_family = 1;
family = tf[1-i];
}
}
nservs = __lookup_serv(ports, serv, proto, socktype, flags);
if (nservs < 0) return nservs;
naddrs = __lookup_name(addrs, canon, host, family, flags);
if (naddrs < 0) return naddrs;
if (no_family) return EAI_NODATA;
nais = nservs * naddrs;
canon_len = strlen(canon);
out = calloc(1, nais * sizeof(*out) + canon_len + 1);
if (!out) return EAI_MEMORY;
if (canon_len) {
outcanon = (void *)&out[nais];
memcpy(outcanon, canon, canon_len+1);
} else {
outcanon = 0;
}
for (k=i=0; i<naddrs; i++) for (j=0; j<nservs; j++, k++) {
out[k].slot = k;
out[k].ai = (struct addrinfo){
.ai_family = addrs[i].family,
.ai_socktype = ports[j].socktype,
.ai_protocol = ports[j].proto,
.ai_addrlen = addrs[i].family == AF_INET
? sizeof(struct sockaddr_in)
: sizeof(struct sockaddr_in6),
.ai_addr = (void *)&out[k].sa,
.ai_canonname = outcanon };
if (k) out[k-1].ai.ai_next = &out[k].ai;
if (addrs[i].family == AF_INET) {
out[k].sa.sin.sin_family = AF_INET;
out[k].sa.sin.sin_port = htons(ports[j].port);
memcpy(&out[k].sa.sin.sin_addr, &addrs[i].addr, 4);
} else if (addrs[i].family == AF_INET6) {
out[k].sa.sin6.sin6_family = AF_INET6;
out[k].sa.sin6.sin6_port = htons(ports[j].port);
out[k].sa.sin6.sin6_scope_id = addrs[i].scopeid;
memcpy(&out[k].sa.sin6.sin6_addr, &addrs[i].addr, 16);
}
}
atomic_store_explicit(&out[0].ref, nais, memory_order_relaxed);
*res = &out->ai;
return 0;
}

50
third_party/musl/gethostbyaddr.c vendored Normal file
View file

@ -0,0 +1,50 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "third_party/musl/netdb.h"
struct hostent *gethostbyaddr(const void *a, socklen_t l, int af)
{
static struct hostent *h;
size_t size = 63;
struct hostent *res;
int err;
do {
free(h);
h = malloc(size+=size+1);
if (!h) {
h_errno = NO_RECOVERY;
return 0;
}
err = gethostbyaddr_r(a, l, af, h,
(void *)(h+1), size-sizeof *h, &res, &h_errno);
} while (err == ERANGE);
return res;
}

103
third_party/musl/gethostbyaddr_r.c vendored Normal file
View file

@ -0,0 +1,103 @@
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
vi: set noet ft=c ts=8 sw=8 fenc=utf-8 :vi
Musl Libc
Copyright © 2005-2014 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr6.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "third_party/musl/netdb.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
errno_t gethostbyaddr_r(const void *a, socklen_t l, int af,
struct hostent *h, char *buf, size_t buflen,
struct hostent **res, int *err)
{
union {
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
} sa = { .sin.sin_family = af };
socklen_t sl = af==AF_INET6 ? sizeof sa.sin6 : sizeof sa.sin;
int i;
*res = 0;
/* Load address argument into sockaddr structure */
if (af==AF_INET6 && l==16) memcpy(&sa.sin6.sin6_addr, a, 16);
else if (af==AF_INET && l==4) memcpy(&sa.sin.sin_addr, a, 4);
else {
*err = NO_RECOVERY;
return EINVAL;
}
/* Align buffer and check for space for pointers and ip address */
i = (uintptr_t)buf & (sizeof(char *)-1);
if (!i) i = sizeof(char *);
if (buflen <= 5*sizeof(char *)-i + l) return ERANGE;
buf += sizeof(char *)-i;
buflen -= 5*sizeof(char *)-i + l;
h->h_addr_list = (void *)buf;
buf += 2*sizeof(char *);
h->h_aliases = (void *)buf;
buf += 2*sizeof(char *);
h->h_addr_list[0] = buf;
memcpy(h->h_addr_list[0], a, l);
buf += l;
h->h_addr_list[1] = 0;
h->h_aliases[0] = buf;
h->h_aliases[1] = 0;
switch (getnameinfo((void *)&sa, sl, buf, buflen, 0, 0, 0)) {
case EAI_AGAIN:
*err = TRY_AGAIN;
return EAGAIN;
case EAI_OVERFLOW:
return ERANGE;
default:
case EAI_FAIL:
*err = NO_RECOVERY;
return EBADMSG;
case EAI_SYSTEM:
*err = NO_RECOVERY;
return errno;
case 0:
break;
}
h->h_addrtype = af;
h->h_length = l;
h->h_name = h->h_aliases[0];
*res = h;
return 0;
}

Some files were not shown because too many files have changed in this diff Show more