path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/net/finger/fingersyn.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bsr.h" #include "libc/macros.internal.h" /** * Fingers IP+TCP SYN packet. * * This returns a hash-like magic number that reflects the SYN packet * structure, e.g. ordering of options, maximum segment size, etc. */ uint32_t FingerSyn(const char *p, size_t n) { uint32_t h = 0; int i, j, k, q, r, iplen, tcplen, ttl; if (n >= 20 + 20 && n >= (iplen = (p[0] & 0x0F) * 4) + 20 && n >= iplen + (tcplen = ((p[iplen + 12] & 0xF0) >> 4) * 4)) { n = iplen + tcplen; // Time to Live // ttl<=256 Crisco, Solaris 6 // ttl<=128 Windows, OpenVMS 8+ // ttl<=64 Mac, Linux, BSD, Solaris 8+, Tru64, HP-UX ttl = p[8] & 255; h += _bsr(MAX(1, ttl - 1)); h *= 0x9e3779b1; // TCP Options // We care about the order and presence of leading common options. for (j = 0, i = iplen + 20; i < n; ++j) { k = p[i] & 255; if (k == 0 || k == 1 || k == 2 || k == 3 || k == 4 || k == 8) { if (k <= 1) { ++i; } else if (i + 1 < n) { i += p[i + 1] & 255; } else { break; } } else { break; } h += j << 8 | k; h *= 0x9e3779b1; } if (!h) { ++h; } } return h; }
3,071
65
jart/cosmopolitan
false
cosmopolitan/net/finger/getsynfingeros.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/dce.h" #include "net/finger/finger.h" /** * Turns result of FingerprintSyn() into operating system. */ int GetSynFingerOs(uint32_t x) { switch (x) { case 0x7e7a6599: return _HOSTXNU; case 0xbb724187: return _HOSTLINUX; case 0xb228b212: return _HOSTWINDOWS; case 0x77c30887: return _HOSTFREEBSD; case 0xc45d694b: return _HOSTOPENBSD; default: return 0; } }
2,274
41
jart/cosmopolitan
false
cosmopolitan/net/https/certhashost.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/slice.h" #include "net/https/https.h" bool CertHasHost(const mbedtls_x509_crt *cert, const void *s, size_t n) { const mbedtls_x509_sequence *cur; for (cur = &cert->subject_alt_names; cur; cur = cur->next) { if ((cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) == MBEDTLS_X509_SAN_DNS_NAME) { if (cur->buf.len > 2 && cur->buf.p[0] == '*' && cur->buf.p[1] == '.') { // handle subject alt name like *.foo.com // - match examples // - bar.foo.com // - zoo.foo.com // - does not match // - foo.com // - zoo.bar.foo.com if (n > cur->buf.len - 1 && SlicesEqualCase((char *)s + n - (cur->buf.len - 1), cur->buf.len - 1, cur->buf.p + 1, cur->buf.len - 1) && !memchr(s, '.', n - (cur->buf.len - 1))) { return true; } } else { // handle subject alt name like foo.com if (SlicesEqualCase(s, n, cur->buf.p, cur->buf.len)) { return true; } } } } return false; }
2,946
52
jart/cosmopolitan
false
cosmopolitan/net/https/generatehardrandom.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/rand.h" #include "net/https/https.h" int GenerateHardRandom(void *ctx, unsigned char *p, size_t n) { rngset(p, n, rdseed, 0); return 0; }
2,000
26
jart/cosmopolitan
false
cosmopolitan/net/https/certhasip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "net/https/https.h" bool CertHasIp(const mbedtls_x509_crt *cert, uint32_t ip) { const mbedtls_x509_sequence *cur; for (cur = &cert->subject_alt_names; cur; cur = cur->next) { if ((cur->buf.tag & MBEDTLS_ASN1_TAG_VALUE_MASK) == MBEDTLS_X509_SAN_IP_ADDRESS && cur->buf.len == 4 && ip == READ32BE(cur->buf.p)) { return true; } } return false; }
2,260
33
jart/cosmopolitan
false
cosmopolitan/net/https/formatx509name.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "net/https/https.h" char *FormatX509Name(mbedtls_x509_name *name) { char *s = calloc(1, 1000); CHECK_GT(mbedtls_x509_dn_gets(s, 1000, name), 0); return s; }
2,037
27
jart/cosmopolitan
false
cosmopolitan/net/https/formatssltime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" void FormatSslTime(char p[restrict hasatleast 16], struct tm *tm) { p[0x0] = '0' + (tm->tm_year + 1900) / 1000; p[0x1] = '0' + (tm->tm_year + 1900) / 100 % 10; p[0x2] = '0' + (tm->tm_year + 1900) / 10 % 10; p[0x3] = '0' + (tm->tm_year + 1900) % 10; p[0x4] = '0' + (tm->tm_mon + 1) / 10; p[0x5] = '0' + (tm->tm_mon + 1) % 10; p[0x6] = '0' + tm->tm_mday / 10; p[0x7] = '0' + tm->tm_mday % 10; p[0x8] = '0' + tm->tm_hour / 10; p[0x9] = '0' + tm->tm_hour % 10; p[0xa] = '0' + tm->tm_min / 10; p[0xb] = '0' + tm->tm_min % 10; p[0xc] = '0' + tm->tm_sec / 10; p[0xd] = '0' + tm->tm_sec % 10; p[0xe] = 0; }
2,495
38
jart/cosmopolitan
false
cosmopolitan/net/https/https.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += NET_HTTPS NET_HTTPS_ARTIFACTS += NET_HTTPS_A NET_HTTPS = $(NET_HTTPS_A_DEPS) $(NET_HTTPS_A) NET_HTTPS_A = o/$(MODE)/net/https/https.a NET_HTTPS_A_FILES := $(wildcard net/https/*) NET_HTTPS_A_CERTS := $(wildcard usr/share/ssl/root/*) NET_HTTPS_A_HDRS = $(filter %.h,$(NET_HTTPS_A_FILES)) NET_HTTPS_A_SRCS = $(filter %.c,$(NET_HTTPS_A_FILES)) NET_HTTPS_A_OBJS = \ o/$(MODE)/usr/share/ssl/root/.zip.o \ $(NET_HTTPS_A_SRCS:%.c=o/$(MODE)/%.o) \ $(NET_HTTPS_A_CERTS:%=o/$(MODE)/%.zip.o) NET_HTTPS_A_CHECKS = \ $(NET_HTTPS_A).pkg \ $(NET_HTTPS_A_HDRS:%=o/$(MODE)/%.ok) NET_HTTPS_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_TIME \ LIBC_X \ LIBC_ZIPOS \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_MBEDTLS NET_HTTPS_A_DEPS := \ $(call uniq,$(foreach x,$(NET_HTTPS_A_DIRECTDEPS),$($(x)))) $(NET_HTTPS_A): net/https/ \ $(NET_HTTPS_A).pkg \ $(NET_HTTPS_A_OBJS) $(NET_HTTPS_A).pkg: \ $(NET_HTTPS_A_OBJS) \ $(foreach x,$(NET_HTTPS_A_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/usr/share/ssl/root/.zip.o: \ usr/share/ssl/root NET_HTTPS_LIBS = $(foreach x,$(NET_HTTPS_ARTIFACTS),$($(x))) NET_HTTPS_SRCS = $(foreach x,$(NET_HTTPS_ARTIFACTS),$($(x)_SRCS)) NET_HTTPS_HDRS = $(foreach x,$(NET_HTTPS_ARTIFACTS),$($(x)_HDRS)) NET_HTTPS_OBJS = $(foreach x,$(NET_HTTPS_ARTIFACTS),$($(x)_OBJS)) NET_HTTPS_CHECKS = $(foreach x,$(NET_HTTPS_ARTIFACTS),$($(x)_CHECKS)) .PHONY: o/$(MODE)/net/https o/$(MODE)/net/https: $(NET_HTTPS_CHECKS)
1,832
63
jart/cosmopolitan
false
cosmopolitan/net/https/sslcache.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/sslcache.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/errno.h" #include "libc/intrin/bits.h" #include "libc/intrin/cmpxchg.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/time/time.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/x509_crt.h" #define PROT (PROT_READ | PROT_WRITE) #define FLAGS MAP_SHARED static uint32_t HashSslSession(mbedtls_ssl_session *session) { int i; uint32_t h; h = session->ciphersuite; h *= 0x9e3779b1; h = session->compression; h *= 0x9e3779b1; for (i = 0; i < session->id_len; i++) { h += session->id[i]; h *= 0x9e3779b1; } return h; } static struct SslCache *OpenSslCache(const char *path, size_t size) { int fd; struct stat st; struct SslCache *c = NULL; if (path) { if ((fd = open(path, O_RDWR | O_CREAT, 0600)) != -1) { CHECK_NE(-1, fstat(fd, &st)); if (st.st_size && st.st_size != size) { WARNF("unlinking sslcache because size changed from %,zu to %,zu", st.st_size, size); unlink(path); fd = open(path, O_RDWR | O_CREAT, 0600); st.st_size = 0; } if (fd != -1) { if (!st.st_size) CHECK_NE(-1, ftruncate(fd, size)); c = mmap(0, size, PROT, FLAGS, fd, 0); close(fd); } } else { WARNF("sslcache open(%`'s) failed %s", path, strerror(errno)); } } return c; } struct SslCache *CreateSslCache(const char *path, size_t bytes, int lifetime) { size_t ents, size; struct SslCache *c; if (!bytes) bytes = 10 * 1024 * 1024; if (lifetime <= 0) lifetime = 24 * 60 * 60; ents = _rounddown2pow(MAX(2, bytes / sizeof(struct SslCacheEntry))); size = sizeof(struct SslCache) + sizeof(struct SslCacheEntry) * ents; size = ROUNDUP(size, FRAMESIZE); c = OpenSslCache(path, size); if (!c) c = mmap(0, size, PROT, FLAGS | MAP_ANONYMOUS, -1, 0); CHECK_NE(MAP_FAILED, c); VERBOSEF("opened %`'s %,zu bytes with %,u slots", c ? path : "anonymous shared memory", size, ents); c->lifetime = lifetime; c->size = size; c->mask = ents - 1; return c; } void FreeSslCache(struct SslCache *cache) { if (!cache) return; CHECK_NE(-1, munmap(cache, cache->size)); } int UncacheSslSession(void *data, mbedtls_ssl_session *session) { int64_t ts; uint64_t tick; unsigned char *ticket; struct SslCache *cache; mbedtls_x509_crt *cert; struct SslCacheEntry *e; uint32_t i, hash, ticketlen; INFOF("uncache"); cache = data; hash = HashSslSession(session); i = hash & cache->mask; e = cache->p + i; if (!(tick = e->tick) || hash != e->hash) { NOISEF("%u empty", i); return 1; } asm volatile("" ::: "memory"); if (session->ciphersuite != e->session.ciphersuite || session->compression != e->session.compression || session->id_len != e->session.id_len || memcmp(session->id, e->session.id, e->session.id_len)) { VERBOSEF("%u sslcache collision", i); return 1; } ts = time(0); if (!(e->time <= ts && ts <= e->time + cache->lifetime)) { DEBUGF("%u sslcache expired", i); _cmpxchg(&e->tick, tick, 0); return 1; } cert = 0; ticket = 0; if ((e->certlen && (!(cert = calloc(1, sizeof(*cert))) || mbedtls_x509_crt_parse_der(cert, e->cert, e->certlen)))) { goto Contention; } if ((ticketlen = e->ticketlen)) { if (!(ticket = malloc(ticketlen))) goto Contention; memcpy(ticket, e->ticket, ticketlen); } mbedtls_ssl_session_free(session); memcpy(session, &e->session, sizeof(*session)); asm volatile("" ::: "memory"); if (tick != e->tick) goto Contention; session->peer_cert = cert; session->ticket = ticket; session->ticket_len = ticketlen; DEBUGF("%u restored ssl from cache", i); return 0; Contention: WARNF("%u sslcache contention 0x%08x", i, hash); mbedtls_x509_crt_free(cert); free(ticket); free(cert); return 1; } int CacheSslSession(void *data, const mbedtls_ssl_session *session) { int pid; uint64_t tick; uint32_t i, hash; struct SslCache *cache; struct SslCacheEntry *e; cache = data; if (session->peer_cert && session->peer_cert->raw.len > sizeof(cache->p[0].cert)) { WARNF("%s too big %zu", "cert", session->peer_cert->raw.len); return 1; } if (session->ticket && session->ticket_len > sizeof(cache->p[0].ticket)) { WARNF("%s too big %zu", "ticket", session->ticket_len); return 1; } pid = getpid(); hash = HashSslSession(session); i = hash & cache->mask; e = cache->p + i; e->tick = 0; e->pid = pid; asm volatile("" ::: "memory"); memcpy(&e->session, session, sizeof(*session)); if (session->peer_cert) { e->certlen = session->peer_cert->raw.len; memcpy(e->cert, session->peer_cert->raw.p, session->peer_cert->raw.len); } else { e->certlen = 0; } if (session->ticket) { e->ticketlen = session->ticket_len; memcpy(e->ticket, session->ticket, session->ticket_len); } else { e->ticketlen = 0; } e->hash = hash; e->time = time(0); tick = rdtsc(); asm volatile("" ::: "memory"); if (tick && _cmpxchg(&e->pid, pid, 0)) { DEBUGF("%u saved %s%s %`#.*s", i, mbedtls_ssl_get_ciphersuite_name(session->ciphersuite), session->compression ? " DEFLATE" : "", session->id_len, session->id); e->tick = tick; return 0; } else { WARNF("%u congestion", i); return 1; } }
7,585
216
jart/cosmopolitan
false
cosmopolitan/net/https/sslroots.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" STATIC_YOINK("zip_uri_support"); STATIC_YOINK("usr/share/ssl/root/"); STATIC_YOINK("usr/share/ssl/root/amazon.pem"); STATIC_YOINK("usr/share/ssl/root/certum.pem"); STATIC_YOINK("usr/share/ssl/root/comodo.pem"); STATIC_YOINK("usr/share/ssl/root/digicert.pem"); STATIC_YOINK("usr/share/ssl/root/geotrust.pem"); STATIC_YOINK("usr/share/ssl/root/globalsign.pem"); STATIC_YOINK("usr/share/ssl/root/godaddy.pem"); STATIC_YOINK("usr/share/ssl/root/google.pem"); STATIC_YOINK("usr/share/ssl/root/isrg.pem"); STATIC_YOINK("usr/share/ssl/root/quovadis.pem"); STATIC_YOINK("usr/share/ssl/root/redbean.pem"); STATIC_YOINK("usr/share/ssl/root/starfield.pem"); STATIC_YOINK("usr/share/ssl/root/verisign.pem"); char ssl_root_support;
2,586
38
jart/cosmopolitan
false
cosmopolitan/net/https/https.h
#ifndef COSMOPOLITAN_NET_HTTPS_HTTPS_H_ #define COSMOPOLITAN_NET_HTTPS_HTTPS_H_ #include "libc/time/struct/tm.h" #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/ecp.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/pk.h" #include "third_party/mbedtls/ssl_ciphersuites.h" #include "third_party/mbedtls/x509_crt.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Cert { mbedtls_x509_crt *cert; mbedtls_pk_context *key; }; char *GetTlsError(int); char *DescribeSslVerifyFailure(int); mbedtls_x509_crt *GetSslRoots(void); void InitializeRng(mbedtls_ctr_drbg_context *); int GetEntropy(void *, unsigned char *, size_t); void FormatSslTime(char[restrict hasatleast 16], struct tm *); void ChooseCertificateLifetime(char[16], char[16]); void LogCertificate(const char *, mbedtls_x509_crt *); bool IsSelfSigned(mbedtls_x509_crt *); char *FormatX509Name(mbedtls_x509_name *); void TlsDie(const char *, int) wontreturn; bool ChainCertificate(mbedtls_x509_crt *, mbedtls_x509_crt *); bool CertHasIp(const mbedtls_x509_crt *, uint32_t); bool CertHasHost(const mbedtls_x509_crt *, const void *, size_t); bool IsServerCert(const struct Cert *, mbedtls_pk_type_t); void TlsDebug(void *, int, const char *, int, const char *); int GenerateHardRandom(void *, unsigned char *, size_t); void GenerateCertificateSerial(mbedtls_x509write_cert *); mbedtls_pk_context *InitializeKey(struct Cert *, mbedtls_x509write_cert *, mbedtls_md_type_t, int); struct Cert FinishCertificate(struct Cert *, mbedtls_x509write_cert *, mbedtls_pk_context *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTPS_HTTPS_H_ */
1,766
45
jart/cosmopolitan
false
cosmopolitan/net/https/describesslverifyfailure.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "net/https/https.h" #include "third_party/mbedtls/x509.h" static const struct thatispacked SslVerifyString { int code; const char *str; } kSslVerifyStrings[] = { {MBEDTLS_X509_BADCERT_BAD_KEY, "badcert_bad_key"}, {MBEDTLS_X509_BADCERT_BAD_MD, "badcert_bad_md"}, {MBEDTLS_X509_BADCERT_BAD_PK, "badcert_bad_pk"}, {MBEDTLS_X509_BADCERT_CN_MISMATCH, "badcert_cn_mismatch"}, {MBEDTLS_X509_BADCERT_EXPIRED, "badcert_expired"}, {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "badcert_ext_key_usage"}, {MBEDTLS_X509_BADCERT_FUTURE, "badcert_future"}, {MBEDTLS_X509_BADCERT_KEY_USAGE, "badcert_key_usage"}, {MBEDTLS_X509_BADCERT_MISSING, "badcert_missing"}, {MBEDTLS_X509_BADCERT_NOT_TRUSTED, "badcert_not_trusted"}, {MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "badcert_ns_cert_type"}, {MBEDTLS_X509_BADCERT_OTHER, "badcert_other"}, {MBEDTLS_X509_BADCERT_REVOKED, "badcert_revoked"}, {MBEDTLS_X509_BADCERT_SKIP_VERIFY, "badcert_skip_verify"}, {MBEDTLS_X509_BADCRL_BAD_KEY, "badcrl_bad_key"}, {MBEDTLS_X509_BADCRL_BAD_MD, "badcrl_bad_md"}, {MBEDTLS_X509_BADCRL_BAD_PK, "badcrl_bad_pk"}, {MBEDTLS_X509_BADCRL_EXPIRED, "badcrl_expired"}, {MBEDTLS_X509_BADCRL_FUTURE, "badcrl_future"}, {MBEDTLS_X509_BADCRL_NOT_TRUSTED, "badcrl_not_trusted"}, }; char *DescribeSslVerifyFailure(int flags) { int i; char *p, *q; p = malloc(1024); q = stpcpy(p, "verify failed"); for (i = 0; i < ARRAYLEN(kSslVerifyStrings); ++i) { if (!(flags & kSslVerifyStrings[i].code)) continue; q = stpcpy(stpcpy(q, " "), kSslVerifyStrings[i].str); } return p; }
3,540
62
jart/cosmopolitan
false
cosmopolitan/net/https/chaincertificate.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "libc/mem/gc.internal.h" #include "net/https/https.h" bool ChainCertificate(mbedtls_x509_crt *cert, mbedtls_x509_crt *parent) { if (!mbedtls_x509_crt_check_signature(cert, parent, 0)) { DEBUGF("chaining %`'s to %`'s", gc(FormatX509Name(&cert->subject)), gc(FormatX509Name(&parent->subject))); cert->next = parent; return true; } else { WARNF("signature check failed for %`'s -> %`'s", gc(FormatX509Name(&cert->subject)), gc(FormatX509Name(&parent->subject))); return false; } }
2,407
36
jart/cosmopolitan
false
cosmopolitan/net/https/getsslroots.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/dirent.h" #include "libc/errno.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/dt.h" #include "libc/sysv/consts/o.h" #include "libc/x/x.h" #include "net/https/https.h" #include "third_party/mbedtls/x509_crt.h" STATIC_YOINK("ssl_root_support"); static void FreeSslRoots(mbedtls_x509_crt *c) { mbedtls_x509_crt_free(c); free(c); } /** * Returns singleton of SSL roots stored in /zip/usr/share/ssl/root/... */ mbedtls_x509_crt *GetSslRoots(void) { int fd; DIR *d; uint8_t *p; size_t n, m; struct dirent *e; static bool once; char path[PATH_MAX]; static mbedtls_x509_crt *c; if (!once) { if ((c = calloc(1, sizeof(*c)))) { m = stpcpy(path, "/zip/usr/share/ssl/root/") - path; if ((d = opendir(path))) { while ((e = readdir(d))) { if (e->d_type != DT_REG) continue; if (m + (n = strlen(e->d_name)) >= ARRAYLEN(path)) continue; memcpy(path + m, e->d_name, n + 1); CHECK((p = xslurp(path, &n))); CHECK_GE(mbedtls_x509_crt_parse(c, p, n + 1), 0, "%s", path); free(p); } closedir(d); } __cxa_atexit(FreeSslRoots, c, 0); } once = true; } return c; }
3,207
72
jart/cosmopolitan
false
cosmopolitan/net/https/tlsdebug.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "net/https/https.h" void TlsDebug(void *c, int v, const char *f, int l, const char *s) { flogf(v, f, l, 0, "TLS %s", s); }
1,997
25
jart/cosmopolitan
false
cosmopolitan/net/https/isservercert.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" #include "third_party/mbedtls/asn1.h" #include "third_party/mbedtls/oid.h" bool IsServerCert(const struct Cert *cert, mbedtls_pk_type_t type) { return cert->cert && cert->key && !cert->cert->ca_istrue && mbedtls_pk_get_type(cert->key) == type && !mbedtls_x509_crt_check_extended_key_usage( cert->cert, MBEDTLS_OID_SERVER_AUTH, MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH)); }
2,285
30
jart/cosmopolitan
false
cosmopolitan/net/https/isselfsigned.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" bool IsSelfSigned(mbedtls_x509_crt *cert) { return !mbedtls_x509_name_cmp(&cert->issuer, &cert->subject); }
1,976
24
jart/cosmopolitan
false
cosmopolitan/net/https/getentropy.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/stdio/rand.h" #include "net/https/https.h" int GetEntropy(void *c, unsigned char *p, size_t n) { rngset(p, n, rdrand, 0); return 0; }
2,018
27
jart/cosmopolitan
false
cosmopolitan/net/https/choosecertificatelifetime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "net/https/https.h" void ChooseCertificateLifetime(char notbefore[16], char notafter[16]) { struct tm tm; int64_t past, now, future, lifetime, tolerance; tolerance = 60 * 60 * 24; lifetime = 60 * 60 * 24 * 365; now = nowl(); past = now - tolerance; future = now + tolerance + lifetime; FormatSslTime(notbefore, gmtime_r(&past, &tm)); FormatSslTime(notafter, gmtime_r(&future, &tm)); }
2,310
34
jart/cosmopolitan
false
cosmopolitan/net/https/logcertificate.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "net/https/https.h" void LogCertificate(const char *msg, mbedtls_x509_crt *cert) { char *s; size_t n; if (LOGGABLE(kLogDebug)) { if ((s = malloc((n = 15000)))) { if (mbedtls_x509_crt_info(s, n, " ", cert) > 0) { DEBUGF("%s\n%s", msg, _chomp(s)); } free(s); } } }
2,177
34
jart/cosmopolitan
false
cosmopolitan/net/https/getsslcachefile.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/safemacros.internal.h" #include "libc/fmt/fmt.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "net/https/sslcache.h" /** * Returns recommended path argument for CreateSslCache(). * @return pointer to static memory */ char *GetSslCacheFile(void) { static char sslcachefile[PATH_MAX]; if (snprintf(sslcachefile, sizeof(sslcachefile), "%s/%s.sslcache", firstnonnull(getenv("TMPDIR"), "/tmp"), getenv("USER")) < ARRAYLEN(sslcachefile)) { return sslcachefile; } else { return 0; } }
2,418
39
jart/cosmopolitan
false
cosmopolitan/net/https/tlserror.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" #include "third_party/mbedtls/error.h" char *GetTlsError(int r) { static char b[128]; mbedtls_strerror(r, b, sizeof(b)); return b; }
2,005
27
jart/cosmopolitan
false
cosmopolitan/net/https/initializerng.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/stdio/rand.h" #include "net/https/https.h" #include "third_party/mbedtls/ctr_drbg.h" void InitializeRng(mbedtls_ctr_drbg_context *r) { volatile unsigned char b[64]; mbedtls_ctr_drbg_init(r); CHECK(getrandom(b, 64, 0) == 64); CHECK(!mbedtls_ctr_drbg_seed(r, GetEntropy, 0, b, 64)); mbedtls_platform_zeroize(b, 64); }
2,206
31
jart/cosmopolitan
false
cosmopolitan/net/https/tlsdie.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/https/https.h" void TlsDie(const char *s, int r) { if (IsTiny()) { (fprintf)(stderr, "error: %s (-0x%04x %s)\n", s, -r, GetTlsError(r)); } else { (fprintf)(stderr, "error: %s (grep -0x%04x)\n", s, -r); } exit(1); }
2,082
29
jart/cosmopolitan
false
cosmopolitan/net/https/initializekey.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "net/https/https.h" mbedtls_pk_context *InitializeKey(struct Cert *ca, mbedtls_x509write_cert *wcert, mbedtls_md_type_t md_alg, int type) { mbedtls_pk_context *k; mbedtls_ctr_drbg_context kr; k = calloc(1, sizeof(mbedtls_pk_context)); mbedtls_x509write_crt_init(wcert); mbedtls_x509write_crt_set_issuer_key(wcert, ca ? ca->key : k); mbedtls_x509write_crt_set_subject_key(wcert, k); mbedtls_x509write_crt_set_md_alg(wcert, md_alg); mbedtls_x509write_crt_set_version(wcert, MBEDTLS_X509_CRT_VERSION_3); CHECK_EQ(0, mbedtls_pk_setup(k, mbedtls_pk_info_from_type(type))); return k; }
2,542
36
jart/cosmopolitan
false
cosmopolitan/net/https/finishcertificate.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/x/xasprintf.h" #include "net/https/https.h" struct Cert FinishCertificate(struct Cert *ca, mbedtls_x509write_cert *wcert, mbedtls_pk_context *key) { int i, n, rc; unsigned char *p; mbedtls_x509_crt *cert; p = malloc((n = FRAMESIZE)); i = mbedtls_x509write_crt_der(wcert, p, n, GenerateHardRandom, 0); if (i < 0) FATALF("write key (grep -0x%04x)", -i); cert = calloc(1, sizeof(mbedtls_x509_crt)); mbedtls_x509_crt_parse(cert, p + n - i, i); if (ca) cert->next = ca->cert; mbedtls_x509write_crt_free(wcert); free(p); if ((rc = mbedtls_pk_check_pair(&cert->pk, key))) { FATALF("generate key (grep -0x%04x)", -rc); } LogCertificate(_gc(xasprintf("generated %s certificate", mbedtls_pk_get_name(&cert->pk))), cert); return (struct Cert){cert, key}; }
2,761
45
jart/cosmopolitan
false
cosmopolitan/net/https/sslcache.h
#ifndef COSMOPOLITAN_NET_HTTPS_SSLCACHE_H_ #define COSMOPOLITAN_NET_HTTPS_SSLCACHE_H_ #include "third_party/mbedtls/ssl.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct SslCache { size_t size; int lifetime; uint32_t mask; struct SslCacheEntry { int64_t time; volatile uint64_t tick; volatile int pid; uint32_t hash; unsigned certlen; unsigned ticketlen; mbedtls_ssl_session session; uint8_t cert[1500]; uint8_t ticket[500]; } p[]; }; struct SslCache *CreateSslCache(const char *, size_t, int); void FreeSslCache(struct SslCache *); int UncacheSslSession(void *, mbedtls_ssl_session *); int CacheSslSession(void *, const mbedtls_ssl_session *); char *GetSslCacheFile(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTPS_SSLCACHE_H_ */
858
33
jart/cosmopolitan
false
cosmopolitan/net/https/generatecertificateserial.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/rand.h" #include "net/https/https.h" #include "third_party/mbedtls/bignum.h" void GenerateCertificateSerial(mbedtls_x509write_cert *wcert) { mbedtls_x509write_crt_set_serial( wcert, &(mbedtls_mpi){1, 2, (uint64_t[]){rdrand(), rdrand()}}); }
2,107
27
jart/cosmopolitan
false
cosmopolitan/net/http/iscloudflare.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if `x` is Cloudflare IPv4 address. * * @see https://www.cloudflare.com/ips/ (April 8, 2021) */ bool IsCloudflareIp(uint32_t x) { return (x & 0xfffffc00) == 0x6715f400 || // 103.21.244.0/22 (x & 0xfffffc00) == 0x6716c800 || // 103.22.200.0/22 (x & 0xfffffc00) == 0x671f0400 || // 103.31.4.0/22 (x & 0xfff80000) == 0x68100000 || // 104.16.0.0/13 (x & 0xfffc0000) == 0x68180000 || // 104.24.0.0/14 (x & 0xffffc000) == 0x6ca2c000 || // 108.162.192.0/18 (x & 0xfffffc00) == 0x83004800 || // 131.0.72.0/22 (x & 0xffffc000) == 0x8d654000 || // 141.101.64.0/18 (x & 0xfffe0000) == 0xa29e0000 || // 162.158.0.0/15 (x & 0xfff80000) == 0xac400000 || // 172.64.0.0/13 (x & 0xfffff000) == 0xadf53000 || // 173.245.48.0/20 (x & 0xfffff000) == 0xbc726000 || // 188.114.96.0/20 (x & 0xfffff000) == 0xbe5df000 || // 190.93.240.0/20 (x & 0xfffffc00) == 0xc5eaf000 || // 197.234.240.0/22 (x & 0xffff8000) == 0xc6298000; // 198.41.128.0/17 }
2,952
43
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpheader.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/gethttpheader.inc" #include "net/http/http.h" /** * Returns small number for HTTP header, or -1 if not found. */ int GetHttpHeader(const char *str, size_t len) { const struct HttpHeaderSlot *slot; if ((slot = LookupHttpHeader(str, len))) { return slot->code; } else { return -1; } }
2,157
33
jart/cosmopolitan
false
cosmopolitan/net/http/isacceptablepath.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/http.h" /** * Returns true if path seems legit. * * 1. The substring "//" is disallowed. * 2. We won't serve hidden files (segment starts with '.'). * The only exception is `/.well-known/`. * 3. We won't serve paths with segments equal to "." or "..". * * It is assumed that the URI parser already took care of percent * escape decoding as well as ISO-8859-1 decoding. The input needs * to be a UTF-8 string. This function takes overlong encodings into * consideration, so you don't need to call Underlong() beforehand. * * @param size if -1 implies strlen * @see IsReasonablePath() */ bool IsAcceptablePath(const char *data, size_t size) { const char *p, *e; int x, y, a, b, t, i, n; if (size == -1) size = data ? strlen(data) : 0; t = 0; y = '/'; p = data; e = p + size; while (p < e) { x = *p++ & 0xff; if (UNLIKELY(x >= 0300)) { a = ThomPikeByte(x); n = ThomPikeLen(x) - 1; if (p + n <= e) { for (i = 0;;) { b = p[i] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++i == n) { x = a; p += i; break; } } } } if (x == '\\') { x = '/'; } if (y == '/') { if (x == '.' && // allow /.well-known/ in the first position (p - data > 2 || size < 13 || memcmp(data, "/.well-known/", 13) != 0)) return false; if (x == '/' && t) return false; } y = x; t = 1; } return true; }
3,478
81
jart/cosmopolitan
false
cosmopolitan/net/http/formathttpdatetime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "net/http/http.h" /** * Formats HTTP timestamp, e.g. * * Sun, 04 Oct 2020 19:50:10 GMT * * This function is the same as: * * strftime(p, 30, "%a, %d %b %Y %H:%M:%S %Z", tm) * * Except this function goes 10x faster: * * FormatHttpDateTime l: 25𝑐 8𝑛𝑠 * strftime l: 709𝑐 229𝑛𝑠 * * @param tm must be zulu see gmtime_r() and nowl() * @see ParseHttpDateTime() */ char *FormatHttpDateTime(char p[hasatleast 30], struct tm *tm) { unsigned i; p = mempcpy(p, kWeekdayNameShort[tm->tm_wday], 3); *p++ = ','; *p++ = ' '; i = MIN(MAX(tm->tm_mday, 1), 31); *p++ = '0' + i / 10; *p++ = '0' + i % 10; *p++ = ' '; i = MIN(MAX(tm->tm_mon, 0), 11); p = mempcpy(p, kMonthNameShort[i], 3); *p++ = ' '; i = MIN(MAX(tm->tm_year + 1900, 0), 9999); *p++ = '0' + i / 1000; *p++ = '0' + i / 100 % 10; *p++ = '0' + i / 10 % 10; *p++ = '0' + i % 10; *p++ = ' '; i = MIN(MAX(tm->tm_hour, 0), 23); *p++ = '0' + i / 10; *p++ = '0' + i % 10; *p++ = ':'; i = MIN(MAX(tm->tm_min, 0), 59); *p++ = '0' + i / 10; *p++ = '0' + i % 10; *p++ = ':'; i = MIN(MAX(tm->tm_sec, 0), 59); *p++ = '0' + i / 10; *p++ = '0' + i % 10; *p++ = ' '; *p++ = 'G'; *p++ = 'M'; *p++ = 'T'; *p = '\0'; return p; }
3,276
78
jart/cosmopolitan
false
cosmopolitan/net/http/parseip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/ip.h" /** * Parse IPv4 host address. * * @param n if -1 implies strlen * @return -1 on failure, otherwise 32-bit host-order unsigned integer * @see ParseCidr() */ int64_t ParseIp(const char *s, size_t n) { int c, j; size_t i; unsigned b, x; bool dotted = false; if (n == -1) n = s ? strlen(s) : 0; if (!n) return -1; for (b = x = j = i = 0; i < n; ++i) { c = s[i] & 255; if (isdigit(c)) { if (__builtin_mul_overflow(b, 10, &b) || // __builtin_add_overflow(b, c - '0', &b) || // (b > 255 && dotted)) { return -1; } } else if (c == '.') { if (b > 255) return -1; dotted = true; x <<= 8; x |= b; b = 0; ++j; } else { return -1; } } x <<= 8; x |= b; return x; }
2,677
59
jart/cosmopolitan
false
cosmopolitan/net/http/findcontenttype.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/bits.h" #include "libc/intrin/bswap.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/http.h" static const struct ContentTypeExtension { unsigned char ext[8]; const char *mime; } kContentTypeExtension[] = { {"7z", "application/x-7z-compressed"}, // {"aac", "audio/aac"}, // {"apng", "image/apng"}, // {"atom", "application/atom+xml"}, // {"avi", "video/x-msvideo"}, // {"avif", "image/avif"}, // {"azw", "application/vnd.amazon.ebook"}, // {"bmp", "image/bmp"}, // {"bz2", "application/x-bzip2"}, // {"c", "text/plain"}, // {"cc", "text/plain"}, // {"css", "text/css"}, // {"csv", "text/csv"}, // {"diff", "text/plain"}, // {"diff", "text/plain"}, // {"doc", "application/msword"}, // {"epub", "application/epub+zip"}, // {"gif", "image/gif"}, // {"gz", "application/gzip"}, // {"h", "text/plain"}, // {"htm", "text/html"}, // {"html", "text/html"}, // {"i", "text/plain"}, // {"ico", "image/vnd.microsoft.icon"}, // {"jar", "application/java-archive"}, // {"jpeg", "image/jpeg"}, // {"jpg", "image/jpeg"}, // {"js", "text/javascript"}, // {"json", "application/json"}, // {"m4a", "audio/mpeg"}, // {"markdown", "text/plain"}, // {"md", "text/plain"}, // {"mid", "audio/midi"}, // {"midi", "audio/midi"}, // {"mjs", "text/javascript"}, // {"mp2", "audio/mpeg"}, // {"mp3", "audio/mpeg"}, // {"mp4", "video/mp4"}, // {"mpeg", "video/mpeg"}, // {"mpg", "video/mpeg"}, // {"oga", "audio/ogg"}, // {"ogg", "application/ogg"}, // {"ogv", "video/ogg"}, // {"ogx", "application/ogg"}, // {"otf", "font/otf"}, // {"patch", "text/plain"}, // {"pdf", "application/pdf"}, // {"png", "image/png"}, // {"rar", "application/vnd.rar"}, // {"rtf", "application/rtf"}, // {"s", "text/plain"}, // {"sh", "application/x-sh"}, // {"sqlite", "application/vnd.sqlite3"}, // {"sqlite3", "application/vnd.sqlite3"}, // {"svg", "image/svg+xml"}, // {"swf", "application/x-shockwave-flash"}, // {"t38", "image/t38"}, // {"tar", "application/x-tar"}, // {"tiff", "image/tiff"}, // {"ttf", "font/ttf"}, // {"txt", "text/plain"}, // {"ul", "audio/basic"}, // {"ulaw", "audio/basic"}, // {"wasm", "application/wasm"}, // {"wav", "audio/x-wav"}, // {"weba", "audio/webm"}, // {"webm", "video/webm"}, // {"webp", "image/webp"}, // {"woff", "font/woff"}, // {"woff2", "font/woff2"}, // {"wsdl", "application/wsdl+xml"}, // {"xhtml", "application/xhtml+xml"}, // {"xls", "application/vnd.ms-excel"}, // {"xml", "application/xml"}, // {"xsl", "application/xslt+xml"}, // {"xslt", "application/xslt+xml"}, // {"xz", "application/x-xz"}, // {"z", "application/zlib"}, // {"zip", "application/zip"}, // {"zst", "application/zstd"}, // }; static inline int CompareInts(const uint64_t x, uint64_t y) { return x > y ? 1 : x < y ? -1 : 0; } static const char *BisectContentType(uint64_t ext) { int c, m, l, r; l = 0; r = ARRAYLEN(kContentTypeExtension) - 1; while (l <= r) { m = (l + r) >> 1; c = CompareInts(READ64BE(kContentTypeExtension[m].ext), ext); if (c < 0) { l = m + 1; } else if (c > 0) { r = m - 1; } else { return kContentTypeExtension[m].mime; } } return 0; } /** * Returns Content-Type for file extension. */ const char *FindContentType(const char *p, size_t n) { int c; uint64_t w; if (n == -1) n = p ? strlen(p) : 0; for (w = 0; n--;) { c = p[n] & 255; if (c == '.') { return BisectContentType(bswap_64(w)); } w <<= 8; w |= kToLower[c]; } return 0; }
6,989
152
jart/cosmopolitan
false
cosmopolitan/net/http/escapeurl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/x/x.h" #include "net/http/escape.h" #include "net/http/url.h" /** * Escapes URL component using generic table. * * This function is agnostic to the underlying charset. * Always using UTF-8 is a good idea. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno * @see kEscapeAuthority * @see kEscapeIpLiteral * @see kEscapePath * @see kEscapePathSegment * @see kEscapeParam * @see kEscapeFragment */ char *EscapeUrl(const char *p, size_t n, size_t *z, const char T[256]) { char *r, *q; struct UrlView v; if (n == -1) n = p ? strlen(p) : 0; if (z) *z = 0; if ((q = r = malloc(n * 6 + 1))) { v.p = p, v.n = n; q = EscapeUrlView(r, &v, T); if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; }
2,783
56
jart/cosmopolitan
false
cosmopolitan/net/http/kescapefragment.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '/?.~_@:!$&'"'"'()*+,;=-' -iskEscapeFragment // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠ “# % ! § &‘()*+,-./ 0x20 // < > 0123456789:; = ⁇ 0x30 // @ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|} ⌂ pqrstuvwxyz ~ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapeFragment[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, // 0x30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,183
61
jart/cosmopolitan
false
cosmopolitan/net/http/indentlines.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/x/x.h" #include "net/http/escape.h" /** * Inserts spaces before lines. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @param j is number of spaces to use * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *IndentLines(const char *p, size_t n, size_t *z, size_t j) { char *r, *q; const char *l; size_t i, t, m, a; if (n == -1) n = p ? strlen(p) : 0; r = 0; t = 0; do { if ((l = memchr(p, '\n', n))) { m = l + 1 - p; a = *p != '\r' && *p != '\n' ? j : 0; } else { m = n; a = n ? j : 0; } if ((q = realloc(r, t + a + m + 1))) { r = q; } else { free(r); if (z) *z = 0; return 0; } memset(r + t, ' ', a); memcpy(r + t + a, p, m); t += a + m; p += m; n -= m; } while (l); if (z) *z = t; r[t] = '\0'; return r; }
2,810
65
jart/cosmopolitan
false
cosmopolitan/net/http/parseforwarded.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/http.h" /** * Parses X-Forwarded-For. * * This header is used by reverse proxies. For example: * * X-Forwarded-For: 203.0.110.2, 203.0.113.42:31337 * * The port is optional and will be set to zero if absent. * * @param s is input data * @param n if -1 implies strlen * @param ip receives last/right ip on success if not NULL * @param port receives port on success if not NULL * @return 0 on success or -1 on failure * @see RFC7239's poorly designed Forwarded header */ int ParseForwarded(const char *s, size_t n, uint32_t *ip, uint16_t *port) { int c, t; size_t i; char *r; uint32_t x; if (n == -1) n = s ? strlen(s) : 0; if (n) { t = x = i = 0; if ((r = memrchr(s, ',', n))) { i = r - s; if ((s[++i] & 255) == ' ') ++i; // skip optional space } do { c = s[i++] & 255; if (isdigit(c)) { t *= 10; t += c - '0'; if (t > 255) { return -1; } } else if (c == '.') { x <<= 8; x |= t; t = 0; } else if (c == ':') { break; } else { return -1; } } while (i < n); x <<= 8; x |= t; t = 0; if (c == ':') { while (i < n) { c = s[i++] & 255; if (isdigit(c)) { t *= 10; t += c - '0'; if (t > 65535) { return -1; } } else { return -1; } } } if (ip) *ip = x; if (port) *port = t; return 0; } else { return -1; } }
3,407
92
jart/cosmopolitan
false
cosmopolitan/net/http/http.h
#ifndef COSMOPOLITAN_LIBC_HTTP_HTTP_H_ #define COSMOPOLITAN_LIBC_HTTP_HTTP_H_ #include "libc/time/struct/tm.h" #define kHttpRequest 0 #define kHttpResponse 1 #define kHttpGet 1 #define kHttpHead 2 #define kHttpPost 3 #define kHttpPut 4 #define kHttpDelete 5 #define kHttpOptions 6 #define kHttpConnect 7 #define kHttpTrace 8 #define kHttpCopy 9 #define kHttpLock 10 #define kHttpMerge 11 #define kHttpMkcol 12 #define kHttpMove 13 #define kHttpNotify 14 #define kHttpPatch 15 #define kHttpReport 16 #define kHttpUnlock 17 #define kHttpStateStart 0 #define kHttpStateMethod 1 #define kHttpStateUri 2 #define kHttpStateVersion 3 #define kHttpStateStatus 4 #define kHttpStateMessage 5 #define kHttpStateName 6 #define kHttpStateColon 7 #define kHttpStateValue 8 #define kHttpStateCr 9 #define kHttpStateLf1 10 #define kHttpStateLf2 11 #define kHttpClientStateHeaders 0 #define kHttpClientStateBody 1 #define kHttpClientStateBodyChunked 2 #define kHttpClientStateBodyLengthed 3 #define kHttpStateChunkStart 0 #define kHttpStateChunkSize 1 #define kHttpStateChunkExt 2 #define kHttpStateChunkLf1 3 #define kHttpStateChunk 4 #define kHttpStateChunkCr2 5 #define kHttpStateChunkLf2 6 #define kHttpStateTrailerStart 7 #define kHttpStateTrailer 8 #define kHttpStateTrailerLf1 9 #define kHttpStateTrailerLf2 10 #define kHttpHost 0 #define kHttpCacheControl 1 #define kHttpConnection 2 #define kHttpAccept 3 #define kHttpAcceptLanguage 4 #define kHttpAcceptEncoding 5 #define kHttpUserAgent 6 #define kHttpReferer 7 #define kHttpXForwardedFor 8 #define kHttpOrigin 9 #define kHttpUpgradeInsecureRequests 10 #define kHttpPragma 11 #define kHttpCookie 12 #define kHttpDnt 13 #define kHttpSecGpc 14 #define kHttpFrom 15 #define kHttpIfModifiedSince 16 #define kHttpXRequestedWith 17 #define kHttpXForwardedHost 18 #define kHttpXForwardedProto 19 #define kHttpXCsrfToken 20 #define kHttpSaveData 21 #define kHttpRange 22 #define kHttpContentLength 23 #define kHttpContentType 24 #define kHttpVary 25 #define kHttpDate 26 #define kHttpServer 27 #define kHttpExpires 28 #define kHttpContentEncoding 29 #define kHttpLastModified 30 #define kHttpEtag 31 #define kHttpAllow 32 #define kHttpContentRange 33 #define kHttpAcceptCharset 34 #define kHttpAccessControlAllowCredentials 35 #define kHttpAccessControlAllowHeaders 36 #define kHttpAccessControlAllowMethods 37 #define kHttpAccessControlAllowOrigin 38 #define kHttpAccessControlMaxAge 39 #define kHttpAccessControlMethod 40 #define kHttpAccessControlRequestHeaders 41 #define kHttpAccessControlRequestMethod 42 #define kHttpAccessControlRequestMethods 43 #define kHttpAge 44 #define kHttpAuthorization 45 #define kHttpContentBase 46 #define kHttpContentDescription 47 #define kHttpContentDisposition 48 #define kHttpContentLanguage 49 #define kHttpContentLocation 50 #define kHttpContentMd5 51 #define kHttpExpect 52 #define kHttpIfMatch 53 #define kHttpIfNoneMatch 54 #define kHttpIfRange 55 #define kHttpIfUnmodifiedSince 56 #define kHttpKeepAlive 57 #define kHttpLink 58 #define kHttpLocation 59 #define kHttpMaxForwards 60 #define kHttpProxyAuthenticate 61 #define kHttpProxyAuthorization 62 #define kHttpProxyConnection 63 #define kHttpPublic 64 #define kHttpRetryAfter 65 #define kHttpTe 66 #define kHttpTrailer 67 #define kHttpTransferEncoding 68 #define kHttpUpgrade 69 #define kHttpWarning 70 #define kHttpWwwAuthenticate 71 #define kHttpVia 72 #define kHttpStrictTransportSecurity 73 #define kHttpXFrameOptions 74 #define kHttpXContentTypeOptions 75 #define kHttpAltSvc 76 #define kHttpReferrerPolicy 77 #define kHttpXXssProtection 78 #define kHttpAcceptRanges 79 #define kHttpSetCookie 80 #define kHttpSecChUa 81 #define kHttpSecChUaMobile 82 #define kHttpSecFetchSite 83 #define kHttpSecFetchMode 84 #define kHttpSecFetchUser 85 #define kHttpSecFetchDest 86 #define kHttpCfRay 87 #define kHttpCfVisitor 88 #define kHttpCfConnectingIp 89 #define kHttpCfIpcountry 90 #define kHttpSecChUaPlatform 91 #define kHttpCdnLoop 92 #define kHttpHeadersMax 93 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct HttpSlice { short a, b; }; struct HttpHeader { struct HttpSlice k; struct HttpSlice v; }; struct HttpHeaders { unsigned n, c; struct HttpHeader *p; }; struct HttpMessage { int i, a, status; unsigned char t; unsigned char type; unsigned char method; unsigned char version; struct HttpSlice k; struct HttpSlice uri; struct HttpSlice scratch; struct HttpSlice message; struct HttpSlice headers[kHttpHeadersMax]; struct HttpSlice xmethod; struct HttpHeaders xheaders; }; struct HttpUnchunker { int t; size_t i; size_t j; ssize_t m; }; extern const char kHttpToken[256]; extern const char kHttpMethod[18][8]; extern const bool kHttpRepeatable[kHttpHeadersMax]; const char *GetHttpReason(int); const char *GetHttpHeaderName(int); int GetHttpHeader(const char *, size_t); int GetHttpMethod(const char *, size_t); void InitHttpMessage(struct HttpMessage *, int); void DestroyHttpMessage(struct HttpMessage *); int ParseHttpMessage(struct HttpMessage *, const char *, size_t); bool HeaderHas(struct HttpMessage *, const char *, int, const char *, size_t); int64_t ParseContentLength(const char *, size_t); char *FormatHttpDateTime(char[hasatleast 30], struct tm *); bool ParseHttpRange(const char *, size_t, long, long *, long *); int64_t ParseHttpDateTime(const char *, size_t); bool IsValidHttpToken(const char *, size_t); bool IsValidCookieValue(const char *, size_t); bool IsAcceptablePath(const char *, size_t); bool IsAcceptableHost(const char *, size_t); bool IsAcceptablePort(const char *, size_t); bool IsReasonablePath(const char *, size_t); int ParseForwarded(const char *, size_t, uint32_t *, uint16_t *); bool IsMimeType(const char *, size_t, const char *); ssize_t Unchunk(struct HttpUnchunker *, char *, size_t, size_t *); const char *FindContentType(const char *, size_t); bool IsNoCompressExt(const char *, size_t); char *FoldHeader(struct HttpMessage *, char *, int, size_t *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_HTTP_HTTP_H_ */
7,852
222
jart/cosmopolitan
false
cosmopolitan/net/http/headerhassubstring.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/str/str.h" #include "net/http/http.h" /** * Returns true if standard header has substring. * * @param m is message parsed by ParseHttpMessage * @param b is buffer that ParseHttpMessage parsed * @param h is known header, e.g. kHttpAcceptEncoding * @param s should not contain comma * @param n is byte length of s where -1 implies strlen * @return true if substring present */ bool HeaderHas(struct HttpMessage *m, const char *b, int h, const char *s, size_t n) { size_t i; _unassert(0 <= h && h < kHttpHeadersMax); if (n == -1) n = s ? strlen(s) : 0; if (m->headers[h].a) { if (memmem(b + m->headers[h].a, m->headers[h].b - m->headers[h].a, s, n)) { return true; } if (kHttpRepeatable[h]) { for (i = 0; i < m->xheaders.n; ++i) { if (GetHttpHeader(b + m->xheaders.p[i].k.a, m->xheaders.p[i].k.b - m->xheaders.p[i].k.a) == h && memmem(b + m->xheaders.p[i].v.a, m->xheaders.p[i].v.b - m->xheaders.p[i].v.a, s, n)) { return true; } } } } return false; }
2,979
55
jart/cosmopolitan
false
cosmopolitan/net/http/khttprepeatable.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/http.h" /** * Set of standard comma-separate HTTP headers that may span lines. * * These headers may specified on multiple lines, e.g. * * Allow: GET * Allow: POST * * Is the same as: * * Allow: GET, POST * * Standard headers that aren't part of this set will be overwritten in * the event that they're specified multiple times. For example, * * Content-Type: application/octet-stream * Content-Type: text/plain; charset=utf-8 * * Is the same as: * * Content-Type: text/plain; charset=utf-8 * * This set exists to optimize header lookups and parsing. The existence * of standard headers that aren't in this set is an O(1) operation. The * repeatable headers in this list require an O(1) operation if they are * not present, otherwise the extended headers list needs to be crawled. * * Please note non-standard headers exist, e.g. Cookie, that may span * multiple lines, even though they're not comma-delimited. For those * headers we simply don't add them to the perfect hash table. * * @note we choose to not recognize this grammar for kHttpConnection * @note `grep '[A-Z][a-z]*".*":"' rfc2616` * @note `grep ':.*#' rfc2616` * @see RFC7230 § 4.2 */ const bool kHttpRepeatable[kHttpHeadersMax] = { [kHttpAcceptCharset] = true, [kHttpAcceptEncoding] = true, [kHttpAcceptLanguage] = true, [kHttpAccept] = true, [kHttpAllow] = true, [kHttpCacheControl] = true, [kHttpContentEncoding] = true, [kHttpContentLanguage] = true, [kHttpExpect] = true, [kHttpIfMatch] = true, [kHttpIfNoneMatch] = true, [kHttpPragma] = true, [kHttpProxyAuthenticate] = true, [kHttpPublic] = true, [kHttpTe] = true, [kHttpTrailer] = true, [kHttpTransferEncoding] = true, [kHttpUpgrade] = true, [kHttpVary] = true, [kHttpVia] = true, [kHttpWarning] = true, [kHttpWwwAuthenticate] = true, [kHttpXForwardedFor] = true, [kHttpAccessControlAllowHeaders] = true, [kHttpAccessControlAllowMethods] = true, [kHttpAccessControlRequestHeaders] = true, [kHttpAccessControlRequestMethods] = true, };
3,982
86
jart/cosmopolitan
false
cosmopolitan/net/http/escapehost.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL host or registry name. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeHost(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeAuthority); }
2,187
32
jart/cosmopolitan
false
cosmopolitan/net/http/isacceptableport.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/http.h" /** * Returns true if port seems legit. * * Here's examples of permitted inputs: * * - "" * - 0 * - 65535 * * Here's some examples of forbidden inputs: * * - -1 * - 65536 * - https * * @param n if -1 implies strlen */ bool IsAcceptablePort(const char *s, size_t n) { int p, c; size_t i; if (n == -1) n = s ? strlen(s) : 0; for (p = i = 0; i < n; ++i) { c = s[i] & 255; if ('0' <= c && c <= '9') { p *= 10; p += c - '0'; if (p > 65535) { return false; } } else { return false; } } return true; }
2,467
57
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpmethod.inc
/* ANSI-C code produced by gperf version 3.1 */ /* Command-line: gperf gethttpmethod.gperf */ /* Computed positions: -k'1-2' */ /* clang-format off */ #if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) /* The character set is not based on ISO-646. */ #error "gperf generated tables don't work with this execution character set. Please report a bug to <[email protected]>." #endif #line 1 "gethttpmethod.gperf" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/http.h" #define GPERF_DOWNCASE #line 12 "gethttpmethod.gperf" struct HttpMethodSlot { char name[8]; char code; }; #define TOTAL_KEYWORDS 17 #define MIN_WORD_LENGTH 3 #define MAX_WORD_LENGTH 7 #define MIN_HASH_VALUE 3 #define MAX_HASH_VALUE 25 /* maximum key range = 23, duplicates = 0 */ #ifndef GPERF_DOWNCASE #define GPERF_DOWNCASE 1 static unsigned char gperf_downcase[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; #endif #ifndef GPERF_CASE_STRNCMP #define GPERF_CASE_STRNCMP 1 static inline int gperf_case_strncmp (register const char *s1, register const char *s2, register size_t n) { for (; n > 0;) { unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; if (c1 != 0 && c1 == c2) { n--; continue; } return (int)c1 - (int)c2; } return 0; } #endif #ifdef __GNUC__ __inline #else #ifdef __cplusplus inline #endif #endif static unsigned int hash (register const char *str, register size_t len) { static const unsigned char asso_values[] = { 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 0, 26, 5, 15, 0, 26, 5, 0, 26, 26, 10, 15, 10, 0, 5, 0, 26, 10, 26, 5, 0, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 0, 26, 5, 15, 0, 26, 5, 0, 26, 26, 10, 15, 10, 0, 5, 0, 26, 10, 26, 5, 0, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26 }; return len + asso_values[(unsigned char)str[1]] + asso_values[(unsigned char)str[0]]; } static inline const struct HttpMethodSlot * LookupHttpMethod (register const char *str, register size_t len) { static const struct HttpMethodSlot wordlist[] = { {""}, {""}, {""}, #line 18 "gethttpmethod.gperf" {"PUT", kHttpPut}, #line 16 "gethttpmethod.gperf" {"HEAD", kHttpHead}, #line 28 "gethttpmethod.gperf" {"PATCH", kHttpPatch}, #line 30 "gethttpmethod.gperf" {"UNLOCK", kHttpUnlock}, {""}, #line 15 "gethttpmethod.gperf" {"GET", kHttpGet}, #line 17 "gethttpmethod.gperf" {"POST", kHttpPost}, {""}, #line 27 "gethttpmethod.gperf" {"NOTIFY", kHttpNotify}, #line 19 "gethttpmethod.gperf" {"OPTIONS", kHttpOptions}, {""}, #line 22 "gethttpmethod.gperf" {"COPY", kHttpCopy}, #line 24 "gethttpmethod.gperf" {"MERGE", kHttpMerge}, #line 29 "gethttpmethod.gperf" {"REPORT", kHttpReport}, #line 20 "gethttpmethod.gperf" {"CONNECT", kHttpConnect}, {""}, #line 26 "gethttpmethod.gperf" {"MOVE", kHttpMove}, #line 21 "gethttpmethod.gperf" {"TRACE", kHttpTrace}, #line 14 "gethttpmethod.gperf" {"DELETE", kHttpDelete}, {""}, {""}, #line 23 "gethttpmethod.gperf" {"LOCK", kHttpLock}, #line 25 "gethttpmethod.gperf" {"MKCOL", kHttpMkcol} }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { register unsigned int key = hash (str, len); if (key <= MAX_HASH_VALUE) { register const char *s = wordlist[key].name; if ((((unsigned char)*str ^ (unsigned char)*s) & ~32) == 0 && !gperf_case_strncmp (str, s, len) && s[len] == '\0') return &wordlist[key]; } } return 0; }
7,504
197
jart/cosmopolitan
false
cosmopolitan/net/http/kescapesegment.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '.-~_@:!$&'"'"'()*+,;=' -iskEscapeSegment // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠ “# % / ! § &‘()*+,-. 0x20 // < >⁇ 0123456789:; = 0x30 // @ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|} ⌂ pqrstuvwxyz ~ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapeSegment[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, // 0x30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,179
61
jart/cosmopolitan
false
cosmopolitan/net/http/ismulticastip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is used for multicast. */ bool IsMulticastIp(uint32_t x) { return (x >> 28) == 0xE; /* 224.0.0.0/4 */ }
2,005
27
jart/cosmopolitan
false
cosmopolitan/net/http/kescapeauthority.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '_.!~*'"'"'();&=+$,-' -iskEscapeAuthority // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠ “# % / ! $ &‘()*+,-. 0x20 // : < >⁇ 0123456789 ; = 0x30 // @ ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|} ⌂ pqrstuvwxyz ~ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapeAuthority[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, // 0x30 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,180
61
jart/cosmopolitan
false
cosmopolitan/net/http/escapehtml.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/x/x.h" #include "net/http/escape.h" /** * Escapes HTML entities. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeHtml(const char *p, size_t n, size_t *z) { int c; size_t i; char *q, *r; if (z) *z = 0; if (n == -1) n = p ? strlen(p) : 0; if ((q = r = malloc(n * 6 + 1))) { for (i = 0; i < n; ++i) { switch ((c = p[i])) { case '&': q[0] = '&'; q[1] = 'a'; q[2] = 'm'; q[3] = 'p'; q[4] = ';'; q += 5; break; case '<': q[0] = '&'; q[1] = 'l'; q[2] = 't'; q[3] = ';'; q += 4; break; case '>': q[0] = '&'; q[1] = 'g'; q[2] = 't'; q[3] = ';'; q += 4; break; case '"': q[0] = '&'; q[1] = 'q'; q[2] = 'u'; q[3] = 'o'; q[4] = 't'; q[5] = ';'; q += 6; break; case '\'': q[0] = '&'; q[1] = '#'; q[2] = '3'; q[3] = '9'; q[4] = ';'; q += 5; break; default: *q++ = c; break; } } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; }
3,346
91
jart/cosmopolitan
false
cosmopolitan/net/http/hascontrolcodes.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/escape.h" /** * Returns true if C0 or C1 control codes are present * * @param p is input value * @param n if -1 implies strlen * @param f can have kControlWs, kControlC0, kControlC1 to forbid * @return index of first forbidden character or -1 * @see VisualizeControlCodes() */ ssize_t HasControlCodes(const char *p, size_t n, int f) { char t[256]; wint_t x, a, b; size_t i, j, m, g; bzero(t, sizeof(t)); if (f & kControlC0) memset(t + 0x00, 1, 0x20 - 0x00), t[0x7F] = 1; if (f & kControlC1) memset(t + 0x80, 1, 0xA0 - 0x80); t['\t'] = t['\r'] = t['\n'] = t['\v'] = !!(f & kControlWs); if (n == -1) n = p ? strlen(p) : 0; for (i = 0; i < n;) { g = i; x = p[i++] & 0xff; if (UNLIKELY(x >= 0300)) { a = ThomPikeByte(x); m = ThomPikeLen(x) - 1; if (i + m <= n) { for (j = 0;;) { b = p[i + j] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++j == m) { x = a; i += j; break; } } } } if (x < 256 && t[x]) { return g; } } return -1; }
3,077
67
jart/cosmopolitan
false
cosmopolitan/net/http/encodelatin1.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/intrin/pcmpgtb.h" #include "libc/intrin/pmovmskb.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "net/http/escape.h" /** * Encodes UTF-8 to ISO-8859-1. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @param f can kControlC0, kControlC1, kControlWs to forbid * @return allocated NUL-terminated buffer, or NULL w/ errno * @error EILSEQ means UTF-8 found we can't or won't re-encode * @error ENOMEM means malloc() failed */ char *EncodeLatin1(const char *p, size_t n, size_t *z, int f) { int c; size_t i; char t[256]; char *r, *q; bzero(t, sizeof(t)); if (f & kControlC0) memset(t + 0x00, 1, 0x20 - 0x00), t[0x7F] = 1; if (f & kControlC1) memset(t + 0x80, 1, 0xA0 - 0x80); t['\t'] = t['\r'] = t['\n'] = t['\v'] = !!(f & kControlWs); if (z) *z = 0; if (n == -1) n = p ? strlen(p) : 0; if ((q = r = malloc(n + 1))) { for (i = 0; i < n;) { c = p[i++] & 0xff; if (c >= 0300) { if ((c <= 0303) && i < n && (p[i] & 0300) == 0200) { c = (c & 037) << 6 | p[i++] & 077; } else { goto Invalid; } } if (t[c]) { goto Invalid; } *q++ = c; } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; Invalid: free(r); errno = EILSEQ; return NULL; }
3,286
74
jart/cosmopolitan
false
cosmopolitan/net/http/isripeip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is managed by RIPE NCC. */ bool IsRipeIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 2 || a == 5 || a == 25 || a == 31 || a == 37 || a == 46 || a == 51 || a == 53 || a == 57 || a == 62 || a == 77 || a == 78 || a == 79 || a == 80 || a == 81 || a == 82 || a == 83 || a == 84 || a == 85 || a == 86 || a == 87 || a == 88 || a == 89 || a == 90 || a == 91 || a == 92 || a == 93 || a == 94 || a == 95 || a == 109 || a == 141 || a == 145 || a == 151 || a == 176 || a == 178 || a == 185 || a == 188 || a == 193 || a == 194 || a == 195 || a == 212 || a == 213 || a == 217; }
2,545
35
jart/cosmopolitan
false
cosmopolitan/net/http/encodebase64.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "net/http/escape.h" #define CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /** * Encodes binary to base64 ascii representation. * * @param data is input value * @param size if -1 implies strlen * @param out_size if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EncodeBase64(const char *data, size_t size, size_t *out_size) { size_t n; unsigned w; char *r, *q; const unsigned char *p, *pe; if (size == -1) size = data ? strlen(data) : 0; if ((n = size) % 3) n += 3 - size % 3; n /= 3, n *= 4; if ((r = malloc(n + 1))) { for (q = r, p = (void *)data, pe = p + size; p < pe; p += 3) { w = p[0] << 020; if (p + 1 < pe) w |= p[1] << 010; if (p + 2 < pe) w |= p[2] << 000; *q++ = CHARS[(w >> 18) & 077]; *q++ = CHARS[(w >> 12) & 077]; *q++ = p + 1 < pe ? CHARS[(w >> 6) & 077] : '='; *q++ = p + 2 < pe ? CHARS[w & 077] : '='; } *q++ = '\0'; } else { n = 0; } if (out_size) { *out_size = n; } return r; }
2,973
60
jart/cosmopolitan
false
cosmopolitan/net/http/tokenbucket.h
#ifndef COSMOPOLITAN_NET_HTTP_TOKENBUCKET_H_ #define COSMOPOLITAN_NET_HTTP_TOKENBUCKET_H_ #include "libc/atomic.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void ReplenishTokens(atomic_uint_fast64_t *, size_t); int AcquireToken(atomic_schar *, uint32_t, int); int CountTokens(atomic_schar *, uint32_t, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTP_TOKENBUCKET_H_ */
445
14
jart/cosmopolitan
false
cosmopolitan/net/http/url.h
#ifndef COSMOPOLITAN_NET_HTTP_URL_H_ #define COSMOPOLITAN_NET_HTTP_URL_H_ #define kUrlPlus 1 #define kUrlLatin1 2 #define kUrlOpaque 4 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct UrlView { size_t n; char *p; }; struct UrlParams { size_t n; struct UrlParam { struct UrlView key; struct UrlView val; } * p; }; struct Url { struct UrlView scheme; /* must be [A-Za-z][-+.0-9A-Za-z]* or empty */ struct UrlView user; /* depends on host non-absence */ struct UrlView pass; /* depends on user non-absence */ struct UrlView host; /* or reg_name */ struct UrlView port; /* depends on host non-absence */ struct UrlView path; /* or opaque_part */ struct UrlParams params; struct UrlView fragment; }; char *EncodeUrl(struct Url *, size_t *); char *ParseUrl(const char *, size_t, struct Url *, int); char *ParseParams(const char *, size_t, struct UrlParams *); char *ParseHost(const char *, size_t, struct Url *); char *EscapeUrlView(char *, struct UrlView *, const char[256]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTP_URL_H_ */
1,151
44
jart/cosmopolitan
false
cosmopolitan/net/http/escapesegment.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL path segment. * * Please note this will URI encode the slash character. That's because * segments are the labels between the slashes in a path. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeSegment(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeSegment); }
2,312
35
jart/cosmopolitan
false
cosmopolitan/net/http/foldheader.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "net/http/http.h" /** * Collapses repeating headers onto a single line. */ char *FoldHeader(struct HttpMessage *msg, char *b, int h, size_t *z) { char *p; size_t i, n, m; struct HttpHeader *x; n = msg->headers[h].b - msg->headers[h].a; if ((p = malloc(n))) { memcpy(p, b + msg->headers[h].a, n); for (i = 0; i < msg->xheaders.n; ++i) { x = msg->xheaders.p + i; if (GetHttpHeader(b + x->k.a, x->k.b - x->k.a) == h) { m = x->v.b - x->v.a; if (!(p = realloc(p, n + 2 + m))) abort(); memcpy(mempcpy(p + n, ", ", 2), b + x->v.a, m); n += 2 + m; } } *z = n; } return p; }
2,580
47
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpmethod.gperf
%{ #include "libc/str/str.h" #include "net/http/http.h" #define GPERF_DOWNCASE %} %compare-strncmp %ignore-case %language=ANSI-C %readonly-tables %struct-type %define lookup-function-name LookupHttpMethod struct HttpMethodSlot { char name[8]; char code; }; %% DELETE, kHttpDelete GET, kHttpGet HEAD, kHttpHead POST, kHttpPost PUT, kHttpPut OPTIONS, kHttpOptions CONNECT, kHttpConnect TRACE, kHttpTrace COPY, kHttpCopy LOCK, kHttpLock MERGE, kHttpMerge MKCOL, kHttpMkcol MOVE, kHttpMove NOTIFY, kHttpNotify PATCH, kHttpPatch REPORT, kHttpReport UNLOCK, kHttpUnlock
667
31
jart/cosmopolitan
false
cosmopolitan/net/http/isanonymousip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is anonymous proxy provider. */ bool IsAnonymousIp(uint32_t x) { return (x & 0xffffffff) == 0x1f0e8527 || (x & 0xffffff00) == 0x2e138900 || (x & 0xffffff00) == 0x2e138f00 || (x & 0xfffffffe) == 0x32074e58 || (x & 0xfffffe00) == 0x3e490800 || (x & 0xffffffff) == 0x3feb9bd2 || (x & 0xffffffff) == 0x400c7617 || (x & 0xffffffff) == 0x400c7658 || (x & 0xffffff00) == 0x432b9c00 || (x & 0xffffff00) == 0x450a8b00 || (x & 0xffffff00) == 0x46e8f500 || (x & 0xffffffff) == 0x4a5209e0 || (x & 0xfffffe00) == 0x50fe4a00 || (x & 0xfffffe00) == 0x5d735200 || (x & 0xfffffe00) == 0x5d735400 || (x & 0xffffffff) == 0x602fe214 || (x & 0xffffff00) == 0x93cb7800 || (x & 0xffffffff) == 0xb0094b2b || (x & 0xffffffff) == 0xb9246491 || (x & 0xffffff00) == 0xc0ee1500 || (x & 0xffffffff) == 0xc16b1147 || (x & 0xffffffff) == 0xc6906958 || (x & 0xffffff00) == 0xc772df00 || (x & 0xffffff00) == 0xc7bcec00 || (x & 0xffffffff) == 0xc8c8c8c8 || (x & 0xffffff00) == 0xce47a200 || (x & 0xffffff00) == 0xcec46700 || (x & 0xffffffff) == 0xd02be134 || (x & 0xffffff00) == 0xd1d8c600 || (x & 0xfffffffc) == 0xd43fa9e8 || (x & 0xffffffff) == 0xd5eaf973 || (x & 0xffffff00) == 0xd897b400; }
3,196
42
jart/cosmopolitan
false
cosmopolitan/net/http/isnocompressext.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/intrin/bswap.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/http.h" static const char kNoCompressExts[][8] = { "bz2", // "gif", // "gz", // "jpg", // "lz4", // "mp4", // "mpeg", // "mpg", // "png", // "webp", // "xz", // "zip", // }; static bool BisectNoCompressExts(uint64_t ext) { int c, m, l, r; l = 0; r = ARRAYLEN(kNoCompressExts) - 1; while (l <= r) { m = (l + r) >> 1; if (READ64BE(kNoCompressExts[m]) < ext) { l = m + 1; } else if (READ64BE(kNoCompressExts[m]) > ext) { r = m - 1; } else { return true; } } return false; } bool IsNoCompressExt(const char *p, size_t n) { int c, i; uint64_t w; if (n == -1) n = p ? strlen(p) : 0; if (n) { for (i = w = 0; n--;) { c = p[n] & 255; if (c == '.') break; if (++i > 8) return false; w <<= 8; w |= kToLower[c]; } return BisectNoCompressExts(bswap_64(w)); } return false; }
2,953
74
jart/cosmopolitan
false
cosmopolitan/net/http/visualizecontrolcodes.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/tpenc.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/escape.h" /** * Makes control codes and trojan source plainly viewable. * * This is useful for logging data like HTTP messages, where we don't * want full blown C string literal escaping, but we don't want things * like raw ANSI control codes from untrusted devices in our terminals. * * This function also canonicalizes overlong encodings. Therefore it * isn't necessary to say VisualizeControlCodes(Underlong(𝑥))) since * VisualizeControlCodes(𝑥) will do the same thing. * * @param data is input value * @param size if -1 implies strlen * @param out_size if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *VisualizeControlCodes(const char *data, size_t size, size_t *out_size) { uint64_t w; char *r, *q; unsigned i, n; wint_t x, a, b; const char *p, *e; if (size == -1) size = data ? strlen(data) : 0; if ((r = malloc(size * 6 + 1))) { q = r; p = data; e = p + size; while (p < e) { x = *p++ & 0xff; if (x >= 0300) { a = ThomPikeByte(x); n = ThomPikeLen(x) - 1; if (p + n <= e) { for (i = 0;;) { b = p[i] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++i == n) { x = a; p += i; break; } } } } // remap trojan source characters if (x == 0x2028) { x = L'↵'; // line separator } else if (x == 0x2029) { x = L'¶'; // paragraph separator } else if (x == 0x202A) { x = L'⟫'; // left-to-right embedding } else if (x == 0x202B) { x = L'⟪'; // right-to-left embedding } else if (x == 0x202D) { x = L'❯'; // left-to-right override } else if (x == 0x202E) { x = L'❮'; // right-to-left override } else if (x == 0x2066) { x = L'⟩'; // left-to-right isolate } else if (x == 0x2067) { x = L'⟨'; // right-to-left isolate } else if (x == 0x2068) { x = L'⧽'; // first strong isolate } else if (x == 0x202C) { x = L'⇮'; // pop directional formatting } else if (x == 0x2069) { x = L'⇯'; // pop directional isolate } if (0x80 <= x && x < 0xA0) { q[0] = '\\'; q[1] = 'u'; q[2] = '0'; q[3] = '0'; q[4] = "0123456789abcdef"[(x & 0xF0) >> 4]; q[5] = "0123456789abcdef"[(x & 0x0F) >> 0]; q += 6; } else { if (0x00 <= x && x < 0x20) { if (x != '\t' && x != '\r' && x != '\n') { x += 0x2400; /* Control Pictures */ } } else if (x == 0x7F) { x = 0x2421; } w = _tpenc(x); do { *q++ = w; } while ((w >>= 8)); } } n = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } else { n = 0; } if (out_size) { *out_size = n; } return r; }
4,981
129
jart/cosmopolitan
false
cosmopolitan/net/http/escapeparam.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes query/form name/parameter. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeParam(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeParam); }
2,184
32
jart/cosmopolitan
false
cosmopolitan/net/http/isapnicip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is managed by APNIC. */ bool IsApnicIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 1 || a == 14 || a == 27 || a == 36 || a == 39 || a == 42 || a == 43 || a == 49 || a == 58 || a == 59 || a == 60 || a == 61 || a == 101 || a == 103 || a == 106 || a == 110 || a == 111 || a == 112 || a == 113 || a == 114 || a == 115 || a == 116 || a == 117 || a == 118 || a == 119 || a == 120 || a == 121 || a == 122 || a == 123 || a == 124 || a == 125 || a == 126 || a == 133 || a == 150 || a == 153 || a == 163 || a == 171 || a == 175 || a == 180 || a == 182 || a == 183 || a == 202 || a == 203 || a == 210 || a == 211 || a == 218 || a == 219 || a == 220 || a == 221 || a == 222 || a == 223; }
2,666
36
jart/cosmopolitan
false
cosmopolitan/net/http/isacceptablehost.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/dns/dns.h" #include "libc/str/str.h" #include "net/http/http.h" extern const char kHostChars[256]; // -_0-9A-Za-z /** * Returns true if host seems legit. * * This function may be called after ParseUrl() or ParseHost() has * already handled things like percent encoding. There's currently * no support for IPv6 and IPv7. * * Here's examples of permitted inputs: * * - "" * - 1.2.3.4 * - 1.2.3.4.arpa * - localservice * - hello.example * - _hello.example * - -hello.example * - hi-there.example * * Here's some examples of forbidden inputs: * * - ::1 * - 1.2.3 * - 1.2.3.4.5 * - .hi.example * - hi..example * * @param n if -1 implies strlen */ bool IsAcceptableHost(const char *s, size_t n) { size_t i; int c, b, j; if (n == -1) n = s ? strlen(s) : 0; if (!n) return true; if (n > DNS_NAME_MAX) { return false; } for (b = j = i = 0; i < n; ++i) { c = s[i] & 255; if (isdigit(c)) { b *= 10; b += c - '0'; } else if (c == '.') { if (!i || s[i - 1] == '.') { return false; } b = 0; ++j; } else { for (;;) { if (!kHostChars[c] && (c != '.' || (!i || s[i - 1] == '.'))) { return false; } if (++i < n) { c = s[i] & 255; } else { return true; } } } } if (j != 3) { return false; } if (i && s[i - 1] == '.') { return false; } return true; }
3,296
93
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpreason.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/itoa.h" #include "libc/macros.internal.h" #include "net/http/http.h" static const struct thatispacked HttpReason { short code; const char *name; } kHttpReason[] = { {100, "Continue"}, {101, "Switching Protocols"}, {102, "Processing"}, {200, "OK"}, {201, "Created"}, {202, "Accepted"}, {203, "Non-authoritative Information"}, {204, "No Content"}, {205, "Reset Content"}, {206, "Partial Content"}, {207, "Multi-Status"}, {208, "Already Reported"}, {226, "IM Used"}, {300, "Multiple Choices"}, {301, "Moved Permanently"}, {302, "Found"}, {303, "See Other"}, {304, "Not Modified"}, {305, "Use Proxy"}, {307, "Temporary Redirect"}, {308, "Permanent Redirect"}, {400, "Bad Request"}, {401, "Unauthorized"}, {402, "Payment Required"}, {403, "Forbidden"}, {404, "Not Found"}, {405, "Method Not Allowed"}, {406, "Not Acceptable"}, {407, "Proxy Authentication Required"}, {408, "Request Timeout"}, {409, "Conflict"}, {410, "Gone"}, {411, "Length Required"}, {412, "Precondition Failed"}, {413, "Payload Too Large"}, {414, "Request-URI Too Long"}, {415, "Unsupported Media Type"}, {416, "Requested Range Not Satisfiable"}, {417, "Expectation Failed"}, {418, "I'm a teapot"}, {421, "Misdirected Request"}, {422, "Unprocessable Entity"}, {423, "Locked"}, {424, "Failed Dependency"}, {426, "Upgrade Required"}, {428, "Precondition Required"}, {429, "Too Many Requests"}, {431, "Request Header Fields Too Large"}, {444, "Connection Closed Without Response"}, {451, "Unavailable For Legal Reasons"}, {499, "Client Closed Request"}, {500, "Internal Server Error"}, {501, "Not Implemented"}, {502, "Bad Gateway"}, {503, "Service Unavailable"}, {504, "Gateway Timeout"}, {505, "HTTP Version Not Supported"}, {506, "Variant Also Negotiates"}, {507, "Insufficient Storage"}, {508, "Loop Detected"}, {510, "Not Extended"}, {511, "Network Authentication Required"}, {599, "Network Connect Timeout Error"}, }; /** * Returns string describing HTTP reason phrase. * * @see https://tools.ietf.org/html/rfc2616 * @see https://tools.ietf.org/html/rfc6585 */ const char *GetHttpReason(int code) { int m, l, r; l = 0; r = ARRAYLEN(kHttpReason) - 1; while (l <= r) { m = (l + r) >> 1; if (kHttpReason[m].code < code) { l = m + 1; } else if (kHttpReason[m].code > code) { r = m - 1; } else { return kHttpReason[m].name; } } return ""; }
4,472
114
jart/cosmopolitan
false
cosmopolitan/net/http/khostchars.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DA _- -skHostChars // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // - ␠!“#§%&‘()*+, ./ 0x20 // 0123456789 :;<=>⁇ 0x30 // ABCDEFGHIJKLMNO @ 0x40 // PQRSTUVWXYZ _ [⭝]^ 0x50 // abcdefghijklmno ` 0x60 // pqrstuvwxyz {|}~⌂ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kHostChars[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 0x50 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 0x70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 };
4,148
61
jart/cosmopolitan
false
cosmopolitan/net/http/isdodip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IP is owned by the U.S. Department of Defense. */ bool IsDodIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 6 || a == 7 || a == 11 || a == 21 || a == 22 || a == 26 || a == 28 || a == 29 || a == 30 || a == 33 || a == 55 || a == 214 || a == 215; }
2,167
30
jart/cosmopolitan
false
cosmopolitan/net/http/underlong.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/pcmpgtb.h" #include "libc/intrin/pmovmskb.h" #include "libc/intrin/tpenc.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/escape.h" /** * Canonicalizes overlong Thompson-Pike encodings. * * Please note that the IETF banned these numbers, so if you want to * enforce their ban you can simply strcmp() the result to check for * the existence of banned numbers. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *Underlong(const char *p, size_t n, size_t *z) { uint64_t w; char *r, *q; size_t i, j, m; wint_t x, a, b; int8_t v1[16], v2[16], vz[16]; if (z) *z = 0; if (n == -1) n = p ? strlen(p) : 0; if ((q = r = malloc(n * 2 + 1))) { for (i = 0; i < n;) { bzero(vz, 16); /* 50x speedup for ASCII */ while (i + 16 < n) { memcpy(v1, p + i, 16); pcmpgtb(v2, v1, vz); if (pmovmskb((void *)v2) != 0xFFFF) break; memcpy(q, v1, 16); q += 16; i += 16; } x = p[i++] & 0xff; if (x >= 0300) { a = ThomPikeByte(x); m = ThomPikeLen(x) - 1; if (i + m <= n) { for (j = 0;;) { b = p[i + j] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++j == m) { x = a; i += j; break; } } } } w = _tpenc(x); do { *q++ = w; } while ((w >>= 8)); } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; }
3,569
86
jart/cosmopolitan
false
cosmopolitan/net/http/getipcategoryname.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Describes IP address. * @see CategorizeIp() */ const char *GetIpCategoryName(int c) { switch (c) { case kIpMulticast: return "MULTICAST"; case kIpLoopback: return "LOOPBACK"; case kIpPrivate: return "PRIVATE"; case kIpTestnet: return "TESTNET"; case kIpAfrinic: return "AFRINIC"; case kIpLacnic: return "LACNIC"; case kIpApnic: return "APNIC"; case kIpArin: return "ARIN"; case kIpRipe: return "RIPE"; case kIpDod: return "DOD"; case kIpAtt: return "AT&T"; case kIpApple: return "APPLE"; case kIpFord: return "FORD"; case kIpCogent: return "COGENT"; case kIpPrudential: return "PRUDENTIAL"; case kIpUsps: return "USPS"; case kIpComcast: return "COMCAST"; case kIpFuture: return "FUTURE"; case kIpAnonymous: return "ANONYMOUS"; default: return NULL; } }
2,828
69
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpheader.inc
/* ANSI-C code produced by gperf version 3.1 */ /* Command-line: gperf gethttpheader.gperf */ /* Computed positions: -k'5,10-11,22,$' */ // clang-format off #if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) /* The character set is not based on ISO-646. */ #error "gperf generated tables don't work with this execution character set. Please report a bug to <[email protected]>." #endif #line 1 "gethttpheader.gperf" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/http.h" #define GPERF_DOWNCASE #line 12 "gethttpheader.gperf" struct thatispacked HttpHeaderSlot { char *name; char code; }; #define TOTAL_KEYWORDS 93 #define MIN_WORD_LENGTH 2 #define MAX_WORD_LENGTH 32 #define MIN_HASH_VALUE 3 #define MAX_HASH_VALUE 181 /* maximum key range = 179, duplicates = 0 */ #ifndef GPERF_DOWNCASE #define GPERF_DOWNCASE 1 static unsigned char gperf_downcase[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; #endif #ifndef GPERF_CASE_STRNCMP #define GPERF_CASE_STRNCMP 1 static inline int gperf_case_strncmp (register const char *s1, register const char *s2, register size_t n) { for (; n > 0;) { unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; if (c1 != 0 && c1 == c2) { n--; continue; } return (int)c1 - (int)c2; } return 0; } #endif #ifdef __GNUC__ __inline #else #ifdef __cplusplus inline #endif #endif static inline unsigned int hash (register const char *str, register size_t len) { static const unsigned char asso_values[] = { 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 35, 182, 182, 182, 182, 182, 182, 182, 5, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 15, 182, 30, 60, 10, 5, 40, 0, 40, 182, 80, 40, 90, 0, 45, 5, 0, 45, 0, 0, 0, 182, 0, 182, 45, 182, 182, 182, 182, 182, 182, 182, 15, 182, 30, 60, 10, 5, 40, 0, 40, 182, 80, 40, 90, 0, 45, 5, 0, 45, 0, 0, 0, 182, 0, 182, 45, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182 }; register unsigned int hval = len; switch (hval) { default: hval += asso_values[(unsigned char)str[21]]; /*FALLTHROUGH*/ case 21: case 20: case 19: case 18: case 17: case 16: case 15: case 14: case 13: case 12: case 11: hval += asso_values[(unsigned char)str[10]]; /*FALLTHROUGH*/ case 10: hval += asso_values[(unsigned char)str[9]]; /*FALLTHROUGH*/ case 9: case 8: case 7: case 6: case 5: hval += asso_values[(unsigned char)str[4]]; /*FALLTHROUGH*/ case 4: case 3: case 2: break; } return hval + asso_values[(unsigned char)str[len - 1]]; } static inline const struct thatispacked HttpHeaderSlot * LookupHttpHeader (register const char *str, register size_t len) { static const struct thatispacked HttpHeaderSlot wordlist[] = { {""}, {""}, {""}, #line 27 "gethttpheader.gperf" {"DNT", kHttpDnt}, #line 14 "gethttpheader.gperf" {"Host", kHttpHost}, #line 46 "gethttpheader.gperf" {"Allow", kHttpAllow}, {""}, {""}, #line 73 "gethttpheader.gperf" {"Location", kHttpLocation}, {""}, {""}, #line 17 "gethttpheader.gperf" {"Accept", kHttpAccept}, #line 80 "gethttpheader.gperf" {"TE", kHttpTe}, #line 58 "gethttpheader.gperf" {"Age", kHttpAge}, #line 40 "gethttpheader.gperf" {"Date", kHttpDate}, {""}, {""}, {""}, #line 86 "gethttpheader.gperf" {"Via", kHttpVia}, {""}, #line 16 "gethttpheader.gperf" {"Connection", kHttpConnection}, {""}, {""}, #line 67 "gethttpheader.gperf" {"If-Match", kHttpIfMatch}, {""}, #line 36 "gethttpheader.gperf" {"Range", kHttpRange}, #line 92 "gethttpheader.gperf" {"X-XSS-Protection", kHttpXXssProtection}, {""}, #line 50 "gethttpheader.gperf" {"Access-Control-Allow-Headers", kHttpAccessControlAllowHeaders}, #line 55 "gethttpheader.gperf" {"Access-Control-RequestHeaders", kHttpAccessControlRequestHeaders}, #line 57 "gethttpheader.gperf" {"Access-Control-Request-Methods", kHttpAccessControlRequestMethods}, #line 53 "gethttpheader.gperf" {"Access-Control-MaxAge", kHttpAccessControlMaxAge}, #line 83 "gethttpheader.gperf" {"Upgrade", kHttpUpgrade}, #line 69 "gethttpheader.gperf" {"If-Range", kHttpIfRange}, #line 37 "gethttpheader.gperf" {"Content-Length", kHttpContentLength}, #line 88 "gethttpheader.gperf" {"X-Frame-Options", kHttpXFrameOptions}, #line 66 "gethttpheader.gperf" {"Expect", kHttpExpect}, #line 90 "gethttpheader.gperf" {"Alt-Svc", kHttpAltSvc}, {""}, #line 61 "gethttpheader.gperf" {"Content-Description", kHttpContentDescription}, {""}, #line 85 "gethttpheader.gperf" {"WWW-Authenticate", kHttpWwwAuthenticate}, {""}, {""}, #line 45 "gethttpheader.gperf" {"ETag", kHttpEtag}, #line 20 "gethttpheader.gperf" {"User-Agent", kHttpUserAgent}, #line 23 "gethttpheader.gperf" {"Origin", kHttpOrigin}, #line 60 "gethttpheader.gperf" {"Content-Base", kHttpContentBase}, #line 47 "gethttpheader.gperf" {"Content-Range", kHttpContentRange}, #line 39 "gethttpheader.gperf" {"Vary", kHttpVary}, #line 24 "gethttpheader.gperf" {"Upgrade-Insecure-Requests", kHttpUpgradeInsecureRequests}, #line 63 "gethttpheader.gperf" {"Content-Language", kHttpContentLanguage}, #line 42 "gethttpheader.gperf" {"Expires", kHttpExpires}, #line 106 "gethttpheader.gperf" {"CDN-Loop", kHttpCdnLoop}, #line 95 "gethttpheader.gperf" {"Sec-CH-UA", kHttpSecChUa}, {""}, #line 26 "gethttpheader.gperf" {"Cookie", kHttpCookie}, #line 89 "gethttpheader.gperf" {"X-Content-Type-Options", kHttpXContentTypeOptions}, #line 93 "gethttpheader.gperf" {"Accept-Ranges", kHttpAcceptRanges}, #line 35 "gethttpheader.gperf" {"Save-Data", kHttpSaveData}, #line 94 "gethttpheader.gperf" {"Set-Cookie", kHttpSetCookie}, #line 41 "gethttpheader.gperf" {"Server", kHttpServer}, #line 49 "gethttpheader.gperf" {"Access-Control-Allow-Credentials", kHttpAccessControlAllowCredentials}, {""}, #line 98 "gethttpheader.gperf" {"Sec-Fetch-Site", kHttpSecFetchSite}, #line 71 "gethttpheader.gperf" {"Keep-Alive", kHttpKeepAlive}, #line 102 "gethttpheader.gperf" {"CF-RAY", kHttpCfRay}, #line 82 "gethttpheader.gperf" {"Transfer-Encoding", kHttpTransferEncoding}, {""}, #line 62 "gethttpheader.gperf" {"Content-Disposition", kHttpContentDisposition}, #line 18 "gethttpheader.gperf" {"Accept-Language", kHttpAcceptLanguage}, #line 77 "gethttpheader.gperf" {"Proxy-Connection", kHttpProxyConnection}, #line 52 "gethttpheader.gperf" {"Access-Control-Allow-Origin", kHttpAccessControlAllowOrigin}, #line 68 "gethttpheader.gperf" {"If-None-Match", kHttpIfNoneMatch}, #line 70 "gethttpheader.gperf" {"If-Unmodified-Since", kHttpIfUnmodifiedSince}, {""}, #line 78 "gethttpheader.gperf" {"Public", kHttpPublic}, #line 28 "gethttpheader.gperf" {"Sec-GPC", kHttpSecGpc}, {""}, #line 48 "gethttpheader.gperf" {"Accept-Charset", kHttpAcceptCharset}, {""}, #line 54 "gethttpheader.gperf" {"Access-Control-Method", kHttpAccessControlMethod}, #line 38 "gethttpheader.gperf" {"Content-Type", kHttpContentType}, #line 75 "gethttpheader.gperf" {"Proxy-Authenticate", kHttpProxyAuthenticate}, #line 72 "gethttpheader.gperf" {"Link", kHttpLink}, {""}, #line 31 "gethttpheader.gperf" {"X-Requested-With", kHttpXRequestedWith}, #line 84 "gethttpheader.gperf" {"Warning", kHttpWarning}, {""}, #line 56 "gethttpheader.gperf" {"Access-Control-Request-Method", kHttpAccessControlRequestMethod}, {""}, #line 65 "gethttpheader.gperf" {"Content-MD5", kHttpContentMd5}, #line 81 "gethttpheader.gperf" {"Trailer", kHttpTrailer}, {""}, #line 29 "gethttpheader.gperf" {"From", kHttpFrom}, {""}, #line 43 "gethttpheader.gperf" {"Content-Encoding", kHttpContentEncoding}, #line 21 "gethttpheader.gperf" {"Referer", kHttpReferer}, #line 59 "gethttpheader.gperf" {"Authorization", kHttpAuthorization}, #line 100 "gethttpheader.gperf" {"Sec-Fetch-User", kHttpSecFetchUser}, {""}, #line 64 "gethttpheader.gperf" {"Content-Location", kHttpContentLocation}, {""}, {""}, {""}, {""}, #line 104 "gethttpheader.gperf" {"CF-Connecting-IP", kHttpCfConnectingIp}, #line 105 "gethttpheader.gperf" {"CF-IPCountry", kHttpCfIpcountry}, #line 15 "gethttpheader.gperf" {"Cache-Control", kHttpCacheControl}, #line 76 "gethttpheader.gperf" {"Proxy-Authorization", kHttpProxyAuthorization}, {""}, #line 25 "gethttpheader.gperf" {"Pragma", kHttpPragma}, {""}, {""}, #line 101 "gethttpheader.gperf" {"Sec-Fetch-Dest", kHttpSecFetchDest}, {""}, {""}, {""}, #line 51 "gethttpheader.gperf" {"Access-Control-Allow-Methods", kHttpAccessControlAllowMethods}, {""}, {""}, {""}, #line 74 "gethttpheader.gperf" {"Max-Forwards", kHttpMaxForwards}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, #line 32 "gethttpheader.gperf" {"X-Forwarded-Host", kHttpXForwardedHost}, {""}, {""}, {""}, #line 19 "gethttpheader.gperf" {"Accept-Encoding", kHttpAcceptEncoding}, {""}, {""}, {""}, {""}, #line 103 "gethttpheader.gperf" {"CF-Visitor", kHttpCfVisitor}, {""}, #line 30 "gethttpheader.gperf" {"If-Modified-Since", kHttpIfModifiedSince}, {""}, {""}, {""}, {""}, #line 34 "gethttpheader.gperf" {"X-CSRF-Token", kHttpXCsrfToken}, {""}, {""}, {""}, {""}, {""}, #line 44 "gethttpheader.gperf" {"Last-Modified", kHttpLastModified}, #line 99 "gethttpheader.gperf" {"Sec-Fetch-Mode", kHttpSecFetchMode}, #line 91 "gethttpheader.gperf" {"Referrer-Policy", kHttpReferrerPolicy}, #line 79 "gethttpheader.gperf" {"Retry-After", kHttpRetryAfter}, {""}, {""}, {""}, #line 87 "gethttpheader.gperf" {"Strict-Transport-Security", kHttpStrictTransportSecurity}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, #line 22 "gethttpheader.gperf" {"X-Forwarded-For", kHttpXForwardedFor}, {""}, #line 33 "gethttpheader.gperf" {"X-Forwarded-Proto", kHttpXForwardedProto}, #line 97 "gethttpheader.gperf" {"Sec-CH-UA-Platform", kHttpSecChUaPlatform}, {""}, {""}, #line 96 "gethttpheader.gperf" {"Sec-CH-UA-Mobile", kHttpSecChUaMobile} }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { register unsigned int key = hash (str, len); if (key <= MAX_HASH_VALUE) { register const char *s = wordlist[key].name; if ((((unsigned char)*str ^ (unsigned char)*s) & ~32) == 0 && !gperf_case_strncmp (str, s, len) && s[len] == '\0') return &wordlist[key]; } } return 0; }
16,754
417
jart/cosmopolitan
false
cosmopolitan/net/http/escapepass.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL password. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapePass(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeAuthority); }
2,174
32
jart/cosmopolitan
false
cosmopolitan/net/http/escapefragment.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL fragment. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeFragment(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeFragment); }
2,177
32
jart/cosmopolitan
false
cosmopolitan/net/http/kescapepath.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '.-~_@:!$&'"'"'()*+,;=/' -iskEscapePath // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠ “# % ! § &‘()*+,-./ 0x20 // < >⁇ 0123456789:; = 0x30 // @ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|} ⌂ pqrstuvwxyz ~ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapePath[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, // 0x30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,174
61
jart/cosmopolitan
false
cosmopolitan/net/http/parsehttprange.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/str/str.h" #include "net/http/http.h" /** * Parses HTTP Range request header. * * Here are some example values: * * Range: bytes=0- (everything) * Range: bytes=0-499 (first 500 bytes) * Range: bytes=500-999 (second 500 bytes) * Range: bytes=-500 (final 500 bytes) * Range: bytes=0-0,-1 (first and last and always) * Range: bytes=500-600,601-999 (overlong but legal) */ bool ParseHttpRange(const char *p, size_t n, long resourcelength, long *out_start, long *out_length) { long start, length, ending; *out_start = 0; *out_length = 0; if (memchr(p, ',', n)) return false; if (n < 7 || memcmp(p, "bytes=", 6) != 0) return false; p += 6, n -= 6; if (n && *p == '-') { ++p, --n; length = 0; while (n && '0' <= *p && *p <= '9') { if (__builtin_mul_overflow(length, 10, &length)) return false; if (__builtin_add_overflow(length, *p - '0', &length)) return false; ++p, --n; } if (__builtin_sub_overflow(resourcelength, length, &start)) return false; } else { start = 0; while (n && '0' <= *p && *p <= '9') { if (__builtin_mul_overflow(start, 10, &start)) return false; if (__builtin_add_overflow(start, *p - '0', &start)) return false; ++p, --n; } if (n && *p == '-') { ++p, --n; if (!n) { length = MAX(start, resourcelength) - start; } else { length = 0; while (n && '0' <= *p && *p <= '9') { if (__builtin_mul_overflow(length, 10, &length)) return false; if (__builtin_add_overflow(length, *p - '0', &length)) return false; ++p, --n; } if (__builtin_add_overflow(length, 1, &length)) return false; if (__builtin_sub_overflow(length, start, &length)) return false; } } else if (__builtin_sub_overflow(resourcelength, start, &length)) { return false; } } if (n) return false; if (start < 0) return false; if (length < 1) return false; if (start > resourcelength) return false; if (__builtin_add_overflow(start, length, &ending)) return false; if (ending > resourcelength) { length = resourcelength - start; } *out_start = start; *out_length = length; return true; }
4,198
89
jart/cosmopolitan
false
cosmopolitan/net/http/parseurl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/limits.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/x/x.h" #include "net/http/escape.h" #include "net/http/url.h" struct UrlParser { char *p, *q; const char *s; unsigned c, i, n, f; }; static void EmitLatin1(char **p, int c) { (*p)[0] = 0300 | c >> 6; (*p)[1] = 0200 | c & 077; *p += 2; } static bool EmitKey(struct UrlParser *u, struct UrlParams *h) { struct UrlParam *p; if ((p = realloc(h->p, ++h->n * sizeof(*h->p)))) { p[h->n - 1].key.p = u->q; p[h->n - 1].key.n = u->p - u->q; u->q = u->p; h->p = p; return true; } else { return false; } } static void EmitVal(struct UrlParser *u, struct UrlParams *h, bool t) { if (!t) { if (u->p > u->q || u->c != '?') { if (EmitKey(u, h)) { h->p[h->n - 1].val.p = NULL; h->p[h->n - 1].val.n = 0; } } } else { h->p[h->n - 1].val.p = u->q; h->p[h->n - 1].val.n = u->p - u->q; u->q = u->p; } } static void ParseEscape(struct UrlParser *u) { int a, b, c = '%'; if (u->i + 2 <= u->n && ((a = kHexToInt[u->s[u->i + 0] & 255]) != -1 && (b = kHexToInt[u->s[u->i + 1] & 255]) != -1)) { c = a << 4 | b; u->i += 2; } *u->p++ = c; } static bool ParseScheme(struct UrlParser *u, struct Url *h) { while (u->i < u->n) { u->c = u->s[u->i++] & 255; if (u->c == '/') { if (u->i == 1 && u->i < u->n && u->s[u->i] == '/') { ++u->i; return true; } else { *u->p++ = '/'; return false; } } else if (u->c == ':' && u->i > 1) { h->scheme.p = u->q; h->scheme.n = u->p - u->q; u->q = u->p; if (u->i < u->n && u->s[u->i] == '/') { if (u->i + 1 < u->n && u->s[u->i + 1] == '/') { u->i += 2; return true; } else { return false; } } else { u->f |= kUrlOpaque; return false; } } else if (u->c == '#' || u->c == '?') { h->path.p = u->q; h->path.n = u->p - u->q; u->q = u->p; return false; } else if (u->c == '%') { ParseEscape(u); return false; } else if (u->c >= 0200 && (u->f & kUrlLatin1)) { EmitLatin1(&u->p, u->c); return false; } else { *u->p++ = u->c; if (u->i == 1) { if (!(('A' <= u->c && u->c <= 'Z') || ('a' <= u->c && u->c <= 'z'))) { return false; } } else { if (!(('0' <= u->c && u->c <= '9') || ('A' <= u->c && u->c <= 'Z') || ('a' <= u->c && u->c <= 'z') || u->c == '+' || u->c == '-' || u->c == '.')) { return false; } } } } return false; } static void ParseAuthority(struct UrlParser *u, struct Url *h) { unsigned t = 1; const char *c = NULL; while (u->i < u->n) { u->c = u->s[u->i++] & 255; if (u->c == '/' || u->c == '#' || u->c == '?') { break; } else if (u->c == '[') { t = 0; } else if (u->c == ']') { t = 1; } else if (u->c == ':' && t > 0) { *u->p++ = ':'; c = u->p; ++t; } else if (u->c == '@') { if (c) { h->user.p = u->q; h->user.n = c - 1 - u->q; h->pass.p = c; h->pass.n = u->p - c; c = NULL; t = 1; } else { h->user.p = u->q; h->user.n = u->p - u->q; } u->q = u->p; } else if (u->c == '%') { ParseEscape(u); } else if (u->c >= 0200 && (u->f & kUrlLatin1)) { EmitLatin1(&u->p, u->c); } else { *u->p++ = u->c; } } if (t == 2) { h->host.p = u->q; h->host.n = c - 1 - u->q; h->port.p = c; h->port.n = u->p - c; c = NULL; } else { h->host.p = u->q; h->host.n = u->p - u->q; } u->q = u->p; if (u->c == '/') { *u->p++ = u->c; } } static void ParsePath(struct UrlParser *u, struct UrlView *h) { while (u->i < u->n) { u->c = u->s[u->i++] & 255; if (u->c == '#') { break; } else if (u->c == '?' && !(u->f & kUrlOpaque)) { break; } else if (u->c == '%') { ParseEscape(u); } else if (u->c >= 0200 && (u->f & kUrlLatin1)) { EmitLatin1(&u->p, u->c); } else { *u->p++ = u->c; } } h->p = u->q; h->n = u->p - u->q; u->q = u->p; } static void ParseQuery(struct UrlParser *u, struct UrlParams *h) { bool t = false; if (!h->p) h->p = malloc(0); while (u->i < u->n) { u->c = u->s[u->i++] & 255; if (u->c == '#') { break; } else if (u->c == '%') { ParseEscape(u); } else if (u->c == '+') { *u->p++ = (u->f & kUrlPlus) ? ' ' : '+'; } else if (u->c == '&') { EmitVal(u, h, t); t = false; } else if (u->c == '=') { if (!t) { t = EmitKey(u, h); } else { *u->p++ = '='; } } else if (u->c >= 0200 && (u->f & kUrlLatin1)) { EmitLatin1(&u->p, u->c); } else { *u->p++ = u->c; } } EmitVal(u, h, t); } static void ParseFragment(struct UrlParser *u, struct UrlView *h) { while (u->i < u->n) { u->c = u->s[u->i++] & 255; if (u->c == '%') { ParseEscape(u); } else if (u->c >= 0200 && (u->f & kUrlLatin1)) { EmitLatin1(&u->p, u->c); } else { *u->p++ = u->c; } } h->p = u->q; h->n = u->p - u->q; u->q = u->p; } /** * Parses URL. * * This parser is charset agnostic. Percent encoded bytes are decoded * for all fields (with the exception of scheme). Returned values might * contain things like NUL characters, spaces, control codes, and * non-canonical encodings. Absent can be discerned from empty by * checking if the pointer is set. * * There's no failure condition for this routine. This is a permissive * parser. This doesn't normalize path segments like `.` or `..` so use * IsAcceptablePath() to check for those. No restrictions are imposed * beyond that which is strictly necessary for parsing. All the s * that is provided will be consumed to the one of the fields. Strict * conformance is enforced on some fields more than others, like scheme, * since it's the most non-deterministically defined field of them all. * * Please note this is a URL parser, not a URI parser. Which means we * support everything the URI spec says we should do except for the * things we won't do, like tokenizing path segments into an array * and then nesting another array beneath each of those for storing * semicolon parameters. So this parser won't make SIP easy. What it * can do is parse HTTP URLs and most URIs like s:opaque, better in * fact than most things which claim to be URI parsers. * * @param s is value like `/hi?x=y&z` or `http://a.example/hi#x` * @param n is byte length and -1 implies strlen * @param h is assumed to be uninitialized * @param f is flags which may have: * - `FLAGS_PLUS` to turn `+` into space in query params * - `FLAGS_LATIN1` to transcode ISO-8859-1 input into UTF-8 * @return memory backing UrlView needing free (and h.params.p too) * @see URI Generic Syntax RFC3986 RFC2396 * @see EncodeUrl() */ char *ParseUrl(const char *s, size_t n, struct Url *h, int f) { char *m; struct UrlParser u; if (n == -1) n = s ? strlen(s) : 0; u.i = 0; u.c = 0; u.s = s; u.n = n; u.f = f; bzero(h, sizeof(*h)); if ((m = malloc((f & kUrlLatin1) ? u.n * 2 : u.n))) { u.q = u.p = m; if (ParseScheme(&u, h)) ParseAuthority(&u, h); if (u.c != '#' && u.c != '?') ParsePath(&u, &h->path); if (u.c == '?') ParseQuery(&u, &h->params); if (u.c == '#') ParseFragment(&u, &h->fragment); } return m; } /** * Parses HTTP POST key-value params. * * These are similar to the parameters found in a Request-URI, except * usually submitted via an HTTP POST request. We translate `+` into * space. The mime type is application/x-www-form-urlencoded. * * This parser is charset agnostic. Returned values might contain things * like NUL characters, NUL, control codes, and non-canonical encodings. * Absent can be discerned from empty by checking if the pointer is set. * * There's no failure condition for this routine. This is a permissive * parser that doesn't impose character restrictions beyond what is * necessary for parsing. * * @param s is value like `foo=bar&x=y&z` * @param n is byte length and -1 implies strlen * @param h must be zeroed by caller and this appends if reused * @return UrlView memory with same n needing free (h.p needs free too) */ char *ParseParams(const char *s, size_t n, struct UrlParams *h) { char *m; struct UrlParser u; if (n == -1) n = s ? strlen(s) : 0; u.i = 0; u.s = s; u.n = n; u.c = '?'; u.f = kUrlPlus; if ((m = malloc(u.n))) { u.q = u.p = m; ParseQuery(&u, h); } return m; } /** * Parses HTTP Host header. * * The input is ISO-8859-1 which is transcoded to UTF-8. Therefore we * assume percent-encoded bytes are expressed as UTF-8. Returned values * might contain things like NUL characters, C0, and C1 control codes. * UTF-8 isn't checked for validity and may contain overlong values. * Absent can be discerned from empty by checking if the pointer is set. * * This function turns an HTTP header HOST[:PORT] into two strings, one * for host and the other for port. You may then call IsAcceptableHost() * and IsAcceptablePort() to see if they are valid values. After that a * function like sscanf() can be used to do the thing you likely thought * this function would do. * * This function doesn't initialize h since it's assumed this will be * called conditionally after ParseRequestUri() if the host is absent. * Fields unrelated to authority won't be impacted by this function. * * @param s is value like `127.0.0.1` or `foo.example:80` * @param n is byte length and -1 implies strlen * @param h is needs to be initialized by caller * @return memory backing UrlView needing free */ char *ParseHost(const char *s, size_t n, struct Url *h) { char *m; struct UrlParser u; if (n == -1) n = s ? strlen(s) : 0; u.i = 0; u.c = 0; u.s = s; u.n = n; u.f = kUrlLatin1; if ((m = malloc(u.n * 2))) { u.q = u.p = m; ParseAuthority(&u, h); } return m; }
12,080
380
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpheadername.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/http.h" const char *GetHttpHeaderName(int h) { switch (h) { case kHttpHost: return "Host"; case kHttpCacheControl: return "Cache-Control"; case kHttpConnection: return "Connection"; case kHttpAccept: return "Accept"; case kHttpAcceptLanguage: return "Accept-Language"; case kHttpAcceptEncoding: return "Accept-Encoding"; case kHttpUserAgent: return "User-Agent"; case kHttpReferer: return "Referer"; case kHttpXForwardedFor: return "X-Forwarded-For"; case kHttpOrigin: return "Origin"; case kHttpUpgradeInsecureRequests: return "Upgrade-Insecure-Requests"; case kHttpPragma: return "Pragma"; case kHttpCookie: return "Cookie"; case kHttpDnt: return "DNT"; case kHttpSecGpc: return "Sec-GPC"; case kHttpFrom: return "From"; case kHttpIfModifiedSince: return "If-Modified-Since"; case kHttpXRequestedWith: return "X-Requested-With"; case kHttpXForwardedHost: return "X-Forwarded-Host"; case kHttpXForwardedProto: return "X-Forwarded-Proto"; case kHttpXCsrfToken: return "X-CSRF-Token"; case kHttpSaveData: return "Save-Data"; case kHttpRange: return "Range"; case kHttpContentLength: return "Content-Length"; case kHttpContentType: return "Content-Type"; case kHttpVary: return "Vary"; case kHttpDate: return "Date"; case kHttpServer: return "Server"; case kHttpExpires: return "Expires"; case kHttpContentEncoding: return "Content-Encoding"; case kHttpLastModified: return "Last-Modified"; case kHttpEtag: return "ETag"; case kHttpAllow: return "Allow"; case kHttpContentRange: return "Content-Range"; case kHttpAcceptCharset: return "Accept-Charset"; case kHttpAccessControlAllowCredentials: return "Access-Control-Allow-Credentials"; case kHttpAccessControlAllowHeaders: return "Access-Control-Allow-Headers"; case kHttpAccessControlAllowMethods: return "Access-Control-Allow-Methods"; case kHttpAccessControlAllowOrigin: return "Access-Control-Allow-Origin"; case kHttpAccessControlMaxAge: return "Access-Control-MaxAge"; case kHttpAccessControlMethod: return "Access-Control-Method"; case kHttpAccessControlRequestHeaders: return "Access-Control-RequestHeaders"; case kHttpAccessControlRequestMethod: return "Access-Control-Request-Method"; case kHttpAccessControlRequestMethods: return "Access-Control-Request-Methods"; case kHttpAge: return "Age"; case kHttpAuthorization: return "Authorization"; case kHttpContentBase: return "Content-Base"; case kHttpContentDescription: return "Content-Description"; case kHttpContentDisposition: return "Content-Disposition"; case kHttpContentLanguage: return "Content-Language"; case kHttpContentLocation: return "Content-Location"; case kHttpContentMd5: return "Content-MD5"; case kHttpExpect: return "Expect"; case kHttpIfMatch: return "If-Match"; case kHttpIfNoneMatch: return "If-None-Match"; case kHttpIfRange: return "If-Range"; case kHttpIfUnmodifiedSince: return "If-Unmodified-Since"; case kHttpKeepAlive: return "Keep-Alive"; case kHttpLink: return "Link"; case kHttpLocation: return "Location"; case kHttpMaxForwards: return "Max-Forwards"; case kHttpProxyAuthenticate: return "Proxy-Authenticate"; case kHttpProxyAuthorization: return "Proxy-Authorization"; case kHttpProxyConnection: return "Proxy-Connection"; case kHttpPublic: return "Public"; case kHttpRetryAfter: return "Retry-After"; case kHttpTe: return "TE"; case kHttpTrailer: return "Trailer"; case kHttpTransferEncoding: return "Transfer-Encoding"; case kHttpUpgrade: return "Upgrade"; case kHttpWarning: return "Warning"; case kHttpWwwAuthenticate: return "WWW-Authenticate"; case kHttpVia: return "Via"; case kHttpStrictTransportSecurity: return "Strict-Transport-Security"; case kHttpXFrameOptions: return "X-Frame-Options"; case kHttpXContentTypeOptions: return "X-Content-Type-Options"; case kHttpAltSvc: return "Alt-Svc"; case kHttpReferrerPolicy: return "Referrer-Policy"; case kHttpXXssProtection: return "X-XSS-Protection"; case kHttpAcceptRanges: return "Accept-Ranges"; case kHttpSetCookie: return "Set-Cookie"; case kHttpSecChUa: return "Sec-CH-UA"; case kHttpSecChUaMobile: return "Sec-CH-UA-Mobile"; case kHttpSecFetchSite: return "Sec-Fetch-Site"; case kHttpSecFetchMode: return "Sec-Fetch-Mode"; case kHttpSecFetchUser: return "Sec-Fetch-User"; case kHttpSecFetchDest: return "Sec-Fetch-Dest"; case kHttpCfRay: return "CF-RAY"; case kHttpCfVisitor: return "CF-Visitor"; case kHttpCfConnectingIp: return "CF-Connecting-IP"; case kHttpCfIpcountry: return "CF-IPCountry"; case kHttpCdnLoop: return "CDN-Loop"; case kHttpSecChUaPlatform: return "Sec-CH-UA-Platform"; default: return NULL; } }
7,322
213
jart/cosmopolitan
false
cosmopolitan/net/http/decodebase64.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "net/http/escape.h" static const signed char kBase64[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, // 0x20 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, // 0x30 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x40 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, // 0x50 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 0x60 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, // 0x70 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x80 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x90 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xa0 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xb0 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xc0 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xd0 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xe0 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0xf0 }; /** * Decodes base64 ascii representation to binary. * * This supports the following alphabets: * * - ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ * - ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ * * @param data is input value * @param size if -1 implies strlen * @param out_size if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *DecodeBase64(const char *data, size_t size, size_t *out_size) { size_t n; char *r, *q; int a, b, c, d, w; const char *p, *pe; if (size == -1) size = data ? strlen(data) : 0; if ((r = malloc(ROUNDUP(size, 4) / 4 * 3 + 1))) { q = r; p = data; pe = p + size; for (;;) { do { if (p == pe) goto Done; a = kBase64[*p++ & 0xff]; } while (a == -1); if (a == -2) continue; do { if (p == pe) goto Done; b = kBase64[*p++ & 0xff]; } while (b == -1); if (b == -2) continue; do { c = p < pe ? kBase64[*p++ & 0xff] : -2; } while (c == -1); do { d = p < pe ? kBase64[*p++ & 0xff] : -2; } while (d == -1); w = a << 18 | b << 12; if (c != -2) w |= c << 6; if (d != -2) w |= d; *q++ = (w & 0xFF0000) >> 020; if (c != -2) *q++ = (w & 0x00FF00) >> 010; if (d != -2) *q++ = (w & 0x0000FF) >> 000; } Done: n = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } else { n = 0; } if (out_size) { *out_size = n; } return r; }
4,780
102
jart/cosmopolitan
false
cosmopolitan/net/http/escapejsstringliteral.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "libc/str/utf16.h" #include "libc/x/x.h" #include "net/http/escape.h" static const char kEscapeLiteral[128] = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 2, 9, 4, 3, 9, 9, // 0x00 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 0x10 0, 0, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 6, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 0, // 0x30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, // 0x50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, // 0x70 }; /** * Escapes UTF-8 data for JavaScript or JSON string literal. * * HTML entities and forward slash are escaped too for added safety. * Single quote (`'`) is \uxxxx-encoded for consistency, as it's * allowed in JavaScript, but not in JSON strings. * * We assume the UTF-8 is well-formed and can be represented as UTF-16. * Things that can't be decoded will fall back to binary. Things that * can't be encoded will use invalid codepoint markers. This function is * agnostic to numbers that have been used with malicious intent in the * past under buggy software. Noncanonical encodings such as overlong * NUL are canonicalized as NUL. Therefore it isn't necessary to say * EscapeJsStringLiteral(Underlong(𝑥)) since EscapeJsStringLiteral(𝑥) * will do the same thing. * * @param r is realloc'able output buffer reused between calls * @param y is used to track byte length of `*r` * @param p is input value * @param n if -1 implies strlen * @param out_size if non-NULL receives output length * @return *r on success, or null w/ errno */ char *EscapeJsStringLiteral(char **r, size_t *y, const char *p, size_t n, size_t *z) { char *q; uint64_t w; size_t i, j, m; wint_t x, a, b; if (z) *z = 0; // TODO(jart): why is this here? if (n == -1) n = p ? strlen(p) : 0; q = *r; i = n * 8 + 6 + 1; // only need *6 but *8 is faster if (i > *y) { if ((q = realloc(q, i))) { *r = q; *y = i; } } if (q) { for (i = 0; i < n;) { x = p[i++] & 0xff; if (x >= 0300) { a = ThomPikeByte(x); m = ThomPikeLen(x) - 1; if (i + m <= n) { for (j = 0;;) { b = p[i + j] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++j == m) { x = a; i += j; break; } } } } switch (0 <= x && x <= 127 ? kEscapeLiteral[x] : 9) { case 0: *q++ = x; break; case 1: q[0] = '\\'; q[1] = 't'; q += 2; break; case 2: q[0] = '\\'; q[1] = 'n'; q += 2; break; case 3: q[0] = '\\'; q[1] = 'r'; q += 2; break; case 4: q[0] = '\\'; q[1] = 'f'; q += 2; break; case 5: q[0] = '\\'; q[1] = '\\'; q += 2; break; case 6: q[0] = '\\'; q[1] = '/'; q += 2; break; case 7: q[0] = '\\'; q[1] = '"'; q += 2; break; case 9: w = EncodeUtf16(x); do { q[0] = '\\'; q[1] = 'u'; q[2] = "0123456789abcdef"[(w & 0xF000) >> 014]; q[3] = "0123456789abcdef"[(w & 0x0F00) >> 010]; q[4] = "0123456789abcdef"[(w & 0x00F0) >> 004]; q[5] = "0123456789abcdef"[(w & 0x000F) >> 000]; q += 6; } while ((w >>= 16)); break; default: unreachable; } } if (z) *z = q - *r; *q++ = '\0'; } return *r; }
5,805
156
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpheader.gperf
%{ #include "libc/str/str.h" #include "net/http/http.h" #define GPERF_DOWNCASE %} %compare-strncmp %ignore-case %language=ANSI-C %readonly-tables %struct-type %define lookup-function-name LookupHttpHeader struct thatispacked HttpHeaderSlot { char *name; char code; }; %% Host, kHttpHost Cache-Control, kHttpCacheControl Connection, kHttpConnection Accept, kHttpAccept Accept-Language, kHttpAcceptLanguage Accept-Encoding, kHttpAcceptEncoding User-Agent, kHttpUserAgent Referer, kHttpReferer X-Forwarded-For, kHttpXForwardedFor Origin, kHttpOrigin Upgrade-Insecure-Requests, kHttpUpgradeInsecureRequests Pragma, kHttpPragma Cookie, kHttpCookie DNT, kHttpDnt Sec-GPC, kHttpSecGpc From, kHttpFrom If-Modified-Since, kHttpIfModifiedSince X-Requested-With, kHttpXRequestedWith X-Forwarded-Host, kHttpXForwardedHost X-Forwarded-Proto, kHttpXForwardedProto X-CSRF-Token, kHttpXCsrfToken Save-Data, kHttpSaveData Range, kHttpRange Content-Length, kHttpContentLength Content-Type, kHttpContentType Vary, kHttpVary Date, kHttpDate Server, kHttpServer Expires, kHttpExpires Content-Encoding, kHttpContentEncoding Last-Modified, kHttpLastModified ETag, kHttpEtag Allow, kHttpAllow Content-Range, kHttpContentRange Accept-Charset, kHttpAcceptCharset Access-Control-Allow-Credentials, kHttpAccessControlAllowCredentials Access-Control-Allow-Headers, kHttpAccessControlAllowHeaders Access-Control-Allow-Methods, kHttpAccessControlAllowMethods Access-Control-Allow-Origin, kHttpAccessControlAllowOrigin Access-Control-MaxAge, kHttpAccessControlMaxAge Access-Control-Method, kHttpAccessControlMethod Access-Control-RequestHeaders, kHttpAccessControlRequestHeaders Access-Control-Request-Method, kHttpAccessControlRequestMethod Access-Control-Request-Methods, kHttpAccessControlRequestMethods Age, kHttpAge Authorization, kHttpAuthorization Content-Base, kHttpContentBase Content-Description, kHttpContentDescription Content-Disposition, kHttpContentDisposition Content-Language, kHttpContentLanguage Content-Location, kHttpContentLocation Content-MD5, kHttpContentMd5 Expect, kHttpExpect If-Match, kHttpIfMatch If-None-Match, kHttpIfNoneMatch If-Range, kHttpIfRange If-Unmodified-Since, kHttpIfUnmodifiedSince Keep-Alive, kHttpKeepAlive Link, kHttpLink Location, kHttpLocation Max-Forwards, kHttpMaxForwards Proxy-Authenticate, kHttpProxyAuthenticate Proxy-Authorization, kHttpProxyAuthorization Proxy-Connection, kHttpProxyConnection Public, kHttpPublic Retry-After, kHttpRetryAfter TE, kHttpTe Trailer, kHttpTrailer Transfer-Encoding, kHttpTransferEncoding Upgrade, kHttpUpgrade Warning, kHttpWarning WWW-Authenticate, kHttpWwwAuthenticate Via, kHttpVia Strict-Transport-Security, kHttpStrictTransportSecurity X-Frame-Options, kHttpXFrameOptions X-Content-Type-Options, kHttpXContentTypeOptions Alt-Svc, kHttpAltSvc Referrer-Policy, kHttpReferrerPolicy X-XSS-Protection, kHttpXXssProtection Accept-Ranges, kHttpAcceptRanges Set-Cookie, kHttpSetCookie Sec-CH-UA, kHttpSecChUa Sec-CH-UA-Mobile, kHttpSecChUaMobile Sec-CH-UA-Platform, kHttpSecChUaPlatform Sec-Fetch-Site, kHttpSecFetchSite Sec-Fetch-Mode, kHttpSecFetchMode Sec-Fetch-User, kHttpSecFetchUser Sec-Fetch-Dest, kHttpSecFetchDest CF-RAY, kHttpCfRay CF-Visitor, kHttpCfVisitor CF-Connecting-IP, kHttpCfConnectingIp CF-IPCountry, kHttpCfIpcountry CDN-Loop, kHttpCdnLoop
5,087
107
jart/cosmopolitan
false
cosmopolitan/net/http/parsecontentlength.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/http.h" #define MAXIMUM (1024L * 1024L * 1024L * 1024L) /** * Parses Content-Length header. * * @param size is byte length and -1 implies strlen * @return -1 on invalid or overflow, otherwise >=0 value */ int64_t ParseContentLength(const char *s, size_t n) { size_t i; int64_t r; if (n == -1) n = s ? strlen(s) : 0; if (!n) return -1; for (r = i = 0; i < n; ++i) { if (s[i] == ',' && i > 0) break; if (!isdigit(s[i])) return -1; r *= 10; r += s[i] - '0'; if (r >= MAXIMUM) return -1; } return r; }
2,420
44
jart/cosmopolitan
false
cosmopolitan/net/http/ismimetype.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/http.h" /** * Returns true if content-type 𝑡 has mime-type 𝑠. */ bool IsMimeType(const char *t, size_t n, const char *s) { size_t i; if (n == -1) n = t ? strlen(t) : 0; for (i = 0; i < n; ++i) { if (!s[i]) return !kHttpToken[t[i] & 0xFF]; if (kToLower[s[i] & 0xFF] != kToLower[t[i] & 0xFF]) return false; } return !s[i]; }
2,266
35
jart/cosmopolitan
false
cosmopolitan/net/http/isarinip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is managed by ARIN. */ bool IsArinIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 3 || a == 4 || a == 8 || a == 9 || a == 13 || a == 15 || a == 16 || a == 18 || a == 20 || a == 23 || a == 24 || a == 32 || a == 34 || a == 35 || a == 40 || a == 44 || a == 45 || a == 47 || a == 50 || a == 52 || a == 54 || a == 63 || a == 64 || a == 65 || a == 66 || a == 67 || a == 68 || a == 69 || a == 70 || a == 71 || a == 72 || a == 74 || a == 75 || a == 76 || a == 96 || a == 97 || a == 98 || a == 99 || a == 100 || a == 104 || a == 107 || a == 108 || a == 128 || a == 129 || a == 130 || a == 131 || a == 132 || a == 134 || a == 135 || a == 136 || a == 137 || a == 138 || a == 139 || a == 140 || a == 142 || a == 143 || a == 144 || a == 146 || a == 147 || a == 148 || a == 149 || a == 152 || a == 155 || a == 156 || a == 157 || a == 158 || a == 159 || a == 160 || a == 161 || a == 162 || a == 164 || a == 165 || a == 166 || a == 167 || a == 168 || a == 169 || a == 170 || a == 172 || a == 173 || a == 174 || a == 184 || a == 192 || a == 198 || a == 199 || a == 204 || a == 205 || a == 206 || a == 207 || a == 208 || a == 209 || a == 216; }
3,178
43
jart/cosmopolitan
false
cosmopolitan/net/http/parsecidr.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/ip.h" /** * Parse IPv4 network address. * * For example, a router address might be `10.10.10.1/24` in which case * the IP address word `0x0a0a0a01` would be returned, whose CIDR would * be 24. That means your IP address is on a network with 24 bits which * converts to a netmask `0xffffff00` by using `1u << (32 - res.cidr)`. * You may specify the IP address portion as an integer. As an example, * the value `168430081/1` would be the same as `10.10.10.1/1` * * @param n if -1 implies strlen * @return ip is uint32 IPv4 address, or -1 on failure * @return cidr is number of bits in network, on interval [1,32]; it * defaults to 32; if the return ip is -1 then cidr is undefined */ struct Cidr ParseCidr(const char *s, size_t n) { size_t i; const char *p; struct Cidr c; if (n == -1) n = s ? strlen(s) : 0; if ((p = strchr(s, '/'))) { if ((c.addr = ParseIp(s, (i = p - s))) != -1) { c.cidr = 0; for (++i; i < n; ++i) { if (isdigit(s[i])) { c.cidr *= 10; c.cidr += s[i] - '0'; if (c.cidr > 32) { c.cidr = -1; break; } } else { c.cidr = -1; break; } } if (c.cidr <= 0) { c.addr = -1; } } } else { c.addr = ParseIp(s, n); c.cidr = 32; } return c; }
3,224
68
jart/cosmopolitan
false
cosmopolitan/net/http/ip.h
#ifndef COSMOPOLITAN_NET_HTTP_IP_H_ #define COSMOPOLITAN_NET_HTTP_IP_H_ #define kIpUnknown 0 #define kIpMulticast 1 #define kIpLoopback 2 #define kIpPrivate 3 #define kIpTestnet 4 #define kIpAfrinic 5 #define kIpLacnic 6 #define kIpApnic 7 #define kIpArin 8 #define kIpRipe 9 #define kIpDod 10 #define kIpAtt 11 #define kIpApple 12 #define kIpFord 13 #define kIpCogent 14 #define kIpPrudential 15 #define kIpUsps 16 #define kIpComcast 17 #define kIpFuture 18 #define kIpAnonymous 19 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Cidr { int64_t addr; int cidr; }; int64_t ParseIp(const char *, size_t); struct Cidr ParseCidr(const char *, size_t); bool IsDodIp(uint32_t); bool IsArinIp(uint32_t); bool IsRipeIp(uint32_t); bool IsApnicIp(uint32_t); bool IsLacnicIp(uint32_t); bool IsPublicIp(uint32_t); bool IsPrivateIp(uint32_t); bool IsAfrinicIp(uint32_t); bool IsTestnetIp(uint32_t); bool IsLoopbackIp(uint32_t); bool IsMulticastIp(uint32_t); bool IsAnonymousIp(uint32_t); int CategorizeIp(uint32_t); const char *GetIpCategoryName(int); bool IsCloudflareIp(uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTP_IP_H_ */
1,286
54
jart/cosmopolitan
false
cosmopolitan/net/http/escapepath.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL path. * * This is the same as EscapePathSegment() except slash is allowed. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapePath(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapePath); }
2,236
34
jart/cosmopolitan
false
cosmopolitan/net/http/parsehttpmessage.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/bits.h" #include "libc/limits.h" #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" #include "libc/x/x.h" #include "net/http/http.h" #define LIMIT (SHRT_MAX - 2) /** * Initializes HTTP message parser. */ void InitHttpMessage(struct HttpMessage *r, int type) { _unassert(type == kHttpRequest || type == kHttpResponse); bzero(r, sizeof(*r)); r->type = type; } /** * Destroys HTTP message parser. */ void DestroyHttpMessage(struct HttpMessage *r) { if (r->xheaders.p) { free(r->xheaders.p); r->xheaders.p = NULL; r->xheaders.n = 0; } } /** * Parses HTTP request or response. * * This parser is responsible for determining the length of a message * and slicing the strings inside it. Performance is attained using * perfect hash tables. No memory allocation is performed for normal * messages. Line folding is forbidden. State persists across calls so * that fragmented messages can be handled efficiently. A limitation on * message size is imposed to make the header data structures smaller. * * This parser assumes ISO-8859-1 and guarantees no C0 or C1 control * codes are present in message fields, with the exception of tab. * Please note that fields like kHttpStateUri may use UTF-8 percent encoding. * This parser doesn't care if you choose ASA X3.4-1963 or MULTICS newlines. * * kHttpRepeatable defines which standard header fields are O(1) and * which ones may have comma entries spilled over into xheaders. For * most headers it's sufficient to simply check the static slice. If * r->headers[kHttpFoo].a is zero then the header is totally absent. * * This parser has linear complexity. Each character only needs to be * considered a single time. That's the case even if messages are * fragmented. If a message is valid but incomplete, this function will * return zero so that it can be resumed as soon as more data arrives. * * This parser takes about 400 nanoseconds to parse a 403 byte Chrome * HTTP request under MODE=rel on a Core i9 which is about three cycles * per byte or a gigabyte per second of throughput per core. * * @note we assume p points to a buffer that has >=SHRT_MAX bytes * @see HTTP/1.1 RFC2616 RFC2068 * @see HTTP/1.0 RFC1945 */ int ParseHttpMessage(struct HttpMessage *r, const char *p, size_t n) { int c, h, i; for (n = MIN(n, LIMIT); r->i < n; ++r->i) { c = p[r->i] & 0xff; switch (r->t) { case kHttpStateStart: if (c == '\r' || c == '\n') break; /* RFC7230 § 3.5 */ if (!kHttpToken[c]) return ebadmsg(); r->t = r->type == kHttpRequest ? kHttpStateMethod : kHttpStateVersion; r->a = r->i; break; case kHttpStateMethod: for (;;) { if (c == ' ') { r->method = GetHttpMethod(p + r->a, r->i - r->a); r->xmethod.a = r->a; r->xmethod.b = r->i; r->a = r->i + 1; r->t = kHttpStateUri; break; } else if (!kHttpToken[c]) { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateUri: for (;;) { if (c == ' ' || c == '\r' || c == '\n') { if (r->i == r->a) return ebadmsg(); r->uri.a = r->a; r->uri.b = r->i; if (c == ' ') { r->a = r->i + 1; r->t = kHttpStateVersion; } else { r->version = 9; r->t = c == '\r' ? kHttpStateCr : kHttpStateLf1; } break; } else if (c < 0x20 || (0x7F <= c && c < 0xA0)) { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateVersion: if (c == ' ' || c == '\r' || c == '\n') { if (r->i - r->a == 8 && (READ64BE(p + r->a) & 0xFFFFFFFFFF00FF00) == 0x485454502F002E00 && isdigit(p[r->a + 5]) && isdigit(p[r->a + 7])) { r->version = (p[r->a + 5] - '0') * 10 + (p[r->a + 7] - '0'); if (r->type == kHttpRequest) { r->t = c == '\r' ? kHttpStateCr : kHttpStateLf1; } else { r->t = kHttpStateStatus; } } else { return ebadmsg(); } } break; case kHttpStateStatus: for (;;) { if (c == ' ' || c == '\r' || c == '\n') { if (r->status < 100) return ebadmsg(); if (c == ' ') { r->a = r->i + 1; r->t = kHttpStateMessage; } else { r->t = c == '\r' ? kHttpStateCr : kHttpStateLf1; } break; } else if ('0' <= c && c <= '9') { r->status *= 10; r->status += c - '0'; if (r->status > 999) return ebadmsg(); } else { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateMessage: for (;;) { if (c == '\r' || c == '\n') { r->message.a = r->a; r->message.b = r->i; r->t = c == '\r' ? kHttpStateCr : kHttpStateLf1; break; } else if (c < 0x20 || (0x7F <= c && c < 0xA0)) { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateCr: if (c != '\n') return ebadmsg(); r->t = kHttpStateLf1; break; case kHttpStateLf1: if (c == '\r') { r->t = kHttpStateLf2; break; } else if (c == '\n') { return ++r->i; } else if (!kHttpToken[c]) { /* * 1. Forbid empty header name (RFC2616 §2.2) * 2. Forbid line folding (RFC7230 §3.2.4) */ return ebadmsg(); } r->k.a = r->i; r->t = kHttpStateName; break; case kHttpStateName: for (;;) { if (c == ':') { r->k.b = r->i; r->t = kHttpStateColon; break; } else if (!kHttpToken[c]) { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateColon: if (c == ' ' || c == '\t') break; r->a = r->i; r->t = kHttpStateValue; /* fallthrough */ case kHttpStateValue: for (;;) { if (c == '\r' || c == '\n') { i = r->i; while (i > r->a && (p[i - 1] == ' ' || p[i - 1] == '\t')) --i; if ((h = GetHttpHeader(p + r->k.a, r->k.b - r->k.a)) != -1 && (!r->headers[h].a || !kHttpRepeatable[h])) { r->headers[h].a = r->a; r->headers[h].b = i; } else { if (r->xheaders.n == r->xheaders.c) { unsigned c2; struct HttpHeader *p1, *p2; p1 = r->xheaders.p; c2 = r->xheaders.c; if (c2 == 0) { c2 = 1; } else { c2 = c2 * 2; } if ((p2 = realloc(p1, c2 * sizeof(*p1)))) { r->xheaders.p = p2; r->xheaders.c = c2; } } if (r->xheaders.n < r->xheaders.c) { r->xheaders.p[r->xheaders.n].k = r->k; r->xheaders.p[r->xheaders.n].v.a = r->a; r->xheaders.p[r->xheaders.n].v.b = i; r->xheaders.p = r->xheaders.p; ++r->xheaders.n; } } r->t = c == '\r' ? kHttpStateCr : kHttpStateLf1; break; } else if ((c < 0x20 && c != '\t') || (0x7F <= c && c < 0xA0)) { return ebadmsg(); } if (++r->i == n) break; c = p[r->i] & 0xff; } break; case kHttpStateLf2: if (c == '\n') { return ++r->i; } return ebadmsg(); default: unreachable; } } if (r->i < LIMIT) { return 0; } else { return ebadmsg(); } }
10,266
282
jart/cosmopolitan
false
cosmopolitan/net/http/isafrinicip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is managed by AFRINIC. */ bool IsAfrinicIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 41 || a == 102 || a == 105 || a == 154 || a == 196 || a == 197 || (x & 0xffffe000) == 0xca7b0000 /* 202.123.0.0/19 */; }
2,134
29
jart/cosmopolitan
false
cosmopolitan/net/http/islacnicip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/ip.h" /** * Returns true if IPv4 address is managed by LACNIC. */ bool IsLacnicIp(uint32_t x) { int a = (x & 0xff000000) >> 24; return a == 177 || a == 179 || a == 181 || a == 186 || a == 187 || a == 189 || a == 190 || a == 191 || a == 200 || a == 201; }
2,126
29
jart/cosmopolitan
false
cosmopolitan/net/http/encodehttpheadervalue.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/escape.h" /** * Encodes HTTP header value. * * This operation involves the following: * * 1. Trim whitespace. * 2. Turn UTF-8 into ISO-8859-1. * 3. Make sure no C0 or C1 control codes are present (except tab). * * If the input value isn't thompson-pike encoded then this * implementation will fall back to latin1 in most cases. * * @param data is input value * @param size if -1 implies strlen * @param out_size if non-NULL receives output length on success * @return allocated NUL-terminated string, or NULL w/ errno */ char *EncodeHttpHeaderValue(const char *data, size_t size, size_t *out_size) { bool t; wint_t x; size_t n; char *r, *q; const char *p, *e; if (size == -1) size = data ? strlen(data) : 0; if ((r = malloc(size + 1))) { t = 0; q = r; p = data; e = p + size; while (p < e) { x = *p++ & 0xff; if (x >= 0300) { if (p < e && ThomPikeCont(*p)) { if (ThomPikeLen(x) == 2) { x = ThomPikeMerge(ThomPikeByte(x), *p++); } else { x = 0; } } } if (!t) { if (x == ' ' || x == '\t') { continue; } else { t = true; } } if ((0x20 <= x && x <= 0x7E) || (0xA0 <= x && x <= 0xFF) || x == '\t') { *q++ = x; } else { free(r); errno = EILSEQ; return NULL; } } while (q > r && (q[-1] == ' ' || q[-1] == '\t')) --q; n = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } else { n = 0; } if (out_size) { *out_size = n; } return r; }
3,578
92
jart/cosmopolitan
false
cosmopolitan/net/http/escape.h
#ifndef COSMOPOLITAN_NET_HTTP_ESCAPE_H_ #define COSMOPOLITAN_NET_HTTP_ESCAPE_H_ #define kControlWs 1 #define kControlC0 2 #define kControlC1 4 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern const char kEscapeAuthority[256]; extern const char kEscapeIp[256]; extern const char kEscapePath[256]; extern const char kEscapeSegment[256]; extern const char kEscapeParam[256]; extern const char kEscapeFragment[256]; char *EscapeHtml(const char *, size_t, size_t *); char *EscapeUrl(const char *, size_t, size_t *, const char[256]); char *EscapeUser(const char *, size_t, size_t *); char *EscapePass(const char *, size_t, size_t *); char *EscapeIp(const char *, size_t, size_t *); char *EscapeHost(const char *, size_t, size_t *); char *EscapePath(const char *, size_t, size_t *); char *EscapeParam(const char *, size_t, size_t *); char *EscapeFragment(const char *, size_t, size_t *); char *EscapeSegment(const char *, size_t, size_t *); char *EscapeJsStringLiteral(char **, size_t *, const char *, size_t, size_t *); ssize_t HasControlCodes(const char *, size_t, int); char *Underlong(const char *, size_t, size_t *); char *DecodeLatin1(const char *, size_t, size_t *); char *EncodeLatin1(const char *, size_t, size_t *, int); char *EncodeHttpHeaderValue(const char *, size_t, size_t *); char *VisualizeControlCodes(const char *, size_t, size_t *); char *IndentLines(const char *, size_t, size_t *, size_t); char *EncodeBase64(const char *, size_t, size_t *); char *DecodeBase64(const char *, size_t, size_t *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_NET_HTTP_ESCAPE_H_ */
1,645
43
jart/cosmopolitan
false
cosmopolitan/net/http/escapeip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" /** * Escapes URL IP-literal. * * This is the same as EscapeHost except colon is permitted. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *EscapeIp(const char *p, size_t n, size_t *z) { return EscapeUrl(p, n, z, kEscapeAuthority); }
2,238
34
jart/cosmopolitan
false
cosmopolitan/net/http/isreasonablepath.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "libc/str/thompike.h" #include "net/http/http.h" /** * Returns true if path doesn't contain "." or ".." segments. * * @param size if -1 implies strlen * @see IsAcceptablePath() */ bool IsReasonablePath(const char *data, size_t size) { const char *p, *e; int x, y, z, a, b, i, n; if (size == -1) size = data ? strlen(data) : 0; z = '/'; y = '/'; x = '/'; p = data; e = p + size; while (p < e) { x = *p++ & 0xff; if (x >= 0300) { a = ThomPikeByte(x); n = ThomPikeLen(x) - 1; if (p + n <= e) { for (i = 0;;) { b = p[i] & 0xff; if (!ThomPikeCont(b)) break; a = ThomPikeMerge(a, b); if (++i == n) { x = a; p += i; break; } } } } if (x == '\\') { x = '/'; } if (z == '/' && y == '.' && x == '/') return false; if (z == '/' && y == '.' && x == '.') return false; z = y; y = x; } if (y == '/' && x == '.') return false; if (z == '/' && y == '.' && x == '.') return false; return true; }
2,950
68
jart/cosmopolitan
false
cosmopolitan/net/http/gethttpmethod.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/gethttpmethod.inc" #include "net/http/http.h" /** * Converts HTTP method string into internal index * * @param len if -1 implies strlen * @return small number for HTTP method, or 0 if not found. */ int GetHttpMethod(const char *str, size_t len) { const struct HttpMethodSlot *slot; if (len == -1) len = str ? strlen(str) : 0; if ((slot = LookupHttpMethod(str, len))) { return slot->code; } else { return 0; } }
2,290
37
jart/cosmopolitan
false
cosmopolitan/net/http/isvalidcookievalue.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "net/http/http.h" static inline bool IsCookieOctet(unsigned char i) { return i > 0x20 && i < 0x7F && i != ',' && i != ';' && i != '\\' && i != ' ' && i != '"'; } /** * Returns true if string is a valid cookie value * (any ASCII excluding control char, whitespace, * double quotes, comma, semicolon, and backslash). * * @param n if -1 implies strlen */ bool IsValidCookieValue(const char *s, size_t n) { size_t i; if (n == -1) n = s ? strlen(s) : 0; for (i = 0; i < n; ++i) { if (!IsCookieOctet(s[i])) { return false; } } return true; }
2,450
44
jart/cosmopolitan
false
cosmopolitan/net/http/encodeurl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "net/http/escape.h" #include "net/http/url.h" static size_t DimensionUrl(struct Url *h) { size_t i, n; n = 0; n += h->scheme.n; n += 1; n += 2; n += h->user.n * 3; n += 1; n += h->pass.n * 3; n += 1; n += 1; n += h->host.n * 3; n += 1; n += 1; n += h->port.n * 3; n += 1; n += h->path.n * 3; n += 1; n += h->params.n; for (i = 0; i < h->params.n; ++i) { n += h->params.p[i].key.n * 3; n += 1; n += h->params.p[i].val.n * 3; } n += 1; n += h->fragment.n * 3; n += 1; return n; } static bool NeedsSquareBrackets(struct Url *h) { int c; size_t i; if (!memchr(h->host.p, ':', h->host.n)) return false; if (h->pass.p) return true; if (h->host.n >= 4 && h->host.p[0] == 'v' && h->host.p[2] == '.' && kHexToInt[h->host.p[1] & 0xFF] != -1) { for (i = 3; i < h->host.n; ++i) { if (kEscapeIp[h->host.p[i] & 0xFF]) { return false; } } } else { for (i = 0; i < h->host.n; ++i) { c = h->host.p[i] & 0xFF; if (!(kHexToInt[c] || c == '.' || c == ':')) { return false; } } } return true; } /** * Encodes URL. * * @param z if not null receives string length of result * @return nul-terminated url string needing free * @see ParseUrl() */ char *EncodeUrl(struct Url *h, size_t *z) { size_t i, n; char *m, *p; if ((p = m = malloc(DimensionUrl(h)))) { if (h->scheme.n) { p = mempcpy(p, h->scheme.p, h->scheme.n); *p++ = ':'; } if (h->host.p) { *p++ = '/'; *p++ = '/'; if (h->user.p) { p = EscapeUrlView(p, &h->user, kEscapeAuthority); if (h->pass.p) { *p++ = ':'; p = EscapeUrlView(p, &h->pass, kEscapeAuthority); } *p++ = '@'; } if (h->host.p) { if (NeedsSquareBrackets(h)) { *p++ = '['; p = EscapeUrlView(p, &h->host, kEscapeIp); *p++ = ']'; } else { p = EscapeUrlView(p, &h->host, kEscapeAuthority); } if (h->port.p) { *p++ = ':'; p = EscapeUrlView(p, &h->port, kEscapeAuthority); } } if (h->path.n && h->path.p[0] != '/') { *p++ = '/'; } } p = EscapeUrlView(p, &h->path, kEscapePath); if (h->params.p) { *p++ = '?'; for (i = 0; i < h->params.n; ++i) { if (i) *p++ = '&'; p = EscapeUrlView(p, &h->params.p[i].key, kEscapeParam); if (h->params.p[i].val.p) { *p++ = '='; p = EscapeUrlView(p, &h->params.p[i].val, kEscapeParam); } } } if (h->fragment.p) { *p++ = '#'; p = EscapeUrlView(p, &h->fragment, kEscapeFragment); } n = p - m; *p++ = '\0'; if ((p = realloc(m, p - m))) m = p; } else { n = 0; } if (z) *z = n; return m; }
4,761
146
jart/cosmopolitan
false
cosmopolitan/net/http/parsehttpdatetime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/time/time.h" #include "libc/str/str.h" #include "net/http/http.h" static unsigned ParseMonth(const char *p) { int i; for (i = 0; i < 12; ++i) { if ((READ32LE(p) & 0x00ffffff) == READ32LE(kMonthNameShort[i])) { return i + 1; } } return 1; } /** * Parses HTTP timestamp, e.g. * * Sun, 04 Oct 2020 19:50:10 GMT * * @return seconds from unix epoch * @param n if -1 implies strlen * @see FormatHttpDateTime() */ int64_t ParseHttpDateTime(const char *p, size_t n) { unsigned weekday, year, month, day, hour, minute, second, yday, leap; if (n == -1) n = p ? strlen(p) : 0; if (n != 29) return 0; day = (p[5] - '0') * 10 + (p[6] - '0') - 1; month = ParseMonth(p + 8); year = (p[12] - '0') * 1000 + (p[13] - '0') * 100 + (p[14] - '0') * 10 + (p[15] - '0') - 1900; hour = (p[17] - '0') * 10 + (p[18] - '0'); minute = (p[20] - '0') * 10 + (p[21] - '0'); second = (p[23] - '0') * 10 + (p[24] - '0'); leap = year % 4 == 0 && (year % 100 || year % 400 == 0); yday = day + kMonthYearDay[leap][month - 1]; return second + minute * 60 + hour * 3600 + yday * 86400 + (year - 70) * 31536000ull + ((year - 69) / 4) * 86400ull - ((year - 1) / 100) * 86400ull + ((year + 299) / 400) * 86400ull; }
3,141
60
jart/cosmopolitan
false
cosmopolitan/net/http/kescapeip.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '_-.!~*'"'"'();&=+$,:' -iskEscapeIp // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠ “# % / ! § &‘()*+,-. 0x20 // < >⁇ 0123456789:; = 0x30 // @ ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|} ⌂ pqrstuvwxyz ~ 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapeIp[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, // 0x30 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,168
61
jart/cosmopolitan
false
cosmopolitan/net/http/kescapeparam.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2023 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/escape.h" // generated by: // o//tool/build/xlat.com -DUL '.-*_' -iskEscapeParam // // present absent // ──────────────── ──────────────── // ∅☺☻♥♦♣♠•◘○◙♂♀♪♫☼ 0x00 // ►◄↕‼¶§▬↨↑↓→←∟↔▲▼ 0x10 // ␠!“#§%&‘() +, / * -. 0x20 // :;<=>⁇ 0123456789 0x30 // @ ABCDEFGHIJKLMNO 0x40 // [⭝]^ PQRSTUVWXYZ _ 0x50 // ` abcdefghijklmno 0x60 // {|}~⌂ pqrstuvwxyz 0x70 // ÇüéâäàåçêëèïîìÄÅ 0x80 // ÉæÆôöòûùÿÖÜ¢£¥€ƒ 0x90 // áíóúñѪº¿⌐¬½¼¡«» 0xa0 // ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐ 0xb0 // └┴┬├─┼╞╟╚╔╩╦╠═╬╧ 0xc0 // ╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ 0xd0 // αßΓπΣσμτΦΘΩδ∞φε∩ 0xe0 // ≡±≥≤⌠⌡÷≈°∙×√ⁿ²■λ 0xf0 const char kEscapeParam[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, // 0x20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, // 0x30 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // 0x50 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, // 0x70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xc0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xd0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xe0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xf0 };
4,158
61
jart/cosmopolitan
false
cosmopolitan/net/http/http.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += NET_HTTP NET_HTTP_ARTIFACTS += NET_HTTP_A NET_HTTP = $(NET_HTTP_A_DEPS) $(NET_HTTP_A) NET_HTTP_A = o/$(MODE)/net/http/http.a NET_HTTP_A_FILES := $(wildcard net/http/*) NET_HTTP_A_HDRS = $(filter %.h,$(NET_HTTP_A_FILES)) NET_HTTP_A_INCS = $(filter %.inc,$(NET_HTTP_A_FILES)) NET_HTTP_A_SRCS = $(filter %.c,$(NET_HTTP_A_FILES)) NET_HTTP_A_OBJS = $(NET_HTTP_A_SRCS:%.c=o/$(MODE)/%.o) NET_HTTP_A_CHECKS = \ $(NET_HTTP_A).pkg \ $(NET_HTTP_A_HDRS:%=o/$(MODE)/%.ok) NET_HTTP_A_DIRECTDEPS = \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_TIME NET_HTTP_A_DEPS := \ $(call uniq,$(foreach x,$(NET_HTTP_A_DIRECTDEPS),$($(x)))) $(NET_HTTP_A): net/http/ \ $(NET_HTTP_A).pkg \ $(NET_HTTP_A_OBJS) $(NET_HTTP_A).pkg: \ $(NET_HTTP_A_OBJS) \ $(foreach x,$(NET_HTTP_A_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/net/http/gethttpheadername.o \ o/$(MODE)/net/http/categorizeip.o \ o/$(MODE)/net/http/getipcategoryname.o \ o/$(MODE)/net/http/isafrinicip.o \ o/$(MODE)/net/http/isanonymousip.o \ o/$(MODE)/net/http/isapnicip.o \ o/$(MODE)/net/http/isarinip.o \ o/$(MODE)/net/http/isdodip.o \ o/$(MODE)/net/http/islacnicip.o \ o/$(MODE)/net/http/isloopbackip.o \ o/$(MODE)/net/http/ismulticastip.o \ o/$(MODE)/net/http/isripeip.o \ o/$(MODE)/net/http/istestnetip.o: private \ OVERRIDE_CFLAGS += \ -Os # we need -O3 because: # we're dividing by constants o/$(MODE)/net/http/formathttpdatetime.o: private\ OVERRIDE_CFLAGS += \ -O3 NET_HTTP_LIBS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x))) NET_HTTP_SRCS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x)_SRCS)) NET_HTTP_HDRS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x)_HDRS)) NET_HTTP_INCS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x)_INCS)) NET_HTTP_OBJS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x)_OBJS)) NET_HTTP_CHECKS = $(foreach x,$(NET_HTTP_ARTIFACTS),$($(x)_CHECKS)) .PHONY: o/$(MODE)/net/http o/$(MODE)/net/http: $(NET_HTTP_CHECKS)
2,203
71
jart/cosmopolitan
false
cosmopolitan/net/http/decodelatin1.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/pcmpgtb.h" #include "libc/intrin/pmovmskb.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "net/http/escape.h" /** * Decodes ISO-8859-1 to UTF-8. * * @param p is input value * @param n if -1 implies strlen * @param z if non-NULL receives output length * @return allocated NUL-terminated buffer, or NULL w/ errno */ char *DecodeLatin1(const char *p, size_t n, size_t *z) { int c; size_t i; char *r, *q; int8_t v1[16], v2[16], vz[16]; if (z) *z = 0; if (n == -1) n = p ? strlen(p) : 0; if ((q = r = malloc(n * 2 + 1))) { for (i = 0; i < n;) { bzero(vz, 16); /* 3x speedup for ASCII */ while (i + 16 < n) { memcpy(v1, p + i, 16); pcmpgtb(v2, v1, vz); if (pmovmskb((void *)v2) != 0xFFFF) break; memcpy(q, v1, 16); q += 16; i += 16; } c = p[i++] & 0xff; if (c < 0200) { *q++ = c; } else { *q++ = 0300 | c >> 6; *q++ = 0200 | c & 077; } } if (z) *z = q - r; *q++ = '\0'; if ((q = realloc(r, q - r))) r = q; } return r; }
2,948
65
jart/cosmopolitan
false
cosmopolitan/net/http/khttpmethod.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "net/http/http.h" const char kHttpMethod[18][8] = { "WUT", // "GET", // "HEAD", // "POST", // "PUT", // "DELETE", // "OPTIONS", // "CONNECT", // "TRACE", // "COPY", // "LOCK", // "MERGE", // "MKCOL", // "MOVE", // "NOTIFY", // "PATCH", // "REPORT", // "UNLOCK", // };
2,243
41
jart/cosmopolitan
false