From 249866e3d1e11dc72eaa1305f4bb479ded92ef38 Mon Sep 17 00:00:00 2001 From: Jannis Hoffmann Date: Tue, 9 Jul 2024 13:58:20 +0200 Subject: reorganized file structure Moved c files into src/. Corrected VERSION file. Removed BUILD and FILES. --- src/Makefile | 123 +++++++++++++ src/TARGETS | 79 ++++++++ src/alloc.c | 50 ++++++ src/base64.c | 124 +++++++++++++ src/buffer.c | 226 +++++++++++++++++++++++ src/byte.c | 99 ++++++++++ src/case.c | 134 ++++++++++++++ src/cdbmake.c | 158 ++++++++++++++++ src/cdbread.c | 169 ++++++++++++++++++ src/configure | 69 +++++++ src/constmap.c | 169 ++++++++++++++++++ src/dnsstub/Makefile | 23 +++ src/dnsstub/README.md | 171 ++++++++++++++++++ src/dnsstub/TARGETS | 18 ++ src/dnsstub/dns_cname.c | 59 ++++++ src/dnsstub/dns_dfd.c | 76 ++++++++ src/dnsstub/dns_domain.c | 80 +++++++++ src/dnsstub/dns_dtda.c | 43 +++++ src/dnsstub/dns_ip.c | 198 ++++++++++++++++++++ src/dnsstub/dns_ipq.c | 236 ++++++++++++++++++++++++ src/dnsstub/dns_mx.c | 63 +++++++ src/dnsstub/dns_name.c | 80 +++++++++ src/dnsstub/dns_nd.c | 48 +++++ src/dnsstub/dns_packet.c | 85 +++++++++ src/dnsstub/dns_random.c | 70 ++++++++ src/dnsstub/dns_rcip.c | 114 ++++++++++++ src/dnsstub/dns_rcrw.c | 141 +++++++++++++++ src/dnsstub/dns_resolve.c | 39 ++++ src/dnsstub/dns_sortip.c | 45 +++++ src/dnsstub/dns_transmit.c | 436 +++++++++++++++++++++++++++++++++++++++++++++ src/dnsstub/dns_txt.c | 64 +++++++ src/env.c | 136 ++++++++++++++ src/errstr.c | 163 +++++++++++++++++ src/fd.c | 30 ++++ src/fmt.c | 85 +++++++++ src/getln.c | 43 +++++ src/getoptb.c | 100 +++++++++++ src/iopause.c | 84 +++++++++ src/ip4.c | 166 +++++++++++++++++ src/ip6.c | 360 +++++++++++++++++++++++++++++++++++++ src/lock.c | 22 +++ src/logmsg.c | 97 ++++++++++ src/ndelay.c | 24 +++ src/open.c | 25 +++ src/pathexec.c | 121 +++++++++++++ src/prot.c | 31 ++++ src/readclose.c | 43 +++++ src/scan.c | 120 +++++++++++++ src/seek.c | 30 ++++ src/sharedlib | 2 + src/sig.c | 110 ++++++++++++ src/socket_bind.c | 79 ++++++++ src/socket_connect.c | 66 +++++++ src/socket_if.c | 36 ++++ src/socket_info.c | 58 ++++++ src/socket_recv.c | 39 ++++ src/socket_send.c | 62 +++++++ src/socket_setup.c | 99 ++++++++++ src/socket_tcp.c | 63 +++++++ src/socket_udp.c | 57 ++++++ src/str.c | 135 ++++++++++++++ src/stralloc.c | 126 +++++++++++++ src/tai.c | 59 ++++++ src/taia.c | 104 +++++++++++ src/timeout.c | 59 ++++++ src/timeoutconn.c | 112 ++++++++++++ src/uint128p.c | 100 +++++++++++ src/uint16p.c | 40 +++++ src/uint32p.c | 47 +++++ src/uint64p.c | 62 +++++++ src/uint8p.c | 39 ++++ src/wait.c | 25 +++ 72 files changed, 6748 insertions(+) create mode 100644 src/Makefile create mode 100644 src/TARGETS create mode 100644 src/alloc.c create mode 100644 src/base64.c create mode 100644 src/buffer.c create mode 100644 src/byte.c create mode 100644 src/case.c create mode 100644 src/cdbmake.c create mode 100644 src/cdbread.c create mode 100755 src/configure create mode 100644 src/constmap.c create mode 100644 src/dnsstub/Makefile create mode 100644 src/dnsstub/README.md create mode 100644 src/dnsstub/TARGETS create mode 100644 src/dnsstub/dns_cname.c create mode 100644 src/dnsstub/dns_dfd.c create mode 100644 src/dnsstub/dns_domain.c create mode 100644 src/dnsstub/dns_dtda.c create mode 100644 src/dnsstub/dns_ip.c create mode 100644 src/dnsstub/dns_ipq.c create mode 100644 src/dnsstub/dns_mx.c create mode 100644 src/dnsstub/dns_name.c create mode 100644 src/dnsstub/dns_nd.c create mode 100644 src/dnsstub/dns_packet.c create mode 100644 src/dnsstub/dns_random.c create mode 100644 src/dnsstub/dns_rcip.c create mode 100644 src/dnsstub/dns_rcrw.c create mode 100644 src/dnsstub/dns_resolve.c create mode 100644 src/dnsstub/dns_sortip.c create mode 100644 src/dnsstub/dns_transmit.c create mode 100644 src/dnsstub/dns_txt.c create mode 100644 src/env.c create mode 100644 src/errstr.c create mode 100644 src/fd.c create mode 100644 src/fmt.c create mode 100644 src/getln.c create mode 100644 src/getoptb.c create mode 100644 src/iopause.c create mode 100644 src/ip4.c create mode 100644 src/ip6.c create mode 100644 src/lock.c create mode 100644 src/logmsg.c create mode 100644 src/ndelay.c create mode 100644 src/open.c create mode 100644 src/pathexec.c create mode 100644 src/prot.c create mode 100644 src/readclose.c create mode 100644 src/scan.c create mode 100644 src/seek.c create mode 100755 src/sharedlib create mode 100644 src/sig.c create mode 100644 src/socket_bind.c create mode 100644 src/socket_connect.c create mode 100644 src/socket_if.c create mode 100644 src/socket_info.c create mode 100644 src/socket_recv.c create mode 100644 src/socket_send.c create mode 100644 src/socket_setup.c create mode 100644 src/socket_tcp.c create mode 100644 src/socket_udp.c create mode 100644 src/str.c create mode 100644 src/stralloc.c create mode 100644 src/tai.c create mode 100644 src/taia.c create mode 100644 src/timeout.c create mode 100644 src/timeoutconn.c create mode 100644 src/uint128p.c create mode 100644 src/uint16p.c create mode 100644 src/uint32p.c create mode 100644 src/uint64p.c create mode 100644 src/uint8p.c create mode 100644 src/wait.c (limited to 'src') diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..8426968 --- /dev/null +++ b/src/Makefile @@ -0,0 +1,123 @@ +# Makefile for qlibs + +SHELL=/bin/sh + +# static flags - DO NOT EDIT! +CCFLAGS=-Iinclude + +SRCS=*.c +OBJS=*.o +COMPILE=./compile +MAKELIB=./makelib +SHAREDLIB=./sharedlib + +default: clean check libs + +check: + @[ -f $(COMPILE) ] && [ -f $(MAKELIB) ] || ./configure + +clean: + @echo -n Cleaning up libs ... + @rm -f `cat TARGETS` + @cd dnsstub ; make -s clean ; cd .. + @echo " done!" + +core: alloc.a buffer.a case.a cdb.a constmap.a env.a \ +fd.a fs.a getln.a getopt.a lock.a logmsg.a ndelay.a open.a \ +seek.a sig.a str.a stralloc.a time.a wait.a \ +ip.a socket.a dnsresolv.a + +libs: obj core qlibs.a dnsresolv.a + +obj: + @echo Making all in qlibs ... + $(COMPILE) $(CCFLAGS) $(CFLAGS) $(SRCS) + +install: setup + +setup: + @./install + +shared: $(COMPILE) $(SHAREDLIB) $(OBJS) ./dnsstub/$(OBJS) + @echo Building shared qlibs ... + $(SHAREDLIB) $(LDFLAGS) $(OBJS) -o libqlibs.so + $(SHAREDLIB) $(LDFLAGS) ./dnsstub/$(OBJS) -o libdnsresolv.so + +qlibs.a: obj socket.a + $(MAKELIB) $(LDFLAGS) qlibs.a *.o + ln -sf qlibs.a libqlibs.a + +dnsresolv.a: + @echo "Building @dnsresolv lib ..." + @cd dnsstub ; make + @cp dnsstub/dnsresolv.a dnsresolv.a + ln -sf dnsresolv.a libdnsresolv.a + +socket.a: ip.a + @echo "Building socket lib ..." + $(MAKELIB) $(LDFLAGS) socket.a socket_if.o socket_bind.o socket_connect.o \ + socket_info.o socket_setup.o socket_tcp.o socket_udp.o ip.a + +# build each file separately (backwards compat) - better use recipe qlibs.a +alloc.a: alloc.o + $(MAKELIB) $(LDFLAGS) alloc.a alloc.o + +buffer.a: buffer.o + $(MAKELIB) $(LDFLAGS) buffer.a buffer.o + +case.a: case.o + $(MAKELIB) $(LDFLAGS) case.a case.o + +cdb.a: cdbread.o cdbmake.o uint32p.o seek.o buffer.o + $(MAKELIB) $(LDFLAGS) cdb.a cdbread.o cdbmake.o uint32p.o seek.o buffer.o + +constmap.a: constmap.o alloc.o buffer.o scan.o + $(MAKELIB) $(LDFLAGS) constmap.a constmap.o alloc.o buffer.o scan.o + +env.a: env.o + $(MAKELIB) $(LDFLAGS) env.a env.o + +fd.a: fd.o + $(MAKELIB) $(LDFLAGS) fd.a fd.o + +fs.a: fmt.o scan.o + $(MAKELIB) $(LDFLAGS) fs.a fmt.o scan.o + +getln.a: getln.o + $(MAKELIB) $(LDFLAGS) getln.a getln.o + +getopt.a: getoptb.o + $(MAKELIB) $(LDFLAGS) getopt.a getoptb.o + +ip.a: ip4.o ip6.o socket_if.o + $(MAKELIB) $(LDFLAGS) ip.a ip4.o ip6.o socket_if.o + +lock.a: lock.o + $(MAKELIB) $(LDFLAGS) lock.a lock.o + +ndelay.a: ndelay.o + $(MAKELIB) $(LDFLAGS) ndelay.a ndelay.o + +open.a: open.o + $(MAKELIB) $(LDFLAGS) open.a open.o + +seek.a: seek.o + $(MAKELIB) $(LDFLAGS) seek.a seek.o + +sig.a: sig.o + $(MAKELIB) $(LDFLAGS) sig.a sig.o + +str.a: str.o byte.o stralloc.o alloc.o + $(MAKELIB) $(LDFLAGS) str.a str.o byte.o stralloc.o alloc.o + +stralloc.a: stralloc.o alloc.o + $(MAKELIB) $(LDFLAGS) stralloc.a stralloc.o alloc.o + +logmsg.a: errstr.o logmsg.o + $(MAKELIB) $(LDFLAGS) logmsg.a errstr.o logmsg.o + +time.a: iopause.o tai.o taia.o timeout.o timeoutconn.o + $(MAKELIB) $(LDFLAGS) time.a iopause.o tai.o taia.o timeout.o timeoutconn.o + +wait.a: wait.o + $(MAKELIB) $(LDFLAGS) wait.a wait.o diff --git a/src/TARGETS b/src/TARGETS new file mode 100644 index 0000000..df6d6ee --- /dev/null +++ b/src/TARGETS @@ -0,0 +1,79 @@ +alloc.a +alloc.o +base64.o +buffer.a +buffer.o +byte.o +case.a +case.o +cdb.a +cdbmake.o +cdbread.o +constmap.a +constmap.o +compile +dnsresolv.a +env.a +env.o +errstr.o +fd.a +fd.o +fmt.o +fs.a +getln.a +getln.o +getopt.a +getoptb.o +iopause.o +ip.a +ip4.o +ip6.o +libdnsresolv.a +libqlibs.a +lock.a +lock.o +logmsg.a +logmsg.o +makelib +ndelay.a +ndelay.o +open.a +open.o +pathexec.o +prot.o +qlibs.a +readclose.o +scan.o +seek.a +seek.o +sig.a +sig.o +socket.a +socket_bind.o +socket_connect.o +socket_if.o +socket_info.o +socket_recv.o +socket_send.o +socket_setup.o +socket_tcp.o +socket_udp.o +str.a +str.o +stralloc.a +stralloc.o +sysmsg.o +tai.o +taia.o +time.a +timeout.o +timeoutconn.o +uint128p.o +uint16p.o +uint32p.o +uint64p.o +uint8p.o +wait.a +wait.o +libdnsresolv.so +libqlibs.so diff --git a/src/alloc.c b/src/alloc.c new file mode 100644 index 0000000..8ec0a7e --- /dev/null +++ b/src/alloc.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include "byte.h" +#include "alloc.h" + +#define ALIGNMENT 16 /* XXX: assuming that this alignment is enough */ +#define SPACE 4096 /* must be multiple of ALIGNMENT */ + +typedef union { char irrelevant[ALIGNMENT]; double d; } aligned; +static aligned realspace[SPACE / ALIGNMENT]; +#define space ((char *) realspace) +static unsigned int avail = SPACE; /* multiple of ALIGNMENT; 0<=avail<=SPACE */ + +/*@null@*//*@out@*/char *alloc(unsigned int n) { + char *x; + +/* Guninski exploit + patch from Qualys (CVE-2005-1513) */ + + if (n >= (INT_MAX >> 3)) { + errno = ENOMEM; + return 0; + } + + n = ALIGNMENT + n - (n & (ALIGNMENT - 1)); /* XXX: could overflow */ + if (n <= avail) { avail -= n; return space + avail; } + x = malloc(n); + if (!x) errno = ENOMEM; + return x; +} + +void alloc_free(char *x) +{ + if (x >= space) + if (x < space + SPACE) + return; /* XXX: assuming that pointers are flat */ + free(x); +} + +int alloc_re(char **x,unsigned int m,unsigned int n) +{ + char *y; + + y = alloc(n); + if (!y) return 0; + byte_copy(y,m,*x); + qfree(*x); + *x = y; + return 1; +} diff --git a/src/base64.c b/src/base64.c new file mode 100644 index 0000000..986201e --- /dev/null +++ b/src/base64.c @@ -0,0 +1,124 @@ +#include "base64.h" +#include "stralloc.h" +#include "str.h" + +/** + @file base64.c + @author unkown + @source unknown + @brief base64 en+decoding of strings +*/ + +static char *b64alpha = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +#define B64PAD '=' + +/* returns 0 ok, 1 illegal, -1 problem */ + +int b64decode(const unsigned char *in,int l,stralloc *out) /* not null terminated */ +{ + int p = 0; + int n; + unsigned int x; + int i, j; + char *s; + unsigned char b[3]; + + if (l == 0) { + if (!stralloc_copys(out,"")) return -1; + return 0; + } + + while (in[l-1] == B64PAD) { + p ++; + l--; + } + + n = (l + p) / 4; + i = (n * 3) - p; + if (!stralloc_ready(out,i)) return -1; + out->len = i; + s = out->s; + + for (i = 0; i < n - 1 ; i++) { + x = 0; + for (j = 0; j < 4; j++) { + if(in[j] >= 'A' && in[j] <= 'Z') + x = (x << 6) + (unsigned int)(in[j] - 'A' + 0); + else if(in[j] >= 'a' && in[j] <= 'z') + x = (x << 6) + (unsigned int)(in[j] - 'a' + 26); + else if(in[j] >= '0' && in[j] <= '9') + x = (x << 6) + (unsigned int)(in[j] - '0' + 52); + else if(in[j] == '+') + x = (x << 6) + 62; + else if(in[j] == '/') + x = (x << 6) + 63; + else if(in[j] == '=') + x = (x << 6); + } + + s[2] = (unsigned char)(x & 255); x >>= 8; + s[1] = (unsigned char)(x & 255); x >>= 8; + s[0] = (unsigned char)(x & 255); x >>= 8; + s += 3; in += 4; + } + + x = 0; + for (j = 0; j < 4; j++) { + if(in[j] >= 'A' && in[j] <= 'Z') + x = (x << 6) + (unsigned int)(in[j] - 'A' + 0); + else if(in[j] >= 'a' && in[j] <= 'z') + x = (x << 6) + (unsigned int)(in[j] - 'a' + 26); + else if(in[j] >= '0' && in[j] <= '9') + x = (x << 6) + (unsigned int)(in[j] - '0' + 52); + else if(in[j] == '+') + x = (x << 6) + 62; + else if(in[j] == '/') + x = (x << 6) + 63; + else if(in[j] == '=') + x = (x << 6); + } + + b[2] = (unsigned char)(x & 255); x >>= 8; + b[1] = (unsigned char)(x & 255); x >>= 8; + b[0] = (unsigned char)(x & 255); x >>= 8; + + for (i = 0; i < 3 - p; i++) + s[i] = b[i]; + + return 0; +} + +int b64encode(stralloc *in,stralloc *out) /* not null terminated */ +{ + unsigned char a, b, c; + int i; + char *s; + + if (in->len == 0) { + if (!stralloc_copys(out,"")) return -1; + return 0; + } + + i = in->len / 3 * 4 + 4; + if (!stralloc_ready(out,i)) return -1; + s = out->s; + + for (i = 0; i < in->len; i += 3) { + a = in->s[i]; + b = i + 1 < in->len ? in->s[i + 1] : 0; + c = i + 2 < in->len ? in->s[i + 2] : 0; + + *s++ = b64alpha[a >> 2]; + *s++ = b64alpha[((a & 3 ) << 4) | (b >> 4)]; + + if (i + 1 >= in->len) *s++ = B64PAD; + else *s++ = b64alpha[((b & 15) << 2) | (c >> 6)]; + + if (i + 2 >= in->len) *s++ = B64PAD; + else *s++ = b64alpha[c & 63]; + } + out->len = s - out->s; + + return 0; +} diff --git a/src/buffer.c b/src/buffer.c new file mode 100644 index 0000000..92d72b1 --- /dev/null +++ b/src/buffer.c @@ -0,0 +1,226 @@ +#include +#include "buffer.h" +#include "str.h" +#include "byte.h" +#include "error.h" + +/** + @file buffer.c + @author djb + @brief input/output routines +*/ + +void buffer_init(buffer *s,ssize_t (*op)(),int fd,char *buf,size_t len) +{ + s->x = buf; + s->fd = fd; + s->op = op; + s->p = 0; + s->n = len; +} + +ssize_t buffer_0_read(int fd,char *buf,size_t len) +{ + if (buffer_flush(buffer_1) == -1) return -1; + return read(fd,buf,len); +} + +char buffer_0_space[BUFFER_INSIZE]; +static buffer it0 = BUFFER_INIT(buffer_0_read,0,buffer_0_space,sizeof(buffer_0_space)); +buffer *buffer_0 = &it0; + +char buffer_1_space[BUFFER_OUTSIZE]; +static buffer it1 = BUFFER_INIT(write,1,buffer_1_space,sizeof(buffer_1_space)); +buffer *buffer_1 = &it1; + +char buffer_2_space[BUFFER_OUTSIZE]; +static buffer it2 = BUFFER_INIT(write,2,buffer_2_space,sizeof(buffer_2_space)); +buffer *buffer_2 = &it2; + +char buffer_0_small[BUFFER_SMALL]; +static buffer is0 = BUFFER_INIT(buffer_0_read,0,buffer_0_small,sizeof(buffer_0_small)); +buffer *buffer_0small = &is0; + +char buffer_1_small[BUFFER_SMALL]; +static buffer is1 = BUFFER_INIT(write,1,buffer_1_small,sizeof(buffer_1_small)); +buffer *buffer_1small = &is1; + +char buffer_2_small[BUFFER_SMALL]; +static buffer is2 = BUFFER_INIT(write,2,buffer_2_small,sizeof(buffer_2_small)); +buffer *buffer_2small = &is2; + +ssize_t buffer_unixread(int fd,char *buf,size_t len) +{ + return read(fd,buf,len); +} + +ssize_t buffer_unixwrite(int fd,char *buf,size_t len) +{ + return write(fd,buf,len); +} + +int buffer_copy(buffer *bout,buffer *bin) +{ + int n; + char *x; + + for (;;) { + n = buffer_feed(bin); + if (n < 0) return -2; + if (!n) return 0; + x = buffer_PEEK(bin); + if (buffer_put(bout,x,n) == -1) return -3; + buffer_SEEK(bin,n); + } +} + +static int oneread(ssize_t (*op)(),int fd,char *buf,size_t len) +{ + int r; + + for (;;) { + r = op(fd,buf,len); + if (r == -1) if (errno == EINTR) continue; + return r; + } +} + +static int getthis(buffer *s,char *buf,size_t len) +{ + if (len > s->p) len = s->p; + s->p -= len; + byte_copy(buf,len,s->x + s->n); + s->n += len; + return len; +} + +int buffer_feed(buffer *s) +{ + int r; + + if (s->p) return s->p; + r = oneread(s->op,s->fd,s->x,s->n); + if (r <= 0) return r; + s->p = r; + s->n -= r; + if (s->n > 0) byte_copyr(s->x + s->n,r,s->x); + return r; +} + +int buffer_bget(buffer *s,char *buf,size_t len) +{ + int r; + + if (s->p > 0) return getthis(s,buf,len); + if (s->n <= len) return oneread(s->op,s->fd,buf,s->n); + r = buffer_feed(s); + if (r <= 0) return r; + return getthis(s,buf,len); +} + +int buffer_get(buffer *s,char *buf,size_t len) +{ + int r; + + if (s->p > 0) return getthis(s,buf,len); + if (s->n <= len) return oneread(s->op,s->fd,buf,len); + r = buffer_feed(s); + if (r <= 0) return r; + return getthis(s,buf,len); +} + +char *buffer_peek(buffer *s) +{ + return s->x + s->n; +} + +void buffer_seek(buffer *s,size_t len) +{ + s->n += len; + s->p -= len; +} + +static int allwrite(ssize_t (*op)(),int fd,const char *buf,size_t len) +{ + int w; + + while (len) { + w = op(fd,buf,len); + if (w == -1) { + if (errno == EINTR) continue; + return -1; /* note that some data may have been written */ + } + if (w == 0) /* luser's fault */ + ; + buf += w; + len -= w; + } + return 0; +} + +int buffer_flush(buffer *s) +{ + int p; + + p = s->p; + if (!p) return 0; + s->p = 0; + return allwrite(s->op,s->fd,s->x,p); +} + +int buffer_putalign(buffer *s,const char *buf,size_t len) +{ + unsigned int n; + + while (len > (n = s->n - s->p)) { + byte_copy(s->x + s->p,n,buf); s->p += n; buf += n; len -= n; + if (buffer_flush(s) == -1) return -1; + } + /* now len <= s->n - s->p */ + byte_copy(s->x + s->p,len,buf); + s->p += len; + return 0; +} + +int buffer_put(buffer *s,const char *buf,size_t len) +{ + unsigned int n; + + n = s->n; + if (len > n - s->p) { + if (buffer_flush(s) == -1) return -1; + /* now s->p == 0 */ + if (n < BUFFER_OUTSIZE) n = BUFFER_OUTSIZE; + while (len > s->n) { + if (n > len) n = len; + if (allwrite(s->op,s->fd,buf,n) == -1) return -1; + buf += n; + len -= n; + } + } + /* now len <= s->n - s->p */ + byte_copy(s->x + s->p,len,buf); + s->p += len; + return 0; +} + +int buffer_putflush(buffer *s,const char *buf,size_t len) +{ + if (buffer_flush(s) == -1) return -1; + return allwrite(s->op,s->fd,buf,len); +} + +int buffer_putsalign(buffer *s,const char *buf) +{ + return buffer_putalign(s,buf,str_len(buf)); +} + +int buffer_puts(buffer *s,const char *buf) +{ + return buffer_put(s,buf,str_len(buf)); +} + +int buffer_putsflush(buffer *s,const char *buf) +{ + return buffer_putflush(s,buf,str_len(buf)); +} diff --git a/src/byte.c b/src/byte.c new file mode 100644 index 0000000..c9d6d23 --- /dev/null +++ b/src/byte.c @@ -0,0 +1,99 @@ +#include "byte.h" + +/** + @file byte.c + @author djb + @brief byte manipulation functions +*/ + +unsigned int byte_chr(char *s,register unsigned int n,int c) +{ + register char ch; + register char *t; + + ch = c; + t = s; + for (;;) { + if (!n) { break; } if (*t == ch) { break; } ++t; --n; + if (!n) { break; } if (*t == ch) { break; } ++t; --n; + if (!n) { break; } if (*t == ch) { break; } ++t; --n; + if (!n) { break; } if (*t == ch) { break; } ++t; --n; + } + return t - s; +} + +void byte_copy(register char *to,register unsigned int n,register char *from) +{ + for (;;) { + if (!n) { return; } *to++ = *from++; --n; + if (!n) { return; } *to++ = *from++; --n; + if (!n) { return; } *to++ = *from++; --n; + if (!n) { return; } *to++ = *from++; --n; + } +} + +void byte_copyr(register char *to,register unsigned int n,register char *from) +{ + to += n; + from += n; + for (;;) { + if (!n) { return; } *--to = *--from; --n; + if (!n) { return; } *--to = *--from; --n; + if (!n) { return; } *--to = *--from; --n; + if (!n) { return; } *--to = *--from; --n; + } +} + +int byte_diff(register char *s,register unsigned int n,register char *t) +{ + for (;;) { + if (!n) { return 0; } if (*s != *t) { break; } ++s; ++t; --n; + if (!n) { return 0; } if (*s != *t) { break; } ++s; ++t; --n; + if (!n) { return 0; } if (*s != *t) { break; } ++s; ++t; --n; + if (!n) { return 0; } if (*s != *t) { break; } ++s; ++t; --n; + } + return ((int)(unsigned int)(unsigned char) *s) + - ((int)(unsigned int)(unsigned char) *t); +} + +unsigned int byte_rchr(char *s,register unsigned int n,int c) +{ + register char ch; + register char *t; + register char *u; + + ch = c; + t = s; + u = 0; + for (;;) { + if (!n) { break; } if (*t == ch) { u = t; } ++t; --n; + if (!n) { break; } if (*t == ch) { u = t; } ++t; --n; + if (!n) { break; } if (*t == ch) { u = t; } ++t; --n; + if (!n) { break; } if (*t == ch) { u = t; } ++t; --n; + } + if (!u) { u = t; } + return u - s; +} + +void byte_zero(char *s,register unsigned int n) +{ + for (;;) { + if (!n) { break; } *s++ = 0; --n; + if (!n) { break; } *s++ = 0; --n; + if (!n) { break; } *s++ = 0; --n; + if (!n) { break; } *s++ = 0; --n; + } +} + +void byte_fill(char *s,register unsigned int n,const int c) +{ + register char ch; + + ch = c; + for (;;) { + if (!n) { break; } *s++ = ch; --n; + if (!n) { break; } *s++ = ch; --n; + if (!n) { break; } *s++ = ch; --n; + if (!n) { break; } *s++ = ch; --n; + } +} diff --git a/src/case.c b/src/case.c new file mode 100644 index 0000000..47eb8ed --- /dev/null +++ b/src/case.c @@ -0,0 +1,134 @@ +#include "case.h" +#include "str.h" + +/** + @file case.c + @author djb + @brief string comparison and helper functions; case insensitive +*/ + +int case_diffb(register char *s,unsigned int len,register char *t) +{ + register unsigned char x; + register unsigned char y; + + while (len > 0) { + --len; + x = *s++ - 'A'; + if (x <= 'Z' - 'A') x += 'a'; else x += 'A'; + y = *t++ - 'A'; + if (y <= 'Z' - 'A') y += 'a'; else y += 'A'; + if (x != y) + return ((int)(unsigned int) x) - ((int)(unsigned int) y); + } + return 0; +} + +int case_diffs(register char *s,register char *t) +{ + register unsigned char x; + register unsigned char y; + + for (;;) { + x = *s++ - 'A'; + if (x <= 'Z' - 'A') x += 'a'; else x += 'A'; + y = *t++ - 'A'; + if (y <= 'Z' - 'A') y += 'a'; else y += 'A'; + if (x != y) break; + if (!x) break; + } + return ((int)(unsigned int) x) - ((int)(unsigned int) y); +} + +int case_diffrs(register char *s,register char *t) +{ + register unsigned char x = 0; + register unsigned char y = 0; + unsigned int lens = str_len(s); + unsigned int lent = str_len(t); + + while (lens > 0 && lent > 0) { + x = s[--lens] - 'A'; + if (x <= 'Z' - 'A') x += 'a'; else x += 'A'; + y = t[--lent] - 'A'; + if (y <= 'Z' - 'A') y += 'a'; else y += 'A'; + if (x != y) break; + if (!x) break; + if (!y) break; + } + return ((int)(unsigned int) x) - ((int)(unsigned int) y); +} + +void case_lowerb(char *s,unsigned int len) +{ + unsigned char x; + while (len > 0) { + --len; + x = *s - 'A'; + if (x <= 'Z' - 'A') *s = x + 'a'; + ++s; + } +} + +void case_lowers(char *s) +{ + unsigned char x; + while ((x = *s)) { + x -= 'A'; + if (x <= 'Z' - 'A') *s = x + 'a'; + ++s; + } +} + +void case_upperb(char *s,unsigned int len) +{ + unsigned char x; + while (len > 0) { + --len; + x = *s - 'a'; + if (x <= 'z' - 'a') *s = x + 'A'; + ++s; + } +} + +void case_uppers(char *s) +{ + unsigned char x; + while ((x = *s)) { + x -= 'a'; + if (x <= 'z' - 'a') *s = x + 'A'; + ++s; + } +} + +int case_startb(register char *s,unsigned int len,register char *t) +{ + register unsigned char x; + register unsigned char y; + + for (;;) { + y = *t++ - 'A'; + if (y <= 'Z' - 'A') y += 'a'; else y += 'A'; + if (!y) return 1; + if (!len) return 0; + --len; + x = *s++ - 'A'; + if (x <= 'Z' - 'A') x += 'a'; else x += 'A'; + if (x != y) return 0; + } +} + +int case_starts(register char *s,register char *t) +{ + register unsigned char x; + register unsigned char y; + + for (;;) { + x = *s++ - 'A'; + if (x <= 'Z' - 'A') x += 'a'; else x += 'A'; + y = *t++ - 'A'; + if (y <= 'Z' - 'A') y += 'a'; else y += 'A'; + if (!y) return 1; + if (x != y) return 0; + } +} diff --git a/src/cdbmake.c b/src/cdbmake.c new file mode 100644 index 0000000..28e170c --- /dev/null +++ b/src/cdbmake.c @@ -0,0 +1,158 @@ +#include +#include "seek.h" +#include "error.h" +#include "alloc.h" +#include "cdbread.h" +#include "cdbmake.h" + +/** + @file cdbmake.c + @author djb + @source ucspi-tcp + @brief constant data base (cdb) generation +*/ + +int cdb_make_start(struct cdb_make *c,int fd) +{ + c->head = 0; + c->split = 0; + c->hash = 0; + c->numentries = 0; + c->fd = fd; + c->pos = sizeof(c->final); + buffer_init(&c->b,write,fd,c->bspace,sizeof(c->bspace)); + return seek_set(fd,c->pos); +} + +static int posplus(struct cdb_make *c,uint32 len) +{ + uint32 newpos = c->pos + len; + if (newpos < len) { errno = ENOMEM; return -1; } + c->pos = newpos; + return 0; +} + +int cdb_make_addend(struct cdb_make *c,unsigned int keylen,unsigned int datalen,uint32 h) +{ + struct cdb_hplist *head; + + head = c->head; + if (!head || (head->num >= CDB_HPLIST)) { + head = (struct cdb_hplist *) alloc(sizeof(struct cdb_hplist)); + if (!head) return -1; + head->num = 0; + head->next = c->head; + c->head = head; + } + head->hp[head->num].h = h; + head->hp[head->num].p = c->pos; + ++head->num; + ++c->numentries; + if (posplus(c,8) == -1) return -1; + if (posplus(c,keylen) == -1) return -1; + if (posplus(c,datalen) == -1) return -1; + return 0; +} + +int cdb_make_addbegin(struct cdb_make *c,unsigned int keylen,unsigned int datalen) +{ + char buf[8]; + + if (keylen > 0xffffffff) { errno = ENOMEM; return -1; } + if (datalen > 0xffffffff) { errno = ENOMEM; return -1; } + + uint32_pack(buf,keylen); + uint32_pack(buf + 4,datalen); + if (buffer_putalign(&c->b,buf,8) == -1) return -1; + return 0; +} + +int cdb_make_add(struct cdb_make *c,char *key,unsigned int keylen,char *data,unsigned int datalen) +{ + if (cdb_make_addbegin(c,keylen,datalen) == -1) return -1; + if (buffer_putalign(&c->b,key,keylen) == -1) return -1; + if (buffer_putalign(&c->b,data,datalen) == -1) return -1; + return cdb_make_addend(c,keylen,datalen,cdb_hash(key,keylen)); +} + +int cdb_make_finish(struct cdb_make *c) +{ + char buf[8]; + int i; + uint32 len; + uint32 u; + uint32 memsize; + uint32 count; + uint32 where; + struct cdb_hplist *x; + struct cdb_hp *hp; + + for (i = 0; i < 256; ++i) + c->count[i] = 0; + + for (x = c->head; x; x = x->next) { + i = x->num; + while (i--) + ++c->count[255 & x->hp[i].h]; + } + + memsize = 1; + for (i = 0; i < 256; ++i) { + u = c->count[i] * 2; + if (u > memsize) + memsize = u; + } + + memsize += c->numentries; /* no overflow possible up to now */ + u = (uint32) 0 - (uint32) 1; + u /= sizeof(struct cdb_hp); + if (memsize > u) { errno = ENOMEM; return -1; } + + c->split = (struct cdb_hp *) alloc(memsize * sizeof(struct cdb_hp)); + if (!c->split) return -1; + + c->hash = c->split + c->numentries; + + u = 0; + for (i = 0; i < 256; ++i) { + u += c->count[i]; /* bounded by numentries, so no overflow */ + c->start[i] = u; + } + + for (x = c->head; x; x = x->next) { + i = x->num; + while (i--) + c->split[--c->start[255 & x->hp[i].h]] = x->hp[i]; + } + + for (i = 0; i < 256; ++i) { + count = c->count[i]; + + len = count + count; /* no overflow possible */ + uint32_pack(c->final + 8 * i,c->pos); + uint32_pack(c->final + 8 * i + 4,len); + + for (u = 0; u < len; ++u) + c->hash[u].h = c->hash[u].p = 0; + + hp = c->split + c->start[i]; + for (u = 0; u < count; ++u) { + where = (hp->h >> 8) % len; + while (c->hash[where].p) + if (++where == len) + where = 0; + c->hash[where] = *hp++; + } + + for (u = 0; u < len; ++u) { + uint32_pack(buf,c->hash[u].h); + uint32_pack(buf + 4,c->hash[u].p); + if (buffer_putalign(&c->b,buf,8) == -1) return -1; + if (posplus(c,8) == -1) return -1; + } + } + + if (buffer_flush(&c->b) == -1) return -1; + if (seek_begin(c->fd) == -1) return -1; + return buffer_putflush(&c->b,c->final,sizeof(c->final)); +} diff --git a/src/cdbread.c b/src/cdbread.c new file mode 100644 index 0000000..c8ffa42 --- /dev/null +++ b/src/cdbread.c @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include "error.h" +#include "seek.h" +#include "byte.h" +#include "cdbread.h" + +/** + @file cdbread.c + @author djb + @source ucspi-tcp, fastforward + @brief read entries from a cdb +*/ + +uint32 cdb_unpack(unsigned char *buf) +{ + uint32 num; + num = buf[3]; num <<= 8; + num += buf[2]; num <<= 8; + num += buf[1]; num <<= 8; + num += buf[0]; + return num; +} + +void cdb_free(struct cdb *c) +{ + if (c->map) { + munmap(c->map,c->size); + c->map = 0; + } +} + +void cdb_findstart(struct cdb *c) +{ + c->loop = 0; +} + +void cdb_init(struct cdb *c,int fd) +{ + struct stat st; + char *x; + + cdb_free(c); + cdb_findstart(c); + c->fd = fd; + + if (fstat(fd,&st) == 0) + if (st.st_size <= 0xffffffff) { + x = mmap(0,st.st_size,PROT_READ,MAP_SHARED,fd,0); + if (x + 1) { + c->size = st.st_size; + c->map = x; + } + } +} + +int cdb_read(struct cdb *c,char *buf,unsigned int len,uint32 pos) +{ + if (c->map) { + if ((pos > c->size) || (c->size - pos < len)) goto FORMAT; + byte_copy(buf,len,c->map + pos); + } + else { + if (seek_set(c->fd,pos) == -1) return -1; + while (len > 0) { + int r; + do + r = read(c->fd,buf,len); + while ((r == -1) && (errno == EINTR)); + if (r == -1) return -1; + if (r == 0) goto FORMAT; + buf += r; + len -= r; + } + } + return 0; + + FORMAT: + errno = EPROTO; + return -1; +} + +static int match(struct cdb *c,char *key,unsigned int len,uint32 pos) +{ + char buf[32]; + int n; + + while (len > 0) { + n = sizeof(buf); + if (n > len) n = len; + if (cdb_read(c,buf,n,pos) == -1) return -1; + if (byte_diff(buf,n,key)) return 0; + pos += n; + key += n; + len -= n; + } + return 1; +} + +int cdb_findnext(struct cdb *c,char *key,unsigned int len) +{ + char buf[8]; + uint32 pos; + uint32 u; + + if (!c->loop) { + u = cdb_hash(key,len); + if (cdb_read(c,buf,8,(u << 3) & 2047) == -1) return -1; + uint32_unpack(buf + 4,&c->hslots); + if (!c->hslots) return 0; + uint32_unpack(buf,&c->hpos); + c->khash = u; + u >>= 8; + u %= c->hslots; + u <<= 3; + c->kpos = c->hpos + u; + } + + while (c->loop < c->hslots) { + if (cdb_read(c,buf,8,c->kpos) == -1) return -1; + uint32_unpack(buf + 4,&pos); + if (!pos) return 0; + c->loop += 1; + c->kpos += 8; + if (c->kpos == c->hpos + (c->hslots << 3)) c->kpos = c->hpos; + uint32_unpack(buf,&u); + if (u == c->khash) { + if (cdb_read(c,buf,8,pos) == -1) return -1; + uint32_unpack(buf,&u); + if (u == len) + switch(match(c,key,len,pos + 8)) { + case -1: + return -1; + case 1: + uint32_unpack(buf + 4,&c->dlen); + c->dpos = pos + 8 + len; + return 1; + } + } + } + + return 0; +} + +int cdb_find(struct cdb *c,char *key,unsigned int len) +{ + cdb_findstart(c); + return cdb_findnext(c,key,len); +} + +uint32 cdb_hashadd(uint32 h,unsigned char c) +{ + h += (h << 5); + return h ^ c; +} + +uint32 cdb_hash(char *buf,unsigned int len) +{ + uint32 h; + + h = CDB_HASHSTART; + while (len) { + h = cdb_hashadd(h,*buf++); + --len; + } + return h; +} diff --git a/src/configure b/src/configure new file mode 100755 index 0000000..47b0f08 --- /dev/null +++ b/src/configure @@ -0,0 +1,69 @@ +#!/bin/sh +#******************************************************************************** +# Very simple configure script for qlibs + +. ../conf-build +# Add $HDRDIR as include option to default $CFLAGS +[ "$HDRDIR" ] && CFLAGS="$CFLAGS -I$HDRDIR" + +#******************************************************************************** +# check for system header files +# +# Usually, 'select.h' should (have to) be in this location ... +SELECT_H="/usr/include/sys/select.h" +echo -n "Checking for select.h ..." +if [ -f $SELECT_H ] ; then CFLAGS="$CFLAGS -DHAS_SELECT_H" + else echo -n " not" ; fi +echo " found!" + +# On linux we have flock, other systems have lockf instead +echo -n "Checking for flock/lockf ..." +which flock 2>/dev/null >/dev/null +if [ $? -eq 0 ] ; then CCOPTS="$CFLAGS -DHASFLOCK=1" ; echo -n " flock" + else echo -n " lockf" ; fi +echo " found!" + +# Current systems provide a poll interface ... via +POLL_H="/usr/include/poll.h" +POLL_H1="/usr/include/sys/poll.h" +echo -n "Checking for poll.h ..." +if [ -f $POLL_H -o -f $POLL_H1 ] ; then CFLAGS="$CFLAGS -DHAS_POLL_H" + else echo -n " not" ; fi +echo " found!" + +# Current systems support for 8 and 64 bit integers ... via +STDINT_H="/usr/include/stdint.h" +echo -n "Checking for uint8_t ..." +if [ `grep -c uint_least8_t $STDINT_H` ] ; then CFLAGS="$CFLAGS -DHAS_UINT8_H" + else echo -n " not" ; fi +echo " found!" +echo -n "Checking for uint64_t ..." +if [ `grep -c uint_least64_t $STDINT_H` ] ; then CFLAGS="$CFLAGS -DHAS_UINT64_H" + else echo -n " not" ; fi +echo " found!" + +#******************************************************************************** +# Create compile, load, makelib, sharedlib +echo -n "Checking for compile ... " +CC="cc" +( echo '#!/bin/sh' + echo exec "$CC" "$CFLAGS" -c '${1+"$@"}' ) > compile +chmod 755 compile +echo " created!" + +echo -n "Checking for makelib ... " +( echo '#!/bin/sh' ; + echo "" ; + echo 'main="$1"; shift' ; \ + echo 'rm -f "$main"' ; \ + echo 'ar cr "$main" ${1+"$@"}' ; \ + echo 'ranlib "$main"') > makelib +chmod 755 makelib +echo " created!" + +echo -n "Checking for sharedlib ... " +CC="cc" +( echo '#!/bin/sh' + echo exec "$CC" -shared '${1+"$@"}' ) > sharedlib +chmod 755 sharedlib +echo " created!" diff --git a/src/constmap.c b/src/constmap.c new file mode 100644 index 0000000..ecd5a92 --- /dev/null +++ b/src/constmap.c @@ -0,0 +1,169 @@ +#include "constmap.h" +#include "alloc.h" +#include "case.h" + +static constmap_hash hash(char *s,int len) +{ + unsigned char ch; + constmap_hash h; + h = 5381; + while (len > 0) { + ch = *s++ - 'A'; + if (ch <= 'Z' - 'A') ch += 'a' - 'A'; + h = ((h << 5) + h) ^ ch; + --len; + } + return h; +} + +char *constmap(struct constmap *cm,char *s,int len) +{ + constmap_hash h; + int pos; + h = hash(s,len); + pos = cm->first[h & cm->mask]; + while (pos != -1) { + if (h == cm->hash[pos]) + if (len == cm->inputlen[pos]) + if (!case_diffb(cm->input[pos],len,s)) + return cm->input[pos] + cm->inputlen[pos] + 1; + pos = cm->next[pos]; + } + return 0; +} + +int constmap_init(struct constmap *cm,char *s,int len,int flagcolon) +{ + int i; + int j; + int k; + int pos; + constmap_hash h; + + cm->num = 0; + for (j = 0; j < len; ++j) if (!s[j]) ++cm->num; + + h = 64; + while (h && (h < cm->num)) h += h; + cm->mask = h - 1; + + cm->first = (int *) alloc(sizeof(int) * h); + if (cm->first) { + cm->input = (char **) alloc(sizeof(char *) * cm->num); + if (cm->input) { + cm->inputlen = (int *) alloc(sizeof(int) * cm->num); + if (cm->inputlen) { + cm->hash = (constmap_hash *) alloc(sizeof(constmap_hash) * cm->num); + if (cm->hash) { + cm->next = (int *) alloc(sizeof(int) * cm->num); + if (cm->next) { + for (h = 0; h <= cm->mask; ++h) + cm->first[h] = -1; + pos = 0; + i = 0; + for (j = 0; j < len; ++j) + if (!s[j]) { + k = j - i; + if (flagcolon) { + for (k = i; k < j; ++k) + if (s[k] == ':') break; + if (k >= j) { i = j + 1; continue; } + k -= i; + } + cm->input[pos] = s + i; + cm->inputlen[pos] = k; + h = hash(s + i,k); + cm->hash[pos] = h; + h &= cm->mask; + cm->next[pos] = cm->first[h]; + cm->first[h] = pos; + ++pos; + i = j + 1; + } + return 1; + } + alloc_free(cm->hash); + } + alloc_free(cm->inputlen); + } + alloc_free(cm->input); + } + alloc_free(cm->first); + } + return 0; +} + +int constmap_init_char(struct constmap *cm,char *s,int len,int flagcolon,char flagchar) +{ + int i; + int j; + int k; + int pos; + constmap_hash h; + + if (!flagchar || flagchar == 0 || flagchar == '\0') { + flagchar = ':'; + } + + cm->num = 0; + for (j = 0; j < len; ++j) if (!s[j]) ++cm->num; + + h = 64; + while (h && (h < cm->num)) h += h; + cm->mask = h - 1; + + cm->first = (int *) alloc(sizeof(int) * h); + if (cm->first) { + cm->input = (char **) alloc(sizeof(char *) * cm->num); + if (cm->input) { + cm->inputlen = (int *) alloc(sizeof(int) * cm->num); + if (cm->inputlen) { + cm->hash = (constmap_hash *) alloc(sizeof(constmap_hash) * cm->num); + if (cm->hash) { + cm->next = (int *) alloc(sizeof(int) * cm->num); + if (cm->next) { + for (h = 0; h <= cm->mask; ++h) + cm->first[h] = -1; + pos = 0; + i = 0; + for (j = 0; j < len; ++j) { + if (!s[j]) { + k = j - i; + if (flagcolon) { + for (k = i; k < j; ++k) + if (s[k] == flagchar) break; + if (k >= j) { i = j + 1; continue; } + k -= i; + } + cm->input[pos] = s + i; + cm->inputlen[pos] = k; + h = hash(s + i,k); + cm->hash[pos] = h; + h &= cm->mask; + cm->next[pos] = cm->first[h]; + cm->first[h] = pos; + ++pos; + i = j + 1; + } + } + return 1; + } + alloc_free(cm->hash); + } + alloc_free(cm->inputlen); + } + alloc_free(cm->input); + } + alloc_free(cm->first); + } + return 0; +} + +void constmap_free(struct constmap *cm) +{ + alloc_free(cm->next); + alloc_free(cm->hash); + alloc_free(cm->inputlen); + alloc_free(cm->input); + alloc_free(cm->first); +} diff --git a/src/dnsstub/Makefile b/src/dnsstub/Makefile new file mode 100644 index 0000000..ee7f94d --- /dev/null +++ b/src/dnsstub/Makefile @@ -0,0 +1,23 @@ + +COMPILE=../compile +MAKELIB=../makelib +CCFLAGS=-I../../include + +default: clean check dnsresolv.a + +check: + @[ -f $(COMPILE) ] && [ -f $(MAKELIB) ] || ( cd .. ; ./configure ; ) + +clean: + rm -f `cat TARGETS` + +dnsresolv.a: \ +dns_domain.c dns_dtda.c dns_ip.c dns_ipq.c dns_name.c \ +dns_nd.c dns_packet.c dns_random.c dns_rcip.c dns_rcrw.c dns_resolve.c \ +dns_sortip.c dns_transmit.c dns_txt.c + $(COMPILE) $(CCFLAGS) dns_domain.c dns_dfd.c dns_dtda.c dns_ip.c dns_ipq.c \ + dns_mx.c dns_name.c dns_nd.c dns_packet.c dns_random.c dns_rcip.c \ + dns_rcrw.c dns_resolve.c dns_sortip.c dns_transmit.c dns_txt.c dns_cname.c + $(MAKELIB) dnsresolv.a dns_domain.o dns_dfd.o dns_dtda.o dns_ip.o dns_ipq.o \ + dns_mx.o dns_name.o dns_nd.o dns_packet.o dns_random.o dns_rcip.o \ + dns_rcrw.o dns_resolve.o dns_sortip.o dns_transmit.o dns_txt.o dns_cname.o diff --git a/src/dnsstub/README.md b/src/dnsstub/README.md new file mode 100644 index 0000000..95cd11c --- /dev/null +++ b/src/dnsstub/README.md @@ -0,0 +1,171 @@ +/*! \mainpage + +Stub Resolver +============= + +Simple DJBDNS stub-resolver based on 'djbdns-1.05(IPv6)' allowing for each +calling application individually to include up to 16 DNSCACHEIP(s) +as DNS forwarding/resolving servers to be tried sequentially. + +IP Addresses +------------ + +Here, + - global IPv6, + - IPv6 ULA, and + - IPv6 LLU addresses with a given Interface-Id +can be specified. The IPv4 format could be either a + - legacy dotted-decimal or a + - IPv4-mapped IPv6 address. + +In any case, compactified IPv6 addresses are understood. +IPv4/IPv6 addresses in brackets are understood by dns_ip. + +Resolver Call +------------- + +If $DNSCACHEIP is not provided as environment variable, the stub-resolver +will use the system-wide + - /etc/resolv.conf +file; however now without the capability for IPv6 LLU addresses. +While IPv4-mapped IPv6 addresses are supported here by default as well, +care has to taken not to jeopardize other client's usage. + +Name Qualification +------------------ + +If provided, the stub-resolver uses either a system-wide configuration file + - /etc/dnsrewritefile or assumes this file to available as given in + - $DNSREWRITEFILE +in order to define persistent mapping-rules of local domain names to public +ones (for lookup) or IP addresses (for direct matching). + +Well-known domain names 'localhost', 'ip4-loopback' and 'ip6-loopback' +are handled locally, thus no DNS query is used (RFC 6761). +'localhost' is advertised as '::1' and '::ff:127.0.0.1' in it's native +IPv6 format. It is up to the caller to convert the IPv6-mapped IPv4 +address to the IPv4 format. + +Local domain names can be alternatively specified (per application) using +the environment variable + - $LOCALDOMAIN +to be appended to unqualified hostnames dynamically. This is roughly equivalent +with the 'search' string in /etc/resolv. Several domains names may be +specified within $LOCALDOMAIN separated by blanks. + +See: https://cr.yp.to/djbdns/qualify.html + + +Specific DNS Record type lookup +------------------------------- + +* dns_ip (A, AAAAA) +* dns_name (PTR) +* dns_cname (CNAME) +* dns_txt (TXT) -- now considering several 'labels' +* dns_mx (MX) + + +Internals +--------- + +* UDP message size: +Unlike other implementations, this DNS stub-resolver supports UDP packet +sizes up to 1028 byte without the need for (E)DNS0 packet enhancements. + +* DNS UDP query retrials: +In case the NS is not able to initally reply to the query, +it is retried again at the intervalls {1, 2, 4, 8, 16} secs. + +* DNS name qualification (dns_ip_qualify): +Well-known domain names are qualified locally without invoking a DNS query +while handling IPv4 and IPv6 addresses separately. + +* NS qualification/sorting for NS replies: +NS qualification is not supported (yet), thus we use a randomly sorted +list of NS IP addresses. + +* Query/Reply to/from DNS Cache servers/forwarders: +Neither message (CurveDNS) nor transport layer (TLS) encryption is provided; +the sub-resolver 'trusts' it's upstream caches/forwarders. We recommend to +setup communication on private IPv4/IPv6 addresses; if applicable. + +* DNS TXT Records: +The label substructure is now recognized in the RDATA section; +each label may have the size of 255 byte. +The length information is excluded from the output. +Only printable characters are recognized in the output. + +* Return Codes: +Different from DJB's initial routines, the DNS front-end routines + dns_cname*, dns_ip*, dns_mx*, dns_name*, dns dns_txt* +return now the number of replies received (not bytes!). +Thus, three cases need to be considered: + + - rc < 0: Problem occured (SOFTFAIL, HARDFAIL) + - rc = 0: No answer obtained (but query was successful) = NXDOMAIN + - rc > 0: rc answers received; positive reply + +For return codes < 0, the following conventions have been applied: + + include/dnsresolv.h + +\#define DNS_NXD 0 +\#define DNS_MEM -1 +\#define DNS_ERR -2 /* parsing errors and others */ +\#define DNS_COM -3 /* (socket) communication errors */ +\#define DNS_INT -4 /* internal errors */ +\#define DNS_SOFT -5 /* either -2 or -3 */ +\#define DNS_HARD -6 /* CNAME loop problem */ + +The modification of the return code is typically not problematic, +since mostly just rc = -1 is checked. + +In the future, these return codes are subject of change. +Thus, instead of + + if (dns_XX(...) == -1) + +one shoud use the more general syntax + + if (dns_XX(...) < 0) + +to check for 'negative' results, allowing further actions +and refinements given the calling sequence. + + + +Environment Variables Read +-------------------------- + +$DNSCACHEPIP The upstream resolver's IP[v4|v6] addresses (up to 32). + IPv6 LLU addresses may be suffixed with the interface name. +$DNSREWRITEFILE Alternate location for the system-wide + /etc/dnsrewrite +file +$LOCALDOMAIN Additional local domain name appended to unqualified + hostnames dynamically. + +Sample for the file /etc/dnsrewrite: + +\#annything.local -> me +\-.example.com:me +\# me -> 127.0.0.1 +\=me:127.0.0.1 +\# any.name.a -> any.name.af.mil +\*.a:.af.mil +\# any-name-without-dots -> any-name-without-dots.heaven.af.mil +\?:.heaven.af.mil +\# remove trailing dot +\*.: + +and DJB's explanations are given here: + +Instructions are followed in order, each at most once. There are four types of instructions: + +\=post:new means that the host name post is replaced by new. +\*post:new means that any name of the form prepost is replaced by prenew. +\?post:new means that any name of the form prepost, where pre does not contain dots or brackets, is replaced by prenew. +\-post:new means that any name of the form prepost is replaced by new. + +Erwin Hoffmann, June 2023. diff --git a/src/dnsstub/TARGETS b/src/dnsstub/TARGETS new file mode 100644 index 0000000..62f40be --- /dev/null +++ b/src/dnsstub/TARGETS @@ -0,0 +1,18 @@ +dns_cname.o +dns_dfd.o +dns_domain.o +dns_dtda.o +dns_ip.o +dns_ipq.o +dns_mx.o +dns_name.o +dns_nd.o +dns_packet.o +dns_random.o +dns_rcip.o +dns_rcrw.o +dns_resolve.o +dns_sortip.o +dns_transmit.o +dns_txt.o +dnsresolv.a diff --git a/src/dnsstub/dns_cname.c b/src/dnsstub/dns_cname.c new file mode 100644 index 0000000..408949a --- /dev/null +++ b/src/dnsstub/dns_cname.c @@ -0,0 +1,59 @@ +#include "stralloc.h" +#include "uint_t.h" +#include "byte.h" +#include "ip.h" +#include "case.h" +#include "dnsresolv.h" + +/** + @file dns_cname.c + @author feh + @brief DNS cname lookup +*/ + +static char *q = 0; + +int dns_cname_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[12]; + uint16 numanswers; + uint16 datalen; + int ranswers = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_CNAME)) + if (byte_equal(header + 2,2,DNS_C_IN)) { + if (!dns_packet_getname(buf,len,pos,&q)) return DNS_ERR; + if (dns_domain_todot_cat(out,q) <= 0) return DNS_ERR; + } + pos += datalen; + ++ranswers; + } + + return ranswers; +} + +int dns_cname(stralloc *out,stralloc *fqdn) +{ + int rc; + + if (dns_domain_fromdot(&q,fqdn->s,fqdn->len) <= 0) return DNS_ERR; + if (dns_resolve(q,DNS_T_CNAME) < 0) return DNS_ERR; + if ((rc = dns_cname_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + if (case_equals(out->s,fqdn->s)) rc = -6; // loop DNS_HARD + + return rc; +} diff --git a/src/dnsstub/dns_dfd.c b/src/dnsstub/dns_dfd.c new file mode 100644 index 0000000..756a1f8 --- /dev/null +++ b/src/dnsstub/dns_dfd.c @@ -0,0 +1,76 @@ +#include "error.h" +#include "alloc.h" +#include "byte.h" +#include "dnsresolv.h" + +/** + @file dns_dfd.c + @author djb + @source ucspi-tcp + @brief domain name qualification (domain from dot) +*/ + +int dns_domain_fromdot(char **out,const char *buf,unsigned int n) +{ + char label[63]; + unsigned int labellen = 0; /* <= sizeof label */ + char name[255]; + unsigned int namelen = 0; /* <= sizeof name */ + char ch; + char *x; + + errno = EPROTO; + + for (;;) { + if (!n) break; + ch = *buf++; --n; + if (ch == '.') { + if (labellen) { + if (namelen + labellen + 1 > sizeof(name)) return 0; + name[namelen++] = labellen; + byte_copy(name + namelen,labellen,label); + namelen += labellen; + labellen = 0; + } + continue; + } + if (ch == '\\') { // octal -> decimal + if (!n) break; + ch = *buf++; --n; + if ((ch >= '0') && (ch <= '7')) { + ch -= '0'; + if (n && (*buf >= '0') && (*buf <= '7')) { + ch <<= 3; + ch += *buf - '0'; + ++buf; --n; + if (n && (*buf >= '0') && (*buf <= '7')) { + ch <<= 3; + ch += *buf - '0'; + ++buf; --n; + } + } + } + } + if (labellen >= sizeof(label)) return 0; + label[labellen++] = ch; + } + + if (labellen) { + if (namelen + labellen + 1 > sizeof(name)) return 0; + name[namelen++] = labellen; + byte_copy(name + namelen,labellen,label); + namelen += labellen; + labellen = 0; + } + + if (namelen + 1 > sizeof(name)) return 0; + name[namelen++] = 0; + + x = alloc(namelen); + if (!x) return DNS_MEM; + byte_copy(x,namelen,name); + + if (*out) alloc_free(*out); + *out = x; + return 1; +} diff --git a/src/dnsstub/dns_domain.c b/src/dnsstub/dns_domain.c new file mode 100644 index 0000000..654a827 --- /dev/null +++ b/src/dnsstub/dns_domain.c @@ -0,0 +1,80 @@ +#include "alloc.h" +#include "case.h" +#include "byte.h" +#include "dnsresolv.h" + +/** + @file dns_domain.c + @author djb + @source ucspi-tcp + @brief domain qualification +*/ + +unsigned int dns_domain_length(const char *dn) +{ + const char *x; + unsigned char c; + + x = dn; + while ((c = *x++)) + x += (unsigned int) c; + return x - dn; +} + +void dns_domain_free(char **out) +{ + if (*out) { + alloc_free(*out); + *out = 0; + } +} + +int dns_domain_copy(char **out,const char *in) +{ + unsigned int len; + char *x; + + len = dns_domain_length(in); + x = alloc(len); + if (!x) return 0; + byte_copy(x,len,in); + if (*out) alloc_free(*out); + *out = x; + return 1; +} + +int dns_domain_equal(const char *dn1,const char *dn2) +{ + unsigned int len; + + len = dns_domain_length(dn1); + if (len != dns_domain_length(dn2)) return 0; + + if (case_diffb((char *)dn1,len,(char *)dn2)) return 0; /* safe since 63 < 'A' */ + return 1; +} + +int dns_domain_suffix(const char *big,const char *little) +{ + unsigned char c; + + for (;;) { + if (dns_domain_equal(big,little)) return 1; + c = *big++; + if (!c) return 0; + big += c; + } +} + +unsigned int dns_domain_suffixpos(const char *big,const char *little) +{ + const char *orig = big; + unsigned char c; + + for (;;) { + if (dns_domain_equal(big,little)) return big - orig; + c = *big++; + if (!c) return 0; + big += c; + } +} diff --git a/src/dnsstub/dns_dtda.c b/src/dnsstub/dns_dtda.c new file mode 100644 index 0000000..38358a2 --- /dev/null +++ b/src/dnsstub/dns_dtda.c @@ -0,0 +1,43 @@ +#include "stralloc.h" +#include "dnsresolv.h" + +/** + @file dns_dtda.c + @author djb + @source ucspi-tcp + @brief domain to dot append +*/ + +int dns_domain_todot_cat(stralloc *out,const char *d) +{ + char ch; + char ch2; + unsigned char ch3; + char buf[4]; + + if (!*d) + return stralloc_append(out,"."); + + for (;;) { + ch = *d++; + while (ch--) { + ch2 = *d++; + if ((ch2 >= 'A') && (ch2 <= 'Z')) ch2 += 32; // FQDN -> lowercase + if (((ch2 >= 'a') && (ch2 <= 'z')) || + ((ch2 >= '0') && (ch2 <= '9')) || + (ch2 == '-') || (ch2 == '_')) { + if (!stralloc_append(out,&ch2)) return DNS_MEM; + } + else { // decimal -> octal + ch3 = ch2; + buf[3] = '0' + (ch3 & 7); ch3 >>= 3; + buf[2] = '0' + (ch3 & 7); ch3 >>= 3; + buf[1] = '0' + (ch3 & 7); + buf[0] = '\\'; + if (!stralloc_catb(out,buf,4)) return DNS_MEM; + } + } + if (!*d) return 1; + if (!stralloc_append(out,".")) return DNS_MEM; + } +} diff --git a/src/dnsstub/dns_ip.c b/src/dnsstub/dns_ip.c new file mode 100644 index 0000000..f89728c --- /dev/null +++ b/src/dnsstub/dns_ip.c @@ -0,0 +1,198 @@ +#include "stralloc.h" +#include "uint_t.h" +#include "byte.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_ip.c + @author djb, fefe, feh + @source ucspi-tcp6 + @brief DNS IP query +*/ + +static char *q = 0; + +int dns_ip4_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[12]; + uint16 numanswers; + uint16 datalen; + int ranswers = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_A)) + if (byte_equal(header + 2,2,DNS_C_IN)) + if (datalen == 4) { + if (!dns_packet_copy(buf,len,pos,header,4)) return DNS_ERR; + if (!stralloc_catb(out,header,4)) return DNS_MEM; + } + pos += datalen; + ++ranswers; + } + + dns_sortip4(out->s,out->len); + return ranswers; +} + +int dns_ip4(stralloc *out,stralloc *fqdn) +{ + unsigned int i; + char code = 0; + int dot = 0; + char ch; + char ip[4]; + int r; + int rc = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + if (!stralloc_readyplus(fqdn,1)) return DNS_MEM; + + fqdn->s[fqdn->len] = 0; /* test FQDN string */ + for (i = 1; i < fqdn->len; i++) { + if (fqdn->s[i] >= '_') { code = 127; break; } + if (fqdn->s[i] == '.') dot++; + } + + if (code != 127 && dot == 3) /* if FQDN is just IPv4 */ + if (ip4_scan(fqdn->s,ip) || ip4_scanbracket(fqdn->s,ip)) { + if (!stralloc_copyb(out,ip,4)) return DNS_MEM; + return 1; + } + + code = 0; + for (i = 0; i <= fqdn->len; ++i) { + if (i < fqdn->len) + ch = fqdn->s[i]; + else + ch = '.'; + + if ((ch == '[') || (ch == ']')) continue; + if (ch == '.') { + if (!stralloc_append(out,&code)) return DNS_MEM; + code = 0; + continue; + } + if ((ch >= '0') && (ch <= '9')) { + code *= 10; + code += ch - '0'; + continue; + } + + if (dns_domain_fromdot(&q,fqdn->s,fqdn->len) <= 0) return DNS_ERR; // fdqn -> A query -> response + if (dns_resolve(q,DNS_T_A) >= 0) { + if ((r = dns_ip4_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + rc += r; + } + + return rc; + } + + out->len &= ~3; + return 0; +} + +int dns_ip6_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[16]; + uint16 numanswers; + uint16 datalen; + int ranswers = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_AAAA)) { + if (byte_equal(header + 2,2,DNS_C_IN)) + if (datalen == 16) { + if (!dns_packet_copy(buf,len,pos,header,16)) return DNS_ERR; + if (!stralloc_catb(out,header,16)) return DNS_MEM; + } + } else if (byte_equal(header,2,DNS_T_A)) + if (byte_equal(header + 2,2,DNS_C_IN)) + if (datalen == 4) { + byte_copy(header,12,V4mappedprefix); + if (!dns_packet_copy(buf,len,pos,header + 12,4)) return DNS_ERR; + if (!stralloc_catb(out,header,16)) return DNS_MEM; + } + pos += datalen; + ++ranswers; + } + + dns_sortip6(out->s,out->len); + return ranswers; +} + +int dns_ip6(stralloc *out,stralloc *fqdn) +{ + unsigned int i; + char code; + char ch; + char ip[16]; + int r; + int rc = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + if (!stralloc_readyplus(fqdn,1)) return DNS_MEM; + + fqdn->s[fqdn->len] = 0; /* if FQDN is just IPv6 */ + if (ip6_scan(fqdn->s,ip) || ip6_scanbracket(fqdn->s,ip)) { + if (!stralloc_copyb(out,ip,16)) return DNS_MEM; + return 1; + } + + code = 0; + for (i = 0; i <= fqdn->len; ++i) { + if (i < fqdn->len) + ch = fqdn->s[i]; + else + ch = '.'; + + if ((ch == '[') || (ch == ']')) continue; + if (ch == '.') { + if (!stralloc_append(out,&code)) return DNS_MEM; + code = 0; + continue; + } + if ((ch >= '0') && (ch <= '9')) { + code *= 10; + code += ch - '0'; + continue; + } + + if (dns_domain_fromdot(&q,fqdn->s,fqdn->len) <= 0) return DNS_ERR; // fqdn -> AAAA query -> response + if (dns_resolve(q,DNS_T_AAAA) >= 0) { + if ((r = dns_ip6_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + rc += r; + } + + return rc; + } + + out->len &= ~3; + return 0; +} diff --git a/src/dnsstub/dns_ipq.c b/src/dnsstub/dns_ipq.c new file mode 100644 index 0000000..26c3818 --- /dev/null +++ b/src/dnsstub/dns_ipq.c @@ -0,0 +1,236 @@ +#include "case.h" +#include "byte.h" +#include "str.h" +#include "stralloc.h" +#include "dnsresolv.h" +#include "socket_if.h" +#include "ip.h" + +/** + @file dns_ipq.c + @author djb, feh + @source ucspi-tcp + @brief DNS hostname qualification for ipv4 and ipv6 +*/ + +/** + @fn int doit -> @return number of added chars to name +*/ +static int doit(stralloc *work,const char *rule) +{ + char ch; + unsigned int colon; + unsigned int prefixlen; + + ch = *rule++; + if ((ch != '?') && (ch != '=') && (ch != '*') && (ch != '-')) return 1; + colon = str_chr((char *)rule,':'); + if (!rule[colon]) return 1; + + if (work->len < colon) return 1; + prefixlen = work->len - colon; + if ((ch == '=') && prefixlen) return 1; + if (case_diffb((char *)rule,colon,work->s + prefixlen)) return 1; + if (ch == '?') { + if (byte_chr(work->s,prefixlen,'.') < prefixlen) return 1; + if (byte_chr(work->s,prefixlen,'[') < prefixlen) return 1; + if (byte_chr(work->s,prefixlen,']') < prefixlen) return 1; + } + + work->len = prefixlen; + if (ch == '-') work->len = 0; + return stralloc_cats(work,rule + colon + 1); +} + +/** @fn int dns_ip4_qualify_rules -> @return number of IPv4 addresss with rules */ + +int dns_ip4_qualify_rules(stralloc *ipout,stralloc *fqdn,const stralloc *in,const stralloc *rules) +{ + unsigned int i; + unsigned int j; + unsigned int plus; + unsigned int fqdnlen; + int rc = 0; + + if (!stralloc_copy(fqdn,(stralloc *)in)) return DNS_MEM; + + for (j = i = 0; j < rules->len; ++j) + if (!rules->s[j]) { + if (!doit(fqdn,rules->s + i)) return DNS_INT; + i = j + 1; + } + + fqdnlen = fqdn->len; + plus = byte_chr(fqdn->s,fqdnlen,'+'); + if (plus >= fqdnlen) + return dns_ip4(ipout,fqdn); + + i = plus + 1; + for (;;) { + j = byte_chr(fqdn->s + i,fqdnlen - i,'+'); + byte_copy(fqdn->s + plus,j,fqdn->s + i); + fqdn->len = plus + j; + if (rc += dns_ip4(ipout,fqdn) < 0) return DNS_ERR; + i += j; + if (i >= fqdnlen) return rc; + ++i; + } + return 0; +} + +/** @fn int dns_ip4_qualify -> @return number of IPv4 addresss qualified */ + +int dns_ip4_qualify(stralloc *ipout,stralloc *fqdn,const stralloc *in) +{ + int r; + static stralloc rules; + + if ((r = dns_ip_qualify_localhost(ipout,fqdn,in)) > 0 ) return r; + if (dns_resolvconfrewrite(&rules) < 0) return DNS_INT; + return dns_ip4_qualify_rules(ipout,fqdn,in,&rules); +} + +/** @fn int dns_ip4_qualify_rules -> @return number of IPv6 addresss with rules */ + +int dns_ip6_qualify_rules(stralloc *ipout,stralloc *fqdn,const stralloc *in,const stralloc *rules) +{ + unsigned int i; + unsigned int j; + unsigned int plus; + unsigned int fqdnlen; + int rc = 0; + + if (!stralloc_copy(fqdn,(stralloc *)in)) return DNS_MEM; + + for (j = i = 0; j < rules->len; ++j) + if (!rules->s[j]) { + if (!doit(fqdn,rules->s + i)) return DNS_INT; + i = j + 1; + } + + fqdnlen = fqdn->len; + plus = byte_chr(fqdn->s,fqdnlen,'+'); + if (plus >= fqdnlen) + return dns_ip6(ipout,fqdn); + + i = plus + 1; + for (;;) { + j = byte_chr(fqdn->s + i,fqdnlen - i,'+'); + byte_copy(fqdn->s + plus,j,fqdn->s + i); + fqdn->len = plus + j; + if ((rc += dns_ip6(ipout,fqdn)) < 0) return DNS_ERR; + i += j; + if (i >= fqdnlen) return rc; + ++i; + } + return 0; +} + +/** @fn int dns_ip6_qualify -> @return number of IPv6 addresss qualified */ + +int dns_ip6_qualify(stralloc *ipout,stralloc *fqdn,const stralloc *in) +{ + int r; + static stralloc rules; + + if ((r = dns_ip_qualify_localhost(ipout,fqdn,in)) > 0) return r; + if (dns_resolvconfrewrite(&rules) < 0) return DNS_INT; + return dns_ip6_qualify_rules(ipout,fqdn,in,&rules); +} + +/** @fn int dns_ip_qualify_rules -> @return number of IPv6+IPv4 addresss with rules */ + +int dns_ip_qualify_rules(stralloc *ipout,stralloc *fqdn,const stralloc *in,const stralloc *rules) +{ + unsigned int i; + unsigned int j; + unsigned int k; + unsigned int plus; + unsigned int fqdnlen; + stralloc tmp = {0}; + int rc = 0; + + if (!stralloc_copy(fqdn,(stralloc *)in)) return DNS_MEM; + if (!stralloc_copys(ipout,"")) return DNS_MEM; + + for (j = i = 0; j < rules->len; ++j) + if (!rules->s[j]) { + if (!doit(fqdn,rules->s + i)) return DNS_INT; + i = j + 1; + } + + fqdnlen = fqdn->len; + plus = byte_chr(fqdn->s,fqdnlen,'+'); + if (plus >= fqdnlen) { + rc = dns_ip6(ipout,fqdn); + if (dns_ip4(&tmp,fqdn) > 0) { + for (k = 0; k < tmp.len; k += 4) { + if (!stralloc_catb(ipout,(const char *) V4mappedprefix,12)) return DNS_MEM; + if (!stralloc_catb(ipout,tmp.s + k,4)) return DNS_MEM; + rc++; + } + } + return rc; + } + + i = plus + 1; + for (;;) { + j = byte_chr(fqdn->s + i,fqdnlen - i,'+'); + byte_copy(fqdn->s + plus,j,fqdn->s + i); + fqdn->len = plus + j; + if (!stralloc_copys(ipout,"")) return DNS_MEM; + rc = dns_ip6(&tmp,fqdn); + if (rc) if (!stralloc_cat(ipout,&tmp)) return DNS_MEM; + if (dns_ip4(&tmp,fqdn) > 0) { + for (k = 0; k < tmp.len; k += 4) { + if (!stralloc_catb(ipout,(const char *) V4mappedprefix,12)) return DNS_MEM; + if (!stralloc_catb(ipout,tmp.s + k,4)) return DNS_MEM; + rc++; + } + } + + if (rc < 0) return DNS_ERR; + i += j; + if (i >= fqdnlen) return rc; + ++i; + } + return 0; +} + +/** @fn int dns_ip_qualify_localhost -> @return number of IP addresss */ + +int dns_ip_qualify_localhost(stralloc *ipout,stralloc *fqdn,const stralloc *in) +{ + if (!stralloc_copys(ipout,"")) return DNS_MEM; + if (!stralloc_copys(fqdn,"")) return DNS_MEM; + ipout->len = 0; + + if (byte_equal(in->s,9,LOCALHOST)) { + if (!stralloc_copyb(ipout,(const char *) V6loopback,16)) return DNS_MEM; + if (!stralloc_catb(ipout,(const char *) V46loopback,16)) return DNS_MEM; + if (!stralloc_copys(fqdn,"localhost.localhost.")) return DNS_MEM; + } + if (byte_equal(in->s,13,IP4_LOOPBACK)) { + if (!stralloc_copyb(ipout,(const char *) V46loopback,16)) return DNS_MEM; + if (!stralloc_copys(fqdn,"ip4-loopback.localhost.")) return DNS_MEM; + } + if (byte_equal(in->s,13,IP6_LOOPBACK)) { + if (!stralloc_copyb(ipout,(const char *) V6loopback,16)) return DNS_MEM; + if (!stralloc_copys(fqdn,"ip6-loopback.localhost.")) return DNS_MEM; + } +// if (!stralloc_0(fqdn)) return DNS_MEM; // don't do it + + return ipout->len ? ipout->len % 15 : 0; +} + +/** @fn int dns_ip_qualify -> @return number of IP addresss */ + +int dns_ip_qualify(stralloc *ipout,stralloc *fqdn,const stralloc *in) +{ + int r; + static stralloc rules; + + if ((r = dns_ip_qualify_localhost(ipout,fqdn,in)) > 0 ) return r; + if (dns_resolvconfrewrite(&rules) < 0) return DNS_INT; + return dns_ip_qualify_rules(ipout,fqdn,in,&rules); +} diff --git a/src/dnsstub/dns_mx.c b/src/dnsstub/dns_mx.c new file mode 100644 index 0000000..c0845ef --- /dev/null +++ b/src/dnsstub/dns_mx.c @@ -0,0 +1,63 @@ +#include "stralloc.h" +#include "byte.h" +#include "uint_t.h" +#include "dnsresolv.h" + +/** + @file dns_mx.c + @author djb + @source qmail + @brief dns MX query + @param (on output) stralloc out +*/ + +static char *q = 0; + +int dns_mx_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[12]; + char pref[2]; + uint16 numanswers; + uint16 datalen; + int ranswers = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_MX)) + if (byte_equal(header + 2,2,DNS_C_IN)) { + if (!dns_packet_copy(buf,len,pos,pref,2)) return DNS_ERR; + if (!dns_packet_getname(buf,len,pos + 2,&q)) return DNS_ERR; + if (!stralloc_catb(out,pref,2)) return DNS_MEM; + if (dns_domain_todot_cat(out,q) <= 0) return DNS_ERR; + if (!stralloc_0(out)) return DNS_MEM; + } + pos += datalen; + ++ranswers; + } + + return ranswers; +} + +int dns_mx(stralloc *out,const stralloc *fqdn) +{ + int rc = 0; + + if (dns_domain_fromdot(&q,fqdn->s,fqdn->len) <= 0) return DNS_ERR; + if (dns_resolve(q,DNS_T_MX) >= 0) { + if ((rc = dns_mx_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + } + + return rc; +} diff --git a/src/dnsstub/dns_name.c b/src/dnsstub/dns_name.c new file mode 100644 index 0000000..0723a8f --- /dev/null +++ b/src/dnsstub/dns_name.c @@ -0,0 +1,80 @@ +#include "stralloc.h" +#include "uint_t.h" +#include "byte.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_name.c + @author djb, fefe, feh + @source ucspi-tcp + @brief DNS name query (ptr) +*/ + +static char *q = 0; + +int dns_name_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[12]; + uint16 numanswers; + uint16 datalen; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_PTR)) + if (byte_equal(header + 2,2,DNS_C_IN)) { + if (!dns_packet_getname(buf,len,pos,&q)) return DNS_ERR; + if (dns_domain_todot_cat(out,q) <= 0) return DNS_ERR; + return 1; + } + pos += datalen; + } + + return 0; +} + +int dns_name4(stralloc *out,const char ip[4]) +{ + int rc; + char name[DNS_NAME4_DOMAIN]; + + dns_name4_domain(name,ip); + if (dns_resolve(name,DNS_T_PTR) < 0) return DNS_ERR; + if ((rc = dns_name_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + + return rc; +} + +int dns_name6(stralloc *out,const char ip[16]) +{ + int rc; + char name[DNS_NAME6_DOMAIN]; + + dns_name6_domain(name,ip); + if (dns_resolve(name,DNS_T_PTR) < 0) return DNS_ERR; + if ((rc = dns_name_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + + return rc; +} + +int dns_name(stralloc *out,const char ip[16]) +{ + if (ip6_isv4mapped(ip)) + return dns_name4(out,ip+12); + else + return dns_name6(out,ip); +} diff --git a/src/dnsstub/dns_nd.c b/src/dnsstub/dns_nd.c new file mode 100644 index 0000000..6ce8ed9 --- /dev/null +++ b/src/dnsstub/dns_nd.c @@ -0,0 +1,48 @@ +#include "byte.h" +#include "fmt.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_nd.c + @autor djb, fefe + @source ucspi-tcp + @brief DNS domain name for ip (wire format) +*/ + +int dns_name4_domain(char name[DNS_NAME4_DOMAIN],const char ip[4]) +{ + unsigned int namelen; + unsigned int i; + + namelen = 0; + i = fmt_ulong(name + namelen + 1,(unsigned long) (unsigned char) ip[3]); + name[namelen++] = i; + namelen += i; + i = fmt_ulong(name + namelen + 1,(unsigned long) (unsigned char) ip[2]); + name[namelen++] = i; + namelen += i; + i = fmt_ulong(name + namelen + 1,(unsigned long) (unsigned char) ip[1]); + name[namelen++] = i; + namelen += i; + i = fmt_ulong(name + namelen + 1,(unsigned long) (unsigned char) ip[0]); + name[namelen++] = i; + namelen += i; + byte_copy(name + namelen,14,"\7in-addr\4arpa\0"); + return namelen+14; +} + +int dns_name6_domain(char name[DNS_NAME6_DOMAIN],const char ip[16]) +{ + unsigned int j; + + for (j = 0; j < 16; j++) { + name[j * 4] = 1; + name[j * 4 + 1] = tohex(ip[15 - j] & 15); + name[j * 4 + 2] = 1; + name[j * 4 + 3] = tohex((unsigned char)ip[15 - j] >> 4); + } + byte_copy(name + 4 * 16,10,"\3ip6\4arpa\0"); + return 4 * 16 + 10; +} + diff --git a/src/dnsstub/dns_packet.c b/src/dnsstub/dns_packet.c new file mode 100644 index 0000000..ce322ea --- /dev/null +++ b/src/dnsstub/dns_packet.c @@ -0,0 +1,85 @@ +#include "error.h" +#include "dnsresolv.h" + +/** + @file dns_packet.c + @author djb + @source ucspi-tcp + @brief DNS low level packet routine + @brief DNS should have used LZ77 instead of its own sophomoric compression algorithm. +*/ + +unsigned int dns_packet_copy(const char *buf,unsigned int len,unsigned int pos,char *out,unsigned int outlen) +{ + while (outlen) { + if (pos >= len) { errno = EPROTO; return 0; } + *out = buf[pos++]; + ++out; --outlen; + } + return pos; +} + +unsigned int dns_packet_skipname(const char *buf,unsigned int len,unsigned int pos) +{ + unsigned char ch; + + for (;;) { + if (pos >= len) break; + ch = buf[pos++]; + if (ch >= 192) return pos + 1; + if (ch >= 64) break; + if (!ch) return pos; + pos += ch; + } + + errno = EPROTO; + return 0; +} + +unsigned int dns_packet_getname(const char *buf,unsigned int len,unsigned int pos,char **d) +{ + unsigned int loop = 0; + unsigned int state = 0; + unsigned int firstcompress = 0; + unsigned int where; + unsigned char ch; + char name[255]; + unsigned int namelen = 0; + + for (;;) { + if (pos >= len) goto PROTO; + ch = buf[pos++]; + if (++loop >= 1000) goto PROTO; + + if (state) { + if (namelen + 1 > sizeof(name)) goto PROTO; + name[namelen++] = ch; + --state; + } else { + while (ch >= 192) { + where = ch; where -= 192; where <<= 8; + if (pos >= len) goto PROTO; + ch = buf[pos++]; + if (!firstcompress) firstcompress = pos; + pos = where + ch; + if (pos >= len) goto PROTO; + ch = buf[pos++]; + if (++loop >= 1000) goto PROTO; + } + if (ch >= 64) goto PROTO; + if (namelen + 1 > sizeof(name)) goto PROTO; + name[namelen++] = ch; + if (!ch) break; + state = ch; + } + } + + if (!dns_domain_copy(d,name)) return 0; + + if (firstcompress) return firstcompress; + return pos; + + PROTO: + errno = EPROTO; + return 0; +} diff --git a/src/dnsstub/dns_random.c b/src/dnsstub/dns_random.c new file mode 100644 index 0000000..200cd6c --- /dev/null +++ b/src/dnsstub/dns_random.c @@ -0,0 +1,70 @@ +#include +#include "taia.h" +#include "uint_t.h" +#include "dnsresolv.h" + +/** + @file dns_random.c + @author djb + @source ucspi-tcp + @brief random use of DNS resolvers given their IP +*/ + +static uint32 seed[32]; +static uint32 in[12]; +static uint32 out[8]; +static int outleft = 0; + +#define ROTATE(x,b) (((x) << (b)) | ((x) >> (32 - (b)))) +#define MUSH(i,b) x = t[i] += (((x ^ seed[i]) + sum) ^ ROTATE(x,b)); + +static void surf(void) +{ + uint32 t[12]; uint32 x; uint32 sum = 0; + int r; int i; int loop; + + for (i = 0; i < 12; ++i) t[i] = in[i] ^ seed[12 + i]; + for (i = 0; i < 8; ++i) out[i] = seed[24 + i]; + x = t[11]; + for (loop = 0; loop < 2; ++loop) { + for (r = 0; r < 16; ++r) { + sum += 0x9e3779b9; + MUSH(0,5) MUSH(1,7) MUSH(2,9) MUSH(3,13) + MUSH(4,5) MUSH(5,7) MUSH(6,9) MUSH(7,13) + MUSH(8,5) MUSH(9,7) MUSH(10,9) MUSH(11,13) + } + for (i = 0; i < 8; ++i) out[i] ^= t[i + 4]; + } +} + +void dns_random_init(const char data[128]) +{ + int i; + struct taia t; + char tpack[16]; + + for (i = 0; i < 32; ++i) + uint32_unpack((char *)data + 4 * i,seed + i); + + taia_now(&t); + taia_pack(tpack,&t); + for (i = 0; i < 4; ++i) + uint32_unpack(tpack + 4 * i,in + 4 + i); + + in[8] = getpid(); + in[9] = getppid(); + /* more space in 10 and 11, but this is probably enough */ +} + +unsigned int dns_random(unsigned int n) +{ + if (!n) return 0; + + if (!outleft) { + if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3]; + surf(); + outleft = 8; + } + + return out[--outleft] % n; +} diff --git a/src/dnsstub/dns_rcip.c b/src/dnsstub/dns_rcip.c new file mode 100644 index 0000000..93b0daa --- /dev/null +++ b/src/dnsstub/dns_rcip.c @@ -0,0 +1,114 @@ +#include "taia.h" +#include "readclose.h" +#include "byte.h" +#include "ip.h" +#include "env.h" +#include "dnsresolv.h" +#include "socket_if.h" + +/** + @file dns_rcip.c + @author djb, fefe, feh + @source ucspi-tcp + @brief DNS receive for query +*/ + +static stralloc data = {0}; +static stralloc ifname = {0}; + +static int init(char ip[QUERY_MAXIPLEN],uint32 sid[QUERY_MAXNS]) +{ + int i; + int j; + int k = 0; + int iplen = 0; + char *x; + char ip4[4]; + +/* Read (compactified) IPv4|v6 addresses of resolvers + Store them in array IP with fixed length : + ip(64) -> 16 IPv4 addresses (not used anymore) + ip(512) -> 16*2 IPv6 addresses (we use IPv4 mapped IPv6 addresses) + sid(32) -> the scope for the respective IPv6 or 0 +*/ + for (i = 0; i < QUERY_MAXNS; ++i) sid[i] = 0; + + x = env_get("DNSCACHEIP"); + if (x) + while (iplen <= 240 && *x != '\0') { + if (*x == ' ') + ++x; + else + if ((i = ip6_ifscan(x,ip + iplen,&ifname))) { + if (ifname.len > 2) sid[k] = socket_getifidx(ifname.s); + iplen += 16; k++; + if (*(x += i) == '\0') break; + } + } + + if (!iplen) { + i = openreadclose("/etc/resolv.conf",&data,64); + if (i == -1) return DNS_INT; + if (i) { + if (!stralloc_append(&data,"\n")) return DNS_MEM; + i = 0; + for (j = 0; j < data.len; ++j) + if (data.s[j] == '\n') { + if (byte_equal("nameserver ",11,data.s + i) || byte_equal("nameserver\t",11,data.s + i)) { + i += 10; + while ((data.s[i] == ' ') || (data.s[i] == '\t')) + i++; + if (iplen <= 240) { + data.s[j] = '\0'; /* ip6_ifscan needs terminated string on input */ + if (ip4_scan(data.s + i,ip4)) { + if (byte_equal(ip4,4,"\0\0\0\0")) + byte_copy(ip4,4,"\177\0\0\1"); + byte_copy(ip + iplen,12,V4mappedprefix); + byte_copy(ip + iplen + 12,4,ip4); + sid[k] = 0; iplen += 16; k++; + } else if (ip6_ifscan(data.s + i,ip + iplen,&ifname)) { + if (ifname.len > 2) sid[k] = socket_getifidx(ifname.s); + iplen += 16; k++; + } + } + } + i = j + 1; + } + } + } + + if (!iplen) { + byte_copy(ip,16,"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1"); + iplen = 16; + } + byte_zero(ip + iplen,QUERY_MAXIPLEN - iplen); + return 0; +} + +static int ok = 0; +static unsigned int uses; +static struct taia deadline; +static char ip[QUERY_MAXIPLEN]; /* defined if ok */ +static uint32 scopes[QUERY_MAXNS]; + +int dns_resolvconfip(char s[QUERY_MAXIPLEN],uint32 scope[QUERY_MAXNS]) +{ + struct taia now; + + taia_now(&now); + if (taia_less(&deadline,&now)) ok = 0; + if (!uses) ok = 0; + + if (!ok) { + if (init(ip,scopes) < 0) return DNS_INT; + taia_uint(&deadline,600); + taia_add(&deadline,&now,&deadline); + uses = 10000; + ok = 1; + } + + --uses; + byte_copy(s,QUERY_MAXIPLEN,ip); + byte_copy(scope,128,scopes); + return 0; +} diff --git a/src/dnsstub/dns_rcrw.c b/src/dnsstub/dns_rcrw.c new file mode 100644 index 0000000..4633fed --- /dev/null +++ b/src/dnsstub/dns_rcrw.c @@ -0,0 +1,141 @@ +#include +#include "taia.h" +#include "env.h" +#include "byte.h" +#include "str.h" +#include "readclose.h" +#include "dnsresolv.h" + +/** + @file dns_rcrw.c + @author djb + @source ucspi-tcp + @brief DNS receive rewrite +*/ + +static stralloc data = {0}; + +static int init(stralloc *rules) +{ + char host[256]; + const char *x; + int i; + int j; + int k; + + if (!stralloc_copys(rules,"")) return DNS_MEM; + + x = env_get("DNSREWRITEFILE"); + if (!x) x = "/etc/dnsrewrite"; + + i = openreadclose(x,&data,64); + if (i == -1) return DNS_INT; + + if (i) { + if (!stralloc_append(&data,"\n")) return DNS_MEM; + i = 0; + for (j = 0; j < data.len; ++j) + if (data.s[j] == '\n') { + if (!stralloc_catb(rules,data.s + i,j - i)) return DNS_MEM; + while (rules->len) { + if (rules->s[rules->len - 1] != ' ') + if (rules->s[rules->len - 1] != '\t') + if (rules->s[rules->len - 1] != '\r') + break; + --rules->len; + } + if (!stralloc_0(rules)) return DNS_MEM; + i = j + 1; + } + return 0; + } + + x = env_get("LOCALDOMAIN"); + if (x) { + if (!stralloc_copys(&data,x)) return DNS_MEM; + if (!stralloc_append(&data," ")) return DNS_MEM; + if (!stralloc_copys(rules,"?:")) return DNS_MEM; + i = 0; + for (j = 0; j < data.len; ++j) + if (data.s[j] == ' ') { + if (!stralloc_cats(rules,"+.")) return DNS_MEM; + if (!stralloc_catb(rules,data.s + i,j - i)) return DNS_MEM; + i = j + 1; + } + if (!stralloc_0(rules)) return DNS_MEM; + if (!stralloc_cats(rules,"*.:")) return DNS_MEM; + if (!stralloc_0(rules)) return DNS_MEM; + return 0; + } + + i = openreadclose("/etc/resolv.conf",&data,64); + if (i == -1) return DNS_INT; + + if (i) { + if (!stralloc_append(&data,"\n")) return DNS_MEM; + i = 0; + for (j = 0; j < data.len; ++j) + if (data.s[j] == '\n') { + if (byte_equal("search ",7,data.s + i) || + byte_equal("search\t",7,data.s + i) || + byte_equal("domain ",7,data.s + i) || + byte_equal("domain\t",7,data.s + i)) { + if (!stralloc_copys(rules,"?:")) return DNS_MEM; + i += 7; + while (i < j) { + k = byte_chr(data.s + i,j - i,' '); + k = byte_chr(data.s + i,k,'\t'); + if (!k) { ++i; continue; } + if (!stralloc_cats(rules,"+.")) return DNS_MEM; + if (!stralloc_catb(rules,data.s + i,k)) return DNS_MEM; + i += k; + } + if (!stralloc_0(rules)) return DNS_MEM; + if (!stralloc_cats(rules,"*.:")) return DNS_MEM; + if (!stralloc_0(rules)) return DNS_MEM; + return 0; + } + i = j + 1; + } + } + + host[0] = 0; + if (gethostname(host,sizeof(host)) == -1) return DNS_ERR; + host[(sizeof(host)) - 1] = 0; + i = str_chr(host,'.'); + if (host[i]) { + if (!stralloc_copys(rules,"?:")) return DNS_MEM; + if (!stralloc_cats(rules,host + i)) return DNS_MEM; + if (!stralloc_0(rules)) return DNS_MEM; + } + if (!stralloc_cats(rules,"*.:")) return DNS_MEM; + if (!stralloc_0(rules)) return DNS_MEM; + + return 0; +} + +static int ok = 0; +static unsigned int uses; +static struct taia deadline; +static stralloc rules = {0}; /* defined if ok */ + +int dns_resolvconfrewrite(stralloc *out) +{ + struct taia now; + + taia_now(&now); + if (taia_less(&deadline,&now)) ok = 0; + if (!uses) ok = 0; + + if (!ok) { + if (init(&rules) < 0) return DNS_INT; + taia_uint(&deadline,600); + taia_add(&deadline,&now,&deadline); + uses = 10000; + ok = 1; + } + + --uses; + if (!stralloc_copy(out,&rules)) return DNS_MEM; + return 0; +} diff --git a/src/dnsstub/dns_resolve.c b/src/dnsstub/dns_resolve.c new file mode 100644 index 0000000..bcc4308 --- /dev/null +++ b/src/dnsstub/dns_resolve.c @@ -0,0 +1,39 @@ +#include "iopause.h" +#include "taia.h" +#include "byte.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_resolve.c + @author djb, fefe, feh + @source ucspi-tcp + @brief high-level DNS resolve function +*/ + +struct dns_transmit dns_resolve_tx = {0}; + +int dns_resolve(const char *q,const char qtype[2]) +{ + struct taia stamp; + struct taia deadline; + char servers[QUERY_MAXIPLEN]; + uint32 scopes[QUERY_MAXNS]; + iopause_fd x[1]; + int r; + + if (dns_resolvconfip(servers,scopes) < 0) return DNS_INT; + + if (dns_transmit_start6(&dns_resolve_tx,servers,1,q,qtype,(const char *)V6localnet,scopes) < 0) return DNS_COM; + + for (;;) { + taia_now(&stamp); + taia_uint(&deadline,120); + taia_add(&deadline,&deadline,&stamp); + dns_transmit_io(&dns_resolve_tx,x,&deadline); + iopause(x,1,&deadline,&stamp); + r = dns_transmit_get(&dns_resolve_tx,x,&stamp); + if (r < 0) return DNS_COM; + if (r == 1) return 0; + } +} diff --git a/src/dnsstub/dns_sortip.c b/src/dnsstub/dns_sortip.c new file mode 100644 index 0000000..56742e0 --- /dev/null +++ b/src/dnsstub/dns_sortip.c @@ -0,0 +1,45 @@ +#include "byte.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_sortip.c + @authors djb, fefe, feh + @source ucspi-tcp6 + @brief random sort of DNS servers per IP +*/ + +/* XXX: sort servers by configurable notion of closeness? */ +/* XXX: pay attention to competence of each server? */ +/* XXX: pay attention to qualification (DNSSec, DNSCurve) of each server? */ +/* YYY: we use a randomly sorted list of NS; not depending on answer */ + +void dns_sortip4(char *s,unsigned int n) +{ + unsigned int i; + char tmp[4]; + + n >>= 2; /* 4 byte per IPv4 address */ + while (n > 1) { + i = dns_random(n); + --n; + byte_copy(tmp,4,s + (i << 2)); + byte_copy(s + (i << 2),4,s + (n << 2)); + byte_copy(s + (n << 2),4,tmp); + } +} + +void dns_sortip6(char *s,unsigned int n) +{ + unsigned int i; + char tmp[16]; + + n >>= 4; /* 16 byte per IPv4 address */ + while (n > 1) { + i = dns_random(n); + --n; + byte_copy(tmp,16,s + (i << 4)); + byte_copy(s + (i << 4),16,s + (n << 4)); + byte_copy(s + (n << 4),16,tmp); + } +} diff --git a/src/dnsstub/dns_transmit.c b/src/dnsstub/dns_transmit.c new file mode 100644 index 0000000..2513565 --- /dev/null +++ b/src/dnsstub/dns_transmit.c @@ -0,0 +1,436 @@ +#include +#include +#include +#include "socket_if.h" +#include "alloc.h" +#include "error.h" +#include "byte.h" +#include "uint_t.h" +#include "ip.h" +#include "dnsresolv.h" + +/** + @file dns_transmit.c + @authors djb, fefe, feh + @source qlibs + @brief DNS query function + @brief scope_ids[32] -> 32 LLU root servers supported +*/ + +#define DNSPORT 53 + +uint32 scope_ids[QUERY_MAXNS]; + +static const int timeouts[5] = { 1, 2, 4, 8, 16 }; /* quadratic, not exponentially */ + +int getscopeid(const struct dns_transmit *d,const char *ip) +{ + int i; + + if (byte_diff(ip,2,V6linklocal)) return 0; + for (i = 0; i < QUERY_MAXNS; ++i) + if (byte_equal(d->servers + 16 * i,16,ip)) + return scope_ids[i]; + + return 0; +} + +int serverwantstcp(const char *buf,unsigned int len) +{ + char out[12]; + + if (!dns_packet_copy(buf,len,0,out,12)) return 1; + if (out[2] & 2) return 1; + + return 0; +} + +int serverfailed(const char *buf,unsigned int len) +{ + char out[12]; + unsigned int rcode; + + if (!dns_packet_copy(buf,len,0,out,12)) return 1; + rcode = out[3]; + rcode &= 15; + if (rcode && (rcode != 3)) { errno = EAGAIN; return 1; } + + return 0; +} + +int irrelevant(const struct dns_transmit *d,const char *buf,unsigned int len) +{ + char out[12]; + char *dn; + unsigned int pos; + + pos = dns_packet_copy(buf,len,0,out,12); if (!pos) return 1; + if (byte_diff(out,2,d->query + 2)) return 1; + if (out[4] != 0) return 1; + if (out[5] != 1) return 1; + + dn = 0; + pos = dns_packet_getname(buf,len,pos,&dn); if (!pos) return 1; + if (!dns_domain_equal(dn,d->query + 14)) { alloc_free(dn); return 1; } + alloc_free(dn); + + pos = dns_packet_copy(buf,len,pos,out,4); if (!pos) return 1; + if (byte_diff(out,2,d->qtype)) return 1; + if (byte_diff(out + 2,2,DNS_C_IN)) return 1; + + return 0; +} + +void packetfree(struct dns_transmit *d) +{ + if (!d->packet) return; + alloc_free(d->packet); + d->packet = 0; +} + +void queryfree(struct dns_transmit *d) +{ + if (!d->query) return; + alloc_free(d->query); + d->query = 0; +} + +void socketfree(struct dns_transmit *d) +{ + if (!d->s1) return; + close(d->s1 - 1); + d->s1 = 0; +} + +void dns_transmit_free(struct dns_transmit *d) +{ + queryfree(d); + socketfree(d); + packetfree(d); +} + +int randombind6(struct dns_transmit *d) +{ + int j; + + for (j = 0; j < 10; ++j) { + if (socket_bind6(d->s1 - 1,d->localip,1025 + dns_random(64510),d->scope_id) == 0) + return 0; + } + if (socket_bind6(d->s1 - 1,d->localip,0,d->scope_id) == 0) + return 0; + + return DNS_COM; +} + +int randombind4(struct dns_transmit *d) +{ + int j; + + for (j = 0; j < 10; ++j) { + if (socket_bind4(d->s1 - 1,d->localip + 12,1025 + dns_random(64510)) == 0) + return 0; + } + if (socket_bind4(d->s1 - 1,d->localip + 12,0) == 0) + return 0; + + return DNS_COM; +} + +int thisudp(struct dns_transmit *d) +{ + const char *ip; + + socketfree(d); + + while (d->udploop < 5) { + for (; d->curserver < QUERY_MAXNS; ++d->curserver) { + ip = d->servers + 16 * d->curserver; + if (byte_diff(ip,16,V6localnet)) { + d->query[2] = dns_random(256); + d->query[3] = dns_random(256); + + if (ip6_isv4mapped(ip)) { + d->s1 = 1 + socket_udp4(); + if (!d->s1) { dns_transmit_free(d); return DNS_COM; } + if (randombind4(d) < 0) { dns_transmit_free(d); return DNS_COM; } + } else { + d->s1 = 1 + socket_udp6(); + if (!d->s1) { dns_transmit_free(d); return DNS_COM; } + if (randombind6(d) < 0) { dns_transmit_free(d); return DNS_COM; } + } + + if (byte_equal(ip,2,V6linklocal) && !d->scope_id) + d->scope_id = getscopeid(d,ip); + if (socket_connect(d->s1 - 1,ip,DNSPORT,d->scope_id) == 0) + if (send(d->s1 - 1,d->query + 2,d->querylen - 2,0) == d->querylen - 2) { + struct taia now; + taia_now(&now); + taia_uint(&d->deadline,timeouts[d->udploop]); + taia_add(&d->deadline,&d->deadline,&now); + d->tcpstate = 0; + return 0; + } + socketfree(d); + } + } + ++d->udploop; + d->curserver = 0; + } + + dns_transmit_free(d); return DNS_COM; +} + +int firstudp(struct dns_transmit *d) +{ + d->curserver = 0; + return thisudp(d); +} + +int nextudp(struct dns_transmit *d) +{ + ++d->curserver; + return thisudp(d); +} + +int thistcp(struct dns_transmit *d) +{ + struct taia now; + const char *ip; + + socketfree(d); + packetfree(d); + + for (; d->curserver < QUERY_MAXNS; ++d->curserver) { + ip = d->servers + 16 * d->curserver; + if (byte_diff(ip,16,V6localnet)) { + d->query[2] = dns_random(256); + d->query[3] = dns_random(256); + + if (ip6_isv4mapped(ip)) { + d->s1 = 1 + socket_tcp4(); + if (!d->s1) { dns_transmit_free(d); return DNS_COM; } + if (randombind4(d) < 0) { dns_transmit_free(d); return DNS_COM; } + } else { + d->s1 = 1 + socket_tcp6(); + if (!d->s1) { dns_transmit_free(d); return DNS_COM; } + if (randombind6(d) < 0) { dns_transmit_free(d); return DNS_COM; } + } + + taia_now(&now); + taia_uint(&d->deadline,10); + taia_add(&d->deadline,&d->deadline,&now); + + if (byte_equal(ip,2,V6linklocal) && !d->scope_id) + d->scope_id = getscopeid(d,ip); + if (socket_connect(d->s1 - 1,ip,DNSPORT,d->scope_id) == 0) { + d->tcpstate = 2; + return 0; + } + if ((errno == EINPROGRESS) || (errno == EWOULDBLOCK)) { + d->tcpstate = 1; + return 0; + } + + socketfree(d); + } + } + + dns_transmit_free(d); + return DNS_COM; +} + +int firsttcp(struct dns_transmit *d) +{ + d->curserver = 0; + return thistcp(d); +} + +int nexttcp(struct dns_transmit *d) +{ + ++d->curserver; + return thistcp(d); +} + +int dns_transmit_start(struct dns_transmit *d,const char servers[QUERY_MAXIPLEN], \ + int flagrecursive,const char *q,const char qtype[2],const char localip[16]) +{ + unsigned int len; + + dns_transmit_free(d); + errno = EIO; + + len = dns_domain_length(q); + d->querylen = len + 18; + d->query = alloc(d->querylen); + if (!d->query) return DNS_COM; + + uint16_pack_big(d->query,len + 16); + byte_copy(d->query + 2,12,flagrecursive ? "\0\0\1\0\0\1\0\0\0\0\0\0" : \ + "\0\0\0\0\0\1\0\0\0\0\0\0gcc-bug-workaround"); + byte_copy(d->query + 14,len,q); + byte_copy(d->query + 14 + len,2,qtype); + byte_copy(d->query + 16 + len,2,DNS_C_IN); + + byte_copy(d->qtype,2,(char *) qtype); + d->servers = servers; + byte_copy(d->localip,16,(char *) localip); + + d->udploop = flagrecursive ? 1 : 0; + + if (len + 16 > MSGSIZE) return firsttcp(d); + return firstudp(d); +} + +int dns_transmit_start6(struct dns_transmit *d,const char servers[QUERY_MAXIPLEN], \ + int flagrecursive,const char *q,const char qtype[2], \ + const char localip[16],const uint32 scopes[QUERY_MAXNS]) +{ + byte_copy(scope_ids,128,(char *) scopes); + + return dns_transmit_start(d,servers,flagrecursive,q,qtype,localip); +} + +void dns_transmit_io(struct dns_transmit *d,iopause_fd *x,struct taia *deadline) +{ + x->fd = d->s1 - 1; + + switch (d->tcpstate) { + case 0: case 3: case 4: case 5: + x->events = IOPAUSE_READ; + break; + case 1: case 2: + x->events = IOPAUSE_WRITE; + break; + } + + if (taia_less(&d->deadline,deadline)) + *deadline = d->deadline; +} + +int dns_transmit_get(struct dns_transmit *d,const iopause_fd *x,const struct taia *when) +{ + char udpbuf[MSGSIZE + 1]; + unsigned char ch; + int r; + int fd; + + errno = EIO; + fd = d->s1 - 1; + + if (!x->revents) { + if (taia_less((struct taia *)when,&d->deadline)) return 0; + errno = ETIMEDOUT; + if (d->tcpstate == 0) return nextudp(d); + return nexttcp(d); + } + +/* +have attempted to send UDP query to each server udploop times +have sent query to curserver on UDP socket s +*/ + if (d->tcpstate == 0) { + r = recv(fd,udpbuf,sizeof(udpbuf),0); + if (r <= 0) { + if (errno == ECONNREFUSED) if (d->udploop == 2) return 0; + return nextudp(d); + } + if (r + 1 > sizeof(udpbuf)) return 0; + + if (irrelevant(d,udpbuf,r)) return 0; + if (serverwantstcp(udpbuf,r)) return firsttcp(d); + if (serverfailed(udpbuf,r)) { + if (d->udploop == 2) return 0; + return nextudp(d); + } + socketfree(d); + + d->packetlen = r; + d->packet = alloc(d->packetlen); + if (!d->packet) { dns_transmit_free(d); return DNS_COM; } + byte_copy(d->packet,d->packetlen,udpbuf); + queryfree(d); + return 1; + } + +/* +have sent connection attempt to curserver on TCP socket s +pos not defined +*/ + if (d->tcpstate == 1) { + if (!socket_connected(fd)) return nexttcp(d); + d->pos = 0; + d->tcpstate = 2; + return 0; + } + +/* +have connection to curserver on TCP socket s +have sent pos bytes of query +*/ + if (d->tcpstate == 2) { + r = write(fd,d->query + d->pos,d->querylen - d->pos); + if (r <= 0) return nexttcp(d); + d->pos += r; + if (d->pos == d->querylen) { + struct taia now; + taia_now(&now); + taia_uint(&d->deadline,10); + taia_add(&d->deadline,&d->deadline,&now); + d->tcpstate = 3; + } + return 0; + } + +/* +have sent entire query to curserver on TCP socket s +pos not defined +*/ + if (d->tcpstate == 3) { + r = read(fd,&ch,1); + if (r <= 0) return nexttcp(d); + d->packetlen = ch; + d->tcpstate = 4; + return 0; + } + +/* +have sent entire query to curserver on TCP socket s +pos not defined +have received one byte of packet length into packetlen +*/ + if (d->tcpstate == 4) { + r = read(fd,&ch,1); + if (r <= 0) return nexttcp(d); + d->packetlen <<= 8; + d->packetlen += ch; + d->tcpstate = 5; + d->pos = 0; + d->packet = alloc(d->packetlen); + if (!d->packet) { dns_transmit_free(d); return DNS_COM; } + return 0; + } + +/* +have sent entire query to curserver on TCP socket s +have received entire packet length into packetlen +packet is allocated +have received pos bytes of packet +*/ + if (d->tcpstate == 5) { + r = read(fd,d->packet + d->pos,d->packetlen - d->pos); + if (r <= 0) return nexttcp(d); + d->pos += r; + if (d->pos < d->packetlen) return 0; + + socketfree(d); + if (irrelevant(d,d->packet,d->packetlen)) return nexttcp(d); + if (serverwantstcp(d->packet,d->packetlen)) return nexttcp(d); + if (serverfailed(d->packet,d->packetlen)) return nexttcp(d); + + queryfree(d); + return 1; + } + + return 0; +} diff --git a/src/dnsstub/dns_txt.c b/src/dnsstub/dns_txt.c new file mode 100644 index 0000000..9a1b56a --- /dev/null +++ b/src/dnsstub/dns_txt.c @@ -0,0 +1,64 @@ +#include "stralloc.h" +#include "uint_t.h" +#include "byte.h" +#include "dnsresolv.h" + +int dns_txt_packet(stralloc *out,const char *buf,unsigned int len) +{ + unsigned int pos; + char header[12]; + uint16 numanswers; + uint16 datalen; + char ch; + unsigned int txtlen; + int i; + int ranswers = 0; + + if (!stralloc_copys(out,"")) return DNS_MEM; + + pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 6,&numanswers); + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos += 4; + + while (numanswers--) { + pos = dns_packet_skipname(buf,len,pos); if (!pos) return DNS_ERR; + pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return DNS_ERR; + uint16_unpack_big(header + 8,&datalen); + if (byte_equal(header,2,DNS_T_TXT)) + if (byte_equal(header + 2,2,DNS_C_IN)) { + if (pos + datalen > len) return DNS_ERR; + txtlen = (unsigned char) buf[pos]; + for (i = 1; i < datalen; ++i) { + ch = buf[pos + i]; + if (i == txtlen + 1) // next label + txtlen += (unsigned char) ch + 1; + else { + if (ch < 32) ch = '?'; + if (ch > 126) ch = '?'; + if (!stralloc_append(out,&ch)) return DNS_MEM; + } + } + } + pos += datalen; + ++ranswers; + if (numanswers) if (!stralloc_append(out,"\n")) return DNS_MEM; + } + + return ranswers; +} + +static char *q = 0; + +int dns_txt(stralloc *out,const stralloc *fqdn) +{ + int rc; + + if (dns_domain_fromdot(&q,fqdn->s,fqdn->len) <= 0) return DNS_ERR; + if (dns_resolve(q,DNS_T_TXT) < 0) return DNS_ERR; + if ((rc = dns_txt_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen)) < 0) return DNS_ERR; + dns_transmit_free(&dns_resolve_tx); + dns_domain_free(&q); + + return rc; +} diff --git a/src/env.c b/src/env.c new file mode 100644 index 0000000..2ecaa83 --- /dev/null +++ b/src/env.c @@ -0,0 +1,136 @@ +#include "str.h" +#include "alloc.h" +#include "env.h" + +/** + @file env.c + @author djb + @source ucspi-tcp + @brief setting up environment after fork +*/ + +extern /*@null@*/char *env_get(char *s) +{ + int i; + unsigned int len; + + if (!s) return 0; + len = str_len(s); + for (i = 0; environ[i]; ++i) + if (str_start(environ[i],s) && (environ[i][len] == '=')) + return environ[i] + len + 1; + return 0; +} + +extern char *env_findeq(char *s) +{ + for (; *s; ++s) + if (*s == '=') return s; + return 0; +} + +int env_isinit = 0; /* if env_isinit: */ +static int ea; /* environ is a pointer to ea+1 char*'s. */ +static int en; /* the first en of those are ALLOCATED. environ[en] is 0. */ + +static void env_del(int i) { + alloc_free(environ[i]); + environ[i] = environ[--en]; + environ[en] = 0; +} + +static void env_unsetlen(char *s,int len) +{ + int i; + + for (i = en - 1; i >= 0; --i) + if (!str_diffn(s,environ[i],len)) + if (environ[i][len] == '=') + env_del(i); +} + +int env_unset(char *s) +{ + if (!env_isinit) + if (!env_init()) return 0; + env_unsetlen(s,str_len(s)); + return 1; +} + +int env_set(char *s) { + char *t; + + t = env_findeq(s); + if (t) env_unsetlen(s,t - s); + if (en == ea) { + ea += 30; + if (!alloc_re(&environ,(en + 1) * sizeof(char *),(ea + 1) * sizeof(char *))) + { ea = en; return 0; } + } + environ[en++] = s; + environ[en] = 0; + return 1; +} + +int env_puts(char *s) { + char *u; + + if (!env_isinit) + if (!env_init()) return 0; + u = alloc(str_len(s) + 1); + if (!u) return 0; + str_copy(u,s); + if (!env_set(u)) { alloc_free(u); return 0; } + return 1; +} + +int env_put(char *name,char *value) { + char *ln; + int len; + + if (!env_isinit) + if (!env_init()) return 0; + len = str_len(name); + ln = alloc(len + str_len(value) + 2); + if (!ln) return 0; + str_copy(ln,name); + ln[len] = '='; + str_copy(ln + len + 1,value); + if (!env_set(ln)) { alloc_free(ln); return 0; } + return 1; +} + +int env_init() { + char **newenviron; + int i; + + for (en = 0; environ[en]; ++en) + ; + ea = en + 10; + newenviron = (char **) alloc((ea + 1) * sizeof(char *)); + if (!newenviron) return 0; + + for (en = 0; environ[en]; ++en) { + newenviron[en] = alloc(str_len(environ[en]) + 1); + if (!newenviron[en]) { + for (i = 0; i < en; ++i) alloc_free(newenviron[i]); + alloc_free(newenviron); + return 0; + } + str_copy(newenviron[en],environ[en]); + } + + newenviron[en] = 0; + environ = newenviron; + env_isinit = 1; + return 1; +} + +static char *null = 0; + +void env_clear() { + if (env_isinit) + while (en) env_del(0); + else environ = &null; +} +extern char *env_pick() { return environ[0]; } diff --git a/src/errstr.c b/src/errstr.c new file mode 100644 index 0000000..e2290fb --- /dev/null +++ b/src/errstr.c @@ -0,0 +1,163 @@ +#include "error.h" + +/** + @file errstr.c + @author kp + @source qlibs + @brief error output to log for different conditions and OS +*/ + +#define X(e,s) if (code == e) return s; + +extern char *error_str(int); + +char *errstr(int code) +{ + X(0,"") // NOERROR + X(error_intr,"interrupted system call") // EINTR + X(EINTR, "interrupted system call") + X(error_nomem,"out of memory") // ENOMEM + X(ENOMEM, "out of memory") + X(error_noent,"file does not exist") // ENOENT + X(ENOENT, "file does not exist") + X(error_txtbsy,"text busy") // ETXTBSY + X(ETXTBSY, "text busy") + X(error_io,"input/output error") // EIO + X(EIO, "input/output error") + X(error_exist,"file already exists") // EEXISTS + X(EEXIST, "file already exists") + X(error_timeout,"timed out") // ETIMEDOUT + X(ETIMEDOUT, "timed out") + X(error_inprogress,"operation in progress") // EINPROGRESS + X(EINPROGRESS, "operation in progress") + X(error_again,"temporary failure") // EAGAIN + X(EAGAIN, "temporary failure") + X(error_wouldblock,"input/output would block") // EWOULDBLOCK (intern EAGAIN) + X(EWOULDBLOCK, "input/output would block") + X(error_pipe,"broken pipe") // EPIPE + X(EPIPE, "broken pipe") + X(error_perm,"permission denied") // EPERM + X(EPERM, "permission denied") + X(error_acces,"access denied") // EACCES + X(EACCES, "access denied") + + X(ESRCH, "no such process") + +// X(error_nodevice,"device not configured") // ENXIO + X(ENXIO, "device not configured") + + X(E2BIG, "argument list too long") + X(ENOEXEC, "exec format error") + X(EBADF, "file descriptor not open") + X(ECHILD, "no child processes") + X(EDEADLK, "operation would cause deadlock") + X(EFAULT, "bad address") + X(ENOTBLK, "not a block device") + X(EBUSY, "device busy") + X(EXDEV, "cross-device link") + X(ENODEV, "device does not support operation") +// X(error_notdir,"not a directory") // ENOTDIR + X(ENOTDIR, "not a directory") + X(error_isdir,"is a directory") // EISDIR + X(EISDIR, "is a directory") + X(EINVAL, "invalid argument") + X(ENFILE, "system cannot open more files") + X(EMFILE, "process cannot open more files") + X(ENOTTY, "not a tty") + X(EFBIG, "file too big") + X(ENOSPC, "out of disk space") + X(ESPIPE, "unseekable descriptor") +// X(error_rofs,"read-only file system") // EROFS + X(EROFS, "read-only file system") + X(EMLINK, "too many links") + X(EDOM, "input out of range") + X(ERANGE, "output out of range") + X(EALREADY, "operation already in progress") + X(ENOTSOCK, "not a socket") + X(EDESTADDRREQ, "destination address required") + X(EMSGSIZE, "message too long") + X(EPROTOTYPE, "incorrect protocol type") + X(ENOPROTOOPT, "protocol not available") + X(EPROTONOSUPPORT, "protocol not supported") + X(ESOCKTNOSUPPORT, "socket type not supported") + X(EOPNOTSUPP, "operation not supported") + X(EPFNOSUPPORT, "protocol family not supported") + X(EAFNOSUPPORT, "address family not supported") + X(EADDRINUSE, "address already used") + X(EADDRNOTAVAIL, "address not available") + X(ENETDOWN, "network down") + X(ENETUNREACH, "network unreachable") + X(ENETRESET, "network reset") + X(ECONNABORTED, "connection aborted") + X(error_connreset, "connection reset") // ECONNRESET + X(ECONNRESET, "connection reset") + X(ENOBUFS, "out of buffer space") + X(EISCONN, "already connected") + X(ENOTCONN, "not connected") + X(ESHUTDOWN, "socket shut down") + X(ETOOMANYREFS, "too many references") + X(error_connrefused,"connection refused") // ECONNREFUSED + X(ECONNREFUSED, "connection refused") + X(ELOOP, "symbolic link loop") + X(ENAMETOOLONG, "file name too long") + X(EHOSTDOWN, "host down") + X(EHOSTUNREACH, "host unreachable") + X(ENOTEMPTY, "directory not empty") + X(EUSERS, "too many users") + X(EDQUOT, "disk quota exceeded") + X(ESTALE, "stale NFS file handle") + + /* BSD only (all BSD's, NOT on Linux) */ +// X(EPROCLIM, "too many processes") // -L +FB +OB +NB +// X(EBADRPC, "RPC structure is bad") // -L +FB +OB +NB + +// X(ERPCMISMATCH, "RPC version mismatch") // -L +FB +OB +NB +// X(EPROGUNAVAIL, "RPC program unavailable") // -L +FB +OB +NB +// X(EPROGMISMATCH, "program version mismatch") // -L +FB +OB +NB +// X(EPROCUNAVAIL, "bad procedure for program") // -L +FB +OB +NB +// X(EFTYPE, "bad file type") // -L +FB +OB +NB + + X(ENOLCK, "no locks available") + X(ENOSYS, "system call not available") + X(ENOMSG, "no message of desired type") + X(EIDRM, "identifier removed") + +// X(ERREMOTE, "object not local") // -L -FB -OB -NB + X(EREMOTE, "object not local") // Linux: "Object is remote" +// X(EREMOTE, "too many levels of remote in path") + + /* Linux only */ +// X(ENONET, "machine not on network") // +L -FB -OB -NB +// X(EADV, "advertise error") // +L -FB -OB -NB +// X(ESRMNT, "srmount error") // +L -FB -OB -NB +// X(ECOMM, "communication error") // +L -FB -OB -NB +// X(EREMCHG, "remote address changed") // +L -FB -OB -NB + + X(error_proto,"protocol error") // EPROTO + /* EPROTO: see 'error.h' for OpenBSD compat */ + X(EPROTO, "protocol error") // +L +FB -OB +NB + + /* Linux and NetBSD */ +// X(ENOSTR, "not a stream device") // +L -FB -OB +NB +// X(ETIME, "timer expired") // +L -FB -OB +NB +// X(ENOSR, "out of stream resources") // +L -FB -OB +NB + + /* FreeBSD and NetBSD */ +// X(EAUTH, "authentication error") // -L +FB -OB +NB +// X(ENEEDAUTH, "not authenticated") // -L +FB -OB +NB + + /* NOT on OpenBSD */ +// X(EBADMSG, "bad message type") // +L +FB -OB +NB +// X(ENOLINK, "link severed") // +L +FB -OB +NB +// X(EMULTIHOP, "multihop attempted") // +L +FB -OB +NB + + /* Application/DJB specific */ + X(EHARD, " ") + X(ESOFT, " ") + X(USAGE, "usage error") // qmail; explicit + X(SYNTAX, "syntax error") // djbdns, qmail; explicit + X(DROP, "connection dropped") // ucspi-tcp + X(FATAL, "unable to continue") // all + + return "unknown error"; /* worst case */ +} diff --git a/src/fd.c b/src/fd.c new file mode 100644 index 0000000..776575c --- /dev/null +++ b/src/fd.c @@ -0,0 +1,30 @@ +#include +#include "fd.h" + +/** + @file fd.c + @autor djb + @source qmail + @brief file descriptor manipulation +*/ + +int close(int __fd); /* we won't use unistd.h here */ + +int fd_copy(int to,int from) +{ + if (to == from) return 0; + if (fcntl(from,F_GETFL,0) == -1) return -1; + close(to); + if (fcntl(from,F_DUPFD,to) == -1) return -1; + return 0; +} + +int fd_move(int to,int from) +{ + if (to == from) return 0; + if (fd_copy(to,from) == -1) return -1; + close(from); + return 0; +} + +int fd_coe(int fd) {return fcntl(fd,F_SETFD,1); } diff --git a/src/fmt.c b/src/fmt.c new file mode 100644 index 0000000..52ab5dc --- /dev/null +++ b/src/fmt.c @@ -0,0 +1,85 @@ +#include "fmt.h" + +/** + @file fmt.c + @author djb + @source qmail + @brief formating differnt inputs format for output printing +*/ + +unsigned int fmt_str(register char *s,register char *t) +{ + register unsigned int len; + char ch; + len = 0; + if (s) { while ((ch = t[len])) s[len++] = ch; } + else while (t[len]) len++; + return len; +} + +unsigned int fmt_strn(register char *s,register char *t,register unsigned int n) +{ + register unsigned int len; + char ch; + len = 0; + if (s) { while (n-- && (ch = t[len])) s[len++] = ch; } + else while (n-- && t[len]) len++; + return len; +} + +unsigned int fmt_uint(register char *s,register unsigned int u) +{ + register unsigned long l; l = u; return fmt_ulong(s,l); +} + +unsigned int fmt_uint0(char *s,unsigned int u,unsigned int n) +{ + unsigned int len; + len = fmt_uint(FMT_LEN,u); + while (len < n) { if (s) *s++ = '0'; ++len; } + if (s) fmt_uint(s,u); + return len; +} + +unsigned int fmt_ulong(register char *s,register unsigned long u) +{ + register unsigned int len; register unsigned long q; + len = 1; q = u; + while (q > 9) { ++len; q /= 10; } + if (s) { + s += len; + do { *--s = '0' + (u % 10); u /= 10; } while(u); /* handles u == 0 */ + } + return len; +} + +unsigned int fmt_xlong(register char *s,register unsigned long u) +{ + register unsigned int len; register unsigned long q; + len = 1; q = u; + while (q > 15) { ++len; q /= 16; } + if (s) { + s += len; + do { *--s = tohex(u % 16); u /= 16; } while(u); /* handles u == 0 */ + } + return len; +} + +char tohex(char num) { + if (num < 10) + return num + '0'; + else if (num < 16) + return num - 10 + 'a'; + else + return -1; +} + +int fromhex(unsigned char c) { + if (c >= '0' && c <= '9') + return c-'0'; + else if (c >= 'A' && c <= 'F') + return c -'A' + 10; + else if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + return -1; +} diff --git a/src/getln.c b/src/getln.c new file mode 100644 index 0000000..f83d3c2 --- /dev/null +++ b/src/getln.c @@ -0,0 +1,43 @@ +#include "byte.h" +#include "getln.h" + +/** + @file getln.c + @author djb + @source qmail + @brief evaluting tokenized input arguments +*/ + +int getln(buffer *b,stralloc *sa,int *match,int sep) +{ + char *cont; + unsigned int clen; + + if (sgetln(b,sa,&cont,&clen,sep) == -1) return -1; + if (!clen) { *match = 0; return 0; } + if (!stralloc_catb(sa,cont,clen)) return -1; + *match = 1; + return 0; +} + +int sgetln(buffer *b,stralloc *sa,char **cont,unsigned int *clen,int sep) +{ + register char *x; + register unsigned int i; + int n; + + if (!stralloc_ready(sa,0)) return -1; + sa->len = 0; + + for (;;) { + n = buffer_feed(b); + if (n < 0) return -1; + if (n == 0) { *clen = 0; return 0; } + x = buffer_PEEK(b); + i = byte_chr(x,n,sep); + if (i < n) { buffer_SEEK(b,*clen = i + 1); *cont = x; return 0; } + if (!stralloc_readyplus(sa,n)) return -1; + i = sa->len; + sa->len = i + buffer_get(b,sa->s + i,n); + } +} diff --git a/src/getoptb.c b/src/getoptb.c new file mode 100644 index 0000000..edee6b8 --- /dev/null +++ b/src/getoptb.c @@ -0,0 +1,100 @@ +#include "buffer.h" +#include "getoptb.h" + +/** + @file getoptb.c + @author djb + @source ucspi-tcp + @brief 'getopt' version w/o stdlib +*/ + +#define optind subgetoptind +#define optproblem subgetoptproblem + +int opterr = 1; +char *optprogname = 0; + +int getopt(int argc,char **argv,char *opts) +{ + int c; + char *s; + + if (!optprogname) { + optprogname = *argv; + if (!optprogname) optprogname = ""; + for (s = optprogname;*s;++s) if (*s == '/') optprogname = s + 1; + } + c = subgetopt(argc,argv,opts); + if (opterr) + if (c == '?') { + char chp[2]; chp[0] = optproblem; chp[1] = '\n'; + buffer_puts(buffer_2,optprogname); + if (argv[optind] && (optind < argc)) + buffer_puts(buffer_2,": illegal option -- "); + else + buffer_puts(buffer_2,": option requires an argument -- "); + buffer_put(buffer_2,chp,2); + buffer_flush(buffer_2); + } + return c; +} + +#define optpos subgetoptpos +#define optarg subgetoptarg +#define optdone subgetoptdone + +int optind = 1; +int optpos = 0; +char *optarg = 0; +int optproblem = 0; +int optdone = SUBGETOPTDONE; + +int subgetopt(int argc,char **argv,char *opts) +{ + int c; + char *s; + + optarg = 0; + if (!argv || (optind >= argc) || !argv[optind]) return optdone; + if (optpos && !argv[optind][optpos]) { + ++optind; + optpos = 0; + if ((optind >= argc) || !argv[optind]) return optdone; + } + if (!optpos) { + if (argv[optind][0] != '-') return optdone; + ++optpos; + c = argv[optind][1]; + if ((c == '-') || (c == 0)) { + if (c) ++optind; + optpos = 0; + return optdone; + } + /* otherwise c is reassigned below */ + } + c = argv[optind][optpos]; + ++optpos; + s = opts; + while (*s) { + if (c == *s) { + if (s[1] == ':') { + optarg = argv[optind] + optpos; + ++optind; + optpos = 0; + if (!*optarg) { + optarg = argv[optind]; + if ((optind >= argc) || !optarg) { /* argument past end */ + optproblem = c; + return '?'; + } + ++optind; + } + } + return c; + } + ++s; + if (*s == ':') ++s; + } + optproblem = c; + return '?'; +} diff --git a/src/iopause.c b/src/iopause.c new file mode 100644 index 0000000..94a6fea --- /dev/null +++ b/src/iopause.c @@ -0,0 +1,84 @@ +#include +#include "taia.h" +#include "select.h" +#include "iopause.h" + +/** + @file iopause.c + @author djb + @source qmail + @brief stateful reading from net + @return > 0 if successful +*/ + +int iopause(iopause_fd *x,unsigned int len,struct taia *deadline,struct taia *stamp) +{ + struct taia t; + int millisecs; + double d; + int i, r; + + if (taia_less(deadline,stamp)) + millisecs = 0; + else { + t = *stamp; + taia_sub(&t,deadline,&t); + d = taia_approx(&t); + if (d > 1000.0) d = 1000.0; + millisecs = d * 1000.0 + 20.0; + if (millisecs < 0) millisecs = 20.0; + } + + for (i = 0; i < len; ++i) + x[i].revents = 0; + +#ifdef IOPAUSE_POLL + r = poll(x,len,millisecs); + + /* XXX: some kernels apparently need x[0] even if len is 0 */ + /* XXX: how to handle EAGAIN? are kernels really this dumb? */ + /* XXX: how to handle EINVAL? when exactly can this happen? */ + +#else + struct timeval tv; + fd_set rfds; + fd_set wfds; + int nfds; + int fd; + + FD_ZERO(&rfds); + FD_ZERO(&wfds); + + nfds = 1; + for (i = 0; i < len; ++i) { + fd = x[i].fd; + if (fd < 0) continue; + if (fd >= 8 * sizeof(fd_set)) continue; /*XXX*/ + + if (fd >= nfds) nfds = fd + 1; + if (x[i].events & IOPAUSE_READ) FD_SET(fd,&rfds); + if (x[i].events & IOPAUSE_WRITE) FD_SET(fd,&wfds); + } + + tv.tv_sec = millisecs / 1000; + tv.tv_usec = 1000 * (millisecs % 1000); + + r = select(nfds,&rfds,&wfds,(fd_set *) 0,&tv); + if (r <= 0) return r; + + /* XXX: for EBADF, could seek out and destroy the bad descriptor */ + + for (i = 0; i < len; ++i) { + fd = x[i].fd; + if (fd < 0) continue; + if (fd >= 8 * sizeof(fd_set)) continue; /*XXX*/ + + if (x[i].events & IOPAUSE_READ) + if (FD_ISSET(fd,&rfds)) x[i].revents |= IOPAUSE_READ; + if (x[i].events & IOPAUSE_WRITE) + if (FD_ISSET(fd,&wfds)) x[i].revents |= IOPAUSE_WRITE; + } + +#endif + return r; +} diff --git a/src/ip4.c b/src/ip4.c new file mode 100644 index 0000000..e77cfb6 --- /dev/null +++ b/src/ip4.c @@ -0,0 +1,166 @@ +#include "fmt.h" +#include "scan.h" +#include "str.h" +#include "ip.h" + +/** + @file ip4.c + @author djb, fefe, feh, kp + @source ucspi-tcp, ucspi-tcp6 + @brief handling of IPv4 addresses +*/ + +/** + @brief ip4_fmt + converts IPv4 address to dotted decimal string format + @param input: IPv4 char array + output: IPv4 address string + @return int length of address (ok > 0) + */ + +unsigned int ip4_fmt(char *s,char ip[4]) +{ + unsigned int len; + unsigned int i; + + len = 0; + i = fmt_ulong(s,(unsigned long) (unsigned char) ip[0]); len += i; if (s) s += i; + if (s) { *s++ = '.'; } ++len; + i = fmt_ulong(s,(unsigned long) (unsigned char) ip[1]); len += i; if (s) s += i; + if (s) { *s++ = '.'; } ++len; + i = fmt_ulong(s,(unsigned long) (unsigned char) ip[2]); len += i; if (s) s += i; + if (s) { *s++ = '.'; } ++len; + i = fmt_ulong(s,(unsigned long) (unsigned char) ip[3]); len += i; if (s) s += i; + return len; +} + +/** + @brief ia4_fmt + converts IPv4 address into DNS inverse nibble format + @param input: IPv4 char array + output: IPv4 address string + @return int length of address (ok > 0) + */ + +unsigned int ia4_fmt(char *s,char ip[4]) +{ + unsigned int i; + unsigned int len; + + len = 0; + i = fmt_ulong(s,(unsigned long) ip[3]); len += i; if (s) s += i; + i = fmt_str(s,"."); len += i; if (s) s += i; + i = fmt_ulong(s,(unsigned long) ip[2]); len += i; if (s) s += i; + i = fmt_str(s,"."); len += i; if (s) s += i; + i = fmt_ulong(s,(unsigned long) ip[1]); len += i; if (s) s += i; + i = fmt_str(s,"."); len += i; if (s) s += i; + i = fmt_ulong(s,(unsigned long) ip[0]); len += i; if (s) s += i; + i = fmt_str(s,".in-addr.arpa."); len += i; if (s) s += i; + return len; +} + +/** + @brief ip4_scan + parse IPv4 address string and convert to IP address array + @param input: IPv4 address string + output: IPv4 char array + @return int length of ip_address (ok > 0) + */ + +unsigned int ip4_scan(const char *s,char ip[4]) +{ + unsigned int i; + unsigned int len; + unsigned long u; + + byte_zero(ip,4); + len = 0; + i = scan_ulong((char *)s,&u); if (!i) { return 0; } ip[0] = u; s += i; len += i; + if (*s != '.') { return 0; } ++s; ++len; + i = scan_ulong((char *)s,&u); if (!i) { return 0; } ip[1] = u; s += i; len += i; + if (*s != '.') { return 0; } ++s; ++len; + i = scan_ulong((char *)s,&u); if (!i) { return 0; } ip[2] = u; s += i; len += i; + if (*s != '.') { return 0; } ++s; ++len; + i = scan_ulong((char *)s,&u); if (!i) { return 0; } ip[3] = u; s += i; len += i; + return len; +} + +/** + @brief ip4_scanbracket + parse IPv4 address string enclosed in brackets and convert to IP address array + @param input: IPv4 char array + output: IPv4 char array + @return int length of ip_address (ok > 0) + */ + +unsigned int ip4_scanbracket(const char *s,char ip[4]) +{ + unsigned int len; + + if (*s != '[') return 0; + len = ip4_scan(s + 1,ip); + if (!len) return 0; + if (s[len + 1] != ']') return 0; + return len + 2; +} + +/** + @brief ip4_cidr + parse IPv4 address string + concatinated with the prefix length: 192.168.1/24 + @param input: IPv6 char array + output: IPv6 char array, long plen + @return int length of ip6_address/ip + */ + +unsigned int ip4_cidr(char *s,char ip[4],unsigned long *plen) +{ + unsigned int j = 0; + *plen = 32UL; + + j = str_chr(s,'/'); + if (s[j] == '/') { + s[j] = 0; + j = scan_ulong(s + j + 1,plen); + } + return ip4_scan((const char *)s,ip); +} + +/** + @brief ip4_bytestring + parse IPv4 address and represent as char string with length prefix + @param input: IPv4 char array, prefix length + output: pointer to stralloc bytestring + @return n: number of bytes, if ok; -1: memory shortage; -2: input error + */ + +unsigned int ip4_bytestring(stralloc *ipstring,char ip[4],int prefix) +{ + int i, j, n = 0; + unsigned char number; + + if (!stralloc_readyplus(ipstring,32)) return -1; + if (!stralloc_copys(ipstring,"")) return -1; + + for (i = 0; i < 4; i++) { + number = (unsigned char) ip[i]; + if (number > 255) return -2; + + for (j = 7; j >= 0; j--) { + if (number & (1 << j)) { + n++; + if (!stralloc_cats(ipstring,"1")) return -1; + } else { + n++; + if (!stralloc_cats(ipstring,"0")) return -1; + } + prefix--; + if (!prefix) goto DONE; + } + } + +DONE: + if (!stralloc_0(ipstring)) return 1; + + return n; +} diff --git a/src/ip6.c b/src/ip6.c new file mode 100644 index 0000000..cf8d85b --- /dev/null +++ b/src/ip6.c @@ -0,0 +1,360 @@ +#include "fmt.h" +#include "byte.h" +#include "scan.h" +#include "ip.h" +#include "str.h" + +/** + @file ip6.c + @author djb, fefe, feh + @source ucspi-tcp, ucspi-tcp6 + @brief handling of IPv6 addresses +*/ + +/*** + @brief ip6_fmt + convert IPv6 address to compactified IPv6 address string + @param input: IPv6 char array + output: pointer to IPv6 address string + @return int length of address (ok > 0) + */ + +unsigned int ip6_fmt(char *s,char ip[16]) +{ + unsigned int len; + unsigned int i; + unsigned int temp, temp0; + unsigned int compressing; + unsigned int compressed; + int j; + + len = 0; + compressing = 0; + compressed = 0; + + for (j = 0; j < 16; j += 2) { + if (j == 12 && ip6_isv4mapped(ip)) { + len += ip4_fmt(s,ip+12); + break; + } + + temp = ((unsigned long) (unsigned char) ip[j] << 8) + + (unsigned long) (unsigned char) ip[j+1]; + + temp0 = 0; + if (!compressing && j < 16) + temp0 = ((unsigned long) (unsigned char) ip[j+2] << 8) + + (unsigned long) (unsigned char) ip[j+3]; + + if (temp == 0 && temp0 == 0 && !compressed) { + if (!compressing) { + compressing = 1; + if (j == 0) { + if (s) *s++ = ':'; + ++len; + } + } + } else { + if (compressing) { + compressing = 0; + ++compressed; + if (s) *s++ = ':'; + ++len; + } + i = fmt_xlong(s,temp); + len += i; + if (s) s += i; + if (j < 14) { + if (s) *s++ = ':'; + ++len; + } + } + } + if (compressing) { *s++ = ':'; ++len; } + + return len; +} + +/*** + @brief ip6_fmt_flat + convert IPv6 address to IPv6 address string + @param input: IPv6 char array + output: pointer to IPv6 address string + @return int length of address (ok > 0) + */ + +unsigned int ip6_fmt_flat(char *s,char ip[16]) +{ + int i; + for (i = 0; i < 16; i++) { + *s++ = tohex((unsigned char)ip[i] >> 4); + *s++ = tohex((unsigned char)ip[i] & 15); + } + return 32; +} + +/*** + @brief ia6_fmt + convert IPv6 address to inverse DNS nibble format + 1.2.3.4.5.6.7.8.9.a.b.c.d.e.f.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f.ip6.arpa + @param input: IPv6 char array + output: pointer to IPv6 address string + @return int length of address + */ + +unsigned int ia6_fmt(char *s,char ip[16]) +{ + unsigned int i; + unsigned int len; + int j; + + static char data[] = "0123456789abcdef"; + len = 0; + + for (j = 15; j >= 0; j--) { + i = fmt_str(s,&data[ip[j] & 0x0f]); len += i; if (s) s += i; + i = fmt_str(s,"."); len += i; if (s) s += i; + i = fmt_str(s,&data[ip[j] >> 4 & 0x0f]); len += i; if (s) s += i; + i = fmt_str(s,"."); len += i; if (s) s += i; + } + i = fmt_str(s,"ip6.arpa."); len += i; if (s) s += i; + + return len; +} + + +/*** + @brief ip6_scan_flat + convert IPv6 address string to IPv6 address array + @param input: pointer to IPv6 address string + output: IPv6 char array + @return int length of address (ok > 0) + */ + +unsigned int ip6_scan_flat(const char *s,char ip[16]) +{ + int i, tmp; + + for (i = 0; i < 16; i++) { + tmp = fromhex(*s++); + if (tmp < 0) return 0; + ip[i] = tmp << 4; + tmp = fromhex(*s++); + if (tmp < 0) return 0; + ip[i] += tmp; + } + return 32; +} + +/*** + @brief ip6_scan + parse compactified IPv6 address string and convert to IPv6 address array + @param input: pointer to IPv6 address string + output: IPv6 char array + @return int length of ip6_address/ip + */ + +unsigned int ip6_scan(const char *s,char ip[16]) +{ + unsigned int i, j; + unsigned int len = 0; + unsigned long u; + + char suffix[16]; + int prefixlen = 0; + int suffixlen = 0; + + /* Always return IPv4 as IPv4-mapped IPv6 address */ + if ((i = ip4_scan(s,ip+12))) { + for (len = 0; len < 12; ++len) + ip[len] = V4mappedprefix[len]; + return i; + if (byte_equal(ip+12,4,V4localnet)) { + byte_copy(ip,16,V6localnet); + return 16; + } + } + byte_zero(ip,16); + + for (;;) { + if (*s == ':') { + len++; + if (s[1] == ':') { /* Found "::", skip to part 2 */ + s += 2; len++; + break; + } + s++; + } + i = scan_xlong((char *)s,&u); + if (!i) return 0; + + if (prefixlen == 12 && s[i] == '.') { + /* the last 4 bytes may be written as IPv4 address */ + i = ip4_scan(s,ip+12); + if (i) + return i+len; + else + return 0; + } + + ip[prefixlen++] = (u >> 8); + ip[prefixlen++] = (u & 255); + s += i; len += i; + if (prefixlen == 16) return len; + } + +/* part 2, after "::" */ + for (;;) { + if (*s == ':') { + if (suffixlen == 0) break; + s++; + len++; + } else if (suffixlen != 0) break; + + i = scan_xlong((char *)s,&u); + if (!i) { + len--; + break; + } + + if (suffixlen + prefixlen <= 12 && s[i] == '.') { + j = ip4_scan(s,suffix+suffixlen); + if (j) { + suffixlen += 4; + len += j; + break; + } else + prefixlen = 12 - suffixlen; /* make end-of-loop test true */ + } + + suffix[suffixlen++] = (u >> 8); + suffix[suffixlen++] = (u & 255); + s += i; len += i; + if (prefixlen + suffixlen == 16) break; + } + + for (i = 0; i < suffixlen; i++) + ip[16 - suffixlen + i] = suffix[i]; + + return len; +} + +/*** + @brief ip6_scanbracket + parse IPv6 string address enclosed in brackets + @param input: pointer to IPv6 address string + output: IPv6 char array + @return int length of ip_address (ok > 0) + */ + +unsigned int ip6_scanbracket(const char *s,char ip[16]) +{ + unsigned int len; + + if (*s != '[') return 0; + len = ip6_scan(s + 1,ip); + if (!len) return 0; + if (s[len + 1] != ']') return 0; + return len + 2; +} + +/** + @brief ip6_ifscan + parse compactified IPv6 address string + concatinated with the interface name: fe80::1%eth0 + @param input: pointer to IPv6 address string + output: IPv6 char array, stralloc interface_name + @return int length of ip6_address/ip + */ + +unsigned int ip6_ifscan(char *s,char ip[16],stralloc *ifname) +{ + int i; + int j = 0; + int k = 0; + if (!stralloc_copys(ifname,"0")) return 0; + + if ((j = str_chr(s,'%'))) { + if ((i = str_chr(s+j+1,' '))) k = i; + else if ((i = str_chr(s+j+1,'\n'))) k = i; + else if ((i = str_chr(s+j+1,'\t'))) k = i; + if (k) s[j+k+1] = '\0'; /* input might contain trailing chars */ + if (!stralloc_copys(ifname,s+j+1)) return 0; + s[j] = 0; + } + if (!stralloc_0(ifname)) return 0; + + return ip6_scan(s,ip); +} + +/** + @brief ip6_cidr + parse compactified IPv6 address string + concatinated with the prefix length: fe80::1/64 + @param input: pointer to IPv6 address string + output: IPv6 char array, long plen + @return int length of ip6_address/ip + */ + +unsigned int ip6_cidr(char *s,char ip[16],unsigned long *plen) +{ + unsigned int j = 0; + *plen = 128UL; + + j = str_chr(s,'/'); + if (s[j] == '/') { + s[j] = 0; + j = scan_ulong(s+j+1,plen); + } + return ip6_scan((const char *)s,ip); +} + +/** + @brief ip6_bytestring + parse IPv6 address and represent as char string with length prefix + @param input: IPv6 char array, prefix length + output: pointer to stralloc bit string; + @return n: number of bytes, if ok; -1: memory shortage + */ + +unsigned int ip6_bytestring(stralloc *ipstring,char ip[16],int prefix) +{ + int i, j, n = 0; + unsigned char lowbyte, highbyte; + + if (!stralloc_readyplus(ipstring,128)) return -1; + if (!stralloc_copys(ipstring,"")) return -1; + + for (i = 0; i < 16; i++) { + lowbyte = (unsigned char) (ip[i]) & 0x0f; + highbyte = (unsigned char) (ip[i] >> 4) & 0x0f; + + for (j = 3; j >= 0; j--) { + if (highbyte & (1 << j)) { + n++; + if (!stralloc_cats(ipstring,"1")) return -1; + } else { + n++; + if (!stralloc_cats(ipstring,"0")) return -1; + } + prefix--; + if (!prefix) goto DONE; + } + for (j = 3; j >= 0; j--) { + if (lowbyte & (1 << j)) { + n++; + if (!stralloc_cats(ipstring,"1")) return -1; + } else { + n++; + if (!stralloc_cats(ipstring,"0")) return -1; + } + prefix--; + if (!prefix) goto DONE; + } + } + +DONE: + if (!stralloc_0(ipstring)) return -1; + + return n; +} diff --git a/src/lock.c b/src/lock.c new file mode 100644 index 0000000..4ac6b40 --- /dev/null +++ b/src/lock.c @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include "lock.h" + +/** + @file lock.c + @author djb + @source qmail + @brief locking of resources +*/ + +#ifdef HASFLOCK +int lock_ex(int fd) { return flock(fd,LOCK_EX); } +int lock_exnb(int fd) { return flock(fd,LOCK_EX | LOCK_NB); } +int lock_un(int fd) { return flock(fd,LOCK_UN); } +#else +int lock_ex(int fd) { return lockf(fd,1,0); } +int lock_exnb(int fd) { return lockf(fd,2,0); } +int lock_un(int fd) { return lockf(fd,0,0); } +#endif diff --git a/src/logmsg.c b/src/logmsg.c new file mode 100644 index 0000000..3f079f4 --- /dev/null +++ b/src/logmsg.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include "buffer.h" +#include "fmt.h" +#include "str.h" +#include "stralloc.h" +#include "logmsg.h" + +/** + @file logmsg.c + @author kp, feh + @source qlibs + @brief unified system and error message handling +*/ + +#define WHO "logmsg" + +char *build_log_msg(const char *x[]) +{ + stralloc sa = {0}; + stralloc_copys(&sa,""); + + while(*x) { if (!stralloc_cats(&sa,*x++)) err_sys(WHO,errno); } /* concatenate *x */ + + if (!stralloc_0(&sa)) err_sys(WHO,errno); + return(sa.s); +} + +void logmsg(const char *who,int ecode,unsigned int class,const char *msg) +{ + char strnum[FMT_ULONG]; + char *codestr = ""; + char *classstr = ""; + char *errmsg = ""; + + errno = 0; /* re-initialize errno, value is in 'code' now */ + +/* Part 1: obtain the (error) code -- perhaps received from OS */ + + if (ecode != 0) { + codestr = ""; + if (ecode < 0) { // check for negative error codes + ecode = (ecode^-1) + 1; + codestr = "-"; + } + strnum[fmt_ulong(strnum,ecode)] = 0; /* format for output */ + char *temp = strnum; + codestr = str_cat(codestr,temp); + } + +/* Part 2: behavioral on error */ + + switch (class) { + case ERROR: classstr = "error: "; break; // info + exit + case FATAL: classstr = "fatal: "; break; // info + exit + case DROP: classstr = "drop: "; break; // info + next call/iteration + case ALERT: classstr = "alert: "; break; // info + next statement + case WARN: classstr = "warning: "; break; // info + next statement + case INFO: classstr = "info: "; break; // info + continue + case SYNTAX: classstr = "syntax: "; break; // info + exit + case USAGE: classstr = "usage: "; break; // info + exit + case TEMP: classstr = "temp: "; break; // info + exit + case CAT: classstr = ""; break; // info w/o \n + default: + class = LOG; classstr = ""; break; // custom info + continue + } + +/* Part 3: get system error message */ + + if (class == FATAL || class == DROP) + errmsg = error_str(errno); + +/* Part 4: construct log message: Source: Class (Ecode) Message: Errmsg */ + + buffer_puts(buffer_2,who); + buffer_puts(buffer_2,": "); + buffer_puts(buffer_2,classstr); + if (class == FATAL || class == DROP || class == ERROR) { + buffer_puts(buffer_2,"("); + buffer_puts(buffer_2,codestr); + buffer_puts(buffer_2,") "); + } + buffer_puts(buffer_2,msg); + if (errno) { + buffer_puts(buffer_2,": "); + buffer_puts(buffer_2,errmsg); + } + if (class != CAT) { + buffer_puts(buffer_2,"\n"); + buffer_flush(buffer_2); + } + + if (class == USAGE) _exit(USAGE); + if (class == SYNTAX) _exit(SYNTAX); + if (class == FATAL || class == DROP || class == ERROR) _exit(ecode); +} diff --git a/src/ndelay.c b/src/ndelay.c new file mode 100644 index 0000000..f4b5eb8 --- /dev/null +++ b/src/ndelay.c @@ -0,0 +1,24 @@ +#include +#include +#include "ndelay.h" + +/** + @file ndelay.c + @author djb + @soure qmail + @brief delaying of IO operations +*/ + +#ifndef O_NONBLOCK +#define O_NONBLOCK O_NDELAY +#endif + +int ndelay_on(int fd) +{ + return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) | O_NONBLOCK); +} + +int ndelay_off(int fd) +{ + return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) & ~O_NONBLOCK); +} diff --git a/src/open.c b/src/open.c new file mode 100644 index 0000000..c430698 --- /dev/null +++ b/src/open.c @@ -0,0 +1,25 @@ +#include +#include +#include "open.h" + +/** + @file open.c + @author djb + @source qmail + @brief open a file +*/ + +int open_append(const char *fn) +{ return open(fn,O_WRONLY | O_NDELAY | O_APPEND | O_CREAT,0600); } + +int open_excl(const char *fn) +{ return open(fn,O_WRONLY | O_EXCL | O_CREAT,0644); } + +int open_read(const char *fn) +{ return open(fn,O_RDONLY | O_NDELAY); } + +int open_trunc(const char *fn) +{ return open(fn,O_WRONLY | O_NDELAY | O_TRUNC | O_CREAT,0644); } + +int open_write(const char *fn) +{ return open(fn,O_WRONLY | O_NDELAY); } diff --git a/src/pathexec.c b/src/pathexec.c new file mode 100644 index 0000000..2c1e7d1 --- /dev/null +++ b/src/pathexec.c @@ -0,0 +1,121 @@ +#include +#include "alloc.h" +#include "error.h" +#include "stralloc.h" +#include "str.h" +#include "byte.h" +#include "env.h" +#include "pathexec.h" + +/** + @file pathexec.c + @author djb + @source ucspi-tcp, ucspi-ssl + @brief populate environment after fork +*/ + +static stralloc plus; +static stralloc tmp; + +int pathexec_env(const char *s,const char *t) +{ + if (!s) return 1; + if (!stralloc_copys(&tmp,s)) return 0; + if (t) { + if (!stralloc_cats(&tmp,"=")) return 0; + if (!stralloc_cats(&tmp,t)) return 0; + } + if (!stralloc_0(&tmp)) return 0; + return stralloc_cat(&plus,&tmp); +} + +int pathexec_multienv(stralloc *sa) +{ + if (!sa) return 1; + return stralloc_cat(&plus,sa); +} + +void pathexec(char * const *argv) +{ + char **e; + unsigned int elen; + unsigned int i; + unsigned int j; + unsigned int split; + unsigned int t; + + if (!stralloc_cats(&plus,"")) return; + + elen = 0; + for (i = 0; environ[i]; ++i) + ++elen; + for (i = 0; i < plus.len; ++i) + if (!plus.s[i]) + ++elen; + + e = (char **) alloc((elen + 1) * sizeof(char *)); + if (!e) return; + + elen = 0; + for (i = 0; environ[i]; ++i) + e[elen++] = environ[i]; + + j = 0; + for (i = 0; i < plus.len; ++i) + if (!plus.s[i]) { + split = str_chr(plus.s + j,'='); + for (t = 0; t < elen; ++t) + if (byte_equal(plus.s + j,split,e[t])) + if (e[t][split] == '=') { + --elen; + e[t] = e[elen]; + break; + } + if (plus.s[j + split]) + e[elen++] = plus.s + j; + j = i + 1; + } + e[elen] = 0; + + pathexec_run(*argv,argv,e); + alloc_free(e); +} + +void pathexec_run(const char *file,char *const *argv,char *const *envp) +{ + char *path; + unsigned int split; + int savederrno; + + if (file[str_chr(file,'/')]) { + execve(file,argv,envp); + return; + } + + path = env_get("PATH"); + if (!path) path = "/bin:/usr/bin"; + + savederrno = 0; + for (;;) { + split = str_chr(path,':'); + if (!stralloc_copyb(&tmp,path,split)) return; + if (!split) + if (!stralloc_cats(&tmp,".")) return; + if (!stralloc_cats(&tmp,"/")) return; + if (!stralloc_cats(&tmp,file)) return; + if (!stralloc_0(&tmp)) return; + + execve(tmp.s,argv,envp); + if (errno != ENOENT) { + savederrno = errno; + if ((errno != EACCES) && (errno != EPERM) && (errno != EISDIR)) return; + } + + if (!path[split]) { + if (savederrno) errno = savederrno; + return; + } + path += split; + path += 1; + } +} diff --git a/src/prot.c b/src/prot.c new file mode 100644 index 0000000..907de52 --- /dev/null +++ b/src/prot.c @@ -0,0 +1,31 @@ +#include +#include +#include +//#include "hasshsgr.h" +#include "prot.h" + +/** + @file prot.c + @author djb + @source qmail + @brief setting up uid an gid for OS (short group was for ancient solaris) +*/ + +/* XXX: there are more portability problems here waiting to leap out at me */ + +int prot_gid(int gid) +{ +//#ifdef HASSHORTSETGROUPS +// short x[2]; +// x[0] = gid; x[1] = 73; /* catch errors */ +// if (setgroups(1,x) == -1) return -1; +//#else + if (setgroups(1,(gid_t *)&gid) == -1) return -1; +//#endif + return setgid(gid); /* _should_ be redundant, but on some systems it isn't */ +} + +int prot_uid(int uid) +{ + return setuid(uid); +} diff --git a/src/readclose.c b/src/readclose.c new file mode 100644 index 0000000..b0bce7e --- /dev/null +++ b/src/readclose.c @@ -0,0 +1,43 @@ +#include +#include "open.h" +#include "error.h" +#include "readclose.h" + +/** + @file readclose.c + @author kp + @source qlibs + @brief This is the successor of the older 'slurpclose.c' file. The function + 'slurpclose' is now called 'readclose_append'. The other function + 'readclose' was introduced here initial. +*/ + +int readclose_append(int fd,stralloc *sa,unsigned int bufsize) +{ + int r; + for (;;) { + if (!stralloc_readyplus(sa,bufsize)) { close(fd); return -1; } + r = read(fd,sa->s + sa->len,bufsize); + if (r == -1) if (errno == EINTR) continue; + if (r <= 0) { close(fd); return r; } + sa->len += r; + } +} + +int readclose(int fd,stralloc *sa,unsigned int bufsize) +{ + if (!stralloc_copys(sa,"")) { close(fd); return -1; } + return readclose_append(fd,sa,bufsize); +} + +int openreadclose(const char *fn,stralloc *sa,unsigned int bufsize) +{ + int fd; + fd = open_read((char *) fn); + if (fd == -1) { + if (errno == ENOENT) return 0; + return -1; + } + if (readclose(fd,sa,bufsize) == -1) return -1; + return 1; +} diff --git a/src/scan.c b/src/scan.c new file mode 100644 index 0000000..da3d8ad --- /dev/null +++ b/src/scan.c @@ -0,0 +1,120 @@ +#include "scan.h" + +/** + @file scan.c + @author djb + @source qmail, ucspi-tcp + @brief scanning/conversion of strings to different variable types +*/ + +static long int fromhex(unsigned char c) +{ + if (c>='0' && c<='9') + return c-'0'; + else if (c>='A' && c<='F') + return c-'A'+10; + else if (c>='a' && c<='f') + return c-'a'+10; + return -1; +} + +unsigned int scan_0x(register const char *s,register unsigned int *u) +{ + register unsigned int pos = 0; + register unsigned long result = 0; + register long int c; + + while ((c = fromhex((unsigned char) (s[pos]))) >= 0) { + result = (result << 4) + c; + ++pos; + } + *u = result; + return pos; +} + +unsigned int scan_8long(register const char *s,register unsigned long *u) +{ + register unsigned int pos = 0; + register unsigned long result = 0; + register unsigned long c; + + while ((c = (unsigned long) (unsigned char) (s[pos] - '0')) < 8) { + result = result * 8 + c; + ++pos; + } + *u = result; + return pos; +} + +unsigned int scan_uint(register const char *s,register unsigned int *u) +{ + register unsigned int pos; + unsigned long result; + + pos = scan_ulong(s,&result); + *u = result; + return pos; +} + +unsigned int scan_plusminus(register const char *s,register int *sign) +{ + if (*s == '+') { *sign = 1; return 1; } + if (*s == '-') { *sign = -1; return 1; } + *sign = 1; return 0; +} + +unsigned int scan_long(register const char *s,register long *i) +{ + int sign; + unsigned long u; + register unsigned int len; + + len = scan_plusminus(s,&sign); s += len; + len += scan_ulong(s,&u); + if (sign < 0) *i = -u; else *i = u; + return len; +} + + +unsigned int scan_ulong(register const char *s,register unsigned long *u) +{ + register unsigned int pos = 0; + register unsigned long result = 0; + register unsigned long c; + + while ((c = (unsigned long) (unsigned char) (s[pos] - '0')) < 10) { + result = result * 10 + c; + ++pos; + } + *u = result; + return pos; +} + +unsigned int scan_xlong(const char *s,unsigned long *u) +{ + register const char *t = s; + register int l = 0; + register unsigned char c; + + while ((c = fromhex(*t)) < 16) { + l = (l<<4)+c; + ++t; + } + *u=l; + return t-s; +} + +unsigned int scan_xint(const char *s,unsigned int *i) +{ + register const char *t = s; + register unsigned int l = 0; + register unsigned char c; + + while ((l >> (sizeof(l)*8 - 4)) == 0 + && (c = (unsigned char)fromhex((unsigned char)*t))<16) { + l= (l << 4) + c; + ++t; + } + *i = l; + return (unsigned int)(t-s); +} diff --git a/src/seek.c b/src/seek.c new file mode 100644 index 0000000..ac761a9 --- /dev/null +++ b/src/seek.c @@ -0,0 +1,30 @@ +#include +#include "seek.h" + +/** + @file seek.c + @author djb + @source qmail + @brief seek in an open file descritor +*/ + +off_t lseek(int fd,off_t offset,int whence); +int ftruncate(int fd, off_t length); + +#define CUR 1 /* sigh */ + +seek_pos seek_cur(int fd) +{ return lseek(fd,(off_t) 0,CUR); } + +#define END 2 /* sigh */ + +int seek_end(int fd) +{ if (lseek(fd,(off_t) 0,END) == -1) return -1; return 0; } + +#define SET 0 /* sigh */ + +int seek_set(int fd,seek_pos pos) +{ if (lseek(fd,(off_t) pos,SET) == -1) return -1; return 0; } + +int seek_trunc(int fd,seek_pos pos) +{ return ftruncate(fd,(off_t) pos); } diff --git a/src/sharedlib b/src/sharedlib new file mode 100755 index 0000000..3bf4f26 --- /dev/null +++ b/src/sharedlib @@ -0,0 +1,2 @@ +#!/bin/sh +exec cc -shared ${1+"$@"} diff --git a/src/sig.c b/src/sig.c new file mode 100644 index 0000000..0963948 --- /dev/null +++ b/src/sig.c @@ -0,0 +1,110 @@ +#include +#include "sig.h" + +/** + @file sig.c + @author djb + @source qmail + @brief signal handling functions +*/ + +void sig_alarmblock() { sig_block(SIGALRM); } +void sig_alarmunblock() { sig_unblock(SIGALRM); } +void sig_alarmcatch(f) void (*f)(); { sig_catch(SIGALRM,f); } +void sig_alarmdefault() { sig_catch(SIGALRM,SIG_DFL); } +int sig_alarm = SIGALRM; + +void sig_block(int sig) +{ + sigset_t ss; + sigemptyset(&ss); + sigaddset(&ss,sig); + sigprocmask(SIG_BLOCK,&ss,(sigset_t *) 0); +} + +void sig_unblock(int sig) +{ + sigset_t ss; + sigemptyset(&ss); + sigaddset(&ss,sig); + sigprocmask(SIG_UNBLOCK,&ss,(sigset_t *) 0); +} + +void sig_blocknone() +{ + sigset_t ss; + sigemptyset(&ss); + sigprocmask(SIG_SETMASK,&ss,(sigset_t *) 0); +} + +void sig_catch(int sig,void (*f)()) +{ + struct sigaction sa; + sa.sa_handler = f; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sigaction(sig,&sa,(struct sigaction *) 0); +} + +void sig_pause() +{ + sigset_t ss; + sigemptyset(&ss); + sigsuspend(&ss); +} + +void sig_pipeignore() { sig_catch(SIGPIPE,SIG_IGN); } +void sig_pipedefault() { sig_catch(SIGPIPE,SIG_DFL); } +int sig_pipe = SIGPIPE; + +void sig_childblock() { sig_block(SIGCHLD); } +void sig_childunblock() { sig_unblock(SIGCHLD); } +void sig_childcatch(f) void (*f)(); { sig_catch(SIGCHLD,f); } +void sig_childdefault() { sig_catch(SIGCHLD,SIG_DFL); } +int sig_child = SIGCHLD; + +void sig_hangupblock() { sig_block(SIGHUP); } +void sig_hangupunblock() { sig_unblock(SIGHUP); } +void sig_hangupcatch(f) void (*f)(); { sig_catch(SIGHUP,f); } +void sig_hangupdefault() { sig_catch(SIGHUP,SIG_DFL); } +int sig_hangup = SIGHUP; + +void sig_termblock() { sig_block(SIGTERM); } +void sig_termunblock() { sig_unblock(SIGTERM); } +void sig_termcatch(f) void (*f)(); { sig_catch(SIGTERM,f); } +void sig_termdefault() { sig_catch(SIGTERM,SIG_DFL); } +int sig_term = SIGTERM; + +void sig_bugcatch(void (*f)()) +{ + sig_catch(SIGILL,f); + sig_catch(SIGABRT,f); + sig_catch(SIGFPE,f); + sig_catch(SIGBUS,f); + sig_catch(SIGSEGV,f); +#ifdef SIGSYS + sig_catch(SIGSYS,f); +#endif +#ifdef SIGEMT + sig_catch(SIGEMT,f); +#endif +} +void (*sig_defaulthandler)() = SIG_DFL; + +void sig_miscignore() +{ + sig_catch(SIGVTALRM,SIG_IGN); + sig_catch(SIGPROF,SIG_IGN); + sig_catch(SIGQUIT,SIG_IGN); + sig_catch(SIGINT,SIG_IGN); + sig_catch(SIGHUP,SIG_IGN); +#ifdef SIGXCPU + sig_catch(SIGXCPU,SIG_IGN); +#endif +#ifdef SIGXFSZ + sig_catch(SIGXFSZ,SIG_IGN); +#endif +} +void (*sig_ignorehandler)() = SIG_IGN; + +int sig_cont = SIGCONT; diff --git a/src/socket_bind.c b/src/socket_bind.c new file mode 100644 index 0000000..b942e20 --- /dev/null +++ b/src/socket_bind.c @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include "byte.h" +#include "socket_if.h" +#include "ip.h" + +/** + @file socket_bind.c + @author djb, fefe, feh + @source qmail, djbdns, ucspi-tcp6 + @brief binding a socket to a local resource +*/ + +int socket_bind4(int s,const char ip[4],uint16 port) +{ + struct sockaddr_in sa; + + byte_zero(&sa,sizeof(sa)); + sa.sin_family = AF_INET; + uint16_pack_big((char *)&sa.sin_port,port); + byte_copy((char *)&sa.sin_addr,4,ip); + + return bind(s,(struct sockaddr *)&sa,sizeof(sa)); +} + +int socket_bind4_reuse(int s,const char ip[4],uint16 port) +{ + int opt = 1; + setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); + return socket_bind4(s,ip,port); +} + +/* seems not to be used here -- djbdns requires it */ +void socket_tryreservein(int s,int size) +{ + while (size >= 1024) { + if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size)) == 0) return; + size -= (size >> 5); + } +} + +int socket_bind6(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + struct sockaddr_in6 sa; + + byte_zero(&sa,sizeof(sa)); + sa.sin6_family = AF_INET6; + uint16_pack_big((char *)&sa.sin6_port,port); +/* implicit: sa.sin6_flowinfo = 0; */ + byte_copy((char *)&sa.sin6_addr,16,ip); + sa.sin6_scope_id = scope_id; + + return bind(s,(struct sockaddr *)&sa,sizeof(sa)); +} + +int socket_bind6_reuse(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + int opt = 1; + setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); + return socket_bind6(s,ip,port,scope_id); +} + +int socket_bind(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + if (ip6_isv4mapped(ip)) + return socket_bind4(s,ip + 12,port); + + return socket_bind6(s,ip,port,scope_id); +} + +int socket_bind_reuse(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + if (ip6_isv4mapped(ip)) + return socket_bind4_reuse(s,ip + 12,port); + + return socket_bind6_reuse(s,ip,port,scope_id); +} diff --git a/src/socket_connect.c b/src/socket_connect.c new file mode 100644 index 0000000..7b20659 --- /dev/null +++ b/src/socket_connect.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include +#include "byte.h" +#include "socket_if.h" +#include "ip.h" + +/** + @file socket_connect.c + @author djb, fefe, feh, kp + @source qmail, ucscpi-tcp6 + @brief connection to remote IP host +*/ + +int socket_connect6(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + struct sockaddr_in6 sa; + + byte_zero(&sa,sizeof(sa)); + sa.sin6_family = AF_INET6; + uint16_pack_big((char *)&sa.sin6_port,port); + sa.sin6_flowinfo = 0; + sa.sin6_scope_id = scope_id; + byte_copy((char *)&sa.sin6_addr,16,ip); + + return connect(s,(struct sockaddr *)&sa,sizeof(sa)); +} + +/* this explizit declaration is needed to prevent compiler warnings */ +int read(int _str, void *_buf, int _b); + +int socket_connect4(int s,const char ip[4],uint16 port) +{ + struct sockaddr_in sa; + + byte_zero(&sa,sizeof(sa)); + sa.sin_family = AF_INET; + uint16_pack_big((char *)&sa.sin_port,port); + byte_copy((char *)&sa.sin_addr,4,ip); + + return connect(s,(struct sockaddr *)&sa,sizeof(sa)); +} + +int socket_connect(int s,const char ip[16],uint16 port,uint32 scope_id) +{ + if (ip6_isv4mapped(ip)) + return socket_connect4(s,ip + 12,port); + + return socket_connect6(s,ip,port,scope_id); +} + +int socket_connected(int s) +{ + struct sockaddr_in6 sa; + int dummy; + char ch; + + dummy = sizeof(sa); + if (getpeername(s,(struct sockaddr *)&sa,(socklen_t *)&dummy) == -1) { + read(s,&ch,1); /* sets errno */ + return 0; + } + return 1; +} diff --git a/src/socket_if.c b/src/socket_if.c new file mode 100644 index 0000000..f55af4e --- /dev/null +++ b/src/socket_if.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include +#include "socket_if.h" + +/** + @file socket_if.c + @author fefe, feh + @source ucspi-tcp6 + @brief interface handling for LLU +*/ + +const unsigned char V4loopback[4] = {127,0,0,1}; +const unsigned char V4localnet[4] = {0,0,0,0}; +/* the 'V4mappedprefix' constant is needed by 'ip.a' too */ +const unsigned char V4mappedprefix[12] = {0,0,0,0, 0,0,0,0, 0,0,0xff,0xff}; +const unsigned char V6localnet[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; +const unsigned char V6loopback[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1}; + +uint32 socket_getifidx(const char *ifname) +{ + return if_nametoindex(ifname); +} + +static char ifname[IFNAMSIZ]; + +const char* socket_getifname(uint32 scope_id) +{ + char *tmp = if_indextoname(scope_id,ifname); + if (tmp) + return tmp; + else + return "[unknown]"; +} diff --git a/src/socket_info.c b/src/socket_info.c new file mode 100644 index 0000000..e644798 --- /dev/null +++ b/src/socket_info.c @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include "byte.h" +#include "socket_if.h" +#include "ip.h" + +/** + @file socket_info.c + @author djb, fefe, feh + @source ucspi-tcp6 + @brief querying local and remote info for socket +*/ + +int socket_local(int s,char ip[16],uint16 *port,uint32 *scope_id) +{ + struct sockaddr_in6 sa; + unsigned int dummy = sizeof(sa); + + if (getsockname(s,(struct sockaddr *)&sa,&dummy) == -1) return -1; + + if (sa.sin6_family == AF_INET) { + struct sockaddr_in *sa4 = (struct sockaddr_in*)&sa; + byte_copy(ip,12,V4mappedprefix); + byte_copy(ip+12,4,(char *)&sa4->sin_addr); + uint16_unpack_big((char *)&sa4->sin_port,port); + if (scope_id) *scope_id = 0; + } else { + byte_copy(ip,16,(char *)&sa.sin6_addr); + uint16_unpack_big((char *)&sa.sin6_port,port); + if (scope_id) *scope_id = sa.sin6_scope_id; + } + + return 0; +} + +int socket_remote(int s,char ip[16],uint16 *port,uint32 *scope_id) +{ + struct sockaddr_in6 sa; + unsigned int dummy = sizeof(sa); + + if (getpeername(s,(struct sockaddr *)&sa,&dummy) == -1) return -1; + + if (sa.sin6_family == AF_INET) { + struct sockaddr_in *sa4 = (struct sockaddr_in*)&sa; + byte_copy(ip,12,V4mappedprefix); + byte_copy(ip+12,4,(char *)&sa4->sin_addr); + uint16_unpack_big((char *)&sa4->sin_port,port); + *scope_id = 0; + } else { + byte_copy(ip,16,(char *)&sa.sin6_addr); + uint16_unpack_big((char *)&sa.sin6_port,port); + *scope_id = sa.sin6_scope_id; + } + + return 0; +} diff --git a/src/socket_recv.c b/src/socket_recv.c new file mode 100644 index 0000000..de8c856 --- /dev/null +++ b/src/socket_recv.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include "byte.h" +#include "ip.h" +#include "socket_if.h" + +/** + @file socket_recv.c + @author djb, fefe + @source ucspi-tcp6 + @brief setup receiving socket +*/ + +int socket_recv(int s,char *buf,unsigned int len,char ip[16],uint16 *port,uint32 *scope_id) +{ + struct sockaddr_in6 sa; + unsigned int dummy = sizeof(sa); + int r; + + byte_zero(&sa,dummy); + r = recvfrom(s,buf,len,0,(struct sockaddr *)&sa,&dummy); + if (r == -1) return -1; + + if (sa.sin6_family == AF_INET) { + struct sockaddr_in *sa4 = (struct sockaddr_in *)&sa; + byte_copy(ip,12,V4mappedprefix); + byte_copy(ip+12,4,(char *)&sa4->sin_addr); + uint16_unpack_big((char *)&sa4->sin_port,port); + if (scope_id) *scope_id = 0; + } else { + byte_copy(ip,16,(char *)&sa.sin6_addr); + uint16_unpack_big((char *)&sa.sin6_port,port); + if (scope_id) *scope_id = sa.sin6_scope_id; + } + + return r; +} diff --git a/src/socket_send.c b/src/socket_send.c new file mode 100644 index 0000000..9f09520 --- /dev/null +++ b/src/socket_send.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include "byte.h" +#include "ip.h" +#include "socket_if.h" + +/** + @file socket_send.c + @author djb, fefe, feh + @source ucspi-tcp6 + @brief setup sending socket +*/ + +int socket_send4(int s,const char *buf,unsigned int len,const char ip[4],uint16 port) +{ + struct sockaddr_in sa; + + byte_zero(&sa,sizeof(sa)); + + sa.sin_family = AF_INET; + uint16_pack_big((char *)&sa.sin_port,port); + byte_copy((char *)&sa.sin_addr,4,ip); + + return sendto(s,buf,len,0,(struct sockaddr *)&sa,sizeof(sa)); +} + +int socket_send6(int s,const char *buf,unsigned int len,const char ip[16],uint16 port,uint32 scope_id) +{ + struct sockaddr_in6 sa; + + byte_zero(&sa,sizeof(sa)); + + sa.sin6_family = AF_INET6; + sa.sin6_scope_id = scope_id; + uint16_pack_big((char *)&sa.sin6_port,port); + byte_copy((char *)&sa.sin6_addr,16,ip); + + return sendto(s,buf,len,0,(struct sockaddr *)&sa,sizeof(sa)); +} + +int socket_send(int s,const char *buf,unsigned int len,const char ip[16],uint16 port,uint32 scope_id) +{ + if (ip6_isv4mapped(ip)) + return socket_send4(s,buf,len,ip + 12,port); + else + return socket_send6(s,buf,len,ip,port,scope_id); +} + +int socket_broadcast4(int s,const char *buf,unsigned int len,uint16 port) +{ + struct sockaddr_in sa; + + byte_zero(&sa,sizeof(sa)); + + sa.sin_family = AF_INET; + uint16_pack_big((char *)&sa.sin_port,port); + byte_copy((char *)&sa.sin_addr,4,V4broadcast); + + return sendto(s,buf,len,0,(struct sockaddr *)&sa,sizeof(sa)); +} diff --git a/src/socket_setup.c b/src/socket_setup.c new file mode 100644 index 0000000..fb65fa2 --- /dev/null +++ b/src/socket_setup.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include +#include "byte.h" +#include "socket_if.h" +#include "ip.h" + +/** + @file socket_setup.c + @author djb, feh + @source ucspi-tcp6 + @brief setup listening socket +*/ + +int socket_accept(int s,char ip[16],uint16 *port,uint32 *scope_id) +{ + struct sockaddr_in6 sa; + unsigned int dummy = sizeof(sa); + int fd; + + fd = accept(s,(struct sockaddr *)&sa,&dummy); + if (fd == -1) return -1; + + if (sa.sin6_family == AF_INET) { + struct sockaddr_in *sa4 = (struct sockaddr_in*)&sa; + byte_copy(ip,12,V4mappedprefix); + byte_copy(ip+12,4,(char *)&sa4->sin_addr); + uint16_unpack_big((char *)&sa4->sin_port,port); + if (scope_id) *scope_id = 0; + } else { + byte_copy(ip,16,(char *)&sa.sin6_addr); + uint16_unpack_big((char *)&sa.sin6_port,port); + if (scope_id) *scope_id = sa.sin6_scope_id; + } + + return fd; +} + +int socket_accept4(int s,char ip[4],uint16 *port) +{ + struct sockaddr_in sa; + unsigned int dummy = sizeof(sa); + int fd; + + fd = accept(s,(struct sockaddr *) &sa,&dummy); + if (fd == -1) return -1; + + byte_copy(ip,4,(char *) &sa.sin_addr); + uint16_unpack_big((char *) &sa.sin_port,port); + + return fd; +} + +int socket_listen(int s,int backlog) +{ + return listen(s,backlog); +} + +int socket_ipoptionskill(int s) +{ + int r; + + r = setsockopt(s,IPPROTO_IP,1,(char *) 0,0); /* 1 == IP_OPTIONS */ + r = setsockopt(s,IPPROTO_IPV6,1,(char *) 0,0); + + return r; +} + +int socket_ip6anycast(int s) +{ + int opt = 1; + int r; + +#ifdef GEN_IP_PKTINFO /* Linux */ + r = setsockopt(s,IPPROTO_IP,GEN_IP_PKTINFO,&opt,sizeof(opt)); +#elif IP_PKTINFO /* Solaris */ + r = setsockopt(s,IPPROTO_IP,IP_PKTINFO,&opt,sizeof(opt)); +#elif IP_RECVDSTADDR /* BSD */ + r = setsockopt(s,IPPROTO_IP,IP_RECVDSTADDR,&opt,sizeof(opt)); +#elif IPV6_RECVDSTADDR + r = setsockopt(s,IPPROTO_IPV6,IP_RECVDSTADDR,&opt,sizeof(opt)); +#endif + return r; +} + +int socket_dualstack(int s) +{ + int opt = 0; + + return setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&opt,sizeof(opt)); +} + +int socket_nodualstack(int s) +{ + int opt = 1; + + return setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&opt,sizeof(opt)); +} diff --git a/src/socket_tcp.c b/src/socket_tcp.c new file mode 100644 index 0000000..1ff050e --- /dev/null +++ b/src/socket_tcp.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include "close.h" /* better use unistd.h ? */ +#include "ndelay.h" +#include "socket_if.h" +#include "error.h" + +#ifndef EAFNOSUPPORT +#define EAFNOSUPPORT EINVAL +#endif + +/** + @file socket_tcp.c + @author djb, fefe, feh + @source ucspi-tcp6 + @brief setup TCP stream socket +*/ + +int socket_tcp4(void) +{ + int s; + + s = socket(AF_INET,SOCK_STREAM,0); + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} + +int socket_tcp6(void) +{ + int s; + + s = socket(AF_INET6,SOCK_STREAM,0); + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} + +int socket_tcp(void) +{ + int s; + + s = socket(AF_INET6,SOCK_STREAM,0); + if (s == -1) + if (errno == EINVAL || errno == EAFNOSUPPORT || errno == EPROTO || errno == EPROTONOSUPPORT) + s = socket(AF_INET,SOCK_STREAM,0); + + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} + +int socket_tcpnodelay(int s) +{ + int opt = 1; + return setsockopt(s,IPPROTO_TCP,1,&opt,sizeof(opt)); /* 1 == TCP_NODELAY */ +} diff --git a/src/socket_udp.c b/src/socket_udp.c new file mode 100644 index 0000000..743cdf1 --- /dev/null +++ b/src/socket_udp.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include +#include "close.h" /* better use unistd.h ? */ +#include "ndelay.h" +#include "socket_if.h" +#include "error.h" + +#ifndef EAFNOSUPPORT +#define EAFNOSUPPORT EINVAL +#endif + +/** + @file socket_udp.c + @author djb, fefe, feh + @source ucspi-tcp6 + @brief setup a UDP message socket +*/ + +int socket_udp6(void) +{ + int s; + + s = socket(AF_INET6,SOCK_DGRAM,0); + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} + +int socket_udp4(void) +{ + int s; + + s = socket(AF_INET,SOCK_DGRAM,0); + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} + +int socket_udp(void) +{ + int s; + + s = socket(AF_INET6,SOCK_DGRAM,0); + if (s == -1) + if (errno == EINVAL || errno == EAFNOSUPPORT || errno == EPROTO || errno == EPROTONOSUPPORT) + s = socket(AF_INET,SOCK_DGRAM,0); + + if (s != -1) + if (ndelay_on(s) == -1) { close(s); return -1; } + + return s; +} diff --git a/src/str.c b/src/str.c new file mode 100644 index 0000000..7d5ab5e --- /dev/null +++ b/src/str.c @@ -0,0 +1,135 @@ +#include "str.h" +#include "stralloc.h" + +/** + @file str.c + @author djb + @source qmail + @brief string handling functions +*/ + +unsigned int str_copy(register char *s,register const char *t) +{ + register int len; + + len = 0; + for (;;) { + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + } +} + +unsigned int str_copyb(register char *s,register const char *t,unsigned int max) +{ + register int len; + + len = 0; + + while (max-- > 0) { + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + if (!(*s = *t)) { return len; } ++s; ++t; ++len; + } + + return len; +} + +int str_diff(register const char *s,register const char *t) +{ + register char x; + + for (;;) { + x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + } + return ((int)(unsigned int)(unsigned char) x) + - ((int)(unsigned int)(unsigned char) *t); +} + +int str_diffn(register const char *s,register const char *t,unsigned int len) +{ + register char x; + + for (;;) { + if (!len--) { return 0; } x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + if (!len--) { return 0; } x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + if (!len--) { return 0; } x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + if (!len--) { return 0; } x = *s; if (x != *t) { break; } if (!x) { break; } ++s; ++t; + } + return ((int)(unsigned int)(unsigned char) x) + - ((int)(unsigned int)(unsigned char) *t); +} + +unsigned int str_len(register const char *s) +{ + register const char *t; + + t = s; + for (;;) { + if (!*t) { return t - s; } ++t; + if (!*t) { return t - s; } ++t; + if (!*t) { return t - s; } ++t; + if (!*t) { return t - s; } ++t; + } +} + +unsigned int str_chr(register const char *s,int c) +{ + register char ch; + register const char *t; + + ch = c; + t = s; + for (;;) { + if (!*t) { break; } if (*t == ch) { break; } ++t; + if (!*t) { break; } if (*t == ch) { break; } ++t; + if (!*t) { break; } if (*t == ch) { break; } ++t; + if (!*t) { break; } if (*t == ch) { break; } ++t; + } + return t - s; +} + +unsigned int str_rchr(register const char *s,int c) +{ + register char ch; + register const char *t; + register const char *u; + + ch = c; + t = s; + u = 0; + for (;;) { + if (!*t) { break; } if (*t == ch) { u = t; } ++t; + if (!*t) { break; } if (*t == ch) { u = t; } ++t; + if (!*t) { break; } if (*t == ch) { u = t; } ++t; + if (!*t) { break; } if (*t == ch) { u = t; } ++t; + } + if (!u) u = t; + return u - s; +} + +int str_start(register const char *s,register const char *t) +{ + register char x; + + for (;;) { + x = *t++; if (!x) return 1; if (x != *s++) return 0; + x = *t++; if (!x) return 1; if (x != *s++) return 0; + x = *t++; if (!x) return 1; if (x != *s++) return 0; + x = *t++; if (!x) return 1; if (x != *s++) return 0; + } +} + +char *str_append(char *dest, char const *s) +{ + static stralloc sa = {0}; + + stralloc_copys(&sa,dest); + stralloc_catb(&sa,s,sizeof(s)); + return sa.s; +} diff --git a/src/stralloc.c b/src/stralloc.c new file mode 100644 index 0000000..8c0335e --- /dev/null +++ b/src/stralloc.c @@ -0,0 +1,126 @@ +#include +#include "byte.h" +#include "str.h" +#include "stralloc.h" +#include "alloc.h" + +/** + @file stralloc.c + @author djb + @source qmail, ucspi-tcp + @brief genious dynamic string handling +*/ + +int stralloc_starts(stralloc *sa,const char *s) +{ + int len; + len = str_len(s); + return (sa->len >= len) && byte_equal(s,len,sa->s); +} + +int stralloc_cat(stralloc *sato,stralloc *safrom) +{ + return stralloc_catb(sato,safrom->s,safrom->len); +} + +int stralloc_catb(stralloc *sa,const char *s,unsigned int n) +{ + if (!sa->s) return stralloc_copyb(sa,s,n); + if (!stralloc_readyplus(sa,n + 1)) return 0; + byte_copy(sa->s + sa->len,n,s); + sa->len += n; + sa->s[sa->len] = 'Z'; /* ``offensive programming'' */ + return 1; +} + +int stralloc_cats(stralloc *sa,const char *s) +{ + return stralloc_catb(sa,s,str_len(s)); +} + +int stralloc_copy(stralloc *sato,stralloc *safrom) +{ + return stralloc_copyb(sato,safrom->s,safrom->len); +} + + +int stralloc_ready(stralloc *sa,size_t len) +{ + register size_t wanted = len+(len>>3)+30; /* heuristic from djb */ + if (wanteds || sa->as,wanted))) // !!! needs stdlib (realloc) + return 0; + sa->a = wanted; + sa->s = tmp; + } + return 1; +} + +int stralloc_readyplus(stralloc *sa,size_t len) +{ + if (sa->s) { + if (sa->len + len < len) return 0; /* catch integer overflow */ + return stralloc_ready(sa,sa->len+len); + } else + return stralloc_ready(sa,len); +} + +int stralloc_copyb(stralloc *sa,const char *s,unsigned int n) +{ + if (!stralloc_ready(sa,n + 1)) return 0; + byte_copy(sa->s,n,s); + sa->len = n; + sa->s[n] = 'Z'; /* ``offensive programming'' */ + return 1; +} + +int stralloc_copys(stralloc *sa,const char *s) +{ + return stralloc_copyb(sa,s,str_len(s)); +} + +int stralloc_catulong0(stralloc *sa,unsigned long u,unsigned int n) +{ + unsigned int len; + unsigned long q; + char *s; + + len = 1; + q = u; + while (q > 9) { ++len; q /= 10; } + if (len < n) len = n; + + if (!stralloc_readyplus(sa,len)) return 0; + s = sa->s + sa->len; + sa->len += len; + while (len) { s[--len] = '0' + (u % 10); u /= 10; } + + return 1; +} + +int stralloc_catlong0(stralloc *sa,long l,unsigned int n) +{ + if (l < 0) { + if (!stralloc_append(sa,"-")) return 0; + l = -l; + } + return stralloc_catulong0(sa,l,n); +} + +int stralloc_append(stralloc *sa,const char *in) +{ + if (stralloc_readyplus(sa,1)) { + sa->s[sa->len] = *in; + ++sa->len; + return 1; + } + return 0; +} + +void stralloc_free(stralloc *sa) { + if (sa->s) free(sa->s); + sa->s = 0; + sa->a = sa->len = 0; +} diff --git a/src/tai.c b/src/tai.c new file mode 100644 index 0000000..65a8225 --- /dev/null +++ b/src/tai.c @@ -0,0 +1,59 @@ +#include +#include "tai.h" + +/** + @file tai.c + @author djb + @source qmail + @brief 'temps atomic' time handling +*/ + +void tai_add(struct tai *t,const struct tai *u,const struct tai *v) +{ + t->x = u->x + v->x; +} + +void tai_now(struct tai *t) +{ + tai_unix(t,time((time_t *) 0)); +} + +void tai_pack(char *s,const struct tai *t) +{ + uint64 x; + + x = t->x; + s[7] = (char)x; x >>= 8; + s[6] = (char)x; x >>= 8; + s[5] = (char)x; x >>= 8; + s[4] = (char)x; x >>= 8; + s[3] = (char)x; x >>= 8; + s[2] = (char)x; x >>= 8; + s[1] = (char)x; x >>= 8; + s[0] = (char)x; +} + +void tai_sub(struct tai *t,const struct tai *u,const struct tai *v) +{ + t->x = u->x - v->x; +} + +void tai_uint(struct tai *t,unsigned int u) +{ + t->x = u; +} + +void tai_unpack(const char *s,struct tai *t) +{ + uint64 x; + + x = (unsigned char) s[0]; + x <<= 8; x += (unsigned char) s[1]; + x <<= 8; x += (unsigned char) s[2]; + x <<= 8; x += (unsigned char) s[3]; + x <<= 8; x += (unsigned char) s[4]; + x <<= 8; x += (unsigned char) s[5]; + x <<= 8; x += (unsigned char) s[6]; + x <<= 8; x += (unsigned char) s[7]; + t->x = x; +} diff --git a/src/taia.c b/src/taia.c new file mode 100644 index 0000000..22bd816 --- /dev/null +++ b/src/taia.c @@ -0,0 +1,104 @@ +#include +#include +#include "taia.h" + +/** + @file taia.c + @author djb + @source qmail + @brief 'tai' attosecond time handling +*/ + +/* XXX: breaks tai encapsulation */ + +void taia_add(struct taia *t,struct taia *u,struct taia *v) +{ + t->sec.x = u->sec.x + v->sec.x; + t->nano = u->nano + v->nano; + t->atto = u->atto + v->atto; + if (t->atto > 999999999UL) { + t->atto -= 1000000000UL; + ++t->nano; + } + if (t->nano > 999999999UL) { + t->nano -= 1000000000UL; + ++t->sec.x; + } +} + +double taia_approx(struct taia *t) +{ + return tai_approx(&t->sec) + taia_frac(t); +} + +double taia_frac(struct taia *t) +{ + return (t->atto * 0.000000001 + t->nano) * 0.000000001; +} + +int taia_less(struct taia *t,struct taia *u) +{ + if (t->sec.x < u->sec.x) return 1; + if (t->sec.x > u->sec.x) return 0; + if (t->nano < u->nano) return 1; + if (t->nano > u->nano) return 0; + return t->atto < u->atto; +} + +int taia_now(struct taia *t) +{ + struct timeval now; + if (gettimeofday(&now,(struct timezone *) 0) == 0) { + tai_unix(&t->sec,now.tv_sec); + t->nano = 1000 * now.tv_usec + 500; + t->atto = 0; + return 0; + } + t->nano = 0; + t->atto = 0; + return -1; +} + +void taia_pack(char *s,struct taia *t) +{ + unsigned long x; + + tai_pack(s,&t->sec); + s += 8; + + x = t->atto; + s[7] = x & 255; x >>= 8; + s[6] = x & 255; x >>= 8; + s[5] = x & 255; x >>= 8; + s[4] = x; + x = t->nano; + s[3] = x & 255; x >>= 8; + s[2] = x & 255; x >>= 8; + s[1] = x & 255; x >>= 8; + s[0] = x; +} + +void taia_sub(struct taia *t,struct taia *u,struct taia *v) +{ + unsigned long unano = u->nano; + unsigned long uatto = u->atto; + + t->sec.x = u->sec.x - v->sec.x; + t->nano = unano - v->nano; + t->atto = uatto - v->atto; + if (t->atto > uatto) { + t->atto += 1000000000UL; + --t->nano; + } + if (t->nano > unano) { + t->nano += 1000000000UL; + --t->sec.x; + } +} + +void taia_uint(struct taia *t,unsigned int s) +{ + t->sec.x = s; + t->nano = 0; + t->atto = 0; +} diff --git a/src/timeout.c b/src/timeout.c new file mode 100644 index 0000000..e721b66 --- /dev/null +++ b/src/timeout.c @@ -0,0 +1,59 @@ +#include +#include "error.h" +#include "iopause.h" +#include "timeout.h" + +/** + @file timeout.c + @author djb + @source qmail + @brief read/write timeout handling +*/ + +int timeoutread(int t,int fd,char *buf,int len) +{ + struct taia now; + struct taia deadline; + iopause_fd x; + + taia_now(&now); + taia_uint(&deadline,t); + taia_add(&deadline,&now,&deadline); + + x.fd = fd; + x.events = IOPAUSE_READ; + for (;;) { + taia_now(&now); + iopause(&x,1,&deadline,&now); + if (x.revents) break; + if (taia_less(&deadline,&now)) { + errno = ETIMEDOUT; + return -1; + } + } + return read(fd,buf,len); +} + +int timeoutwrite(int t,int fd,char *buf,int len) +{ + struct taia now; + struct taia deadline; + iopause_fd x; + + taia_now(&now); + taia_uint(&deadline,t); + taia_add(&deadline,&now,&deadline); + + x.fd = fd; + x.events = IOPAUSE_WRITE; + for (;;) { + taia_now(&now); + iopause(&x,1,&deadline,&now); + if (x.revents) break; + if (taia_less(&deadline,&now)) { + errno = ETIMEDOUT; + return -1; + } + } + return write(fd,buf,len); +} diff --git a/src/timeoutconn.c b/src/timeoutconn.c new file mode 100644 index 0000000..c94f600 --- /dev/null +++ b/src/timeoutconn.c @@ -0,0 +1,112 @@ +#include "ndelay.h" +#include "socket_if.h" +#include "iopause.h" +#include "error.h" +#include "timeoutconn.h" +#include "ip.h" + +/** + @file timeoutconn.c + @author djb, fefe, feh + @source qmail + @brief socket read/write timeout handling; return code of iopause considered +*/ + +int timeoutconn4(int s,char ip[4],uint16 port,unsigned int timeout) +{ + struct taia now; + struct taia deadline; + iopause_fd x; + unsigned int p = 0; + + if (socket_connect4(s,ip,port) == -1) { + if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) return -1; + x.fd = s; + x.events = IOPAUSE_WRITE; + taia_now(&now); + taia_uint(&deadline,timeout); + taia_add(&deadline,&now,&deadline); + for (;;) { + taia_now(&now); + iopause(&x,1,&deadline,&now); + if (x.revents) break; /* 's' available */ + if (taia_less(&deadline,&now)) { + errno = ETIMEDOUT; /* note that connect attempt is continuing */ + return -1; + } + p++; + } + if (!socket_connected(s)) return -1; + } + + if (ndelay_off(s) == -1) return -1; + return 0; +} + +int timeoutconn6(int s,char ip[16],uint16 port,unsigned int timeout,uint32 netif) +{ + struct taia now; + struct taia deadline; + iopause_fd x; + unsigned int p = 0; + + if (socket_connect6(s,ip,port,netif) == -1) { + if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) return -1; + x.fd = s; + x.events = IOPAUSE_WRITE; + taia_now(&now); + taia_uint(&deadline,timeout); + taia_add(&deadline,&now,&deadline); + for (;;) { + taia_now(&now); + iopause(&x,1,&deadline,&now); + if (x.revents) break; /* 's' available */ + if (taia_less(&deadline,&now)) { + errno = ETIMEDOUT; /* note that connect attempt is continuing */ + return -1; + } + p++; + } + if (!socket_connected(s)) return -1; + } + + if (ndelay_off(s) == -1) return -1; + return 0; +} + +int timeoutconn(int s,char ip[16],uint16 port,unsigned int timeout,uint32 netif) +{ + struct taia now; + struct taia deadline; + iopause_fd x; + unsigned int p = 0; + int r; + + if (ip6_isv4mapped(ip)) + r = socket_connect4(s,ip + 12,port); + else + r = socket_connect6(s,ip,port,netif); + + if (r == -1) { + if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) return -1; + x.fd = s; + x.events = IOPAUSE_WRITE; + taia_now(&now); + taia_uint(&deadline,timeout); + taia_add(&deadline,&now,&deadline); + for (;;) { + taia_now(&now); + iopause(&x,1,&deadline,&now); + if (x.revents) break; /* 's' available */ + if (taia_less(&deadline,&now)) { + errno = ETIMEDOUT; /* note that connect attempt is continuing */ + return -1; + } + p++; + } + if (!socket_connected(s)) return -1; + } + + if (ndelay_off(s) == -1) return -1; + return 0; +} diff --git a/src/uint128p.c b/src/uint128p.c new file mode 100644 index 0000000..57c713e --- /dev/null +++ b/src/uint128p.c @@ -0,0 +1,100 @@ +#include "uint_t.h" + +/** + @file uint128p.c + @author feh, jannis + @source djbdns6 + @brief packing/unpacking 128 bit integer to/from char string +*/ + +void uint128_pack(char s[16],uint128 u) +{ + s[0] = u.lo & 255; u.lo >>= 8; + s[1] = u.lo & 255; u.lo >>= 8; + s[2] = u.lo & 255; u.lo >>= 8; + s[3] = u.lo & 255; u.lo >>= 8; + s[4] = u.lo & 255; u.lo >>= 8; + s[5] = u.lo & 255; u.lo >>= 8; + s[6] = u.lo & 255; u.lo >>= 8; + s[7] = u.lo & 255; u.lo >>= 8; + + s[8] = u.hi & 255; u.hi >>= 8; + s[9] = u.hi & 255; u.hi >>= 8; + s[10] = u.hi & 255; u.hi >>= 8; + s[11] = u.hi & 255; u.hi >>= 8; + s[12] = u.hi & 255; u.hi >>= 8; + s[13] = u.hi & 255; u.hi >>= 8; + s[14] = u.hi & 255; u.hi >>= 8; + s[15] = u.hi & 255; +} +void uint128_pack_big(char s[16],uint128 u) +{ + s[15] = u.lo & 255; u.lo >>= 8; + s[14] = u.lo & 255; u.lo >>= 8; + s[13] = u.lo & 255; u.lo >>= 8; + s[12] = u.lo & 255; u.lo >>= 8; + s[11] = u.lo & 255; u.lo >>= 8; + s[10] = u.lo & 255; u.lo >>= 8; + s[9] = u.lo & 255; u.lo >>= 8; + s[8] = u.lo & 255; u.lo >>= 8; + + s[7] = u.hi & 255; u.hi >>= 8; + s[6] = u.hi & 255; u.hi >>= 8; + s[5] = u.hi & 255; u.hi >>= 8; + s[4] = u.hi & 255; u.hi >>= 8; + s[3] = u.hi & 255; u.hi >>= 8; + s[2] = u.hi & 255; u.hi >>= 8; + s[1] = u.hi & 255; u.hi >>= 8; + s[0] = u.hi & 255; +} + +void uint128_unpack(char s[16],uint128 *u) +{ + uint128 result; + result.hi = result.lo = 0ULL; + + result.hi = (unsigned char) s[15]; result.hi <<= 8; + result.hi += (unsigned char) s[14]; result.hi <<= 8; + result.hi += (unsigned char) s[13]; result.hi <<= 8; + result.hi += (unsigned char) s[12]; result.hi <<= 8; + result.hi += (unsigned char) s[11]; result.hi <<= 8; + result.hi += (unsigned char) s[10]; result.hi <<= 8; + result.hi += (unsigned char) s[9]; result.hi <<= 8; + result.hi += (unsigned char) s[8]; //correct + + result.lo += (unsigned char) s[7]; result.lo <<= 8; + result.lo += (unsigned char) s[6]; result.lo <<= 8; + result.lo += (unsigned char) s[5]; result.lo <<= 8; + result.lo += (unsigned char) s[4]; result.lo <<= 8; + result.lo += (unsigned char) s[3]; result.lo <<= 8; + result.lo += (unsigned char) s[2]; result.lo <<= 8; + result.lo += (unsigned char) s[1]; result.lo <<= 8; + result.lo += (unsigned char) s[0]; + + *u = result; +} +void uint128_unpack_big(char s[16],uint128 *u) +{ + uint128 result; + result.hi = result.lo = 0ULL; + + result.hi = (unsigned char) s[0]; result.hi <<= 8; + result.hi += (unsigned char) s[1]; result.hi <<= 8; + result.hi += (unsigned char) s[2]; result.hi <<= 8; + result.hi += (unsigned char) s[3]; result.hi <<= 8; + result.hi += (unsigned char) s[4]; result.hi <<= 8; + result.hi += (unsigned char) s[5]; result.hi <<= 8; + result.hi += (unsigned char) s[6]; result.hi <<= 8; + result.hi += (unsigned char) s[7]; + + result.lo += (unsigned char) s[8]; result.lo <<= 8; + result.lo += (unsigned char) s[9]; result.lo <<= 8; + result.lo += (unsigned char) s[10]; result.lo <<= 8; + result.lo += (unsigned char) s[11]; result.lo <<= 8; + result.lo += (unsigned char) s[12]; result.lo <<= 8; + result.lo += (unsigned char) s[13]; result.lo <<= 8; + result.lo += (unsigned char) s[14]; result.lo <<= 8; + result.lo += (unsigned char) s[15]; + + *u = result; +} diff --git a/src/uint16p.c b/src/uint16p.c new file mode 100644 index 0000000..5dddf21 --- /dev/null +++ b/src/uint16p.c @@ -0,0 +1,40 @@ +#include "uint_t.h" + +/** + @file uint16p.c + @author djb + @source qmail + @brief packing/unpacking 16 bit integer to/from char string +*/ + +void uint16_pack(char s[2],uint16 u) +{ + s[0] = u & 255; + s[1] = u >> 8; +} + +void uint16_pack_big(char s[2],uint16 u) +{ + s[1] = u & 255; + s[0] = u >> 8; +} + +void uint16_unpack(char s[2],uint16 *u) +{ + uint16 result; + + result = (unsigned char) s[1]; result <<= 8; + result += (unsigned char) s[0]; + + *u = result; +} + +void uint16_unpack_big(char s[2],uint16 *u) +{ + uint16 result; + + result = (unsigned char) s[0]; result <<= 8; + result += (unsigned char) s[1]; + + *u = result; +} diff --git a/src/uint32p.c b/src/uint32p.c new file mode 100644 index 0000000..f3f04ea --- /dev/null +++ b/src/uint32p.c @@ -0,0 +1,47 @@ +#include "uint_t.h" + +/** + @file uint32p.c + @author djb + @source qmail + @brief packing/unpacking 32 bit integer to/from char string +*/ + +void uint32_pack(char s[4],uint32 u) +{ + s[0] = u & 255; u >>= 8; + s[1] = u & 255; u >>= 8; + s[2] = u & 255; + s[3] = u >> 8; +} +void uint32_pack_big(char s[4],uint32 u) +{ + s[3] = u & 255; u >>= 8; + s[2] = u & 255; u >>= 8; + s[1] = u & 255; + s[0] = u >> 8; +} + +void uint32_unpack(char s[4],uint32 *u) +{ + uint32 result; + + result = (unsigned char) s[3]; result <<= 8; + result += (unsigned char) s[2]; result <<= 8; + result += (unsigned char) s[1]; result <<= 8; + result += (unsigned char) s[0]; + + *u = result; +} + +void uint32_unpack_big(char s[4],uint32 *u) +{ + uint32 result; + + result = (unsigned char) s[0]; result <<= 8; + result += (unsigned char) s[1]; result <<= 8; + result += (unsigned char) s[2]; result <<= 8; + result += (unsigned char) s[3]; + + *u = result; +} diff --git a/src/uint64p.c b/src/uint64p.c new file mode 100644 index 0000000..41b8ceb --- /dev/null +++ b/src/uint64p.c @@ -0,0 +1,62 @@ +#include "uint_t.h" + +/** + @file uint64p.c + @author feh, jannis + @source djbdns6 + @brief packing/unpacking 64 bit integer to/from char string +*/ + +void uint64_pack(char s[8],uint64 u) +{ + s[0] = u & 255; u >>= 8; + s[1] = u & 255; u >>= 8; + s[2] = u & 255; u >>= 8; + s[3] = u & 255; u >>= 8; + s[4] = u & 255; u >>= 8; + s[5] = u & 255; u >>= 8; + s[6] = u & 255; u >>= 8; + s[7] = u & 255; +} +void uint64_pack_big(char s[8],uint64 u) +{ + s[7] = u & 255; u >>= 8; + s[6] = u & 255; u >>= 8; + s[5] = u & 255; u >>= 8; + s[4] = u & 255; u >>= 8; + s[3] = u & 255; u >>= 8; + s[2] = u & 255; u >>= 8; + s[1] = u & 255; u >>= 8; + s[0] = u & 255; +} + +void uint64_unpack(char s[8],uint64 *u) +{ + uint64 result; + + result = (unsigned char) s[7]; result <<= 8; + result += (unsigned char) s[6]; result <<= 8; + result += (unsigned char) s[5]; result <<= 8; + result += (unsigned char) s[4]; result <<= 8; + result += (unsigned char) s[3]; result <<= 8; + result += (unsigned char) s[2]; result <<= 8; + result += (unsigned char) s[1]; result <<= 8; + result += (unsigned char) s[0]; + + *u = result; +} +void uint64_unpack_big(char s[8],uint64 *u) +{ + uint64 result; + + result = (unsigned char) s[0]; result <<= 8; + result += (unsigned char) s[1]; result <<= 8; + result += (unsigned char) s[2]; result <<= 8; + result += (unsigned char) s[3]; result <<= 8; + result += (unsigned char) s[4]; result <<= 8; + result += (unsigned char) s[5]; result <<= 8; + result += (unsigned char) s[6]; result <<= 8; + result += (unsigned char) s[7]; + + *u = result; +} diff --git a/src/uint8p.c b/src/uint8p.c new file mode 100644 index 0000000..a7a1460 --- /dev/null +++ b/src/uint8p.c @@ -0,0 +1,39 @@ +#include "uint_t.h" + +/** + @file uint8x.c + @author feh + @brief packing/unpacking 8 bit int to/from char string +*/ + +void uint8_pack(char s[2],uint8 u) +{ + s[0] = u & 255; + s[1] = u >> 4; +} + +void uint8_pack_big(char s[2],uint8 u) +{ + s[1] = u & 255; + s[0] = u >> 4; +} + +void uint8_unpack(char s[2],uint8 *u) +{ + uint8 result; + + result = (unsigned char) s[1]; result <<= 4; + result += (unsigned char) s[0]; + + *u = result; +} + +void uint8_unpack_big(char s[2],uint8 *u) +{ + uint8 result; + + result = (unsigned char) s[0]; result <<= 4; + result += (unsigned char) s[1]; + + *u = result; +} diff --git a/src/wait.c b/src/wait.c new file mode 100644 index 0000000..869a120 --- /dev/null +++ b/src/wait.c @@ -0,0 +1,25 @@ +#include +#include +#include "logmsg.h" + +/** + @file wait.c + @author djb + @source qmail + @brief wait for forked processes +*/ + +int wait_nohang(int *wstat) +{ + return waitpid(-1,wstat,WNOHANG); +} + +int wait_pid(int *wstat,int pid) +{ + int r; + + do + r = waitpid(pid,wstat,0); + while ((r == -1) && (errno == EINTR)); + return r; +} -- cgit v1.2.3