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/tool/build/lib/mda.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_MDA_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_MDA_H_ #include "tool/build/lib/panel.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void DrawMda(struct Panel *, uint8_t[25][80][2]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_MDA_H_ */
347
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/breakpoint.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_BREAKPOINT_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_BREAKPOINT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Breakpoints { size_t i, n; struct Breakpoint { int64_t addr; const char *symbol; bool disable; bool oneshot; } * p; }; ssize_t IsAtBreakpoint(struct Breakpoints *, int64_t); ssize_t PushBreakpoint(struct Breakpoints *, struct Breakpoint *); void PopBreakpoint(struct Breakpoints *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_BREAKPOINT_H_ */
597
23
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/memorymalloc.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/log/check.h" #include "libc/mem/mem.h" #include "libc/runtime/pc.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" #include "libc/x/x.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" struct Machine *NewMachine(void) { struct Machine *m; m = xmemalignzero(_Alignof(struct Machine), sizeof(struct Machine)); ResetCpu(m); ResetMem(m); return m; } static void FreeMachineRealFree(struct Machine *m) { struct MachineRealFree *rf; while ((rf = m->realfree)) { m->realfree = rf->next; free(rf); } } void FreeMachine(struct Machine *m) { if (m) { FreeMachineRealFree(m); free(m->real.p); free(m); } } void ResetMem(struct Machine *m) { FreeMachineRealFree(m); ResetTlb(m); bzero(&m->memstat, sizeof(m->memstat)); m->real.i = 0; m->cr3 = 0; } long AllocateLinearPage(struct Machine *m) { long page; if ((page = AllocateLinearPageRaw(m)) != -1) { bzero(m->real.p + page, 4096); } return page; } long AllocateLinearPageRaw(struct Machine *m) { uint8_t *p; size_t i, n; struct MachineRealFree *rf; if ((rf = m->realfree)) { DCHECK(rf->n); DCHECK_EQ(0, rf->i & 4095); DCHECK_EQ(0, rf->n & 4095); DCHECK_LE(rf->i + rf->n, m->real.i); i = rf->i; rf->i += 4096; if (!(rf->n -= 4096)) { m->realfree = rf->next; free(rf); } --m->memstat.freed; ++m->memstat.reclaimed; } else { i = m->real.i; n = m->real.n; p = m->real.p; if (i == n) { if (n) { n += n >> 1; } else { n = 65536; } n = ROUNDUP(n, 4096); if ((p = realloc(p, n))) { m->real.p = p; m->real.n = n; ResetTlb(m); ++m->memstat.resizes; } else { return -1; } } DCHECK_EQ(0, i & 4095); DCHECK_EQ(0, n & 4095); DCHECK_LE(i + 4096, n); m->real.i += 4096; ++m->memstat.allocated; } ++m->memstat.committed; return i; } static uint64_t MachineRead64(struct Machine *m, unsigned long i) { CHECK_LE(i + 8, m->real.n); return Read64(m->real.p + i); } static void MachineWrite64(struct Machine *m, unsigned long i, uint64_t x) { CHECK_LE(i + 8, m->real.n); Write64(m->real.p + i, x); } int ReserveReal(struct Machine *m, size_t n) { uint8_t *p; DCHECK_EQ(0, n & 4095); if (m->real.n < n) { if ((p = realloc(m->real.p, n))) { m->real.p = p; m->real.n = n; ResetTlb(m); ++m->memstat.resizes; } else { return -1; } } return 0; } int ReserveVirtual(struct Machine *m, int64_t virt, size_t size, uint64_t key) { int64_t ti, mi, pt, end, level; for (end = virt + size;;) { for (pt = m->cr3, level = 39; level >= 12; level -= 9) { pt = pt & PAGE_TA; ti = (virt >> level) & 511; mi = (pt & PAGE_TA) + ti * 8; pt = MachineRead64(m, mi); if (level > 12) { if (!(pt & 1)) { if ((pt = AllocateLinearPage(m)) == -1) return -1; MachineWrite64(m, mi, pt | 7); ++m->memstat.pagetables; } continue; } for (;;) { if (!(pt & 1)) { MachineWrite64(m, mi, key); ++m->memstat.reserved; } if ((virt += 4096) >= end) return 0; if (++ti == 512) break; pt = MachineRead64(m, (mi += 8)); } } } } int64_t FindVirtual(struct Machine *m, int64_t virt, size_t size) { uint64_t i, pt, got; got = 0; do { if (virt >= 0x800000000000) return enomem(); for (pt = m->cr3, i = 39; i >= 12; i -= 9) { pt = MachineRead64(m, (pt & PAGE_TA) + ((virt >> i) & 511) * 8); if (!(pt & 1)) break; } if (i >= 12) { got += 1ull << i; } else { virt += 4096; got = 0; } } while (got < size); return virt; } static void AppendRealFree(struct Machine *m, uint64_t real) { struct MachineRealFree *rf; if (m->realfree && real == m->realfree->i + m->realfree->n) { m->realfree->n += 4096; } else if ((rf = malloc(sizeof(struct MachineRealFree)))) { rf->i = real; rf->n = 4096; rf->next = m->realfree; m->realfree = rf; } } int FreeVirtual(struct Machine *m, int64_t base, size_t size) { uint64_t i, mi, pt, end, virt; for (virt = base, end = virt + size; virt < end; virt += 1ull << i) { for (pt = m->cr3, i = 39;; i -= 9) { mi = (pt & PAGE_TA) + ((virt >> i) & 511) * 8; pt = MachineRead64(m, mi); if (!(pt & 1)) { break; } else if (i == 12) { ++m->memstat.freed; if (pt & PAGE_RSRV) { --m->memstat.reserved; } else { --m->memstat.committed; AppendRealFree(m, pt & PAGE_TA); } MachineWrite64(m, mi, 0); break; } } } ResetTlb(m); return 0; }
6,651
225
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/fds.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_FDS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_FDS_H_ #include "libc/calls/struct/iovec.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct MachineFdClosed { unsigned fd; struct MachineFdClosed *next; }; struct MachineFdCb { int (*close)(int); ssize_t (*readv)(int, const struct iovec *, int); ssize_t (*writev)(int, const struct iovec *, int); int (*ioctl)(int, int, ...); int (*poll)(struct pollfd *, uint64_t, int32_t); }; struct MachineFd { int fd; struct MachineFdCb *cb; }; struct MachineFds { size_t i, n; struct MachineFd *p; struct MachineFdClosed *closed; }; int MachineFdAdd(struct MachineFds *); void MachineFdRemove(struct MachineFds *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_FDS_H_ */
916
39
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/bitscan.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_BITSCAN_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_BITSCAN_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef uint64_t (*bitscan_f)(struct Machine *, uint32_t, uint64_t); uint64_t AluBsr(struct Machine *, uint32_t, uint64_t); uint64_t AluBsf(struct Machine *, uint32_t, uint64_t); uint64_t AluPopcnt(struct Machine *, uint32_t, uint64_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_BITSCAN_H_ */
549
16
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ldbl.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_LDBL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_LDBL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ double DeserializeLdbl(const uint8_t[10]); uint8_t *SerializeLdbl(uint8_t[10], double); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_LDBL_H_ */
354
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/javadown.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/mem/mem.h" #include "libc/str/str.h" #include "tool/build/lib/javadown.h" #define FILEOVERVIEW "@fileoverview" struct Lines { size_t n; struct Line { char *p; size_t n; } * p; }; static char *SkipEmptyFirstLine(char *p) { int i = 0; while (p[i] == ' ' || p[i] == '\t') ++i; return p[i] == '\n' ? p + i + 1 : p; } static void DeleteLastEmptyLine(char *p, size_t n) { while (n && (p[n - 1] == ' ' || p[n - 1] == '\t')) --n; if (n && p[n - 1] == '\n') p[n - 1] = '\0'; } static void AppendLine(struct Lines *lines) { lines->p = realloc(lines->p, ++lines->n * sizeof(*lines->p)); bzero(lines->p + lines->n - 1, sizeof(*lines->p)); } static void AppendTag(struct JavadownTags *tags) { tags->p = realloc(tags->p, ++tags->n * sizeof(*tags->p)); bzero(tags->p + tags->n - 1, sizeof(*tags->p)); } static unsigned GetSpacePrefixLen(const char *p, size_t n) { int i; for (i = 0; i < n; ++i) { if (p[i] != ' ' && p[i] != '\t') { break; } } return i; } static unsigned GetSpaceStarPrefixLen(const char *p, size_t n) { int i; i = GetSpacePrefixLen(p, n); if (i < n && (p[i] == '*' || p[i] == '/')) { return p[i + 1] == '/' ? i + 2 : i + 1; } else { return 0; } } static unsigned GetTagLen(const char *p, size_t n) { int i; for (i = 0; i < n; ++i) { if (!islower(p[i])) { break; } } return i; } static unsigned GetMinPrefixLen(struct Lines *lines, unsigned GetPrefixLen(const char *, size_t)) { int i; unsigned n, m; for (m = -1, i = 0; i < lines->n; ++i) { if (lines->p[i].n) { n = GetPrefixLen(lines->p[i].p, lines->p[i].n); if (n < m) m = n; } } return m == -1 ? 0 : m; } static void RemovePrefixes(struct Lines *lines, unsigned m) { int i; for (i = 0; i < lines->n; ++i) { if (m <= lines->p[i].n) { lines->p[i].p += m; lines->p[i].n -= m; } } } static void SplitLines(struct Lines *lines, char *p) { char *q; DeleteLastEmptyLine(p, strlen(p)); p = SkipEmptyFirstLine(p); for (;;) { AppendLine(lines); lines->p[lines->n - 1].p = p; lines->p[lines->n - 1].n = (q = strchr(p, '\n')) ? q - p : strlen(p); if (!q) break; p = q + 1; } RemovePrefixes(lines, GetMinPrefixLen(lines, GetSpaceStarPrefixLen)); RemovePrefixes(lines, GetMinPrefixLen(lines, GetSpacePrefixLen)); } static bool ConsumeFileOverview(struct Lines *lines) { int i; if (lines->n && lines->p[0].n >= strlen(FILEOVERVIEW) && _startswith(lines->p[0].p, FILEOVERVIEW)) { lines->p[0].p += strlen(FILEOVERVIEW); lines->p[0].n -= strlen(FILEOVERVIEW); while (lines->p[0].n && (lines->p[0].p[0] == ' ' || lines->p[0].p[0] == '\t')) { lines->p[0].p += 1; lines->p[0].n -= 1; } return true; } else { return false; } } static void RemoveTrailingWhitespace(struct Lines *lines) { int i; for (i = 0; i < lines->n; ++i) { while (lines->p[i].n && isspace(lines->p[i].p[lines->p[i].n - 1])) { --lines->p[i].n; } } } static int ExtractTitle(struct Javadown *jd, struct Lines *lines) { int i; char *p; size_t n; for (p = NULL, n = i = 0; i < lines->n; ++i) { if (!lines->p[i].n) { ++i; break; } if (*lines->p[i].p == '@') { break; } if (i) { p = realloc(p, ++n); p[n - 1] = ' '; } p = realloc(p, n + lines->p[i].n); memcpy(p + n, lines->p[i].p, lines->p[i].n); n += lines->p[i].n; } p = realloc(p, n + 1); p[n] = '\0'; jd->title = p; return i; } static int ExtractText(struct Javadown *jd, struct Lines *lines, int i) { int j; char *p; size_t n; for (p = NULL, n = j = 0; i + j < lines->n; ++j) { if (lines->p[i + j].n && lines->p[i + j].p[0] == '@') break; if (j) { p = realloc(p, ++n); p[n - 1] = '\n'; } p = realloc(p, n + lines->p[i + j].n); memcpy(p + n, lines->p[i + j].p, lines->p[i + j].n); n += lines->p[i + j].n; } p = realloc(p, n + 1); p[n] = '\0'; jd->text = p; return i; } static void ExtractTags(struct Javadown *jd, struct Lines *lines, int i) { size_t n; char *p, *tag, *text, *p2; unsigned taglen, textlen, n2; for (p = NULL, n = 0; i < lines->n; ++i) { if (!lines->p[i].n) continue; if (lines->p[i].p[0] != '@') continue; tag = lines->p[i].p + 1; taglen = GetTagLen(tag, lines->p[i].n - 1); if (!taglen) continue; text = tag + taglen; tag = strndup(tag, taglen); textlen = lines->p[i].n - 1 - taglen; while (textlen && isspace(*text)) { ++text; --textlen; } text = strndup(text, textlen); while (i + 1 < lines->n && (!lines->p[i + 1].n || lines->p[i + 1].p[0] != '@')) { ++i; p2 = lines->p[i].p; n2 = lines->p[i].n; if (n2 && *p2 == '\t') { p2 += 1; n2 -= 1; } if (n2 >= 4 && !memcmp(p2, " ", 4)) { p2 += 4; n2 -= 4; } text = realloc(text, textlen + 1 + n2 + 1); text[textlen] = '\n'; memcpy(text + textlen + 1, p2, n2); textlen += 1 + n2; text[textlen] = '\0'; } AppendTag(&jd->tags); jd->tags.p[jd->tags.n - 1].tag = tag; jd->tags.p[jd->tags.n - 1].text = text; } } /** * Parses javadown. * * @param data should point to text inside the slash star markers * @param size is length of data in bytes * @return object that should be passed to FreeJavadown() */ struct Javadown *ParseJavadown(const char *data, size_t size) { int i; char *p; struct Lines lines; struct Javadown *jd; bzero(&lines, sizeof(lines)); jd = calloc(1, sizeof(struct Javadown)); p = strndup(data, size); SplitLines(&lines, p); RemoveTrailingWhitespace(&lines); jd->isfileoverview = ConsumeFileOverview(&lines); i = ExtractTitle(jd, &lines); i = ExtractText(jd, &lines, i); ExtractTags(jd, &lines, i); free(lines.p); free(p); return jd; } /** * Frees object returned by ParseJavadown(). */ void FreeJavadown(struct Javadown *jd) { int i; if (jd) { for (i = 0; i < jd->tags.n; ++i) { free(jd->tags.p[i].tag); free(jd->tags.p[i].text); } free(jd->tags.p); free(jd->title); free(jd->text); free(jd); } }
8,116
279
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/syscall.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 "tool/build/lib/syscall.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/ioctl.h" #include "libc/calls/sig.internal.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/sysinfo.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timeval.h" #include "libc/calls/struct/tms.h" #include "libc/calls/struct/utsname.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/weirdtypes.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/runtime/pc.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/select.h" #include "libc/sock/sock.h" #include "libc/sock/struct/sockaddr.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/lock.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/msync.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rusage.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "libc/sysv/consts/ss.h" #include "libc/sysv/consts/tcp.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/consts/w.h" #include "libc/sysv/errfuns.h" #include "libc/time/struct/timezone.h" #include "libc/time/struct/utimbuf.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "third_party/mbedtls/endian.h" #include "tool/build/lib/bits.h" #include "tool/build/lib/case.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/iovs.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/pml4t.h" #include "tool/build/lib/signal.h" #include "tool/build/lib/throw.h" #include "tool/build/lib/xlat.h" #define TIOCGWINSZ_LINUX 0x5413 #define TCGETS_LINUX 0x5401 #define TCSETS_LINUX 0x5402 #define TCSETSW_LINUX 0x5403 #define TCSETSF_LINUX 0x5404 #define ARCH_SET_GS_LINUX 0x1001 #define ARCH_SET_FS_LINUX 0x1002 #define ARCH_GET_FS_LINUX 0x1003 #define ARCH_GET_GS_LINUX 0x1004 #define SOCK_CLOEXEC_LINUX 0x080000 #define O_CLOEXEC_LINUX 0x080000 #define SA_RESTORER 0x04000000 #define POLLIN_LINUX 0x01 #define POLLPRI_LINUX 0x02 #define POLLOUT_LINUX 0x04 #define POLLERR_LINUX 0x08 #define POLLHUP_LINUX 0x10 #define POLLNVAL_LINUX 0x20 #define TIOCGWINSZ_LINUX 0x5413 #define TCGETS_LINUX 0x5401 #define TCSETS_LINUX 0x5402 #define TCSETSW_LINUX 0x5403 #define TCSETSF_LINUX 0x5404 #define ISIG_LINUX 0b0000000000000001 #define ICANON_LINUX 0b0000000000000010 #define ECHO_LINUX 0b0000000000001000 #define OPOST_LINUX 0b0000000000000001 #define POINTER(x) ((void *)(intptr_t)(x)) #define UNPOINTER(x) ((int64_t)(intptr_t)(x)) #define SYSCALL(x, y) CASE(x, asm("# " #y); ax = y) #define XLAT(x, y) CASE(x, return y) #define PNN(x) ResolveAddress(m, x) #define P(x) ((x) ? PNN(x) : 0) #define ASSIGN(D, S) memcpy(&D, &S, MIN(sizeof(S), sizeof(D))) const struct MachineFdCb kMachineFdCbHost = { .close = close, .readv = readv, .poll = poll, .writev = writev, .ioctl = (void *)ioctl, }; static int GetFd(struct Machine *m, int fd) { if (!(0 <= fd && fd < m->fds.i)) return ebadf(); if (!m->fds.p[fd].cb) return ebadf(); return m->fds.p[fd].fd; } static int GetAfd(struct Machine *m, int fd) { if (fd == -100) return AT_FDCWD; return GetFd(m, fd); } static const char *GetSimulated(void) { if (IsGenuineBlink()) { return " SIMULATED"; } else { return ""; } } static int AppendIovsReal(struct Machine *m, struct Iovs *ib, int64_t addr, size_t size) { void *real; size_t have; unsigned got; while (size) { if (!(real = FindReal(m, addr))) return efault(); have = 0x1000 - (addr & 0xfff); got = MIN(size, have); if (AppendIovs(ib, real, got) == -1) return -1; addr += got; size -= got; } return 0; } static int AppendIovsGuest(struct Machine *m, struct Iovs *iv, int64_t iovaddr, long iovlen) { int rc; size_t i, iovsize; struct iovec *guestiovs; if (!__builtin_mul_overflow(iovlen, sizeof(struct iovec), &iovsize) && (0 <= iovsize && iovsize <= 0x7ffff000)) { if ((guestiovs = malloc(iovsize))) { VirtualSendRead(m, guestiovs, iovaddr, iovsize); for (rc = i = 0; i < iovlen; ++i) { if (AppendIovsReal(m, iv, (intptr_t)guestiovs[i].iov_base, guestiovs[i].iov_len) == -1) { rc = -1; break; } } free(guestiovs); } else { rc = enomem(); } } else { rc = eoverflow(); } return rc; } static int OpPrctl(struct Machine *m, int op, int64_t a, int64_t b, int64_t c, int64_t d) { return einval(); } static int OpArchPrctl(struct Machine *m, int code, int64_t addr) { switch (code) { case ARCH_SET_GS: Write64(m->gs, addr); return 0; case ARCH_SET_FS: Write64(m->fs, addr); return 0; case ARCH_GET_GS: VirtualRecvWrite(m, addr, m->gs, 8); return 0; case ARCH_GET_FS: VirtualRecvWrite(m, addr, m->fs, 8); return 0; default: return einval(); } } static int OpMprotect(struct Machine *m, int64_t addr, uint64_t len, int prot) { return 0; } static int OpMadvise(struct Machine *m, int64_t addr, size_t length, int advice) { return enosys(); } static int64_t OpBrk(struct Machine *m, int64_t addr) { addr = ROUNDUP(addr, PAGESIZE); if (addr > m->brk) { if (ReserveVirtual(m, m->brk, addr - m->brk, PAGE_V | PAGE_RW | PAGE_U | PAGE_RSRV) != -1) { m->brk = addr; } } else if (addr < m->brk) { if (FreeVirtual(m, addr, m->brk - addr) != -1) { m->brk = addr; } } return m->brk; } static int OpMunmap(struct Machine *m, int64_t virt, uint64_t size) { VERBOSEF("MUNMAP%s %012lx %,ld", GetSimulated(), virt, size); return FreeVirtual(m, virt, size); } static int64_t OpMmap(struct Machine *m, int64_t virt, size_t size, int prot, int flags, int fd, int64_t offset) { int e; void *tmp; ssize_t rc; uint64_t key; bool recoverable; VERBOSEF("MMAP%s %012lx %,ld %#x %#x %d %#lx", GetSimulated(), virt, size, prot, flags, fd, offset); if (prot & PROT_READ) { key = PAGE_RSRV | PAGE_U | PAGE_V; if (prot & PROT_WRITE) key |= PAGE_RW; if (!(prot & PROT_EXEC)) key |= PAGE_XD; if (flags & 256 /* MAP_GROWSDOWN */) key |= PAGE_GROD; flags = XlatMapFlags(flags); if (fd != -1 && (fd = GetFd(m, fd)) == -1) return -1; if (flags & MAP_FIXED) { recoverable = false; } else { recoverable = true; if (!virt) { if ((virt = FindVirtual(m, m->brk, size)) == -1) return -1; m->brk = virt + size; } else { if ((virt = FindVirtual(m, virt, size)) == -1) return -1; } } if (ReserveVirtual(m, virt, size, key) != -1) { if (fd != -1 && !(flags & MAP_ANONYMOUS)) { // TODO: lazy file mappings CHECK_NOTNULL((tmp = malloc(size))); for (e = errno;;) { rc = pread(fd, tmp, size, offset); if (rc != -1) break; CHECK_EQ(EINTR, errno); errno = e; } CHECK_EQ(size, rc); VirtualRecvWrite(m, virt, tmp, size); free(tmp); } return virt; } else if (recoverable) { FreeVirtual(m, virt, size); return -1; } else { FATALF("unrecoverable oom with mmap(MAP_FIXED)"); } } else { return FreeVirtual(m, virt, size); } } static int OpMsync(struct Machine *m, int64_t virt, size_t size, int flags) { return enosys(); #if 0 size_t i; void *page; virt = ROUNDDOWN(virt, 4096); flags = XlatMsyncFlags(flags); for (i = 0; i < size; i += 4096) { if (!(page = FindReal(m, virt + i))) return efault(); if (msync(page, 4096, flags) == -1) return -1; } return 0; #endif } static int OpClose(struct Machine *m, int fd) { int rc; struct FdClosed *closed; if (!(0 <= fd && fd < m->fds.i)) return ebadf(); if (!m->fds.p[fd].cb) return ebadf(); rc = m->fds.p[fd].cb->close(m->fds.p[fd].fd); MachineFdRemove(&m->fds, fd); return rc; } static int OpOpenat(struct Machine *m, int dirfd, int64_t pathaddr, int flags, int mode) { int fd, i; const char *path; flags = XlatOpenFlags(flags); if ((dirfd = GetAfd(m, dirfd)) == -1) return -1; if ((i = MachineFdAdd(&m->fds)) == -1) return -1; path = LoadStr(m, pathaddr); if ((fd = openat(dirfd, path, flags, mode)) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = fd; VERBOSEF("openat(%#x, %`'s, %#x, %#x) → %d [%d]", dirfd, path, flags, mode, i, fd); fd = i; } else { MachineFdRemove(&m->fds, i); VERBOSEF("openat(%#x, %`'s, %#x, %#x) failed", dirfd, path, flags, mode); } return fd; } static int OpPipe(struct Machine *m, int64_t pipefds_addr) { int i, j, pipefds[2]; if ((i = MachineFdAdd(&m->fds)) != -1) { if ((j = MachineFdAdd(&m->fds)) != -1) { if (pipe(pipefds) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = pipefds[0]; m->fds.p[j].cb = &kMachineFdCbHost; m->fds.p[j].fd = pipefds[1]; pipefds[0] = i; pipefds[1] = j; VirtualRecvWrite(m, pipefds_addr, pipefds, sizeof(pipefds)); return 0; } MachineFdRemove(&m->fds, j); } MachineFdRemove(&m->fds, i); } return -1; } static int OpDup(struct Machine *m, int fd) { int i; if ((fd = GetFd(m, fd)) != -1) { if ((i = MachineFdAdd(&m->fds)) != -1) { if ((fd = dup(fd)) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = fd; return i; } MachineFdRemove(&m->fds, i); } } return -1; } static int OpDup2(struct Machine *m, int fd, int newfd) { int i, rc; if ((fd = GetFd(m, fd)) == -1) return -1; if ((0 <= newfd && newfd < m->fds.i)) { if ((rc = dup2(fd, m->fds.p[newfd].fd)) != -1) { m->fds.p[newfd].cb = &kMachineFdCbHost; m->fds.p[newfd].fd = rc; rc = newfd; } } else if ((i = MachineFdAdd(&m->fds)) != -1) { if ((rc = dup(fd)) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = rc; rc = i; } } else { rc = -1; } return rc; } static int OpDup3(struct Machine *m, int fd, int newfd, int flags) { int i, rc; if (!(flags & ~O_CLOEXEC_LINUX)) { if ((fd = GetFd(m, fd)) == -1) return -1; if ((0 <= newfd && newfd < m->fds.i)) { if ((rc = dup2(fd, m->fds.p[newfd].fd)) != -1) { if (flags & O_CLOEXEC_LINUX) { fcntl(rc, F_SETFD, FD_CLOEXEC); } m->fds.p[newfd].cb = &kMachineFdCbHost; m->fds.p[newfd].fd = rc; rc = newfd; } } else if ((i = MachineFdAdd(&m->fds)) != -1) { if ((rc = dup(fd)) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = rc; rc = i; } } else { rc = -1; } return rc; } else { return einval(); } } static int OpSocket(struct Machine *m, int family, int type, int protocol) { int i, fd; if ((family = XlatSocketFamily(family)) == -1) return -1; if ((type = XlatSocketType(type)) == -1) return -1; if ((protocol = XlatSocketProtocol(protocol)) == -1) return -1; if ((i = MachineFdAdd(&m->fds)) == -1) return -1; if ((fd = socket(family, type, protocol)) != -1) { m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = fd; fd = i; } else { MachineFdRemove(&m->fds, i); } return fd; } static int OpAccept4(struct Machine *m, int fd, int64_t aa, int64_t asa, int flags) { int i, rc; uint32_t addrsize; uint8_t gaddrsize[4]; struct sockaddr_in addr; struct sockaddr_in_bits gaddr; if (!(flags & ~SOCK_CLOEXEC_LINUX)) { if ((fd = GetFd(m, fd)) == -1) return -1; if (aa) { VirtualSendRead(m, gaddrsize, asa, sizeof(gaddrsize)); if (Read32(gaddrsize) < sizeof(gaddr)) return einval(); } if ((i = rc = MachineFdAdd(&m->fds)) != -1) { addrsize = sizeof(addr); if ((rc = accept(fd, (struct sockaddr *)&addr, &addrsize)) != -1) { if (flags & SOCK_CLOEXEC_LINUX) { fcntl(fd, F_SETFD, FD_CLOEXEC); } if (aa) { Write32(gaddrsize, sizeof(gaddr)); XlatSockaddrToLinux(&gaddr, &addr); VirtualRecv(m, asa, gaddrsize, sizeof(gaddrsize)); VirtualRecvWrite(m, aa, &gaddr, sizeof(gaddr)); } m->fds.p[i].cb = &kMachineFdCbHost; m->fds.p[i].fd = rc; rc = i; } else { MachineFdRemove(&m->fds, i); } } return rc; } else { return einval(); } } static int OpConnectBind(struct Machine *m, int fd, int64_t aa, uint32_t as, int impl(int, const struct sockaddr *, uint32_t)) { struct sockaddr_in addr; struct sockaddr_in_bits gaddr; if (as != sizeof(gaddr)) return einval(); if ((fd = GetFd(m, fd)) == -1) return -1; VirtualSendRead(m, &gaddr, aa, sizeof(gaddr)); XlatSockaddrToHost(&addr, &gaddr); return impl(fd, (const struct sockaddr *)&addr, sizeof(addr)); } static int OpBind(struct Machine *m, int fd, int64_t aa, uint32_t as) { return OpConnectBind(m, fd, aa, as, bind); } static int OpConnect(struct Machine *m, int fd, int64_t aa, uint32_t as) { return OpConnectBind(m, fd, aa, as, connect); } static int OpSetsockopt(struct Machine *m, int fd, int level, int optname, int64_t optvaladdr, uint32_t optvalsize) { int rc; void *optval; if ((level = XlatSocketLevel(level)) == -1) return -1; if ((optname = XlatSocketOptname(level, optname)) == -1) return -1; if ((fd = GetFd(m, fd)) == -1) return -1; if (!(optval = malloc(optvalsize))) return -1; VirtualSendRead(m, optval, optvaladdr, optvalsize); rc = setsockopt(fd, level, optname, optval, optvalsize); free(optval); return rc; } static int OpGetsockopt(struct Machine *m, int fd, int level, int optname, int64_t optvaladdr, int64_t optsizeaddr) { int rc; void *optval; uint32_t optsize; if ((level = XlatSocketLevel(level)) == -1) return -1; if ((optname = XlatSocketOptname(level, optname)) == -1) return -1; if ((fd = GetFd(m, fd)) == -1) return -1; if (!optvaladdr) { rc = getsockopt(fd, level, optname, 0, 0); } else { VirtualSendRead(m, &optsize, optsizeaddr, sizeof(optsize)); if (!(optval = malloc(optsize))) return -1; if ((rc = getsockopt(fd, level, optname, optval, &optsize)) != -1) { VirtualRecvWrite(m, optvaladdr, optval, optsize); VirtualRecvWrite(m, optsizeaddr, &optsize, sizeof(optsize)); } free(optval); } return rc; } static int OpSocketName(struct Machine *m, int fd, int64_t aa, int64_t asa, int SocketName(int, struct sockaddr *, socklen_t *)) { int rc; uint32_t addrsize; uint8_t gaddrsize[4]; struct sockaddr_in addr; struct sockaddr_in_bits gaddr; if ((fd = GetFd(m, fd)) == -1) return -1; VirtualSendRead(m, gaddrsize, asa, sizeof(gaddrsize)); if (Read32(gaddrsize) < sizeof(gaddr)) return einval(); addrsize = sizeof(addr); if ((rc = SocketName(fd, (struct sockaddr *)&addr, &addrsize)) != -1) { Write32(gaddrsize, sizeof(gaddr)); XlatSockaddrToLinux(&gaddr, &addr); VirtualRecv(m, asa, gaddrsize, sizeof(gaddrsize)); VirtualRecvWrite(m, aa, &gaddr, sizeof(gaddr)); } return rc; } static int OpGetsockname(struct Machine *m, int fd, int64_t aa, int64_t asa) { return OpSocketName(m, fd, aa, asa, getsockname); } static int OpGetpeername(struct Machine *m, int fd, int64_t aa, int64_t asa) { return OpSocketName(m, fd, aa, asa, getpeername); } static ssize_t OpRead(struct Machine *m, int fd, int64_t addr, size_t size) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) { if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) { if ((rc = m->fds.p[fd].cb->readv(m->fds.p[fd].fd, iv.p, iv.i)) != -1) { SetWriteAddr(m, addr, rc); } } } else { rc = ebadf(); } FreeIovs(&iv); return rc; } static int OpGetdents(struct Machine *m, int dirfd, int64_t addr, uint32_t size) { int rc; DIR *dir; struct dirent *ent; if (size < sizeof(struct dirent)) return einval(); if (0 <= dirfd && dirfd < m->fds.i) { if ((dir = fdopendir(m->fds.p[dirfd].fd))) { rc = 0; while (rc + sizeof(struct dirent) <= size) { if (!(ent = readdir(dir))) break; VirtualRecvWrite(m, addr + rc, ent, ent->d_reclen); rc += ent->d_reclen; } free(dir); } else { rc = -1; } } else { rc = ebadf(); } return rc; } static ssize_t OpPread(struct Machine *m, int fd, int64_t addr, size_t size, int64_t offset) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((rc = GetFd(m, fd)) != -1) { fd = rc; if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) { if ((rc = preadv(fd, iv.p, iv.i, offset)) != -1) { SetWriteAddr(m, addr, rc); } } } FreeIovs(&iv); return rc; } static ssize_t OpWrite(struct Machine *m, int fd, int64_t addr, size_t size) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) { if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) { if ((rc = m->fds.p[fd].cb->writev(m->fds.p[fd].fd, iv.p, iv.i)) != -1) { SetReadAddr(m, addr, rc); } else { VERBOSEF("write(%d [%d], %012lx, %zu) failed: %s", fd, m->fds.p[fd].fd, addr, size, strerror(errno)); } } } else { VERBOSEF("write(%d, %012lx, %zu) bad fd", fd, addr, size); rc = ebadf(); } FreeIovs(&iv); return rc; } static ssize_t OpPwrite(struct Machine *m, int fd, int64_t addr, size_t size, int64_t offset) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((rc = GetFd(m, fd)) != -1) { fd = rc; if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) { if ((rc = pwritev(fd, iv.p, iv.i, offset)) != -1) { SetReadAddr(m, addr, rc); } } } FreeIovs(&iv); return rc; } static int IoctlTiocgwinsz(struct Machine *m, int fd, int64_t addr, int fn(int, int, ...)) { int rc; struct winsize ws; struct winsize_bits gws; if ((rc = fn(fd, TIOCGWINSZ, &ws)) != -1) { XlatWinsizeToLinux(&gws, &ws); VirtualRecvWrite(m, addr, &gws, sizeof(gws)); } return rc; } static int IoctlTcgets(struct Machine *m, int fd, int64_t addr, int fn(int, int, ...)) { int rc; struct termios tio; struct termios_bits gtio; if ((rc = fn(fd, TCGETS, &tio)) != -1) { XlatTermiosToLinux(&gtio, &tio); VirtualRecvWrite(m, addr, &gtio, sizeof(gtio)); } return rc; } static int IoctlTcsets(struct Machine *m, int fd, int64_t request, int64_t addr, int (*fn)(int, int, ...)) { struct termios tio; struct termios_bits gtio; VirtualSendRead(m, &gtio, addr, sizeof(gtio)); XlatLinuxToTermios(&tio, &gtio); return fn(fd, request, &tio); } static int OpIoctl(struct Machine *m, int fd, uint64_t request, int64_t addr) { int (*fn)(int, int, ...); if (!(0 <= fd && fd < m->fds.i) || !m->fds.p[fd].cb) return ebadf(); fn = m->fds.p[fd].cb->ioctl; fd = m->fds.p[fd].fd; switch (request) { case TIOCGWINSZ_LINUX: return IoctlTiocgwinsz(m, fd, addr, fn); case TCGETS_LINUX: return IoctlTcgets(m, fd, addr, fn); case TCSETS_LINUX: return IoctlTcsets(m, fd, TCSETS, addr, fn); case TCSETSW_LINUX: return IoctlTcsets(m, fd, TCSETSW, addr, fn); case TCSETSF_LINUX: return IoctlTcsets(m, fd, TCSETSF, addr, fn); default: return einval(); } } static ssize_t OpReadv(struct Machine *m, int fd, int64_t iovaddr, int iovlen) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) { if ((rc = AppendIovsGuest(m, &iv, iovaddr, iovlen)) != -1) { rc = m->fds.p[fd].cb->readv(m->fds.p[fd].fd, iv.p, iv.i); } } else { rc = ebadf(); } FreeIovs(&iv); return rc; } static ssize_t OpWritev(struct Machine *m, int fd, int64_t iovaddr, int iovlen) { ssize_t rc; struct Iovs iv; InitIovs(&iv); if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) { if ((rc = AppendIovsGuest(m, &iv, iovaddr, iovlen)) != -1) { rc = m->fds.p[fd].cb->writev(m->fds.p[fd].fd, iv.p, iv.i); } } else { rc = ebadf(); } FreeIovs(&iv); return rc; } static int64_t OpLseek(struct Machine *m, int fd, int64_t offset, int whence) { if ((fd = GetFd(m, fd)) == -1) return -1; return lseek(fd, offset, whence); } static ssize_t OpFtruncate(struct Machine *m, int fd, int64_t size) { if ((fd = GetFd(m, fd)) == -1) return -1; return ftruncate(fd, size); } static int OpFaccessat(struct Machine *m, int dirfd, int64_t path, int mode, int flags) { flags = XlatAtf(flags); mode = XlatAccess(mode); if ((dirfd = GetAfd(m, dirfd)) == -1) return -1; return faccessat(dirfd, LoadStr(m, path), mode, flags); } static int OpFstatat(struct Machine *m, int dirfd, int64_t path, int64_t staddr, int flags) { int rc; struct stat st; struct stat_bits gst; flags = XlatAtf(flags); if ((dirfd = GetAfd(m, dirfd)) == -1) return -1; if ((rc = fstatat(dirfd, LoadStr(m, path), &st, flags)) != -1) { XlatStatToLinux(&gst, &st); VirtualRecvWrite(m, staddr, &gst, sizeof(gst)); } return rc; } static int OpFstat(struct Machine *m, int fd, int64_t staddr) { int rc; struct stat st; struct stat_bits gst; if ((fd = GetFd(m, fd)) == -1) return -1; if ((rc = fstat(fd, &st)) != -1) { XlatStatToLinux(&gst, &st); VirtualRecvWrite(m, staddr, &gst, sizeof(gst)); } return rc; } static int OpListen(struct Machine *m, int fd, int backlog) { if ((fd = GetFd(m, fd)) == -1) return -1; return listen(fd, backlog); } static int OpShutdown(struct Machine *m, int fd, int how) { if ((fd = GetFd(m, fd)) == -1) return -1; return shutdown(fd, how); } static int OpFsync(struct Machine *m, int fd) { if ((fd = GetFd(m, fd)) == -1) return -1; return fsync(fd); } static int OpFdatasync(struct Machine *m, int fd) { if ((fd = GetFd(m, fd)) == -1) return -1; return fdatasync(fd); } static int OpFchmod(struct Machine *m, int fd, uint32_t mode) { if ((fd = GetFd(m, fd)) == -1) return -1; return fchmod(fd, mode); } static int OpFcntl(struct Machine *m, int fd, int cmd, int arg) { if ((cmd = XlatFcntlCmd(cmd)) == -1) return -1; if ((arg = XlatFcntlArg(arg)) == -1) return -1; if ((fd = GetFd(m, fd)) == -1) return -1; return fcntl(fd, cmd, arg); } static int OpFadvise(struct Machine *m, int fd, uint64_t offset, uint64_t len, int advice) { if ((fd = GetFd(m, fd)) == -1) return -1; if ((advice = XlatAdvice(advice)) == -1) return -1; return fadvise(fd, offset, len, advice); } static int OpFlock(struct Machine *m, int fd, int lock) { if ((fd = GetFd(m, fd)) == -1) return -1; if ((lock = XlatLock(lock)) == -1) return -1; return flock(fd, lock); } static int OpChdir(struct Machine *m, int64_t path) { return chdir(LoadStr(m, path)); } static int OpMkdir(struct Machine *m, int64_t path, int mode) { return mkdir(LoadStr(m, path), mode); } static int OpMkdirat(struct Machine *m, int dirfd, int64_t path, int mode) { return mkdirat(GetAfd(m, dirfd), LoadStr(m, path), mode); } static int OpMknod(struct Machine *m, int64_t path, uint32_t mode, uint64_t dev) { return mknod(LoadStr(m, path), mode, dev); } static int OpRmdir(struct Machine *m, int64_t path) { return rmdir(LoadStr(m, path)); } static int OpUnlink(struct Machine *m, int64_t path) { return unlink(LoadStr(m, path)); } static int OpUnlinkat(struct Machine *m, int dirfd, int64_t path, int flags) { return unlinkat(GetAfd(m, dirfd), LoadStr(m, path), XlatAtf(flags)); } static int OpRename(struct Machine *m, int64_t src, int64_t dst) { return rename(LoadStr(m, src), LoadStr(m, dst)); } static int OpRenameat(struct Machine *m, int srcdirfd, int64_t src, int dstdirfd, int64_t dst) { return renameat(GetAfd(m, srcdirfd), LoadStr(m, src), GetAfd(m, dstdirfd), LoadStr(m, dst)); } static int OpTruncate(struct Machine *m, int64_t path, uint64_t length) { return truncate(LoadStr(m, path), length); } static int OpLink(struct Machine *m, int64_t existingpath, int64_t newpath) { return link(LoadStr(m, existingpath), LoadStr(m, newpath)); } static int OpSymlink(struct Machine *m, int64_t target, int64_t linkpath) { return symlink(LoadStr(m, target), LoadStr(m, linkpath)); } static int OpChmod(struct Machine *m, int64_t path, uint32_t mode) { return chmod(LoadStr(m, path), mode); } static int OpFork(struct Machine *m) { int pid; pid = fork(); if (!pid) m->isfork = true; return pid; } static int OpExecve(struct Machine *m, int64_t programaddr, int64_t argvaddr, int64_t envpaddr) { return enosys(); } wontreturn static void OpExit(struct Machine *m, int rc) { if (m->isfork) { _Exit(rc); } else { HaltMachine(m, rc | 0x100); } } _Noreturn static void OpExitGroup(struct Machine *m, int rc) { OpExit(m, rc); } static int OpWait4(struct Machine *m, int pid, int64_t opt_out_wstatus_addr, int options, int64_t opt_out_rusage_addr) { int rc; int32_t wstatus; struct rusage hrusage; struct rusage_bits grusage; if ((options = XlatWait(options)) == -1) return -1; if ((rc = wait4(pid, &wstatus, options, &hrusage)) != -1) { if (opt_out_wstatus_addr) { VirtualRecvWrite(m, opt_out_wstatus_addr, &wstatus, sizeof(wstatus)); } if (opt_out_rusage_addr) { XlatRusageToLinux(&grusage, &hrusage); VirtualRecvWrite(m, opt_out_rusage_addr, &grusage, sizeof(grusage)); } } return rc; } static int OpGetrusage(struct Machine *m, int resource, int64_t rusageaddr) { int rc; struct rusage hrusage; struct rusage_bits grusage; if ((resource = XlatRusage(resource)) == -1) return -1; if ((rc = getrusage(resource, &hrusage)) != -1) { XlatRusageToLinux(&grusage, &hrusage); VirtualRecvWrite(m, rusageaddr, &grusage, sizeof(grusage)); } return rc; } static int OpGetrlimit(struct Machine *m, int resource, int64_t rlimitaddr) { return enosys(); } static ssize_t OpReadlinkat(struct Machine *m, int dirfd, int64_t pathaddr, int64_t bufaddr, size_t size) { char *buf; ssize_t rc; const char *path; if ((dirfd = GetAfd(m, dirfd)) == -1) return -1; path = LoadStr(m, pathaddr); if (!(buf = malloc(size))) return enomem(); if ((rc = readlinkat(dirfd, path, buf, size)) != -1) { VirtualRecvWrite(m, bufaddr, buf, rc); } free(buf); return rc; } static int64_t OpGetcwd(struct Machine *m, int64_t bufaddr, size_t size) { size_t n; char *buf; int64_t res; size = MIN(size, PATH_MAX); if (!(buf = malloc(size))) return enomem(); if ((getcwd)(buf, size)) { n = strlen(buf); VirtualRecvWrite(m, bufaddr, buf, n); res = bufaddr; } else { res = -1; } free(buf); return res; } static int OpSigaction(struct Machine *m, int sig, int64_t act, int64_t old, uint64_t sigsetsize) { if ((sig = XlatSignal(sig) - 1) != -1 && (0 <= sig && sig < ARRAYLEN(m->sighand)) && sigsetsize == 8) { if (old) VirtualRecvWrite(m, old, &m->sighand[sig], sizeof(m->sighand[0])); if (act) VirtualSendRead(m, &m->sighand[sig], act, sizeof(m->sighand[0])); return 0; } else { return einval(); } } static int OpSigprocmask(struct Machine *m, int how, int64_t setaddr, int64_t oldsetaddr, uint64_t sigsetsize) { uint8_t set[8]; if ((how = XlatSig(how)) != -1 && sigsetsize == sizeof(set)) { if (oldsetaddr) { VirtualRecvWrite(m, oldsetaddr, m->sigmask, sizeof(set)); } if (setaddr) { VirtualSendRead(m, set, setaddr, sizeof(set)); if (how == SIG_BLOCK) { Write64(m->sigmask, Read64(m->sigmask) | Read64(set)); } else if (how == SIG_UNBLOCK) { Write64(m->sigmask, Read64(m->sigmask) & ~Read64(set)); } else { Write64(m->sigmask, Read64(set)); } } return 0; } else { return einval(); } } static int OpGetitimer(struct Machine *m, int which, int64_t curvaladdr) { int rc; struct itimerval it; struct itimerval_bits git; if ((rc = getitimer(which, &it)) != -1) { XlatItimervalToLinux(&git, &it); VirtualRecvWrite(m, curvaladdr, &git, sizeof(git)); } return rc; } static int OpSetitimer(struct Machine *m, int which, int64_t neuaddr, int64_t oldaddr) { int rc; struct itimerval neu, old; struct itimerval_bits git; VirtualSendRead(m, &git, neuaddr, sizeof(git)); XlatLinuxToItimerval(&neu, &git); if ((rc = setitimer(which, &neu, &old)) != -1) { if (oldaddr) { XlatItimervalToLinux(&git, &old); VirtualRecvWrite(m, oldaddr, &git, sizeof(git)); } } return rc; } static int OpNanosleep(struct Machine *m, int64_t req, int64_t rem) { int rc; struct timespec hreq, hrem; struct timespec_bits gtimespec; if (req) { VirtualSendRead(m, &gtimespec, req, sizeof(gtimespec)); hreq.tv_sec = Read64(gtimespec.tv_sec); hreq.tv_nsec = Read64(gtimespec.tv_nsec); } if ((rc = nanosleep(req ? &hreq : 0, rem ? &hrem : 0)) != -1) { if (rem) { Write64(gtimespec.tv_sec, hrem.tv_sec); Write64(gtimespec.tv_nsec, hrem.tv_nsec); VirtualRecvWrite(m, rem, &gtimespec, sizeof(gtimespec)); } } return rc; } static int OpSigsuspend(struct Machine *m, int64_t maskaddr) { sigset_t mask; uint8_t gmask[8]; VirtualSendRead(m, &gmask, maskaddr, 8); XlatLinuxToSigset(&mask, gmask); return sigsuspend(&mask); } static int OpClockGettime(struct Machine *m, int clockid, int64_t ts) { int rc; struct timespec htimespec; struct timespec_bits gtimespec; if ((rc = clock_gettime(XlatClock(clockid), ts ? &htimespec : 0)) != -1) { if (ts) { Write64(gtimespec.tv_sec, htimespec.tv_sec); Write64(gtimespec.tv_nsec, htimespec.tv_nsec); VirtualRecvWrite(m, ts, &gtimespec, sizeof(gtimespec)); } } return rc; } static int OpGettimeofday(struct Machine *m, int64_t tv, int64_t tz) { int rc; struct timeval htimeval; struct timezone htimezone; struct timeval_bits gtimeval; struct timezone_bits gtimezone; if ((rc = gettimeofday(&htimeval, tz ? &htimezone : 0)) != -1) { Write64(gtimeval.tv_sec, htimeval.tv_sec); Write64(gtimeval.tv_usec, htimeval.tv_usec); VirtualRecvWrite(m, tv, &gtimeval, sizeof(gtimeval)); if (tz) { Write32(gtimezone.tz_minuteswest, htimezone.tz_minuteswest); Write32(gtimezone.tz_dsttime, htimezone.tz_dsttime); VirtualRecvWrite(m, tz, &gtimezone, sizeof(gtimezone)); } } return rc; } static int OpUtimes(struct Machine *m, int64_t pathaddr, int64_t tvsaddr) { const char *path; struct timeval tvs[2]; struct timeval_bits gtvs[2]; path = LoadStr(m, pathaddr); if (tvsaddr) { VirtualSendRead(m, gtvs, tvsaddr, sizeof(gtvs)); tvs[0].tv_sec = Read64(gtvs[0].tv_sec); tvs[0].tv_usec = Read64(gtvs[0].tv_usec); tvs[1].tv_sec = Read64(gtvs[1].tv_sec); tvs[1].tv_usec = Read64(gtvs[1].tv_usec); return utimes(path, tvs); } else { return utimes(path, 0); } } static int OpPoll(struct Machine *m, int64_t fdsaddr, uint64_t nfds, int32_t timeout_ms) { uint64_t gfdssize; struct pollfd hfds[1]; int i, fd, rc, ev, count; struct timespec ts1, ts2; struct pollfd_bits *gfds; int64_t wait, elapsed, timeout; timeout = timeout_ms * 1000L; if (!__builtin_mul_overflow(nfds, sizeof(struct pollfd_bits), &gfdssize) && gfdssize <= 0x7ffff000) { if ((gfds = malloc(gfdssize))) { rc = 0; VirtualSendRead(m, gfds, fdsaddr, gfdssize); ts1 = timespec_mono(); for (;;) { for (i = 0; i < nfds; ++i) { fd = Read32(gfds[i].fd); if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) { hfds[0].fd = m->fds.p[fd].fd; ev = Read16(gfds[i].events); hfds[0].events = (((ev & POLLIN_LINUX) ? POLLIN : 0) | ((ev & POLLOUT_LINUX) ? POLLOUT : 0) | ((ev & POLLPRI_LINUX) ? POLLPRI : 0)); switch (m->fds.p[fd].cb->poll(hfds, 1, 0)) { case 0: Write16(gfds[i].revents, 0); break; case 1: ++rc; ev = 0; if (hfds[0].revents & POLLIN) ev |= POLLIN_LINUX; if (hfds[0].revents & POLLPRI) ev |= POLLPRI_LINUX; if (hfds[0].revents & POLLOUT) ev |= POLLOUT_LINUX; if (hfds[0].revents & POLLERR) ev |= POLLERR_LINUX; if (hfds[0].revents & POLLHUP) ev |= POLLHUP_LINUX; if (hfds[0].revents & POLLNVAL) ev |= POLLERR_LINUX; if (!ev) ev |= POLLERR_LINUX; Write16(gfds[i].revents, ev); break; case -1: ++rc; Write16(gfds[i].revents, POLLERR_LINUX); break; default: break; } } else { Write16(gfds[i].revents, POLLNVAL_LINUX); } } if (rc || !timeout) break; wait = __SIG_POLLING_INTERVAL_MS * 1000; if (timeout < 0) { if (usleep(wait)) { errno = EINTR; rc = -1; goto Finished; } } else { ts2 = timespec_mono(); elapsed = timespec_tomicros(timespec_sub(ts2, ts1)); if (elapsed >= timeout) { break; } if (timeout - elapsed < wait) { wait = timeout - elapsed; } if (usleep(wait)) { errno = EINTR; rc = -1; goto Finished; } } } VirtualRecvWrite(m, fdsaddr, gfds, nfds * sizeof(*gfds)); } else { errno = ENOMEM; rc = -1; } Finished: free(gfds); return rc; } else { return einval(); } } static int OpGetPid(struct Machine *m) { return getpid(); } static int OpGetPpid(struct Machine *m) { return getppid(); } static void OpKill(struct Machine *m, int pid, int sig) { if (!pid || pid == getpid()) { DeliverSignal(m, sig, SI_USER); } else { Write64(m->ax, -3); // ESRCH } } static int OpGetUid(struct Machine *m) { return getuid(); } static int OpGetGid(struct Machine *m) { return getgid(); } static int OpGetTid(struct Machine *m) { return gettid(); } static int OpSchedYield(struct Machine *m) { return sched_yield(); } static int OpAlarm(struct Machine *m, unsigned seconds) { return alarm(seconds); } static int OpPause(struct Machine *m) { return pause(); } static int DoOpen(struct Machine *m, int64_t path, int flags, int mode) { return OpOpenat(m, -100, path, flags, mode); } static int DoCreat(struct Machine *m, int64_t file, int mode) { return DoOpen(m, file, 0x241, mode); } static int DoAccess(struct Machine *m, int64_t path, int mode) { return OpFaccessat(m, -100, path, mode, 0); } static int DoStat(struct Machine *m, int64_t path, int64_t st) { return OpFstatat(m, -100, path, st, 0); } static int DoLstat(struct Machine *m, int64_t path, int64_t st) { return OpFstatat(m, -100, path, st, 0x0400); } static int OpAccept(struct Machine *m, int fd, int64_t sa, int64_t sas) { return OpAccept4(m, fd, sa, sas, 0); } void OpSyscall(struct Machine *m, uint32_t rde) { uint64_t i, ax, di, si, dx, r0, r8, r9; if (m->redraw) { m->redraw(); } ax = Read64(m->ax); if (m->ismetal) { WARNF("metal syscall 0x%03x", ax); } di = Read64(m->di); si = Read64(m->si); dx = Read64(m->dx); r0 = Read64(m->r10); r8 = Read64(m->r8); r9 = Read64(m->r9); switch (ax & 0x1ff) { SYSCALL(0x000, OpRead(m, di, si, dx)); SYSCALL(0x001, OpWrite(m, di, si, dx)); SYSCALL(0x002, DoOpen(m, di, si, dx)); SYSCALL(0x003, OpClose(m, di)); SYSCALL(0x004, DoStat(m, di, si)); SYSCALL(0x005, OpFstat(m, di, si)); SYSCALL(0x006, DoLstat(m, di, si)); SYSCALL(0x007, OpPoll(m, di, si, dx)); SYSCALL(0x008, OpLseek(m, di, si, dx)); SYSCALL(0x009, OpMmap(m, di, si, dx, r0, r8, r9)); SYSCALL(0x01A, OpMsync(m, di, si, dx)); SYSCALL(0x00A, OpMprotect(m, di, si, dx)); SYSCALL(0x00B, OpMunmap(m, di, si)); SYSCALL(0x00C, OpBrk(m, di)); SYSCALL(0x00D, OpSigaction(m, di, si, dx, r0)); SYSCALL(0x00E, OpSigprocmask(m, di, si, dx, r0)); SYSCALL(0x010, OpIoctl(m, di, si, dx)); SYSCALL(0x011, OpPread(m, di, si, dx, r0)); SYSCALL(0x012, OpPwrite(m, di, si, dx, r0)); SYSCALL(0x013, OpReadv(m, di, si, dx)); SYSCALL(0x014, OpWritev(m, di, si, dx)); SYSCALL(0x015, DoAccess(m, di, si)); SYSCALL(0x016, OpPipe(m, di)); SYSCALL(0x017, select(di, P(si), P(dx), P(r0), P(r8))); SYSCALL(0x018, OpSchedYield(m)); SYSCALL(0x01C, OpMadvise(m, di, si, dx)); SYSCALL(0x020, OpDup(m, di)); SYSCALL(0x021, OpDup2(m, di, si)); SYSCALL(0x124, OpDup3(m, di, si, dx)); SYSCALL(0x022, OpPause(m)); SYSCALL(0x023, OpNanosleep(m, di, si)); SYSCALL(0x024, OpGetitimer(m, di, si)); SYSCALL(0x025, OpAlarm(m, di)); SYSCALL(0x026, OpSetitimer(m, di, si, dx)); SYSCALL(0x027, OpGetPid(m)); SYSCALL(0x028, sendfile(di, si, P(dx), r0)); SYSCALL(0x029, OpSocket(m, di, si, dx)); SYSCALL(0x02A, OpConnect(m, di, si, dx)); SYSCALL(0x02B, OpAccept(m, di, di, dx)); SYSCALL(0x02C, sendto(di, PNN(si), dx, r0, P(r8), r9)); SYSCALL(0x02D, recvfrom(di, P(si), dx, r0, P(r8), P(r9))); SYSCALL(0x030, OpShutdown(m, di, si)); SYSCALL(0x031, OpBind(m, di, si, dx)); SYSCALL(0x032, OpListen(m, di, si)); SYSCALL(0x033, OpGetsockname(m, di, si, dx)); SYSCALL(0x034, OpGetpeername(m, di, si, dx)); SYSCALL(0x036, OpSetsockopt(m, di, si, dx, r0, r8)); SYSCALL(0x037, OpGetsockopt(m, di, si, dx, r0, r8)); SYSCALL(0x039, OpFork(m)); SYSCALL(0x03B, OpExecve(m, di, si, dx)); SYSCALL(0x03D, OpWait4(m, di, si, dx, r0)); SYSCALL(0x03F, uname(P(di))); SYSCALL(0x048, OpFcntl(m, di, si, dx)); SYSCALL(0x049, OpFlock(m, di, si)); SYSCALL(0x04A, OpFsync(m, di)); SYSCALL(0x04B, OpFdatasync(m, di)); SYSCALL(0x04C, OpTruncate(m, di, si)); SYSCALL(0x04D, OpFtruncate(m, di, si)); SYSCALL(0x04F, OpGetcwd(m, di, si)); SYSCALL(0x050, OpChdir(m, di)); SYSCALL(0x052, OpRename(m, di, si)); SYSCALL(0x053, OpMkdir(m, di, si)); SYSCALL(0x054, OpRmdir(m, di)); SYSCALL(0x055, DoCreat(m, di, si)); SYSCALL(0x056, OpLink(m, di, si)); SYSCALL(0x057, OpUnlink(m, di)); SYSCALL(0x058, OpSymlink(m, di, si)); SYSCALL(0x05A, OpChmod(m, di, si)); SYSCALL(0x05B, OpFchmod(m, di, si)); SYSCALL(0x060, OpGettimeofday(m, di, si)); SYSCALL(0x061, OpGetrlimit(m, di, si)); SYSCALL(0x062, OpGetrusage(m, di, si)); SYSCALL(0x063, sysinfo(PNN(di))); SYSCALL(0x064, times(PNN(di))); SYSCALL(0x066, OpGetUid(m)); SYSCALL(0x068, OpGetGid(m)); SYSCALL(0x06E, OpGetPpid(m)); SYSCALL(0x075, setresuid(di, si, dx)); SYSCALL(0x077, setresgid(di, si, dx)); SYSCALL(0x082, OpSigsuspend(m, di)); SYSCALL(0x085, OpMknod(m, di, si, dx)); SYSCALL(0x08C, getpriority(di, si)); SYSCALL(0x08D, setpriority(di, si, dx)); SYSCALL(0x0A0, setrlimit(di, P(si))); SYSCALL(0x084, utime(PNN(di), PNN(si))); SYSCALL(0x0EB, OpUtimes(m, di, si)); SYSCALL(0x09D, OpPrctl(m, di, si, dx, r0, r8)); SYSCALL(0x09E, OpArchPrctl(m, di, si)); SYSCALL(0x0BA, OpGetTid(m)); SYSCALL(0x0D9, OpGetdents(m, di, si, dx)); SYSCALL(0x0DD, OpFadvise(m, di, si, dx, r0)); SYSCALL(0x0E4, OpClockGettime(m, di, si)); SYSCALL(0x101, OpOpenat(m, di, si, dx, r0)); SYSCALL(0x102, OpMkdirat(m, di, si, dx)); SYSCALL(0x104, fchownat(GetAfd(m, di), P(si), dx, r0, XlatAtf(r8))); SYSCALL(0x105, futimesat(GetAfd(m, di), P(si), P(dx))); SYSCALL(0x106, OpFstatat(m, di, si, dx, r0)); SYSCALL(0x107, OpUnlinkat(m, di, si, dx)); SYSCALL(0x108, OpRenameat(m, di, si, dx, r0)); SYSCALL(0x10B, OpReadlinkat(m, di, si, dx, r0)); SYSCALL(0x10D, OpFaccessat(m, di, si, dx, r0)); SYSCALL(0x113, splice(di, P(si), dx, P(r0), r8, XlatAtf(r9))); SYSCALL(0x115, sync_file_range(di, si, dx, XlatAtf(r0))); SYSCALL(0x118, utimensat(GetAfd(m, di), P(si), P(dx), XlatAtf(r0))); SYSCALL(0x120, OpAccept4(m, di, si, dx, r0)); SYSCALL(0x177, vmsplice(di, P(si), dx, r0)); case 0x3C: OpExit(m, di); case 0xE7: OpExitGroup(m, di); case 0x00F: OpRestore(m); return; case 0x03E: OpKill(m, di, si); return; default: WARNF("missing syscall 0x%03x", ax); ax = enosys(); break; } Write64(m->ax, ax != -1 ? ax : -(XlatErrno(errno) & 0xfff)); for (i = 0; i < m->freelist.i; ++i) free(m->freelist.p[i]); m->freelist.i = 0; }
44,255
1,423
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/apetest.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/calls/calls.h" int main(int argc, char *argv[]) { write(1, "success\n", 8); }
1,932
24
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/clmul.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/bsr.h" #include "libc/nexgen32e/x86feature.h" #include "tool/build/lib/clmul.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/modrm.h" /** * @fileoverview Carryless Multiplication ISA */ struct clmul { uint64_t x, y; }; static struct clmul clmul(uint64_t a, uint64_t b) { uint64_t t, x = 0, y = 0; if (a && b) { if (_bsrl(a) < _bsrl(b)) t = a, a = b, b = t; for (t = 0; b; a <<= 1, b >>= 1) { if (b & 1) x ^= a, y ^= t; t = t << 1 | a >> 63; } } return (struct clmul){x, y}; } void OpSsePclmulqdq(struct Machine *m, uint32_t rde) { struct clmul res; res = clmul(Read64(XmmRexrReg(m, rde) + ((m->xedd->op.uimm0 & 0x01) << 3)), Read64(GetModrmRegisterXmmPointerRead16(m, rde) + ((m->xedd->op.uimm0 & 0x10) >> 1))); Write64(XmmRexrReg(m, rde) + 0, res.x); Write64(XmmRexrReg(m, rde) + 8, res.y); }
2,750
53
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stats.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 "tool/build/lib/stats.h" unsigned long taken; unsigned long ntaken; unsigned long opcount;
1,937
24
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/syscall.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_SYSCALL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_SYSCALL_H_ #include "tool/build/lib/fds.h" #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern const struct MachineFdCb kMachineFdCbHost; void OpSyscall(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_SYSCALL_H_ */
438
15
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/mda.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/str/tab.internal.h" #include "tool/build/lib/buffer.h" #include "tool/build/lib/mda.h" #define kBlink 1 #define kVisible 2 #define kUnderline 4 #define kBold 8 #define kReverse 16 /** * Decodes Monochrome Display Adapter attributes. * @see https://www.seasip.info/VintagePC/mda.html */ static uint8_t DecodeMdaAttributes(int8_t a) { uint8_t r = 0; if (a & 0x77) { if ((a & 0x77) == 0x70) r |= kReverse; if ((a & 0x07) == 0x01) r |= kUnderline; if (a & 0x08) r |= kBold; if (a < 0) r |= kBlink; r |= kVisible; } return r; } void DrawMda(struct Panel *p, uint8_t v[25][80][2]) { unsigned y, x, n, a, b; n = MIN(25, p->bottom - p->top); for (y = 0; y < n; ++y) { a = -1; for (x = 0; x < 80; ++x) { b = DecodeMdaAttributes(v[y][x][1]); if (a != b) { a = b; AppendStr(&p->lines[y], "\e[0"); if (a & kBold) AppendStr(&p->lines[y], ";1"); if (a & kUnderline) AppendStr(&p->lines[y], ";4"); if (a & kBlink) AppendStr(&p->lines[y], ";5"); if (a & kReverse) AppendStr(&p->lines[y], ";7"); AppendChar(&p->lines[y], 'm'); } if (a) { AppendWide(&p->lines[y], kCp437[v[y][x][0]]); } else { AppendChar(&p->lines[y], ' '); } } } }
3,201
71
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/loader.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_LOADER_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_LOADER_H_ #include "libc/elf/struct/ehdr.h" #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Elf { const char *prog; Elf64_Ehdr *ehdr; size_t size; int64_t base; char *map; size_t mapsize; }; void LoadProgram(struct Machine *, const char *, char **, char **, struct Elf *); void LoadDebugSymbols(struct Elf *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_LOADER_H_ */
597
24
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/bits.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_BITS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_BITS_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct iovec_bits { uint8_t iov_base[8]; uint8_t iov_len[8]; }; struct pollfd_bits { uint8_t fd[4]; uint8_t events[2]; uint8_t revents[2]; }; struct timeval_bits { uint8_t tv_sec[8]; uint8_t tv_usec[8]; }; struct timespec_bits { uint8_t tv_sec[8]; uint8_t tv_nsec[8]; }; struct timezone_bits { uint8_t tz_minuteswest[4]; uint8_t tz_dsttime[4]; }; struct sigaction_bits { uint8_t handler[8]; uint8_t flags[8]; uint8_t restorer[8]; uint8_t mask[8]; }; struct winsize_bits { uint8_t ws_row[2]; uint8_t ws_col[2]; uint8_t ws_xpixel[2]; uint8_t ws_ypixel[2]; }; struct termios_bits { uint8_t c_iflag[4]; uint8_t c_oflag[4]; uint8_t c_cflag[4]; uint8_t c_lflag[4]; uint8_t c_cc[32]; uint8_t c_ispeed[4]; uint8_t c_ospeed[4]; }; struct sockaddr_in_bits { uint8_t sin_family[2]; uint16_t sin_port; uint32_t sin_addr; uint8_t sin_zero[8]; }; struct stat_bits { uint8_t st_dev[8]; uint8_t st_ino[8]; uint8_t st_nlink[8]; uint8_t st_mode[4]; uint8_t st_uid[4]; uint8_t st_gid[4]; uint8_t __pad[4]; uint8_t st_rdev[8]; uint8_t st_size[8]; uint8_t st_blksize[8]; uint8_t st_blocks[8]; struct timespec_bits st_atim; struct timespec_bits st_mtim; struct timespec_bits st_ctim; }; struct itimerval_bits { struct timeval_bits it_interval; struct timeval_bits it_value; }; struct rusage_bits { struct timeval_bits ru_utime; struct timeval_bits ru_stime; uint8_t ru_maxrss[8]; uint8_t ru_ixrss[8]; uint8_t ru_idrss[8]; uint8_t ru_isrss[8]; uint8_t ru_minflt[8]; uint8_t ru_majflt[8]; uint8_t ru_nswap[8]; uint8_t ru_inblock[8]; uint8_t ru_oublock[8]; uint8_t ru_msgsnd[8]; uint8_t ru_msgrcv[8]; uint8_t ru_nsignals[8]; uint8_t ru_nvcsw[8]; uint8_t ru_nivcsw[8]; }; struct siginfo_bits { uint8_t si_signo[4]; uint8_t si_errno[4]; uint8_t si_code[4]; uint8_t __pad[4]; uint8_t payload[112]; }; struct fpstate_bits { uint8_t cwd[2]; uint8_t swd[2]; uint8_t ftw[2]; uint8_t fop[2]; uint8_t rip[8]; uint8_t rdp[8]; uint8_t mxcsr[4]; uint8_t mxcr_mask[4]; uint8_t st[8][16]; uint8_t xmm[16][16]; uint8_t __padding[96]; }; struct ucontext_bits { uint8_t uc_flags[8]; uint8_t uc_link[8]; uint8_t ss_sp[8]; uint8_t ss_flags[4]; uint8_t __pad0[4]; uint8_t ss_size[8]; uint8_t r8[8]; uint8_t r9[8]; uint8_t r10[8]; uint8_t r11[8]; uint8_t r12[8]; uint8_t r13[8]; uint8_t r14[8]; uint8_t r15[8]; uint8_t rdi[8]; uint8_t rsi[8]; uint8_t rbp[8]; uint8_t rbx[8]; uint8_t rdx[8]; uint8_t rax[8]; uint8_t rcx[8]; uint8_t rsp[8]; uint8_t rip[8]; uint8_t eflags[8]; uint8_t cs[2]; uint8_t gs[2]; uint8_t fs[2]; uint8_t ss[2]; uint8_t err[8]; uint8_t trapno[8]; uint8_t oldmask[8]; uint8_t cr2[8]; uint8_t fpstate[8]; uint8_t __pad1[64]; uint8_t uc_sigmask[8]; }; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_BITS_H_ */
3,131
167
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/message.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/log/check.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "tool/build/lib/buffer.h" #include "tool/build/lib/lines.h" #include "tool/build/lib/panel.h" static int GetWidthOfLongestLine(struct Lines *lines) { int i, w, m; for (m = i = 0; i < lines->n; ++i) { w = strwidth(lines->p[i], 0); m = MAX(m, w); } return m; } void PrintMessageBox(int fd, const char *msg, long tyn, long txn) { struct Buffer b; int i, w, h, x, y; struct Lines *lines; lines = NewLines(); AppendLines(lines, msg); h = 3 + lines->n + 3; w = 4 + GetWidthOfLongestLine(lines) + 4; x = (txn / 2. - w / 2.) + .5; y = (tyn / 2. - h / 2.) + .5; bzero(&b, sizeof(b)); AppendFmt(&b, "\e[%d;%dH", y++, x); for (i = 0; i < w; ++i) AppendStr(&b, " "); AppendFmt(&b, "\e[%d;%dH ╔", y++, x); for (i = 0; i < w - 4; ++i) AppendStr(&b, "═"); AppendStr(&b, "╗ "); AppendFmt(&b, "\e[%d;%dH ║ %-*s ║ ", y++, x, w - 8, ""); for (i = 0; i < lines->n; ++i) { AppendFmt(&b, "\e[%d;%dH ║ %-*s ║ ", y++, x, w - 8, lines->p[i]); } FreeLines(lines); AppendFmt(&b, "\e[%d;%dH ║ %-*s ║ ", y++, x, w - 8, ""); AppendFmt(&b, "\e[%d;%dH ╚", y++, x); for (i = 0; i < w - 4; ++i) AppendStr(&b, "═"); AppendStr(&b, "╝ "); AppendFmt(&b, "\e[%d;%dH", y++, x); for (i = 0; i < w; ++i) AppendStr(&b, " "); CHECK_NE(-1, WriteBuffer(&b, fd)); free(b.p); }
3,326
67
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cpuid.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_CPUID_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_CPUID_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpCpuid(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_CPUID_H_ */
347
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cpuid.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 "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" void OpCpuid(struct Machine *m, uint32_t rde) { uint32_t ax, bx, cx, dx; ax = 0; bx = 0; cx = 0; dx = 0; switch (Read32(m->ax)) { case 0: case 0x80000000: ax = 7; bx = 'G' | 'e' << 8 | 'n' << 16 | 'u' << 24; dx = 'i' | 'n' << 8 | 'e' << 16 | 'C' << 24; cx = 'o' | 's' << 8 | 'm' << 16 | 'o' << 24; break; case 1: cx |= 1 << 0; // sse3 cx |= 1 << 1; // pclmulqdq cx |= 1 << 9; // ssse3 cx |= 1 << 23; // popcnt cx |= 1 << 30; // rdrnd cx |= 0 << 25; // aes cx |= 1 << 13; // cmpxchg16b dx |= 1 << 0; // fpu dx |= 1 << 4; // tsc dx |= 1 << 6; // pae dx |= 1 << 8; // cmpxchg8b dx |= 1 << 15; // cmov dx |= 1 << 19; // clflush dx |= 1 << 23; // mmx dx |= 1 << 24; // fxsave dx |= 1 << 25; // sse dx |= 1 << 26; // sse2 break; case 7: switch (Read32(m->cx)) { case 0: bx |= 1 << 0; // fsgsbase bx |= 1 << 9; // erms bx |= 0 << 18; // rdseed cx |= 1 << 22; // rdpid break; default: break; } break; case 0x80000001: cx |= 1 << 0; // lahf dx |= 1 << 0; // fpu dx |= 1 << 8; // cmpxchg8b dx |= 1 << 11; // syscall dx |= 1 << 15; // cmov dx |= 1 << 23; // mmx dx |= 1 << 24; // fxsave dx |= 1 << 27; // rdtscp dx |= 1 << 29; // long break; case 0x80000007: dx |= 1 << 8; // invtsc break; default: break; } Write64(m->ax, ax); Write64(m->bx, bx); Write64(m->cx, cx); Write64(m->dx, dx); }
3,590
89
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/lines.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_LINES_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_LINES_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Lines { size_t n; char **p; }; struct Lines *NewLines(void); void FreeLines(struct Lines *); void AppendLine(struct Lines *, const char *, size_t); void AppendLines(struct Lines *, const char *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_LINES_H_ */
477
19
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/op101.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_OP101_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_OP101_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void Op101(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_OP101_H_ */
345
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/iovs.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_IOVS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_IOVS_H_ #include "libc/calls/struct/iovec.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Iovs { struct iovec *p; unsigned i, n; struct iovec init[2]; }; void InitIovs(struct Iovs *); void FreeIovs(struct Iovs *); int AppendIovs(struct Iovs *, void *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_IOVS_H_ */
488
20
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/buffer.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/calls/calls.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/intrin/tpenc.h" #include "libc/macros.internal.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/fmt.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "tool/build/lib/buffer.h" /* TODO(jart): replace with new append*() library */ void AppendData(struct Buffer *b, char *data, unsigned len) { char *p; unsigned n; if (b->i + len + 1 > b->n) { n = MAX(b->i + len + 1, MAX(16, b->n + (b->n >> 1))); if (!(p = realloc(b->p, n))) return; b->p = p; b->n = n; } memcpy(b->p + b->i, data, len); b->p[b->i += len] = 0; } void AppendChar(struct Buffer *b, char c) { AppendData(b, &c, 1); } void AppendStr(struct Buffer *b, const char *s) { AppendData(b, s, strlen(s)); } void AppendWide(struct Buffer *b, wint_t wc) { unsigned i; uint64_t wb; char buf[8]; i = 0; wb = _tpenc(wc); do { buf[i++] = wb & 0xFF; wb >>= 8; } while (wb); AppendData(b, buf, i); } int AppendFmt(struct Buffer *b, const char *fmt, ...) { int n; char *p; va_list va, vb; va_start(va, fmt); va_copy(vb, va); n = vsnprintf(b->p + b->i, b->n - b->i, fmt, va); if (b->i + n + 1 > b->n) { do { if (b->n) { b->n += b->n >> 1; } else { b->n = 16; } } while (b->i + n + 1 > b->n); b->p = realloc(b->p, b->n); vsnprintf(b->p + b->i, b->n - b->i, fmt, vb); } va_end(vb); va_end(va); b->i += n; return n; } /** * Writes buffer until completion, or error occurs. */ ssize_t WriteBuffer(struct Buffer *b, int fd) { bool t; char *p; ssize_t rc; size_t wrote, n; p = b->p; n = b->i; t = false; do { if ((rc = write(fd, p, n)) != -1) { wrote = rc; p += wrote; n -= wrote; } else if (errno == EINTR) { t = true; } else { return -1; } } while (n); if (!t) { return 0; } else { errno = EINTR; return -1; } }
3,832
119
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ssemov.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/pmovmskb.h" #include "libc/str/str.h" #include "tool/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/ssemov.h" #include "tool/build/lib/throw.h" static void MovdquVdqWdq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead16(m, rde), 16); } static void MovdquWdqVdq(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterXmmPointerWrite16(m, rde), XmmRexrReg(m, rde), 16); } static void MovupsVpsWps(struct Machine *m, uint32_t rde) { MovdquVdqWdq(m, rde); } static void MovupsWpsVps(struct Machine *m, uint32_t rde) { MovdquWdqVdq(m, rde); } static void MovupdVpsWps(struct Machine *m, uint32_t rde) { MovdquVdqWdq(m, rde); } static void MovupdWpsVps(struct Machine *m, uint32_t rde) { MovdquWdqVdq(m, rde); } void OpLddquVdqMdq(struct Machine *m, uint32_t rde) { MovdquVdqWdq(m, rde); } void OpMovntiMdqpGdqp(struct Machine *m, uint32_t rde) { if (Rexw(rde)) { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde), 8); } else { memcpy(ComputeReserveAddressWrite4(m, rde), XmmRexrReg(m, rde), 4); } } static void MovdqaVdqMdq(struct Machine *m, uint32_t rde) { int64_t v; uint8_t *p; v = ComputeAddress(m, rde); SetReadAddr(m, v, 16); if ((v & 15) || !(p = FindReal(m, v))) ThrowSegmentationFault(m, v); memcpy(XmmRexrReg(m, rde), Abp16(p), 16); } static void MovdqaMdqVdq(struct Machine *m, uint32_t rde) { int64_t v; uint8_t *p; v = ComputeAddress(m, rde); SetWriteAddr(m, v, 16); if ((v & 15) || !(p = FindReal(m, v))) ThrowSegmentationFault(m, v); memcpy(Abp16(p), XmmRexrReg(m, rde), 16); } static void MovdqaVdqWdq(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { memcpy(XmmRexrReg(m, rde), XmmRexbRm(m, rde), 16); } else { MovdqaVdqMdq(m, rde); } } static void MovdqaWdqVdq(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { memcpy(XmmRexbRm(m, rde), XmmRexrReg(m, rde), 16); } else { MovdqaMdqVdq(m, rde); } } static void MovntdqMdqVdq(struct Machine *m, uint32_t rde) { MovdqaMdqVdq(m, rde); } static void MovntpsMpsVps(struct Machine *m, uint32_t rde) { MovdqaMdqVdq(m, rde); } static void MovntpdMpdVpd(struct Machine *m, uint32_t rde) { MovdqaMdqVdq(m, rde); } void OpMovntdqaVdqMdq(struct Machine *m, uint32_t rde) { MovdqaVdqMdq(m, rde); } static void MovqPqQq(struct Machine *m, uint32_t rde) { memcpy(MmReg(m, rde), GetModrmRegisterMmPointerRead8(m, rde), 8); } static void MovqQqPq(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterMmPointerWrite8(m, rde), MmReg(m, rde), 8); } static void MovqVdqEqp(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), GetModrmRegisterWordPointerRead8(m, rde), 8); bzero(XmmRexrReg(m, rde) + 8, 8); } static void MovdVdqEd(struct Machine *m, uint32_t rde) { bzero(XmmRexrReg(m, rde), 16); memcpy(XmmRexrReg(m, rde), GetModrmRegisterWordPointerRead4(m, rde), 4); } static void MovqPqEqp(struct Machine *m, uint32_t rde) { memcpy(MmReg(m, rde), GetModrmRegisterWordPointerRead8(m, rde), 8); } static void MovdPqEd(struct Machine *m, uint32_t rde) { memcpy(MmReg(m, rde), GetModrmRegisterWordPointerRead4(m, rde), 4); bzero(MmReg(m, rde) + 4, 4); } static void MovdEdVdq(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { Write64(RegRexbRm(m, rde), Read32(XmmRexrReg(m, rde))); } else { memcpy(ComputeReserveAddressWrite4(m, rde), XmmRexrReg(m, rde), 4); } } static void MovqEqpVdq(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterWordPointerWrite8(m, rde), XmmRexrReg(m, rde), 8); } static void MovdEdPq(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { Write64(RegRexbRm(m, rde), Read32(MmReg(m, rde))); } else { memcpy(ComputeReserveAddressWrite4(m, rde), MmReg(m, rde), 4); } } static void MovqEqpPq(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterWordPointerWrite(m, rde, 8), MmReg(m, rde), 8); } static void MovntqMqPq(struct Machine *m, uint32_t rde) { memcpy(ComputeReserveAddressWrite8(m, rde), MmReg(m, rde), 8); } static void MovqVqWq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead8(m, rde), 8); bzero(XmmRexrReg(m, rde) + 8, 8); } static void MovssVpsWps(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { memcpy(XmmRexrReg(m, rde), XmmRexbRm(m, rde), 4); } else { memcpy(XmmRexrReg(m, rde), ComputeReserveAddressRead4(m, rde), 4); bzero(XmmRexrReg(m, rde) + 4, 12); } } static void MovssWpsVps(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterXmmPointerWrite4(m, rde), XmmRexrReg(m, rde), 4); } static void MovsdVpsWps(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { memcpy(XmmRexrReg(m, rde), XmmRexbRm(m, rde), 8); } else { memcpy(XmmRexrReg(m, rde), ComputeReserveAddressRead8(m, rde), 8); bzero(XmmRexrReg(m, rde) + 8, 8); } } static void MovsdWpsVps(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterXmmPointerWrite8(m, rde), XmmRexrReg(m, rde), 8); } static void MovhlpsVqUq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), XmmRexbRm(m, rde) + 8, 8); } static void MovlpsVqMq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), ComputeReserveAddressRead8(m, rde), 8); } static void MovlpdVqMq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), ComputeReserveAddressRead8(m, rde), 8); } static void MovddupVqWq(struct Machine *m, uint32_t rde) { uint8_t *src; src = GetModrmRegisterXmmPointerRead8(m, rde); memcpy(XmmRexrReg(m, rde) + 0, src, 8); memcpy(XmmRexrReg(m, rde) + 8, src, 8); } static void MovsldupVqWq(struct Machine *m, uint32_t rde) { uint8_t *dst, *src; dst = XmmRexrReg(m, rde); src = GetModrmRegisterXmmPointerRead16(m, rde); memcpy(dst + 0 + 0, src + 0, 4); memcpy(dst + 0 + 4, src + 0, 4); memcpy(dst + 8 + 0, src + 8, 4); memcpy(dst + 8 + 4, src + 8, 4); } static void MovlpsMqVq(struct Machine *m, uint32_t rde) { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde), 8); } static void MovlpdMqVq(struct Machine *m, uint32_t rde) { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde), 8); } static void MovlhpsVqUq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde) + 8, XmmRexbRm(m, rde), 8); } static void MovhpsVqMq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde) + 8, ComputeReserveAddressRead8(m, rde), 8); } static void MovhpdVqMq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde) + 8, ComputeReserveAddressRead8(m, rde), 8); } static void MovshdupVqWq(struct Machine *m, uint32_t rde) { uint8_t *dst, *src; dst = XmmRexrReg(m, rde); src = GetModrmRegisterXmmPointerRead16(m, rde); memcpy(dst + 0 + 0, src + 04, 4); memcpy(dst + 0 + 4, src + 04, 4); memcpy(dst + 8 + 0, src + 12, 4); memcpy(dst + 8 + 4, src + 12, 4); } static void MovhpsMqVq(struct Machine *m, uint32_t rde) { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde) + 8, 8); } static void MovhpdMqVq(struct Machine *m, uint32_t rde) { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde) + 8, 8); } static void MovqWqVq(struct Machine *m, uint32_t rde) { if (IsModrmRegister(rde)) { memcpy(XmmRexbRm(m, rde), XmmRexrReg(m, rde), 8); bzero(XmmRexbRm(m, rde) + 8, 8); } else { memcpy(ComputeReserveAddressWrite8(m, rde), XmmRexrReg(m, rde), 8); } } static void Movq2dqVdqNq(struct Machine *m, uint32_t rde) { memcpy(XmmRexrReg(m, rde), MmRm(m, rde), 8); bzero(XmmRexrReg(m, rde) + 8, 8); } static void Movdq2qPqUq(struct Machine *m, uint32_t rde) { memcpy(MmReg(m, rde), XmmRexbRm(m, rde), 8); } static void MovapsVpsWps(struct Machine *m, uint32_t rde) { MovdqaVdqWdq(m, rde); } static void MovapdVpdWpd(struct Machine *m, uint32_t rde) { MovdqaVdqWdq(m, rde); } static void MovapsWpsVps(struct Machine *m, uint32_t rde) { MovdqaWdqVdq(m, rde); } static void MovapdWpdVpd(struct Machine *m, uint32_t rde) { MovdqaWdqVdq(m, rde); } void OpMovWpsVps(struct Machine *m, uint32_t rde) { uint8_t *p, *r; switch (Rep(rde) | Osz(rde)) { case 0: MovupsWpsVps(m, rde); break; case 1: MovupdWpsVps(m, rde); break; case 2: MovsdWpsVps(m, rde); break; case 3: MovssWpsVps(m, rde); break; default: unreachable; } } void OpMov0f28(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { MovapsVpsWps(m, rde); } else { MovapdVpdWpd(m, rde); } } void OpMov0f6e(struct Machine *m, uint32_t rde) { if (Osz(rde)) { if (Rexw(rde)) { MovqVdqEqp(m, rde); } else { MovdVdqEd(m, rde); } } else { if (Rexw(rde)) { MovqPqEqp(m, rde); } else { MovdPqEd(m, rde); } } } void OpMov0f6f(struct Machine *m, uint32_t rde) { if (Osz(rde)) { MovdqaVdqWdq(m, rde); } else if (Rep(rde) == 3) { MovdquVdqWdq(m, rde); } else { MovqPqQq(m, rde); } } void OpMov0fE7(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { MovntqMqPq(m, rde); } else { MovntdqMdqVdq(m, rde); } } void OpMov0f7e(struct Machine *m, uint32_t rde) { if (Rep(rde) == 3) { MovqVqWq(m, rde); } else if (Osz(rde)) { if (Rexw(rde)) { MovqEqpVdq(m, rde); } else { MovdEdVdq(m, rde); } } else { if (Rexw(rde)) { MovqEqpPq(m, rde); } else { MovdEdPq(m, rde); } } } void OpMov0f7f(struct Machine *m, uint32_t rde) { if (Rep(rde) == 3) { MovdquWdqVdq(m, rde); } else if (Osz(rde)) { MovdqaWdqVdq(m, rde); } else { MovqQqPq(m, rde); } } void OpMov0f10(struct Machine *m, uint32_t rde) { uint8_t *p, *r; switch (Rep(rde) | Osz(rde)) { case 0: MovupsVpsWps(m, rde); break; case 1: MovupdVpsWps(m, rde); break; case 2: MovsdVpsWps(m, rde); break; case 3: MovssVpsWps(m, rde); break; default: unreachable; } } void OpMov0f29(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { MovapsWpsVps(m, rde); } else { MovapdWpdVpd(m, rde); } } void OpMov0f2b(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { MovntpsMpsVps(m, rde); } else { MovntpdMpdVpd(m, rde); } } void OpMov0f12(struct Machine *m, uint32_t rde) { switch (Rep(rde) | Osz(rde)) { case 0: if (IsModrmRegister(rde)) { MovhlpsVqUq(m, rde); } else { MovlpsVqMq(m, rde); } break; case 1: MovlpdVqMq(m, rde); break; case 2: MovddupVqWq(m, rde); break; case 3: MovsldupVqWq(m, rde); break; default: unreachable; } } void OpMov0f13(struct Machine *m, uint32_t rde) { if (Osz(rde)) { MovlpdMqVq(m, rde); } else { MovlpsMqVq(m, rde); } } void OpMov0f16(struct Machine *m, uint32_t rde) { switch (Rep(rde) | Osz(rde)) { case 0: if (IsModrmRegister(rde)) { MovlhpsVqUq(m, rde); } else { MovhpsVqMq(m, rde); } break; case 1: MovhpdVqMq(m, rde); break; case 3: MovshdupVqWq(m, rde); break; default: OpUd(m, rde); break; } } void OpMov0f17(struct Machine *m, uint32_t rde) { if (Osz(rde)) { MovhpdMqVq(m, rde); } else { MovhpsMqVq(m, rde); } } void OpMov0fD6(struct Machine *m, uint32_t rde) { if (Rep(rde) == 3) { Movq2dqVdqNq(m, rde); } else if (Rep(rde) == 2) { Movdq2qPqUq(m, rde); } else if (Osz(rde)) { MovqWqVq(m, rde); } else { OpUd(m, rde); } } void OpPmovmskbGdqpNqUdq(struct Machine *m, uint32_t rde) { Write64(RegRexrReg(m, rde), pmovmskb(XmmRexbRm(m, rde)) & (Osz(rde) ? 0xffff : 0xff)); } void OpMaskMovDiXmmRegXmmRm(struct Machine *m, uint32_t rde) { void *p[2]; uint64_t v; unsigned i, n; uint8_t *mem, b[16]; v = AddressDi(m, rde); n = Osz(rde) ? 16 : 8; mem = BeginStore(m, v, n, p, b); for (i = 0; i < n; ++i) { if (XmmRexbRm(m, rde)[i] & 0x80) { mem[i] = XmmRexrReg(m, rde)[i]; } } EndStore(m, v, n, p, b); }
14,060
519
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/address.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ADDRESS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ADDRESS_H_ #include "libc/assert.h" #include "third_party/xed/x86.h" #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ uint64_t AddressOb(struct Machine *, uint32_t); uint64_t AddressDi(struct Machine *, uint32_t); uint64_t AddressSi(struct Machine *, uint32_t); uint64_t DataSegment(struct Machine *, uint32_t, uint64_t); uint64_t AddSegment(struct Machine *, uint32_t, uint64_t, uint8_t[8]); uint8_t *GetSegment(struct Machine *, uint32_t, int) nosideeffect; forceinline uint64_t MaskAddress(uint32_t mode, uint64_t x) { if (mode != XED_MODE_LONG) { if (mode == XED_MODE_REAL) { x &= 0xffff; } else { x &= 0xffffffff; } } return x; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ADDRESS_H_ */
917
30
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/string.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_STRING_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_STRING_H_ #include "tool/build/lib/machine.h" #define STRING_CMPS 0 #define STRING_MOVS 1 #define STRING_STOS 2 #define STRING_LODS 3 #define STRING_SCAS 4 #define STRING_OUTS 5 #define STRING_INS 6 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpMovsb(struct Machine *, uint32_t); void OpStosb(struct Machine *, uint32_t); void OpMovs(struct Machine *, uint32_t); void OpCmps(struct Machine *, uint32_t); void OpStos(struct Machine *, uint32_t); void OpLods(struct Machine *, uint32_t); void OpScas(struct Machine *, uint32_t); void OpIns(struct Machine *, uint32_t); void OpOuts(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_STRING_H_ */
834
29
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pty.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/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/tpenc.h" #include "libc/log/check.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/thompike.h" #include "libc/str/unicode.h" #include "libc/sysv/errfuns.h" #include "libc/x/x.h" #include "tool/build/lib/pty.h" /** * @fileoverview Pseudoteletypewriter * * \t TAB * \a BELL * \177 BACKSPACE * \r CURSOR START * \b CURSOR LEFT OR CURSOR REWIND * \n CURSOR DOWN AND START IF OPOST * \f CURSOR DOWN AND START IF OPOST * \v CURSOR DOWN AND START OR \e[H\e[J * \eE CURSOR DOWN AND START * \eD CURSOR DOWN * \eM CURSOR UP * \ec FULL RESET * \e7 SAVE CURSOR POSITION * \e8 RESTORE CURSOR POSITION * \e(0 DEC SPECIAL GRAPHICS * \e(B USAS X3.4-1967 * \e#5 SINGLE WIDTH * \e#6 DOUBLE WIDTH * \e#8 SO MANY E * \eZ → \e/Z REPORT IDENTITY * \e[𝑛A CURSOR UP [CLAMPED] * \e[𝑛B CURSOR DOWN [CLAMPED] * \e[𝑛C CURSOR RIGHT [CLAMPED] * \e[𝑛D CURSOR LEFT [CLAMPED] * \e[𝑦;𝑥H SET CURSOR POSITION [CLAMPED] * \e[𝑥G SET CURSOR COLUMN [CLAMPED] * \e[𝑦d SET CURSOR ROW [CLAMPED] * \e[𝑛E CURSOR DOWN AND START [CLAMPED] * \e[𝑛F CURSOR UP AND START [CLAMPED] * \e[𝑛S SCROLL UP * \e[𝑛T SCROLL DOWN * \e[𝑛@ INSERT CELLS * \e[𝑛P DELETE CELLS * \e[𝑛L INSERT LINES * \e[𝑛M DELETE LINES * \e[J ERASE DISPLAY FORWARDS * \e[1J ERASE DISPLAY BACKWARDS * \e[2J ERASE DISPLAY * \e[K ERASE LINE FORWARD * \e[1K ERASE LINE BACKWARD * \e[2K ERASE LINE * \e[𝑛X ERASE CELLS * \e[0m RESET * \e[1m BOLD * \e[2m FAINT * \e[3m ITALIC * \e[4m UNDER * \e[5m BLINK * \e[7m INVERT * \e[8m CONCEAL * \e[9m STRIKE * \e[20m FRAKTUR * \e[21m DUNDER * \e[22m RESET BOLD & FAINT * \e[23m RESET ITALIC & FRAKTUR * \e[24m RESET UNDER & DUNDER * \e[25m RESET BLINK * \e[27m RESET INVERT * \e[28m RESET CONCEAL * \e[29m RESET STRIKE * \e[39m RESET FOREGROUND * \e[49m RESET BACKGROUND * \e[30m BLACK FOREGROUND * \e[31m RED FOREGROUND * \e[32m GREEN FOREGROUND * \e[33m YELLOW FOREGROUND * \e[34m BLUE FOREGROUND * \e[35m MAGENTA FOREGROUND * \e[36m CYAN FOREGROUND * \e[37m WHITE FOREGROUND * \e[40m BLACK BACKGROUND * \e[41m RED BACKGROUND * \e[42m GREEN BACKGROUND * \e[44m YELLOW BACKGROUND * \e[44m BLUE BACKGROUND * \e[45m MAGENTA BACKGROUND * \e[46m CYAN BACKGROUND * \e[47m WHITE BACKGROUND * \e[90m BRIGHT BLACK FOREGROUND * \e[91m BRIGHT RED FOREGROUND * \e[92m BRIGHT GREEN FOREGROUND * \e[93m BRIGHT YELLOW FOREGROUND * \e[94m BRIGHT BLUE FOREGROUND * \e[95m BRIGHT MAGENTA FOREGROUND * \e[96m BRIGHT CYAN FOREGROUND * \e[97m BRIGHT WHITE FOREGROUND * \e[100m BRIGHT BLACK BACKGROUND * \e[101m BRIGHT RED BACKGROUND * \e[102m BRIGHT GREEN BACKGROUND * \e[103m BRIGHT YELLOW BACKGROUND * \e[104m BRIGHT BLUE BACKGROUND * \e[105m BRIGHT MAGENTA BACKGROUND * \e[106m BRIGHT CYAN BACKGROUND * \e[107m BRIGHT WHITE BACKGROUND * \e[38;5;𝑥m XTERM256 FOREGROUND * \e[48;5;𝑥m XTERM256 BACKGROUND * \e[38;2;𝑟;𝑔;𝑏m RGB FOREGROUND * \e[48;2;𝑟;𝑔;𝑏m RGB BACKGROUND * \e[?25h SHOW CURSOR * \e[?25l HIDE CURSOR * \e[s SAVE CURSOR POSITION * \e[u RESTORE CURSOR POSITION * \e[?5h ... \e[?5l REVERSE VIDEO EPILEPSY * \e[0q RESET LEDS * \e[1q TURN ON FIRST LED * \e[2q TURN ON SECOND LED * \e[3q TURN ON THIRD LED * \e[4q TURN ON FOURTH LED * \e[c → \e[?1;0c REPORT DEVICE TYPE * \e[5n → \e[0n REPORT DEVICE STATUS * \e[6n → \e[𝑦;𝑥R REPORT CURSOR POSITION * \e7\e[9979;9979H\e[6n\e8 → \e[𝑦;𝑥R REPORT DISPLAY DIMENSIONS * * @see https://vt100.net/docs/vt220-rm/chapter4.html * @see https://invisible-island.net/xterm/ * @see ANSI X3.64-1979 * @see ISO/IEC 6429 * @see FIPS-86 * @see ECMA-48 */ struct Pty *NewPty(void) { struct Pty *pty; pty = xcalloc(1, sizeof(struct Pty)); PtyResize(pty, 25, 80); PtyFullReset(pty); PtyErase(pty, 0, pty->yn * pty->xn); return pty; } static void FreePtyPlanes(struct Pty *pty) { free(pty->wcs); free(pty->fgs); free(pty->bgs); free(pty->prs); } void FreePty(struct Pty *pty) { if (pty) { FreePtyPlanes(pty); free(pty); } } static wchar_t *GetXlatAscii(void) { unsigned i; static bool once; static wchar_t xlat[128]; if (!once) { for (i = 0; i < 128; ++i) { xlat[i] = i; } once = true; } return xlat; } static wchar_t *GetXlatLineDrawing(void) { unsigned i; static bool once; static wchar_t xlat[128]; if (!once) { for (i = 0; i < 128; ++i) { if (0x5F <= i && i <= 0x7E) { xlat[i] = u" ◆▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·"[i - 0x5F]; } else { xlat[i] = i; } } once = true; } return xlat; } static void XlatAlphabet(wchar_t xlat[128], int a, int b) { unsigned i; for (i = 0; i < 128; ++i) { if ('a' <= i && i <= 'z') { xlat[i] = i - 'a' + a; } else if ('A' <= i && i <= 'Z') { xlat[i] = i - 'A' + b; } else { xlat[i] = i; } } } static wchar_t *GetXlatItalic(void) { static bool once; static wchar_t xlat[128]; if (!once) { XlatAlphabet(xlat, L'𝑎', L'𝐴'); once = true; } return xlat; } static wchar_t *GetXlatBoldItalic(void) { static bool once; static wchar_t xlat[128]; if (!once) { XlatAlphabet(xlat, L'𝒂', L'𝑨'); once = true; } return xlat; } static wchar_t *GetXlatBoldFraktur(void) { static bool once; static wchar_t xlat[128]; if (!once) { XlatAlphabet(xlat, L'𝖆', L'𝕬'); once = true; } return xlat; } static wchar_t *GetXlatFraktur(void) { unsigned i; static bool once; static wchar_t xlat[128]; if (!once) { for (i = 0; i < ARRAYLEN(xlat); ++i) { if ('A' <= i && i <= 'Z') { xlat[i] = L"𝔄𝔅ℭ𝔇𝔈𝔉𝔊ℌℑ𝔍𝔎𝔏𝔐𝔑𝔒𝔓𝔔ℜ𝔖𝔗𝔘𝔙𝔚𝔛𝔜ℨ"[i - 'A']; } else if ('a' <= i && i <= 'z') { xlat[i] = i - 'a' + L'𝔞'; } else { xlat[i] = i; } } once = true; } return xlat; } static wchar_t *GetXlatDoubleWidth(void) { unsigned i; static bool once; static wchar_t xlat[128]; if (!once) { for (i = 0; i < ARRAYLEN(xlat); ++i) { if ('!' <= i && i <= '~') { xlat[i] = -(i - '!' + L'!'); } else { xlat[i] = i; } } once = true; } return xlat; } static wchar_t *GetXlatSgr(struct Pty *pty) { switch (!!(pty->pr & kPtyFraktur) << 2 | !!(pty->pr & kPtyItalic) << 1 | !!(pty->pr & kPtyBold) << 0) { case 0b100: case 0b110: return GetXlatFraktur(); case 0b101: case 0b111: return GetXlatBoldFraktur(); case 0b011: return GetXlatBoldItalic(); case 0b010: return GetXlatItalic(); default: return GetXlatAscii(); } } static void PtySetXlat(struct Pty *pty, wchar_t *xlat) { pty->xlat = xlat; pty->pr &= ~(kPtyItalic | kPtyFraktur); } static void PtySetCodepage(struct Pty *pty, char id) { unsigned i; switch (id) { default: case 'B': PtySetXlat(pty, GetXlatAscii()); break; case '0': PtySetXlat(pty, GetXlatLineDrawing()); break; } } void PtyErase(struct Pty *pty, long dst, long n) { DCHECK_LE(dst + n, pty->yn * pty->xn); wmemset((void *)(pty->wcs + dst), ' ', n); bzero((void *)(pty->prs + dst), n); } void PtyMemmove(struct Pty *pty, long dst, long src, long n) { DCHECK_LE(src + n, pty->yn * pty->xn); DCHECK_LE(dst + n, pty->yn * pty->xn); memmove(pty->wcs + dst, pty->wcs + src, n * 4); memmove(pty->fgs + dst, pty->fgs + src, n * 4); memmove(pty->bgs + dst, pty->bgs + src, n * 4); memmove(pty->prs + dst, pty->prs + src, n * 4); } void PtyFullReset(struct Pty *pty) { pty->y = 0; pty->x = 0; pty->pr = 0; pty->u8 = 0; pty->n8 = 0; pty->conf = 0; pty->save = 0; pty->state = 0; pty->esc.i = 0; pty->input.i = 0; pty->xlat = GetXlatAscii(); PtyErase(pty, 0, pty->yn * pty->xn); } void PtySetY(struct Pty *pty, int y) { pty->conf &= ~kPtyRedzone; pty->y = MAX(0, MIN(pty->yn - 1, y)); } void PtySetX(struct Pty *pty, int x) { pty->conf &= ~kPtyRedzone; pty->x = MAX(0, MIN(pty->xn - 1, x)); } void PtyResize(struct Pty *pty, int yn, int xn) { unsigned y, ym, xm, y0; uint32_t *wcs, *fgs, *bgs, *prs; if (xn < 80) xn = 80; if (yn < 25) yn = 25; if (xn == pty->xn && yn == pty->yn) return; wcs = xcalloc(yn * xn, 4); fgs = xcalloc(yn * xn, 4); bgs = xcalloc(yn * xn, 4); prs = xcalloc(yn * xn, 4); y0 = yn > pty->y + 1 ? 0 : pty->y + 1 - yn; ym = MIN(yn, pty->yn) + y0; xm = MIN(xn, pty->xn); for (y = y0; y < ym; ++y) { memcpy(wcs + y * xn, pty->wcs + y * pty->xn, xm * 4); memcpy(fgs + y * xn, pty->fgs + y * pty->xn, xm * 4); memcpy(bgs + y * xn, pty->bgs + y * pty->xn, xm * 4); memcpy(prs + y * xn, pty->prs + y * pty->xn, xm * 4); } FreePtyPlanes(pty); pty->wcs = wcs; pty->fgs = fgs; pty->bgs = bgs; pty->prs = prs; pty->yn = yn; pty->xn = xn; PtySetY(pty, pty->y); PtySetX(pty, pty->x); } static void PtyConcatInput(struct Pty *pty, const char *data, size_t n) { CONCAT(&pty->input.p, &pty->input.i, &pty->input.n, data, n); } static void PtyScroll(struct Pty *pty) { PtyMemmove(pty, 0, pty->xn, pty->xn * (pty->yn - 1)); PtyErase(pty, pty->xn * (pty->yn - 1), pty->xn); } static void PtyReverse(struct Pty *pty) { PtyMemmove(pty, pty->xn, 0, pty->xn * (pty->yn - 1)); PtyErase(pty, 0, pty->xn); } static void PtyIndex(struct Pty *pty) { if (pty->y < pty->yn - 1) { ++pty->y; } else { PtyScroll(pty); } } static void PtyReverseIndex(struct Pty *pty) { if (pty->y) { --pty->y; } else { PtyReverse(pty); } } static void PtyCarriageReturn(struct Pty *pty) { PtySetX(pty, 0); } static void PtyNewline(struct Pty *pty) { PtyIndex(pty); if (!(pty->conf & kPtyNoopost)) { PtyCarriageReturn(pty); } } static void PtyAdvance(struct Pty *pty) { DCHECK_EQ(pty->xn - 1, pty->x); DCHECK(pty->conf & kPtyRedzone); pty->conf &= ~kPtyRedzone; pty->x = 0; if (pty->y < pty->yn - 1) { ++pty->y; } else { PtyScroll(pty); } } static void PtyWriteGlyph(struct Pty *pty, wint_t wc, int w) { uint32_t i; if (w < 1) wc = ' ', w = 1; if ((pty->conf & kPtyRedzone) || pty->x + w > pty->xn) { PtyAdvance(pty); } i = pty->y * pty->xn + pty->x; pty->wcs[i] = wc; if ((pty->prs[i] = pty->pr) & (kPtyFg | kPtyBg)) { pty->fgs[i] = pty->fg; pty->bgs[i] = pty->bg; } if ((pty->x += w) >= pty->xn) { pty->x = pty->xn - 1; pty->conf |= kPtyRedzone; } } static void PtyWriteTab(struct Pty *pty) { unsigned x, x2; if (pty->conf & kPtyRedzone) { PtyAdvance(pty); } x2 = MIN(pty->xn, ROUNDUP(pty->x + 1, 8)); for (x = pty->x; x < x2; ++x) { pty->wcs[pty->y * pty->xn + x] = ' '; } if (x2 < pty->xn) { pty->x = x2; } else { pty->x = pty->xn - 1; pty->conf |= kPtyRedzone; } } static int PtyAtoi(const char *s, const char **e) { int i; for (i = 0; isdigit(*s); ++s) i *= 10, i += *s - '0'; if (e) *e = s; return i; } static int PtyGetMoveParam(struct Pty *pty) { int x = PtyAtoi(pty->esc.s, NULL); if (x < 1) x = 1; return x; } static void PtySetCursorPosition(struct Pty *pty) { int row, col; const char *s = pty->esc.s; row = max(1, PtyAtoi(s, &s)); if (*s == ';') ++s; col = max(1, PtyAtoi(s, &s)); PtySetY(pty, row - 1); PtySetX(pty, col - 1); } static void PtySetCursorRow(struct Pty *pty) { PtySetY(pty, PtyGetMoveParam(pty) - 1); } static void PtySetCursorColumn(struct Pty *pty) { PtySetX(pty, PtyGetMoveParam(pty) - 1); } static void PtyMoveCursor(struct Pty *pty, int dy, int dx) { int n = PtyGetMoveParam(pty); PtySetY(pty, pty->y + dy * n); PtySetX(pty, pty->x + dx * n); } static void PtyScrollUp(struct Pty *pty) { int n = PtyGetMoveParam(pty); while (n--) PtyScroll(pty); } static void PtyScrollDown(struct Pty *pty) { int n = PtyGetMoveParam(pty); while (n--) PtyReverse(pty); } static void PtySetCursorStatus(struct Pty *pty, bool status) { if (status) { pty->conf &= ~kPtyNocursor; } else { pty->conf |= kPtyNocursor; } } static void PtySetMode(struct Pty *pty, bool status) { const char *p = pty->esc.s; switch (*p++) { case '?': while (isdigit(*p)) { switch (PtyAtoi(p, &p)) { case 25: PtySetCursorStatus(pty, status); break; default: break; } if (*p == ';') { ++p; } } break; default: break; } } static void PtySaveCursorPosition(struct Pty *pty) { pty->save = (pty->y & 0x7FFF) | (pty->x & 0x7FFF) << 16; } static void PtyRestoreCursorPosition(struct Pty *pty) { PtySetY(pty, (pty->save & 0x00007FFF) >> 000); PtySetX(pty, (pty->save & 0x7FFF0000) >> 020); } static void PtyEraseDisplay(struct Pty *pty) { switch (PtyAtoi(pty->esc.s, NULL)) { case 0: PtyErase(pty, pty->y * pty->xn + pty->x, pty->yn * pty->xn - (pty->y * pty->xn + pty->x)); break; case 1: PtyErase(pty, 0, pty->y * pty->xn + pty->x); break; case 2: case 3: PtyErase(pty, 0, pty->yn * pty->xn); break; default: break; } } static void PtyEraseLine(struct Pty *pty) { switch (PtyAtoi(pty->esc.s, NULL)) { case 0: PtyErase(pty, pty->y * pty->xn + pty->x, pty->xn - pty->x); break; case 1: PtyErase(pty, pty->y * pty->xn, pty->x); break; case 2: PtyErase(pty, pty->y * pty->xn, pty->xn); break; default: break; } } static void PtyEraseCells(struct Pty *pty) { int i, n, x; i = pty->y * pty->xn + pty->x; n = pty->yn * pty->xn; x = min(max(PtyAtoi(pty->esc.s, NULL), 1), n - i); PtyErase(pty, i, x); } static int PtyArg1(struct Pty *pty) { return max(1, PtyAtoi(pty->esc.s, NULL)); } static void PtyInsertCells(struct Pty *pty) { int n = min(pty->xn - pty->x, PtyArg1(pty)); PtyMemmove(pty, pty->y * pty->xn + pty->x + n, pty->y * pty->xn + pty->x, pty->xn - (pty->x + n)); PtyErase(pty, pty->y * pty->xn + pty->x, n); } static void PtyInsertLines(struct Pty *pty) { int n = min(pty->yn - pty->y, PtyArg1(pty)); PtyMemmove(pty, (pty->y + n) * pty->xn, pty->y * pty->xn, (pty->yn - pty->y - n) * pty->xn); PtyErase(pty, pty->y * pty->xn, n * pty->xn); } static void PtyDeleteCells(struct Pty *pty) { int n = min(pty->xn - pty->x, PtyArg1(pty)); PtyMemmove(pty, pty->y * pty->xn + pty->x, pty->y * pty->xn + pty->x + n, pty->xn - (pty->x + n)); PtyErase(pty, pty->y * pty->xn + pty->x, n); } static void PtyDeleteLines(struct Pty *pty) { int n = min(pty->yn - pty->y, PtyArg1(pty)); PtyMemmove(pty, pty->y * pty->xn, (pty->y + n) * pty->xn, (pty->yn - pty->y - n) * pty->xn); PtyErase(pty, (pty->y + n) * pty->xn, n * pty->xn); } static void PtyReportDeviceStatus(struct Pty *pty) { static const char report[] = "\e[0n"; PtyWriteInput(pty, report, strlen(report)); } static void PtyReportPreferredVtType(struct Pty *pty) { static const char report[] = "\e[?1;0c"; PtyWriteInput(pty, report, strlen(report)); } static void PtyReportPreferredVtIdentity(struct Pty *pty) { static const char report[] = "\e/Z"; PtyWriteInput(pty, report, strlen(report)); } static void PtyBell(struct Pty *pty) { pty->conf |= kPtyBell; } static void PtyLed(struct Pty *pty) { switch (PtyAtoi(pty->esc.s, NULL)) { case 0: pty->conf &= ~kPtyLed1; pty->conf &= ~kPtyLed2; pty->conf &= ~kPtyLed3; pty->conf &= ~kPtyLed4; break; case 1: pty->conf |= kPtyLed1; break; case 2: pty->conf |= kPtyLed2; break; case 3: pty->conf |= kPtyLed3; break; case 4: pty->conf |= kPtyLed4; break; default: break; } } static void PtyReportCursorPosition(struct Pty *pty) { char *p; char buf[2 + 10 + 1 + 10 + 1]; p = buf; *p++ = '\e'; *p++ = '['; p = FormatInt32(p, (pty->y + 1) & 0x7fff); *p++ = ';'; p = FormatInt32(p, (pty->x + 1) & 0x7fff); *p++ = 'R'; PtyWriteInput(pty, buf, p - buf); } static void PtyCsiN(struct Pty *pty) { switch (PtyAtoi(pty->esc.s, NULL)) { case 5: PtyReportDeviceStatus(pty); break; case 6: PtyReportCursorPosition(pty); break; default: break; } } static void PtySelectGraphicsRendition(struct Pty *pty) { char *p, c; unsigned x; uint8_t code[4]; enum { kSgr, kSgrFg = 010, kSgrFgTrue = 012, kSgrFgXterm = 015, kSgrBg = 020, kSgrBgTrue = 022, kSgrBgXterm = 025, } t; x = 0; t = kSgr; p = pty->esc.s; bzero(code, sizeof(code)); for (;;) { c = *p++; switch (c) { case '\0': return; case '0' ... '9': x *= 10; x += c - '0'; break; case ';': case 'm': code[code[3]] = x; x = 0; switch (t) { case kSgr: switch (code[0]) { case 38: t = kSgrFg; break; case 48: t = kSgrBg; break; case 0: pty->pr = 0; pty->xlat = GetXlatSgr(pty); break; case 1: pty->pr |= kPtyBold; pty->xlat = GetXlatSgr(pty); break; case 2: pty->pr |= kPtyFaint; break; case 3: pty->pr |= kPtyItalic; pty->xlat = GetXlatSgr(pty); break; case 4: pty->pr |= kPtyUnder; break; case 5: pty->pr |= kPtyBlink; break; case 7: pty->pr |= kPtyFlip; break; case 8: pty->pr |= kPtyConceal; break; case 9: pty->pr |= kPtyStrike; break; case 20: pty->pr |= kPtyFraktur; pty->xlat = GetXlatSgr(pty); break; case 21: pty->pr |= kPtyUnder | kPtyDunder; break; case 22: pty->pr &= ~(kPtyFaint | kPtyBold); pty->xlat = GetXlatSgr(pty); break; case 23: pty->pr &= ~kPtyItalic; pty->xlat = GetXlatSgr(pty); break; case 24: pty->pr &= ~(kPtyUnder | kPtyDunder); break; case 25: pty->pr &= ~kPtyBlink; break; case 27: pty->pr &= ~kPtyFlip; break; case 28: pty->pr &= ~kPtyConceal; break; case 29: pty->pr &= ~kPtyStrike; break; case 39: pty->pr &= ~kPtyFg; break; case 49: pty->pr &= ~kPtyBg; break; case 90 ... 97: code[0] -= 90 - 30; code[0] += 8; /* fallthrough */ case 30 ... 37: pty->fg = code[0] - 30; pty->pr |= kPtyFg; pty->pr &= ~kPtyTrue; break; case 100 ... 107: code[0] -= 100 - 40; code[0] += 8; /* fallthrough */ case 40 ... 47: pty->bg = code[0] - 40; pty->pr |= kPtyBg; pty->pr &= ~kPtyTrue; break; default: break; } break; case kSgrFg: case kSgrBg: switch (code[0]) { case 2: case 5: t += code[0]; break; default: t = kSgr; break; } break; case kSgrFgTrue: if (++code[3] == 3) { code[3] = 0; t = kSgr; pty->fg = READ32LE(code); pty->pr |= kPtyFg; pty->pr |= kPtyTrue; } break; case kSgrBgTrue: if (++code[3] == 3) { code[3] = 0; t = kSgr; pty->bg = READ32LE(code); pty->pr |= kPtyBg; pty->pr |= kPtyTrue; } break; case kSgrFgXterm: t = kSgr; pty->fg = code[0]; pty->pr |= kPtyFg; pty->pr &= ~kPtyTrue; break; case kSgrBgXterm: t = kSgr; pty->bg = code[0]; pty->pr |= kPtyBg; pty->pr &= ~kPtyTrue; break; default: abort(); } break; default: break; } } } static void PtyCsi(struct Pty *pty) { switch (pty->esc.s[pty->esc.i - 1]) { case 'f': case 'H': PtySetCursorPosition(pty); break; case 'G': PtySetCursorColumn(pty); break; case 'd': PtySetCursorRow(pty); break; case 'F': pty->x = 0; /* fallthrough */ case 'A': PtyMoveCursor(pty, -1, +0); break; case 'E': pty->x = 0; /* fallthrough */ case 'B': PtyMoveCursor(pty, +1, +0); break; case 'C': PtyMoveCursor(pty, +0, +1); break; case 'D': PtyMoveCursor(pty, +0, -1); break; case 'S': PtyScrollUp(pty); break; case 'T': PtyScrollDown(pty); break; case '@': PtyInsertCells(pty); break; case 'P': PtyDeleteCells(pty); break; case 'L': PtyInsertLines(pty); break; case 'M': PtyDeleteLines(pty); break; case 'J': PtyEraseDisplay(pty); break; case 'K': PtyEraseLine(pty); break; case 'X': PtyEraseCells(pty); break; case 's': PtySaveCursorPosition(pty); break; case 'u': PtyRestoreCursorPosition(pty); break; case 'n': PtyCsiN(pty); break; case 'm': PtySelectGraphicsRendition(pty); break; case 'h': PtySetMode(pty, true); break; case 'l': PtySetMode(pty, false); break; case 'c': PtyReportPreferredVtType(pty); break; case 'q': PtyLed(pty); break; default: break; } } static void PtyScreenAlignmentDisplay(struct Pty *pty) { wmemset((void *)pty->wcs, 'E', pty->yn * pty->xn); } static void PtyEscHash(struct Pty *pty) { switch (pty->esc.s[1]) { case '5': PtySetXlat(pty, GetXlatAscii()); break; case '6': PtySetXlat(pty, GetXlatDoubleWidth()); break; case '8': PtyScreenAlignmentDisplay(pty); break; default: break; } } static void PtyEsc(struct Pty *pty) { switch (pty->esc.s[0]) { case 'c': PtyFullReset(pty); break; case '7': PtySaveCursorPosition(pty); break; case '8': PtyRestoreCursorPosition(pty); break; case 'E': pty->x = 0; case 'D': PtyIndex(pty); break; case 'M': PtyReverseIndex(pty); break; case 'Z': PtyReportPreferredVtIdentity(pty); break; case '(': PtySetCodepage(pty, pty->esc.s[1]); break; case '#': PtyEscHash(pty); break; default: break; } } static void PtyCntrl(struct Pty *pty, int c01) { switch (c01) { case '\a': PtyBell(pty); break; case 0x85: case '\f': case '\v': case '\n': PtyNewline(pty); break; case '\r': PtyCarriageReturn(pty); break; case '\e': pty->state = kPtyEsc; pty->esc.i = 0; break; case '\t': PtyWriteTab(pty); break; case 0x7F: case '\b': pty->x = MAX(0, pty->x - 1); break; case 0x84: PtyIndex(pty); break; case 0x8D: PtyReverseIndex(pty); break; case 0x9B: pty->state = kPtyCsi; break; default: break; } } static void PtyEscAppend(struct Pty *pty, char c) { pty->esc.i = MIN(pty->esc.i + 1, ARRAYLEN(pty->esc.s) - 1); pty->esc.s[pty->esc.i - 1] = c; pty->esc.s[pty->esc.i - 0] = 0; } ssize_t PtyWrite(struct Pty *pty, const void *data, size_t n) { int i; wchar_t wc; const uint8_t *p; for (p = data, i = 0; i < n; ++i) { switch (pty->state) { case kPtyAscii: if (0x00 <= p[i] && p[i] <= 0x7F) { if (0x20 <= p[i] && p[i] <= 0x7E) { if ((wc = pty->xlat[p[i]]) >= 0) { PtyWriteGlyph(pty, wc, 1); } else { PtyWriteGlyph(pty, -wc, 2); } } else { PtyCntrl(pty, p[i]); } } else if (!ThomPikeCont(p[i])) { pty->state = kPtyUtf8; pty->u8 = ThomPikeByte(p[i]); pty->n8 = ThomPikeLen(p[i]) - 1; } break; case kPtyUtf8: if (ThomPikeCont(p[i])) { pty->u8 = ThomPikeMerge(pty->u8, p[i]); if (--pty->n8) break; } wc = pty->u8; if ((0x00 <= wc && wc <= 0x1F) || // (0x7F <= wc && wc <= 0x9F)) { PtyCntrl(pty, wc); } else { PtyWriteGlyph(pty, wc, wcwidth(wc)); } pty->state = kPtyAscii; pty->u8 = 0; --i; break; case kPtyEsc: if (p[i] == '[') { pty->state = kPtyCsi; } else if (0x30 <= p[i] && p[i] <= 0x7E) { PtyEscAppend(pty, p[i]); PtyEsc(pty); pty->state = kPtyAscii; } else if (0x20 <= p[i] && p[i] <= 0x2F) { PtyEscAppend(pty, p[i]); } else { pty->state = kPtyAscii; } break; case kPtyCsi: PtyEscAppend(pty, p[i]); switch (p[i]) { case ':': case ';': case '<': case '=': case '>': case '?': case '0' ... '9': break; case '`': case '~': case '^': case '@': case '[': case ']': case '{': case '}': case '_': case '|': case '\\': case 'A' ... 'Z': case 'a' ... 'z': PtyCsi(pty); pty->state = kPtyAscii; break; default: pty->state = kPtyAscii; continue; } break; default: unreachable; } } return n; } ssize_t PtyWriteInput(struct Pty *pty, const void *data, size_t n) { int c; bool cr; char *p; const char *q; size_t i, j, m; q = data; p = pty->input.p; i = pty->input.i; m = pty->input.n; if (i + n * 2 + 1 > m) { m = MAX(m, 8); do m += m >> 1; while (i + n * 2 + 1 > m); if (!(p = realloc(p, m))) { return -1; } pty->input.p = p; pty->input.n = m; } cr = i && p[i - 1] == '\r'; for (j = 0; j < n; ++j) { c = q[j] & 255; if (c == '\r') { cr = true; } else if (cr) { if (c != '\n') { p[i++] = '\n'; } cr = false; } p[i++] = c; } if (cr) { p[i++] = '\n'; } if (!(pty->conf & kPtyNoecho)) { PtyWrite(pty, p + pty->input.i, i - pty->input.i); } pty->input.i = i; return n; } ssize_t PtyRead(struct Pty *pty, void *buf, size_t size) { char *p; size_t n; n = MIN(size, pty->input.i); if (!(pty->conf & kPtyNocanon)) { if ((p = memchr(pty->input.p, '\n', n))) { n = MIN(n, pty->input.p - p + 1); } else { n = 0; } } memcpy(buf, pty->input.p, n); memcpy(pty->input.p, pty->input.p + n, pty->input.i - n); pty->input.i -= n; return n; } static char *PtyEncodeRgb(char *p, int rgb) { *p++ = '2'; *p++ = ';'; p = FormatUint32(p, (rgb & 0x0000ff) >> 000); *p++ = ';'; p = FormatUint32(p, (rgb & 0x00ff00) >> 010); *p++ = ';'; p = FormatUint32(p, (rgb & 0xff0000) >> 020); return p; } static char *PtyEncodeXterm256(char *p, int xt) { *p++ = '5'; *p++ = ';'; p = FormatUint32(p, xt); return p; } char *PtyEncodeStyle(char *p, uint32_t xr, uint32_t pr, uint32_t fg, uint32_t bg) { *p++ = '\e'; *p++ = '['; if (pr & (kPtyBold | kPtyFaint | kPtyFlip | kPtyUnder | kPtyDunder | kPtyBlink | kPtyStrike | kPtyFg | kPtyBg)) { if (xr & (kPtyBold | kPtyFaint)) { if ((xr & (kPtyBold | kPtyFaint)) ^ (pr & (kPtyBold | kPtyFaint))) { *p++ = '2'; *p++ = '2'; *p++ = ';'; } if (pr & kPtyBold) { *p++ = '1'; *p++ = ';'; } if (pr & kPtyFaint) { *p++ = '2'; *p++ = ';'; } } if (xr & (kPtyUnder | kPtyDunder)) { if ((xr & (kPtyUnder | kPtyDunder)) ^ (pr & (kPtyUnder | kPtyDunder))) { *p++ = '2'; *p++ = '4'; *p++ = ';'; } if (pr & kPtyUnder) { *p++ = '4'; *p++ = ';'; } if (pr & kPtyDunder) { *p++ = '2'; *p++ = '1'; *p++ = ';'; } } if (xr & (kPtyFlip | kPtyBlink | kPtyStrike)) { if (xr & kPtyFlip) { if (!(pr & kPtyFlip)) *p++ = '2'; *p++ = '7'; *p++ = ';'; } if (xr & kPtyBlink) { if (!(pr & kPtyBlink)) *p++ = '2'; *p++ = '5'; *p++ = ';'; } if (xr & kPtyStrike) { if (!(pr & kPtyStrike)) *p++ = '2'; *p++ = '9'; *p++ = ';'; } } if (xr & (kPtyFg | kPtyTrue)) { *p++ = '3'; if (pr & kPtyFg) { *p++ = '8'; *p++ = ';'; if (pr & kPtyTrue) { p = PtyEncodeRgb(p, fg); } else { p = PtyEncodeXterm256(p, fg); } } else { *p++ = '9'; } *p++ = ';'; } if (xr & (kPtyBg | kPtyTrue)) { *p++ = '4'; if (pr & kPtyBg) { *p++ = '8'; *p++ = ';'; if (pr & kPtyTrue) { p = PtyEncodeRgb(p, bg); } else { p = PtyEncodeXterm256(p, bg); } } else { *p++ = '9'; } *p++ = ';'; } DCHECK_EQ(';', p[-1]); p[-1] = 'm'; } else { *p++ = '0'; *p++ = 'm'; } return p; } int PtyAppendLine(struct Pty *pty, struct Buffer *buf, unsigned y) { uint64_t u; char *p, *pb; uint32_t i, j, n, w, wc, np, xp, pr, fg, bg, ci; if (y >= pty->yn) return einval(); n = buf->i + pty->xn * 60; /* torture character length */ if (n > buf->n) { if (!(p = realloc(buf->p, n))) return -1; buf->p = p; buf->n = n; } i = y * pty->xn; j = (y + 1) * pty->xn; pb = buf->p + buf->i; ci = !(pty->conf & kPtyNocursor) && y == pty->y ? i + pty->x : -1; for (pr = 0; i < j; i += w) { np = pty->prs[i]; if (!(np & kPtyConceal)) { wc = pty->wcs[i]; DCHECK(!(0x00 <= wc && wc <= 0x1F)); DCHECK(!(0x7F <= wc && wc <= 0x9F)); if (0x20 <= wc && wc <= 0x7E) { u = wc; w = 1; } else { u = _tpenc(wc); w = max(1, wcwidth(wc)); } } else { u = ' '; w = 1; } if (i == ci) { if (u != ' ') { np ^= kPtyFlip; } else { u = _tpenc(u'▂'); if (pty->conf & kPtyBlinkcursor) { np |= kPtyBlink; } } } fg = bg = -1; xp = pr ^ np; if (np & (kPtyFg | kPtyBg)) { if (np & kPtyFg) { if (pty->fgs[i] != fg) xp |= kPtyFg; fg = pty->fgs[i]; } if (np & kPtyBg) { if (pty->bgs[i] != bg) xp |= kPtyBg; bg = pty->bgs[i]; } } p = pb; if (xp) { pr = np; p = PtyEncodeStyle(p, xp, pr, fg, bg); } do { *p++ = u & 0xFF; u >>= 8; } while (u); DCHECK_LE(p - pb, 60); pb = p; } DCHECK_LE(pb - buf->p, buf->n); buf->i = pb - buf->p; return 0; }
37,686
1,408
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/persist.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PERSIST_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PERSIST_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct ObjectArrayParam { size_t len; size_t size; void *pp; }; struct ObjectParam { size_t size; void *p; uint32_t *magic; int32_t *abi; struct ObjectArrayParam * arrays; }; void PersistObject(const char *, size_t, const struct ObjectParam *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PERSIST_H_ */
538
25
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/xlat.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_XLAT_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_XLAT_H_ #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/sock/struct/sockaddr.h" #include "tool/build/lib/bits.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int UnXlatSicode(int, int); int UnXlatSignal(int); int XlatAccess(int); int XlatAdvice(int); int XlatAtf(int); int XlatClock(int); int XlatErrno(int); int XlatFcntlArg(int); int XlatFcntlCmd(int); int XlatLock(int); int XlatMapFlags(int); int XlatMsyncFlags(int); int XlatOpenFlags(int); int XlatOpenMode(int); int XlatRusage(int); int XlatSig(int); int XlatSignal(int); int XlatSocketFamily(int); int XlatSocketFlags(int); int XlatSocketLevel(int); int XlatSocketOptname(int, int); int XlatSocketProtocol(int); int XlatSocketType(int); int XlatWait(int); void XlatSockaddrToHost(struct sockaddr_in *, const struct sockaddr_in_bits *); void XlatSockaddrToLinux(struct sockaddr_in_bits *, const struct sockaddr_in *); void XlatStatToLinux(struct stat_bits *, const struct stat *); void XlatRusageToLinux(struct rusage_bits *, const struct rusage *); void XlatItimervalToLinux(struct itimerval_bits *, const struct itimerval *); void XlatLinuxToItimerval(struct itimerval *, const struct itimerval_bits *); void XlatLinuxToTermios(struct termios *, const struct termios_bits *); void XlatTermiosToLinux(struct termios_bits *, const struct termios *); void XlatWinsizeToLinux(struct winsize_bits *, const struct winsize *); void XlatSigsetToLinux(uint8_t[8], const sigset_t *); void XlatLinuxToSigset(sigset_t *, const uint8_t[8]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_XLAT_H_ */
1,899
54
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/bcd.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_BCD_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_BCD_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpDas(struct Machine *, uint32_t); void OpAaa(struct Machine *, uint32_t); void OpAas(struct Machine *, uint32_t); void OpAam(struct Machine *, uint32_t); void OpAad(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_BCD_H_ */
499
16
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/machine.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 "tool/build/lib/machine.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "tool/build/lib/abp.h" #include "tool/build/lib/address.h" #include "tool/build/lib/alu.h" #include "tool/build/lib/bcd.h" #include "tool/build/lib/bitscan.h" #include "tool/build/lib/case.h" #include "tool/build/lib/clmul.h" #include "tool/build/lib/cpuid.h" #include "tool/build/lib/cvt.h" #include "tool/build/lib/divmul.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/fpu.h" #include "tool/build/lib/ioports.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/op101.h" #include "tool/build/lib/sse.h" #include "tool/build/lib/ssefloat.h" #include "tool/build/lib/ssemov.h" #include "tool/build/lib/stack.h" #include "tool/build/lib/stats.h" #include "tool/build/lib/string.h" #include "tool/build/lib/syscall.h" #include "tool/build/lib/throw.h" #include "tool/build/lib/time.h" #define OpLfence OpNoop #define OpMfence OpNoop #define OpSfence OpNoop #define OpClflush OpNoop #define OpHintNopEv OpNoop typedef void (*nexgen32e_f)(struct Machine *, uint32_t); static uint64_t ReadMemory(uint32_t rde, uint8_t p[8]) { if (Rexw(rde)) { return Read64(p); } else if (!Osz(rde)) { return Read32(p); } else { return Read16(p); } } static int64_t ReadMemorySigned(uint32_t rde, uint8_t p[8]) { if (Rexw(rde)) { return (int64_t)Read64(p); } else if (!Osz(rde)) { return (int32_t)Read32(p); } else { return (int16_t)Read16(p); } } static void WriteRegister(uint32_t rde, uint8_t p[8], uint64_t x) { if (Rexw(rde)) { Write64(p, x); } else if (!Osz(rde)) { Write64(p, x & 0xffffffff); } else { Write16(p, x); } } static void WriteMemory(uint32_t rde, uint8_t p[8], uint64_t x) { if (Rexw(rde)) { Write64(p, x); } else if (!Osz(rde)) { Write32(p, x); } else { Write16(p, x); } } static void WriteRegisterOrMemory(uint32_t rde, uint8_t p[8], uint64_t x) { if (IsModrmRegister(rde)) { WriteRegister(rde, p, x); } else { WriteMemory(rde, p, x); } } static bool IsParity(struct Machine *m) { return GetFlag(m->flags, FLAGS_PF); } static bool IsBelowOrEqual(struct Machine *m) { return GetFlag(m->flags, FLAGS_CF) | GetFlag(m->flags, FLAGS_ZF); } static bool IsAbove(struct Machine *m) { return !GetFlag(m->flags, FLAGS_CF) && !GetFlag(m->flags, FLAGS_ZF); } static bool IsLess(struct Machine *m) { return GetFlag(m->flags, FLAGS_SF) != GetFlag(m->flags, FLAGS_OF); } static bool IsGreaterOrEqual(struct Machine *m) { return GetFlag(m->flags, FLAGS_SF) == GetFlag(m->flags, FLAGS_OF); } static bool IsLessOrEqual(struct Machine *m) { return GetFlag(m->flags, FLAGS_ZF) | (GetFlag(m->flags, FLAGS_SF) != GetFlag(m->flags, FLAGS_OF)); } static bool IsGreater(struct Machine *m) { return !GetFlag(m->flags, FLAGS_ZF) & (GetFlag(m->flags, FLAGS_SF) == GetFlag(m->flags, FLAGS_OF)); } static void OpNoop(struct Machine *m, uint32_t rde) { } static void OpCmc(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_CF, !GetFlag(m->flags, FLAGS_CF)); } static void OpClc(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_CF, false); } static void OpStc(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_CF, true); } static void OpCli(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_IF, false); } static void OpSti(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_IF, true); } static void OpCld(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_DF, false); } static void OpStd(struct Machine *m, uint32_t rde) { m->flags = SetFlag(m->flags, FLAGS_DF, true); } static void OpPushf(struct Machine *m, uint32_t rde) { Push(m, rde, ExportFlags(m->flags) & 0xFCFFFF); } static void OpPopf(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { ImportFlags(m, Pop(m, rde, 0)); } else { ImportFlags(m, (m->flags & ~0xffff) | Pop(m, rde, 0)); } } static void OpLahf(struct Machine *m, uint32_t rde) { Write8(m->ax + 1, ExportFlags(m->flags)); } static void OpSahf(struct Machine *m, uint32_t rde) { ImportFlags(m, (m->flags & ~0xff) | m->ax[1]); } static void OpLeaGvqpM(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexrReg(m, rde), LoadEffectiveAddress(m, rde).addr); } static relegated void OpPushSeg(struct Machine *m, uint32_t rde) { uint8_t seg = (m->xedd->op.opcode & 070) >> 3; Push(m, rde, Read64(GetSegment(m, rde, seg)) >> 4); } static relegated void OpPopSeg(struct Machine *m, uint32_t rde) { uint8_t seg = (m->xedd->op.opcode & 070) >> 3; Write64(GetSegment(m, rde, seg), Pop(m, rde, 0) << 4); } static relegated void OpMovEvqpSw(struct Machine *m, uint32_t rde) { WriteRegisterOrMemory(rde, GetModrmRegisterWordPointerWriteOszRexw(m, rde), Read64(GetSegment(m, rde, ModrmReg(rde))) >> 4); } static relegated int GetDescriptor(struct Machine *m, int selector, uint64_t *out_descriptor) { uint8_t buf[8]; DCHECK(m->gdt_base + m->gdt_limit <= m->real.n); selector &= -8; if (8 <= selector && selector + 8 <= m->gdt_limit) { SetReadAddr(m, m->gdt_base + selector, 8); *out_descriptor = Read64(m->real.p + m->gdt_base + selector); return 0; } else { return -1; } } static uint64_t GetDescriptorBase(uint64_t d) { return (d & 0xff00000000000000) >> 32 | (d & 0x000000ffffff0000) >> 16; } static uint64_t GetDescriptorLimit(uint64_t d) { return (d & 0x000f000000000000) >> 32 | d & 0xffff; } static int GetDescriptorMode(uint64_t d) { uint8_t kMode[] = { XED_MACHINE_MODE_REAL, XED_MACHINE_MODE_LONG_64, XED_MACHINE_MODE_LEGACY_32, XED_MACHINE_MODE_LONG_64, }; return kMode[(d & 0x0060000000000000) >> 53]; } static bool IsProtectedMode(struct Machine *m) { return m->cr0 & 1; } static relegated void OpMovSwEvqp(struct Machine *m, uint32_t rde) { uint64_t x, d; x = ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)); if (!IsProtectedMode(m)) { x <<= 4; } else if (GetDescriptor(m, x, &d) != -1) { x = GetDescriptorBase(d); } else { ThrowProtectionFault(m); } Write64(GetSegment(m, rde, ModrmReg(rde)), x); } static void OpLsl(struct Machine *m, uint32_t rde) { uint64_t descriptor; if (GetDescriptor(m, Read16(GetModrmRegisterWordPointerRead2(m, rde)), &descriptor) != -1) { WriteRegister(rde, RegRexrReg(m, rde), GetDescriptorLimit(descriptor)); SetFlag(m->flags, FLAGS_ZF, true); } else { SetFlag(m->flags, FLAGS_ZF, false); } } static void ChangeMachineMode(struct Machine *m, int mode) { if (mode == m->mode) return; ResetInstructionCache(m); m->mode = mode; } static void OpJmpf(struct Machine *m, uint32_t rde) { uint64_t descriptor; if (!IsProtectedMode(m)) { Write64(m->cs, m->xedd->op.uimm0 << 4); m->ip = m->xedd->op.disp; } else if (GetDescriptor(m, m->xedd->op.uimm0, &descriptor) != -1) { Write64(m->cs, GetDescriptorBase(descriptor)); m->ip = m->xedd->op.disp; ChangeMachineMode(m, GetDescriptorMode(descriptor)); } else { ThrowProtectionFault(m); } if (m->onlongbranch) { m->onlongbranch(m); } } static void OpInto(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_OF)) { HaltMachine(m, kMachineOverflow); } } static relegated void OpXlatAlBbb(struct Machine *m, uint32_t rde) { uint64_t v; v = MaskAddress(Eamode(rde), Read64(m->bx) + Read8(m->ax)); v = DataSegment(m, rde, v); SetReadAddr(m, v, 1); Write8(m->ax, Read8(ResolveAddress(m, v))); } static void WriteEaxAx(struct Machine *m, uint32_t rde, uint32_t x) { if (!Osz(rde)) { Write64(m->ax, x); } else { Write16(m->ax, x); } } static uint32_t ReadEaxAx(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { return Read32(m->ax); } else { return Read16(m->ax); } } static void OpInAlImm(struct Machine *m, uint32_t rde) { Write8(m->ax, OpIn(m, m->xedd->op.uimm0)); } static void OpInAxImm(struct Machine *m, uint32_t rde) { WriteEaxAx(m, rde, OpIn(m, m->xedd->op.uimm0)); } static void OpInAlDx(struct Machine *m, uint32_t rde) { Write8(m->ax, OpIn(m, Read16(m->dx))); } static void OpInAxDx(struct Machine *m, uint32_t rde) { WriteEaxAx(m, rde, OpIn(m, Read16(m->dx))); } static void OpOutImmAl(struct Machine *m, uint32_t rde) { OpOut(m, m->xedd->op.uimm0, Read8(m->ax)); } static void OpOutImmAx(struct Machine *m, uint32_t rde) { OpOut(m, m->xedd->op.uimm0, ReadEaxAx(m, rde)); } static void OpOutDxAl(struct Machine *m, uint32_t rde) { OpOut(m, Read16(m->dx), Read8(m->ax)); } static void OpOutDxAx(struct Machine *m, uint32_t rde) { OpOut(m, Read16(m->dx), ReadEaxAx(m, rde)); } static void AluEb(struct Machine *m, uint32_t rde, aluop_f op) { uint8_t *p; p = GetModrmRegisterBytePointerWrite(m, rde); Write8(p, op(Read8(p), 0, &m->flags)); } static void AluEvqp(struct Machine *m, uint32_t rde, aluop_f ops[4]) { uint8_t *p; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); WriteRegisterOrMemory(rde, p, ops[RegLog2(rde)](ReadMemory(rde, p), 0, &m->flags)); } static void OpXchgZvqp(struct Machine *m, uint32_t rde) { uint64_t x, y; x = Read64(m->ax); y = Read64(RegRexbSrm(m, rde)); WriteRegister(rde, m->ax, y); WriteRegister(rde, RegRexbSrm(m, rde), x); } static void OpXchgGbEb(struct Machine *m, uint32_t rde) { uint8_t *p; uint8_t x, y; p = GetModrmRegisterBytePointerWrite(m, rde); x = Read8(ByteRexrReg(m, rde)); y = Read8(p); Write8(ByteRexrReg(m, rde), y); Write8(p, x); } static void OpXchgGvqpEvqp(struct Machine *m, uint32_t rde) { uint8_t *p; uint64_t x, y; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); x = ReadMemory(rde, RegRexrReg(m, rde)); y = ReadMemory(rde, p); WriteRegister(rde, RegRexrReg(m, rde), y); WriteRegisterOrMemory(rde, p, x); } static void OpCmpxchgEbAlGb(struct Machine *m, uint32_t rde) { uint8_t *p; uint8_t x, y, z; p = GetModrmRegisterBytePointerWrite(m, rde); x = Read8(m->ax); y = Read8(p); z = Read8(ByteRexrReg(m, rde)); Sub8(x, y, &m->flags); if (GetFlag(m->flags, FLAGS_ZF)) { Write8(p, z); } else { Write8(m->ax, y); } } static void OpCmpxchgEvqpRaxGvqp(struct Machine *m, uint32_t rde) { uint8_t *p; uint64_t x, y, z; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); x = ReadMemory(rde, m->ax); y = ReadMemory(rde, p); z = ReadMemory(rde, RegRexrReg(m, rde)); kAlu[ALU_SUB][RegLog2(rde)](x, y, &m->flags); if (GetFlag(m->flags, FLAGS_ZF)) { WriteRegisterOrMemory(rde, p, z); } else { WriteRegister(rde, m->ax, y); } } static void OpCmpxchg8b(struct Machine *m, uint32_t rde) { uint8_t *p; uint32_t d, a; p = GetModrmRegisterXmmPointerRead8(m, rde); a = Read32(p + 0); d = Read32(p + 4); if (a == Read32(m->ax) && d == Read32(m->dx)) { SetFlag(m->flags, FLAGS_ZF, true); memcpy(p + 0, m->bx, 4); memcpy(p + 4, m->cx, 4); } else { SetFlag(m->flags, FLAGS_ZF, false); Write32(m->ax, a); Write32(m->dx, d); } } static void OpCmpxchg16b(struct Machine *m, uint32_t rde) { uint8_t *p; uint64_t d, a; p = GetModrmRegisterXmmPointerRead16(m, rde); a = Read64(p + 0); d = Read64(p + 8); if (a == Read64(m->ax) && d == Read64(m->dx)) { SetFlag(m->flags, FLAGS_ZF, true); memcpy(p + 0, m->bx, 8); memcpy(p + 8, m->cx, 8); } else { SetFlag(m->flags, FLAGS_ZF, false); Write64(m->ax, a); Write64(m->dx, d); } } static void OpRdrand(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexbRm(m, rde), rdrand()); m->flags = SetFlag(m->flags, FLAGS_CF, true); } static void OpRdseed(struct Machine *m, uint32_t rde) { OpRdrand(m, rde); } static void Op1c7(struct Machine *m, uint32_t rde) { bool ismem; ismem = !IsModrmRegister(rde); switch (ModrmReg(rde)) { case 1: if (ismem) { if (Rexw(rde)) { OpCmpxchg16b(m, rde); } else { OpCmpxchg8b(m, rde); } } else { OpUd(m, rde); } break; case 6: if (!ismem) { OpRdrand(m, rde); } else { OpUd(m, rde); } break; case 7: if (!ismem) { if (Rep(rde) == 3) { OpRdpid(m, rde); } else { OpRdseed(m, rde); } } else { OpUd(m, rde); } break; default: OpUd(m, rde); } } static void OpXaddEbGb(struct Machine *m, uint32_t rde) { uint8_t *p; uint8_t x, y, z; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); x = Read8(p); y = Read8(RegRexrReg(m, rde)); z = Add8(x, y, &m->flags); Write8(p, z); Write8(RegRexrReg(m, rde), x); } static void OpXaddEvqpGvqp(struct Machine *m, uint32_t rde) { uint8_t *p; uint64_t x, y, z; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); x = ReadMemory(rde, p); y = ReadMemory(rde, RegRexrReg(m, rde)); z = kAlu[ALU_ADD][RegLog2(rde)](x, y, &m->flags); WriteRegisterOrMemory(rde, p, z); WriteRegister(rde, RegRexrReg(m, rde), x); } static uint64_t Bts(uint64_t x, uint64_t y) { return x | y; } static uint64_t Btr(uint64_t x, uint64_t y) { return x & ~y; } static uint64_t Btc(uint64_t x, uint64_t y) { return (x & ~y) | (~x & y); } static void OpBit(struct Machine *m, uint32_t rde) { int op; uint8_t *p; unsigned bit; int64_t disp; uint64_t v, x, y, z; uint8_t w, W[2][2] = {{2, 3}, {1, 3}}; w = W[Osz(rde)][Rexw(rde)]; if (m->xedd->op.opcode == 0xBA) { op = ModrmReg(rde); bit = m->xedd->op.uimm0 & ((8 << w) - 1); disp = 0; } else { op = (m->xedd->op.opcode & 070) >> 3; disp = ReadMemorySigned(rde, RegRexrReg(m, rde)); bit = disp & ((8 << w) - 1); disp &= -(8 << w); disp >>= 3; } if (IsModrmRegister(rde)) { p = RegRexbRm(m, rde); } else { v = MaskAddress(Eamode(rde), ComputeAddress(m, rde) + disp); p = ReserveAddress(m, v, 1 << w); if (op == 4) { SetReadAddr(m, v, 1 << w); } else { SetWriteAddr(m, v, 1 << w); } } y = 1; y <<= bit; x = ReadMemory(rde, p); m->flags = SetFlag(m->flags, FLAGS_CF, !!(y & x)); switch (op) { case 4: return; case 5: z = Bts(x, y); break; case 6: z = Btr(x, y); break; case 7: z = Btc(x, y); break; default: OpUd(m, rde); } WriteRegisterOrMemory(rde, p, z); } static void OpSax(struct Machine *m, uint32_t rde) { if (Rexw(rde)) { Write64(m->ax, (int32_t)Read32(m->ax)); } else if (!Osz(rde)) { Write64(m->ax, (uint32_t)(int16_t)Read16(m->ax)); } else { Write16(m->ax, (int8_t)Read8(m->ax)); } } static void OpConvert(struct Machine *m, uint32_t rde) { if (Rexw(rde)) { Write64(m->dx, (uint64_t)((int64_t)Read64(m->ax) >> 63)); } else if (!Osz(rde)) { Write64(m->dx, (uint32_t)((int32_t)Read32(m->ax) >> 31)); } else { Write16(m->dx, (uint16_t)((int16_t)Read16(m->ax) >> 15)); } } static void OpBswapZvqp(struct Machine *m, uint32_t rde) { uint64_t x; x = Read64(RegRexbSrm(m, rde)); if (Rexw(rde)) { Write64( RegRexbSrm(m, rde), ((x & 0xff00000000000000) >> 070 | (x & 0x00000000000000ff) << 070 | (x & 0x00ff000000000000) >> 050 | (x & 0x000000000000ff00) << 050 | (x & 0x0000ff0000000000) >> 030 | (x & 0x0000000000ff0000) << 030 | (x & 0x000000ff00000000) >> 010 | (x & 0x00000000ff000000) << 010)); } else if (!Osz(rde)) { Write64(RegRexbSrm(m, rde), ((x & 0xff000000) >> 030 | (x & 0x000000ff) << 030 | (x & 0x00ff0000) >> 010 | (x & 0x0000ff00) << 010)); } else { Write16(RegRexbSrm(m, rde), (x & 0x00ff) << 010 | (x & 0xff00) << 010); } } static void OpMovEbIb(struct Machine *m, uint32_t rde) { Write8(GetModrmRegisterBytePointerWrite(m, rde), m->xedd->op.uimm0); } static void OpMovAlOb(struct Machine *m, uint32_t rde) { int64_t addr; addr = AddressOb(m, rde); SetWriteAddr(m, addr, 1); Write8(m->ax, Read8(ResolveAddress(m, addr))); } static void OpMovObAl(struct Machine *m, uint32_t rde) { int64_t addr; addr = AddressOb(m, rde); SetReadAddr(m, addr, 1); Write8(ResolveAddress(m, addr), Read8(m->ax)); } static void OpMovRaxOvqp(struct Machine *m, uint32_t rde) { uint64_t v; v = DataSegment(m, rde, m->xedd->op.disp); SetReadAddr(m, v, 1 << RegLog2(rde)); WriteRegister(rde, m->ax, ReadMemory(rde, ResolveAddress(m, v))); } static void OpMovOvqpRax(struct Machine *m, uint32_t rde) { uint64_t v; v = DataSegment(m, rde, m->xedd->op.disp); SetWriteAddr(m, v, 1 << RegLog2(rde)); WriteMemory(rde, ResolveAddress(m, v), Read64(m->ax)); } static void OpMovEbGb(struct Machine *m, uint32_t rde) { memcpy(GetModrmRegisterBytePointerWrite(m, rde), ByteRexrReg(m, rde), 1); } static void OpMovGbEb(struct Machine *m, uint32_t rde) { memcpy(ByteRexrReg(m, rde), GetModrmRegisterBytePointerRead(m, rde), 1); } static void OpMovZbIb(struct Machine *m, uint32_t rde) { Write8(ByteRexbSrm(m, rde), m->xedd->op.uimm0); } static void OpMovZvqpIvqp(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexbSrm(m, rde), m->xedd->op.uimm0); } static relegated void OpIncZv(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { Write32(RegSrm(m, rde), Inc32(Read32(RegSrm(m, rde)), 0, &m->flags)); } else { Write16(RegSrm(m, rde), Inc16(Read16(RegSrm(m, rde)), 0, &m->flags)); } } static relegated void OpDecZv(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { Write32(RegSrm(m, rde), Dec32(Read32(RegSrm(m, rde)), 0, &m->flags)); } else { Write16(RegSrm(m, rde), Dec16(Read16(RegSrm(m, rde)), 0, &m->flags)); } } static void OpMovEvqpIvds(struct Machine *m, uint32_t rde) { WriteRegisterOrMemory(rde, GetModrmRegisterWordPointerWriteOszRexw(m, rde), m->xedd->op.uimm0); } static void OpMovEvqpGvqp(struct Machine *m, uint32_t rde) { WriteRegisterOrMemory(rde, GetModrmRegisterWordPointerWriteOszRexw(m, rde), ReadMemory(rde, RegRexrReg(m, rde))); } static void OpMovzbGvqpEb(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexrReg(m, rde), Read8(GetModrmRegisterBytePointerRead(m, rde))); } static void OpMovzwGvqpEw(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexrReg(m, rde), Read16(GetModrmRegisterWordPointerRead2(m, rde))); } static void OpMovsbGvqpEb(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexrReg(m, rde), (int8_t)Read8(GetModrmRegisterBytePointerRead(m, rde))); } static void OpMovswGvqpEw(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexrReg(m, rde), (int16_t)Read16(GetModrmRegisterWordPointerRead2(m, rde))); } static void OpMovsxdGdqpEd(struct Machine *m, uint32_t rde) { Write64(RegRexrReg(m, rde), (int32_t)Read32(GetModrmRegisterWordPointerRead4(m, rde))); } static void Alub(struct Machine *m, uint32_t rde, aluop_f op) { uint8_t *a = GetModrmRegisterBytePointerWrite(m, rde); Write8(a, op(Read8(a), Read8(ByteRexrReg(m, rde)), &m->flags)); } static void OpAlubAdd(struct Machine *m, uint32_t rde) { Alub(m, rde, Add8); } static void OpAlubOr(struct Machine *m, uint32_t rde) { Alub(m, rde, Or8); } static void OpAlubAdc(struct Machine *m, uint32_t rde) { Alub(m, rde, Adc8); } static void OpAlubSbb(struct Machine *m, uint32_t rde) { Alub(m, rde, Sbb8); } static void OpAlubAnd(struct Machine *m, uint32_t rde) { Alub(m, rde, And8); } static void OpAlubSub(struct Machine *m, uint32_t rde) { Alub(m, rde, Sub8); } static void OpAlubXor(struct Machine *m, uint32_t rde) { Alub(m, rde, Xor8); } static void AlubRo(struct Machine *m, uint32_t rde, aluop_f op) { op(Read8(GetModrmRegisterBytePointerRead(m, rde)), Read8(ByteRexrReg(m, rde)), &m->flags); } static void OpAlubCmp(struct Machine *m, uint32_t rde) { AlubRo(m, rde, Sub8); } static void OpAlubTest(struct Machine *m, uint32_t rde) { AlubRo(m, rde, And8); } static void AlubFlip(struct Machine *m, uint32_t rde, aluop_f op) { Write8(ByteRexrReg(m, rde), op(Read8(ByteRexrReg(m, rde)), Read8(GetModrmRegisterBytePointerRead(m, rde)), &m->flags)); } static void OpAlubFlipAdd(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Add8); } static void OpAlubFlipOr(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Or8); } static void OpAlubFlipAdc(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Adc8); } static void OpAlubFlipSbb(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Sbb8); } static void OpAlubFlipAnd(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, And8); } static void OpAlubFlipSub(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Sub8); } static void OpAlubFlipXor(struct Machine *m, uint32_t rde) { AlubFlip(m, rde, Xor8); } static void AlubFlipRo(struct Machine *m, uint32_t rde, aluop_f op) { op(Read8(ByteRexrReg(m, rde)), Read8(GetModrmRegisterBytePointerRead(m, rde)), &m->flags); } static void OpAlubFlipCmp(struct Machine *m, uint32_t rde) { AlubFlipRo(m, rde, Sub8); } static void OpAlubFlipTest(struct Machine *m, uint32_t rde) { AlubFlipRo(m, rde, And8); } static void Alubi(struct Machine *m, uint32_t rde, aluop_f op) { uint8_t *a = GetModrmRegisterBytePointerWrite(m, rde); Write8(a, op(Read8(a), m->xedd->op.uimm0, &m->flags)); } static void AlubiRo(struct Machine *m, uint32_t rde, aluop_f op) { op(Read8(GetModrmRegisterBytePointerRead(m, rde)), m->xedd->op.uimm0, &m->flags); } static void OpAlubiTest(struct Machine *m, uint32_t rde) { AlubiRo(m, rde, And8); } static void OpAlubiReg(struct Machine *m, uint32_t rde) { if (ModrmReg(rde) == ALU_CMP) { AlubiRo(m, rde, kAlu[ModrmReg(rde)][0]); } else { Alubi(m, rde, kAlu[ModrmReg(rde)][0]); } } static void OpAluw(struct Machine *m, uint32_t rde) { uint8_t *a; a = GetModrmRegisterWordPointerWriteOszRexw(m, rde); WriteRegisterOrMemory( rde, a, kAlu[(m->xedd->op.opcode & 070) >> 3][RegLog2(rde)]( ReadMemory(rde, a), Read64(RegRexrReg(m, rde)), &m->flags)); } static void AluwRo(struct Machine *m, uint32_t rde, aluop_f ops[4]) { ops[RegLog2(rde)]( ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)), Read64(RegRexrReg(m, rde)), &m->flags); } static void OpAluwCmp(struct Machine *m, uint32_t rde) { AluwRo(m, rde, kAlu[ALU_SUB]); } static void OpAluwTest(struct Machine *m, uint32_t rde) { AluwRo(m, rde, kAlu[ALU_AND]); } static void OpAluwFlip(struct Machine *m, uint32_t rde) { WriteRegister( rde, RegRexrReg(m, rde), kAlu[(m->xedd->op.opcode & 070) >> 3][RegLog2(rde)]( Read64(RegRexrReg(m, rde)), ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)), &m->flags)); } static void AluwFlipRo(struct Machine *m, uint32_t rde, aluop_f ops[4]) { ops[RegLog2(rde)]( Read64(RegRexrReg(m, rde)), ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)), &m->flags); } static void OpAluwFlipCmp(struct Machine *m, uint32_t rde) { AluwFlipRo(m, rde, kAlu[ALU_SUB]); } static void OpAluwFlipTest(struct Machine *m, uint32_t rde) { AluwFlipRo(m, rde, kAlu[ALU_AND]); } static void Aluwi(struct Machine *m, uint32_t rde, aluop_f ops[4]) { uint8_t *a; a = GetModrmRegisterWordPointerWriteOszRexw(m, rde); WriteRegisterOrMemory( rde, a, ops[RegLog2(rde)](ReadMemory(rde, a), m->xedd->op.uimm0, &m->flags)); } static void AluwiRo(struct Machine *m, uint32_t rde, aluop_f ops[4]) { ops[RegLog2(rde)]( ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)), m->xedd->op.uimm0, &m->flags); } static void OpAluwiReg(struct Machine *m, uint32_t rde) { if (ModrmReg(rde) == ALU_CMP) { AluwiRo(m, rde, kAlu[ModrmReg(rde)]); } else { Aluwi(m, rde, kAlu[ModrmReg(rde)]); } } static void AluAlIb(struct Machine *m, aluop_f op) { Write8(m->ax, op(Read8(m->ax), m->xedd->op.uimm0, &m->flags)); } static void OpAluAlIbAdd(struct Machine *m, uint32_t rde) { AluAlIb(m, Add8); } static void OpAluAlIbOr(struct Machine *m, uint32_t rde) { AluAlIb(m, Or8); } static void OpAluAlIbAdc(struct Machine *m, uint32_t rde) { AluAlIb(m, Adc8); } static void OpAluAlIbSbb(struct Machine *m, uint32_t rde) { AluAlIb(m, Sbb8); } static void OpAluAlIbAnd(struct Machine *m, uint32_t rde) { AluAlIb(m, And8); } static void OpAluAlIbSub(struct Machine *m, uint32_t rde) { AluAlIb(m, Sub8); } static void OpAluAlIbXor(struct Machine *m, uint32_t rde) { AluAlIb(m, Xor8); } static void OpAluRaxIvds(struct Machine *m, uint32_t rde) { WriteRegister(rde, m->ax, kAlu[(m->xedd->op.opcode & 070) >> 3][RegLog2(rde)]( ReadMemory(rde, m->ax), m->xedd->op.uimm0, &m->flags)); } static void OpCmpAlIb(struct Machine *m, uint32_t rde) { Sub8(Read8(m->ax), m->xedd->op.uimm0, &m->flags); } static void OpCmpRaxIvds(struct Machine *m, uint32_t rde) { kAlu[ALU_SUB][RegLog2(rde)](ReadMemory(rde, m->ax), m->xedd->op.uimm0, &m->flags); } static void OpTestAlIb(struct Machine *m, uint32_t rde) { And8(Read8(m->ax), m->xedd->op.uimm0, &m->flags); } static void OpTestRaxIvds(struct Machine *m, uint32_t rde) { kAlu[ALU_AND][RegLog2(rde)](ReadMemory(rde, m->ax), m->xedd->op.uimm0, &m->flags); } static void Bsuwi(struct Machine *m, uint32_t rde, uint64_t y) { uint8_t *p; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); WriteRegisterOrMemory( rde, p, kBsu[ModrmReg(rde)][RegLog2(rde)](ReadMemory(rde, p), y, &m->flags)); } static void OpBsuwi1(struct Machine *m, uint32_t rde) { Bsuwi(m, rde, 1); } static void OpBsuwiCl(struct Machine *m, uint32_t rde) { Bsuwi(m, rde, Read8(m->cx)); } static void OpBsuwiImm(struct Machine *m, uint32_t rde) { Bsuwi(m, rde, m->xedd->op.uimm0); } static void Bsubi(struct Machine *m, uint32_t rde, uint64_t y) { uint8_t *a = GetModrmRegisterBytePointerWrite(m, rde); Write8(a, kBsu[ModrmReg(rde)][RegLog2(rde)](Read8(a), y, &m->flags)); } static void OpBsubi1(struct Machine *m, uint32_t rde) { Bsubi(m, rde, 1); } static void OpBsubiCl(struct Machine *m, uint32_t rde) { Bsubi(m, rde, Read8(m->cx)); } static void OpBsubiImm(struct Machine *m, uint32_t rde) { Bsubi(m, rde, m->xedd->op.uimm0); } static void OpPushImm(struct Machine *m, uint32_t rde) { Push(m, rde, m->xedd->op.uimm0); } static void Interrupt(struct Machine *m, uint32_t rde, int i) { HaltMachine(m, i); } static void OpInterruptImm(struct Machine *m, uint32_t rde) { Interrupt(m, rde, m->xedd->op.uimm0); } static void OpInterrupt1(struct Machine *m, uint32_t rde) { Interrupt(m, rde, 1); } static void OpInterrupt3(struct Machine *m, uint32_t rde) { Interrupt(m, rde, 3); } static void OpJmp(struct Machine *m, uint32_t rde) { m->ip += m->xedd->op.disp; } static void OpJe(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_ZF)) { OpJmp(m, rde); } } static void OpJne(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_ZF)) { OpJmp(m, rde); } } static void OpJb(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_CF)) { OpJmp(m, rde); } } static void OpJbe(struct Machine *m, uint32_t rde) { if (IsBelowOrEqual(m)) { OpJmp(m, rde); } } static void OpJo(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_OF)) { OpJmp(m, rde); } } static void OpJno(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_OF)) { OpJmp(m, rde); } } static void OpJae(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_CF)) { OpJmp(m, rde); } } static void OpJa(struct Machine *m, uint32_t rde) { if (IsAbove(m)) { OpJmp(m, rde); } } static void OpJs(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_SF)) { OpJmp(m, rde); } } static void OpJns(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_SF)) { OpJmp(m, rde); } } static void OpJp(struct Machine *m, uint32_t rde) { if (IsParity(m)) { OpJmp(m, rde); } } static void OpJnp(struct Machine *m, uint32_t rde) { if (!IsParity(m)) { OpJmp(m, rde); } } static void OpJl(struct Machine *m, uint32_t rde) { if (IsLess(m)) { OpJmp(m, rde); } } static void OpJge(struct Machine *m, uint32_t rde) { if (IsGreaterOrEqual(m)) { OpJmp(m, rde); } } static void OpJle(struct Machine *m, uint32_t rde) { if (IsLessOrEqual(m)) { OpJmp(m, rde); } } static void OpJg(struct Machine *m, uint32_t rde) { if (IsGreater(m)) { OpJmp(m, rde); } } static void OpMovGvqpEvqp(struct Machine *m, uint32_t rde) { WriteRegister( rde, RegRexrReg(m, rde), ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde))); } static void OpCmovo(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_OF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovno(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_OF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovb(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_CF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovae(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_CF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmove(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_ZF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovne(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_ZF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovbe(struct Machine *m, uint32_t rde) { if (IsBelowOrEqual(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmova(struct Machine *m, uint32_t rde) { if (IsAbove(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovs(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_SF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovns(struct Machine *m, uint32_t rde) { if (!GetFlag(m->flags, FLAGS_SF)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovp(struct Machine *m, uint32_t rde) { if (IsParity(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovnp(struct Machine *m, uint32_t rde) { if (!IsParity(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovl(struct Machine *m, uint32_t rde) { if (IsLess(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovge(struct Machine *m, uint32_t rde) { if (IsGreaterOrEqual(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovle(struct Machine *m, uint32_t rde) { if (IsLessOrEqual(m)) { OpMovGvqpEvqp(m, rde); } } static void OpCmovg(struct Machine *m, uint32_t rde) { if (IsGreater(m)) { OpMovGvqpEvqp(m, rde); } } static void SetEb(struct Machine *m, uint32_t rde, bool x) { Write8(GetModrmRegisterBytePointerWrite(m, rde), x); } static void OpSeto(struct Machine *m, uint32_t rde) { SetEb(m, rde, GetFlag(m->flags, FLAGS_OF)); } static void OpSetno(struct Machine *m, uint32_t rde) { SetEb(m, rde, !GetFlag(m->flags, FLAGS_OF)); } static void OpSetb(struct Machine *m, uint32_t rde) { SetEb(m, rde, GetFlag(m->flags, FLAGS_CF)); } static void OpSetae(struct Machine *m, uint32_t rde) { SetEb(m, rde, !GetFlag(m->flags, FLAGS_CF)); } static void OpSete(struct Machine *m, uint32_t rde) { SetEb(m, rde, GetFlag(m->flags, FLAGS_ZF)); } static void OpSetne(struct Machine *m, uint32_t rde) { SetEb(m, rde, !GetFlag(m->flags, FLAGS_ZF)); } static void OpSetbe(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsBelowOrEqual(m)); } static void OpSeta(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsAbove(m)); } static void OpSets(struct Machine *m, uint32_t rde) { SetEb(m, rde, GetFlag(m->flags, FLAGS_SF)); } static void OpSetns(struct Machine *m, uint32_t rde) { SetEb(m, rde, !GetFlag(m->flags, FLAGS_SF)); } static void OpSetp(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsParity(m)); } static void OpSetnp(struct Machine *m, uint32_t rde) { SetEb(m, rde, !IsParity(m)); } static void OpSetl(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsLess(m)); } static void OpSetge(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsGreaterOrEqual(m)); } static void OpSetle(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsLessOrEqual(m)); } static void OpSetg(struct Machine *m, uint32_t rde) { SetEb(m, rde, IsGreater(m)); } static void OpJcxz(struct Machine *m, uint32_t rde) { if (!MaskAddress(Eamode(rde), Read64(m->cx))) { OpJmp(m, rde); } } static void Bitscan(struct Machine *m, uint32_t rde, bitscan_f op) { WriteRegister( rde, RegRexrReg(m, rde), op(m, rde, ReadMemory(rde, GetModrmRegisterWordPointerReadOszRexw(m, rde)))); } static void OpBsf(struct Machine *m, uint32_t rde) { Bitscan(m, rde, AluBsf); } static void OpBsr(struct Machine *m, uint32_t rde) { Bitscan(m, rde, AluBsr); } static void Op1b8(struct Machine *m, uint32_t rde) { if (Rep(rde) == 3) { Bitscan(m, rde, AluPopcnt); } else { OpUd(m, rde); } } static void OpNotEb(struct Machine *m, uint32_t rde) { AluEb(m, rde, Not8); } static void OpNegEb(struct Machine *m, uint32_t rde) { AluEb(m, rde, Neg8); } static relegated void LoadFarPointer(struct Machine *m, uint32_t rde, uint8_t seg[8]) { uint32_t fp; fp = Read32(ComputeReserveAddressRead4(m, rde)); Write64(seg, (fp & 0x0000ffff) << 4); Write16(RegRexrReg(m, rde), fp >> 16); } static relegated void OpLes(struct Machine *m, uint32_t rde) { LoadFarPointer(m, rde, m->es); } static relegated void OpLds(struct Machine *m, uint32_t rde) { LoadFarPointer(m, rde, m->ds); } static relegated void Loop(struct Machine *m, uint32_t rde, bool cond) { uint64_t cx; cx = Read64(m->cx) - 1; if (Eamode(rde) != XED_MODE_REAL) { if (Eamode(rde) == XED_MODE_LEGACY) { cx &= 0xffffffff; } Write64(m->cx, cx); } else { cx &= 0xffff; Write16(m->cx, cx); } if (cx && cond) { OpJmp(m, rde); } } static relegated void OpLoope(struct Machine *m, uint32_t rde) { Loop(m, rde, GetFlag(m->flags, FLAGS_ZF)); } static relegated void OpLoopne(struct Machine *m, uint32_t rde) { Loop(m, rde, !GetFlag(m->flags, FLAGS_ZF)); } static relegated void OpLoop1(struct Machine *m, uint32_t rde) { Loop(m, rde, true); } static const nexgen32e_f kOp0f6[] = { OpAlubiTest, OpAlubiTest, OpNotEb, OpNegEb, OpMulAxAlEbUnsigned, OpMulAxAlEbSigned, OpDivAlAhAxEbUnsigned, OpDivAlAhAxEbSigned, }; static void Op0f6(struct Machine *m, uint32_t rde) { kOp0f6[ModrmReg(rde)](m, rde); } static void OpTestEvqpIvds(struct Machine *m, uint32_t rde) { AluwiRo(m, rde, kAlu[ALU_AND]); } static void OpNotEvqp(struct Machine *m, uint32_t rde) { AluEvqp(m, rde, kAlu[ALU_NOT]); } static void OpNegEvqp(struct Machine *m, uint32_t rde) { AluEvqp(m, rde, kAlu[ALU_NEG]); } static const nexgen32e_f kOp0f7[] = { OpTestEvqpIvds, OpTestEvqpIvds, OpNotEvqp, OpNegEvqp, OpMulRdxRaxEvqpUnsigned, OpMulRdxRaxEvqpSigned, OpDivRdxRaxEvqpUnsigned, OpDivRdxRaxEvqpSigned, }; static void Op0f7(struct Machine *m, uint32_t rde) { kOp0f7[ModrmReg(rde)](m, rde); } static void Op0fe(struct Machine *m, uint32_t rde) { switch (ModrmReg(rde)) { case 0: AluEb(m, rde, Inc8); break; case 1: AluEb(m, rde, Dec8); break; default: OpUd(m, rde); } } static void OpIncEvqp(struct Machine *m, uint32_t rde) { AluEvqp(m, rde, kAlu[ALU_INC]); } static void OpDecEvqp(struct Machine *m, uint32_t rde) { AluEvqp(m, rde, kAlu[ALU_DEC]); } static const nexgen32e_f kOp0ff[] = {OpIncEvqp, OpDecEvqp, OpCallEq, OpUd, OpJmpEq, OpUd, OpPushEvq, OpUd}; static void Op0ff(struct Machine *m, uint32_t rde) { kOp0ff[ModrmReg(rde)](m, rde); } static void OpDoubleShift(struct Machine *m, uint32_t rde) { uint8_t *p; uint64_t x; uint8_t W[2][2] = {{2, 3}, {1, 3}}; p = GetModrmRegisterWordPointerWriteOszRexw(m, rde); WriteRegisterOrMemory( rde, p, BsuDoubleShift(W[Osz(rde)][Rexw(rde)], ReadMemory(rde, p), ReadMemory(rde, RegRexrReg(m, rde)), m->xedd->op.opcode & 1 ? Read8(m->cx) : m->xedd->op.uimm0, m->xedd->op.opcode & 8, &m->flags)); } static void OpFxsave(struct Machine *m, uint32_t rde) { int64_t v; uint8_t buf[32]; bzero(buf, 32); Write16(buf + 0, m->fpu.cw); Write16(buf + 2, m->fpu.sw); Write8(buf + 4, m->fpu.tw); Write16(buf + 6, m->fpu.op); Write32(buf + 8, m->fpu.ip); Write32(buf + 24, m->sse.mxcsr); v = ComputeAddress(m, rde); VirtualRecv(m, v + 0, buf, 32); VirtualRecv(m, v + 32, m->fpu.st, 128); VirtualRecv(m, v + 160, m->xmm, 256); SetWriteAddr(m, v, 416); } static void OpFxrstor(struct Machine *m, uint32_t rde) { int64_t v; uint8_t buf[32]; v = ComputeAddress(m, rde); SetReadAddr(m, v, 416); VirtualSend(m, buf, v + 0, 32); VirtualSend(m, m->fpu.st, v + 32, 128); VirtualSend(m, m->xmm, v + 160, 256); m->fpu.cw = Read16(buf + 0); m->fpu.sw = Read16(buf + 2); m->fpu.tw = Read8(buf + 4); m->fpu.op = Read16(buf + 6); m->fpu.ip = Read32(buf + 8); m->sse.mxcsr = Read32(buf + 24); } static void OpXsave(struct Machine *m, uint32_t rde) { } static void OpLdmxcsr(struct Machine *m, uint32_t rde) { m->sse.mxcsr = Read32(ComputeReserveAddressRead4(m, rde)); } static void OpStmxcsr(struct Machine *m, uint32_t rde) { Write32(ComputeReserveAddressWrite4(m, rde), m->sse.mxcsr); } static void OpRdfsbase(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexbRm(m, rde), Read64(m->fs)); } static void OpRdgsbase(struct Machine *m, uint32_t rde) { WriteRegister(rde, RegRexbRm(m, rde), Read64(m->gs)); } static void OpWrfsbase(struct Machine *m, uint32_t rde) { Write64(m->fs, ReadMemory(rde, RegRexbRm(m, rde))); } static void OpWrgsbase(struct Machine *m, uint32_t rde) { Write64(m->gs, ReadMemory(rde, RegRexbRm(m, rde))); } static void Op1ae(struct Machine *m, uint32_t rde) { bool ismem; ismem = !IsModrmRegister(rde); switch (ModrmReg(rde)) { case 0: if (ismem) { OpFxsave(m, rde); } else { OpRdfsbase(m, rde); } break; case 1: if (ismem) { OpFxrstor(m, rde); } else { OpRdgsbase(m, rde); } break; case 2: if (ismem) { OpLdmxcsr(m, rde); } else { OpWrfsbase(m, rde); } break; case 3: if (ismem) { OpStmxcsr(m, rde); } else { OpWrgsbase(m, rde); } break; case 4: if (ismem) { OpXsave(m, rde); } else { OpUd(m, rde); } break; case 5: OpLfence(m, rde); break; case 6: OpMfence(m, rde); break; case 7: if (ismem) { OpClflush(m, rde); } else { OpSfence(m, rde); } break; default: OpUd(m, rde); } } static void OpSalc(struct Machine *m, uint32_t rde) { if (GetFlag(m->flags, FLAGS_CF)) { m->ax[0] = 255; } else { m->ax[0] = 0; } } static void OpBofram(struct Machine *m, uint32_t rde) { if (m->xedd->op.disp) { m->bofram[0] = m->ip; m->bofram[1] = m->ip + (m->xedd->op.disp & 0xff); } else { m->bofram[0] = 0; m->bofram[1] = 0; } } static void OpBinbase(struct Machine *m, uint32_t rde) { if (m->onbinbase) { m->onbinbase(m); } } static void OpNopEv(struct Machine *m, uint32_t rde) { switch (ModrmMod(rde) << 6 | ModrmReg(rde) << 3 | ModrmRm(rde)) { case 0105: OpBofram(m, rde); break; case 0106: OpBofram(m, rde); break; case 0007: case 0107: case 0207: OpBinbase(m, rde); break; default: OpNoop(m, rde); } } static void OpNop(struct Machine *m, uint32_t rde) { if (Rexb(rde)) { OpXchgZvqp(m, rde); } else if (Rep(rde) == 3) { OpPause(m, rde); } else { OpNoop(m, rde); } } static void OpMovRqCq(struct Machine *m, uint32_t rde) { switch (ModrmReg(rde)) { case 0: Write64(RegRexbRm(m, rde), m->cr0); break; case 2: Write64(RegRexbRm(m, rde), m->cr2); break; case 3: Write64(RegRexbRm(m, rde), m->cr3); break; case 4: Write64(RegRexbRm(m, rde), m->cr4); break; default: OpUd(m, rde); } } static void OpMovCqRq(struct Machine *m, uint32_t rde) { int64_t cr3; switch (ModrmReg(rde)) { case 0: m->cr0 = Read64(RegRexbRm(m, rde)); break; case 2: m->cr2 = Read64(RegRexbRm(m, rde)); break; case 3: cr3 = Read64(RegRexbRm(m, rde)); if (0 <= cr3 && cr3 + 512 * 8 <= m->real.n) { m->cr3 = cr3; } else { ThrowProtectionFault(m); } break; case 4: m->cr4 = Read64(RegRexbRm(m, rde)); break; default: OpUd(m, rde); } } static void OpWrmsr(struct Machine *m, uint32_t rde) { } static void OpRdmsr(struct Machine *m, uint32_t rde) { Write32(m->dx, 0); Write32(m->ax, 0); } static void OpVzeroupper(struct Machine *m, uint32_t rde) { } static void OpEmms(struct Machine *m, uint32_t rde) { if (m->xedd->op.vexvalid) { OpVzeroupper(m, rde); } else { m->fpu.tw = -1; } } static const nexgen32e_f kNexgen32e[] = { [0x000] = OpAlubAdd, [0x001] = OpAluw, [0x002] = OpAlubFlipAdd, [0x003] = OpAluwFlip, [0x004] = OpAluAlIbAdd, [0x005] = OpAluRaxIvds, [0x006] = OpPushSeg, [0x007] = OpPopSeg, [0x008] = OpAlubOr, [0x009] = OpAluw, [0x00A] = OpAlubFlipOr, [0x00B] = OpAluwFlip, [0x00C] = OpAluAlIbOr, [0x00D] = OpAluRaxIvds, [0x00E] = OpPushSeg, [0x00F] = OpPopSeg, [0x010] = OpAlubAdc, [0x011] = OpAluw, [0x012] = OpAlubFlipAdc, [0x013] = OpAluwFlip, [0x014] = OpAluAlIbAdc, [0x015] = OpAluRaxIvds, [0x016] = OpPushSeg, [0x017] = OpPopSeg, [0x018] = OpAlubSbb, [0x019] = OpAluw, [0x01A] = OpAlubFlipSbb, [0x01B] = OpAluwFlip, [0x01C] = OpAluAlIbSbb, [0x01D] = OpAluRaxIvds, [0x01E] = OpPushSeg, [0x01F] = OpPopSeg, [0x020] = OpAlubAnd, [0x021] = OpAluw, [0x022] = OpAlubFlipAnd, [0x023] = OpAluwFlip, [0x024] = OpAluAlIbAnd, [0x025] = OpAluRaxIvds, [0x026] = OpPushSeg, [0x027] = OpPopSeg, [0x028] = OpAlubSub, [0x029] = OpAluw, [0x02A] = OpAlubFlipSub, [0x02B] = OpAluwFlip, [0x02C] = OpAluAlIbSub, [0x02D] = OpAluRaxIvds, [0x02E] = OpUd, [0x02F] = OpDas, [0x030] = OpAlubXor, [0x031] = OpAluw, [0x032] = OpAlubFlipXor, [0x033] = OpAluwFlip, [0x034] = OpAluAlIbXor, [0x035] = OpAluRaxIvds, [0x036] = OpUd, [0x037] = OpAaa, [0x038] = OpAlubCmp, [0x039] = OpAluwCmp, [0x03A] = OpAlubFlipCmp, [0x03B] = OpAluwFlipCmp, [0x03C] = OpCmpAlIb, [0x03D] = OpCmpRaxIvds, [0x03E] = OpUd, [0x03F] = OpAas, [0x040] = OpIncZv, [0x041] = OpIncZv, [0x042] = OpIncZv, [0x043] = OpIncZv, [0x044] = OpIncZv, [0x045] = OpIncZv, [0x046] = OpIncZv, [0x047] = OpIncZv, [0x048] = OpDecZv, [0x049] = OpDecZv, [0x04A] = OpDecZv, [0x04B] = OpDecZv, [0x04C] = OpDecZv, [0x04D] = OpDecZv, [0x04E] = OpDecZv, [0x04F] = OpDecZv, [0x050] = OpPushZvq, [0x051] = OpPushZvq, [0x052] = OpPushZvq, [0x053] = OpPushZvq, [0x054] = OpPushZvq, [0x055] = OpPushZvq, [0x056] = OpPushZvq, [0x057] = OpPushZvq, [0x058] = OpPopZvq, [0x059] = OpPopZvq, [0x05A] = OpPopZvq, [0x05B] = OpPopZvq, [0x05C] = OpPopZvq, [0x05D] = OpPopZvq, [0x05E] = OpPopZvq, [0x05F] = OpPopZvq, [0x060] = OpPusha, [0x061] = OpPopa, [0x062] = OpUd, [0x063] = OpMovsxdGdqpEd, [0x064] = OpUd, [0x065] = OpUd, [0x066] = OpUd, [0x067] = OpUd, [0x068] = OpPushImm, [0x069] = OpImulGvqpEvqpImm, [0x06A] = OpPushImm, [0x06B] = OpImulGvqpEvqpImm, [0x06C] = OpIns, [0x06D] = OpIns, [0x06E] = OpOuts, [0x06F] = OpOuts, [0x070] = OpJo, [0x071] = OpJno, [0x072] = OpJb, [0x073] = OpJae, [0x074] = OpJe, [0x075] = OpJne, [0x076] = OpJbe, [0x077] = OpJa, [0x078] = OpJs, [0x079] = OpJns, [0x07A] = OpJp, [0x07B] = OpJnp, [0x07C] = OpJl, [0x07D] = OpJge, [0x07E] = OpJle, [0x07F] = OpJg, [0x080] = OpAlubiReg, [0x081] = OpAluwiReg, [0x082] = OpAlubiReg, [0x083] = OpAluwiReg, [0x084] = OpAlubTest, [0x085] = OpAluwTest, [0x086] = OpXchgGbEb, [0x087] = OpXchgGvqpEvqp, [0x088] = OpMovEbGb, [0x089] = OpMovEvqpGvqp, [0x08A] = OpMovGbEb, [0x08B] = OpMovGvqpEvqp, [0x08C] = OpMovEvqpSw, [0x08D] = OpLeaGvqpM, [0x08E] = OpMovSwEvqp, [0x08F] = OpPopEvq, [0x090] = OpNop, [0x091] = OpXchgZvqp, [0x092] = OpXchgZvqp, [0x093] = OpXchgZvqp, [0x094] = OpXchgZvqp, [0x095] = OpXchgZvqp, [0x096] = OpXchgZvqp, [0x097] = OpXchgZvqp, [0x098] = OpSax, [0x099] = OpConvert, [0x09A] = OpCallf, [0x09B] = OpFwait, [0x09C] = OpPushf, [0x09D] = OpPopf, [0x09E] = OpSahf, [0x09F] = OpLahf, [0x0A0] = OpMovAlOb, [0x0A1] = OpMovRaxOvqp, [0x0A2] = OpMovObAl, [0x0A3] = OpMovOvqpRax, [0x0A4] = OpMovsb, [0x0A5] = OpMovs, [0x0A6] = OpCmps, [0x0A7] = OpCmps, [0x0A8] = OpTestAlIb, [0x0A9] = OpTestRaxIvds, [0x0AA] = OpStosb, [0x0AB] = OpStos, [0x0AC] = OpLods, [0x0AD] = OpLods, [0x0AE] = OpScas, [0x0AF] = OpScas, [0x0B0] = OpMovZbIb, [0x0B1] = OpMovZbIb, [0x0B2] = OpMovZbIb, [0x0B3] = OpMovZbIb, [0x0B4] = OpMovZbIb, [0x0B5] = OpMovZbIb, [0x0B6] = OpMovZbIb, [0x0B7] = OpMovZbIb, [0x0B8] = OpMovZvqpIvqp, [0x0B9] = OpMovZvqpIvqp, [0x0BA] = OpMovZvqpIvqp, [0x0BB] = OpMovZvqpIvqp, [0x0BC] = OpMovZvqpIvqp, [0x0BD] = OpMovZvqpIvqp, [0x0BE] = OpMovZvqpIvqp, [0x0BF] = OpMovZvqpIvqp, [0x0C0] = OpBsubiImm, [0x0C1] = OpBsuwiImm, [0x0C2] = OpRet, [0x0C3] = OpRet, [0x0C4] = OpLes, [0x0C5] = OpLds, [0x0C6] = OpMovEbIb, [0x0C7] = OpMovEvqpIvds, [0x0C8] = OpUd, [0x0C9] = OpLeave, [0x0CA] = OpRetf, [0x0CB] = OpRetf, [0x0CC] = OpInterrupt3, [0x0CD] = OpInterruptImm, [0x0CE] = OpInto, [0x0CF] = OpUd, [0x0D0] = OpBsubi1, [0x0D1] = OpBsuwi1, [0x0D2] = OpBsubiCl, [0x0D3] = OpBsuwiCl, [0x0D4] = OpAam, [0x0D5] = OpAad, [0x0D6] = OpSalc, [0x0D7] = OpXlatAlBbb, [0x0D8] = OpFpu, [0x0D9] = OpFpu, [0x0DA] = OpFpu, [0x0DB] = OpFpu, [0x0DC] = OpFpu, [0x0DD] = OpFpu, [0x0DE] = OpFpu, [0x0DF] = OpFpu, [0x0E0] = OpLoopne, [0x0E1] = OpLoope, [0x0E2] = OpLoop1, [0x0E3] = OpJcxz, [0x0E4] = OpInAlImm, [0x0E5] = OpInAxImm, [0x0E6] = OpOutImmAl, [0x0E7] = OpOutImmAx, [0x0E8] = OpCallJvds, [0x0E9] = OpJmp, [0x0EA] = OpJmpf, [0x0EB] = OpJmp, [0x0EC] = OpInAlDx, [0x0ED] = OpInAxDx, [0x0EE] = OpOutDxAl, [0x0EF] = OpOutDxAx, [0x0F0] = OpUd, [0x0F1] = OpInterrupt1, [0x0F2] = OpUd, [0x0F3] = OpUd, [0x0F4] = OpHlt, [0x0F5] = OpCmc, [0x0F6] = Op0f6, [0x0F7] = Op0f7, [0x0F8] = OpClc, [0x0F9] = OpStc, [0x0FA] = OpCli, [0x0FB] = OpSti, [0x0FC] = OpCld, [0x0FD] = OpStd, [0x0FE] = Op0fe, [0x0FF] = Op0ff, [0x100] = OpUd, [0x101] = Op101, [0x102] = OpUd, [0x103] = OpLsl, [0x104] = OpUd, [0x105] = OpSyscall, [0x106] = OpUd, [0x107] = OpUd, [0x108] = OpUd, [0x109] = OpUd, [0x10A] = OpUd, [0x10B] = OpUd, [0x10C] = OpUd, [0x10D] = OpHintNopEv, [0x10E] = OpUd, [0x10F] = OpUd, [0x110] = OpMov0f10, [0x111] = OpMovWpsVps, [0x112] = OpMov0f12, [0x113] = OpMov0f13, [0x114] = OpUnpcklpsd, [0x115] = OpUnpckhpsd, [0x116] = OpMov0f16, [0x117] = OpMov0f17, [0x118] = OpHintNopEv, [0x119] = OpHintNopEv, [0x11A] = OpHintNopEv, [0x11B] = OpHintNopEv, [0x11C] = OpHintNopEv, [0x11D] = OpHintNopEv, [0x11E] = OpHintNopEv, [0x11F] = OpNopEv, [0x120] = OpMovRqCq, [0x121] = OpUd, [0x122] = OpMovCqRq, [0x123] = OpUd, [0x124] = OpUd, [0x125] = OpUd, [0x126] = OpUd, [0x127] = OpUd, [0x128] = OpMov0f28, [0x129] = OpMovWpsVps, [0x12A] = OpCvt0f2a, [0x12B] = OpMov0f2b, [0x12C] = OpCvtt0f2c, [0x12D] = OpCvt0f2d, [0x12E] = OpComissVsWs, [0x12F] = OpComissVsWs, [0x130] = OpWrmsr, [0x131] = OpRdtsc, [0x132] = OpRdmsr, [0x133] = OpUd, [0x134] = OpUd, [0x135] = OpUd, [0x136] = OpUd, [0x137] = OpUd, [0x138] = OpUd, [0x139] = OpUd, [0x13A] = OpUd, [0x13B] = OpUd, [0x13C] = OpUd, [0x13D] = OpUd, [0x13E] = OpUd, [0x13F] = OpUd, [0x140] = OpCmovo, [0x141] = OpCmovno, [0x142] = OpCmovb, [0x143] = OpCmovae, [0x144] = OpCmove, [0x145] = OpCmovne, [0x146] = OpCmovbe, [0x147] = OpCmova, [0x148] = OpCmovs, [0x149] = OpCmovns, [0x14A] = OpCmovp, [0x14B] = OpCmovnp, [0x14C] = OpCmovl, [0x14D] = OpCmovge, [0x14E] = OpCmovle, [0x14F] = OpCmovg, [0x150] = OpUd, [0x151] = OpSqrtpsd, [0x152] = OpRsqrtps, [0x153] = OpRcpps, [0x154] = OpAndpsd, [0x155] = OpAndnpsd, [0x156] = OpOrpsd, [0x157] = OpXorpsd, [0x158] = OpAddpsd, [0x159] = OpMulpsd, [0x15A] = OpCvt0f5a, [0x15B] = OpCvt0f5b, [0x15C] = OpSubpsd, [0x15D] = OpMinpsd, [0x15E] = OpDivpsd, [0x15F] = OpMaxpsd, [0x160] = OpSsePunpcklbw, [0x161] = OpSsePunpcklwd, [0x162] = OpSsePunpckldq, [0x163] = OpSsePacksswb, [0x164] = OpSsePcmpgtb, [0x165] = OpSsePcmpgtw, [0x166] = OpSsePcmpgtd, [0x167] = OpSsePackuswb, [0x168] = OpSsePunpckhbw, [0x169] = OpSsePunpckhwd, [0x16A] = OpSsePunpckhdq, [0x16B] = OpSsePackssdw, [0x16C] = OpSsePunpcklqdq, [0x16D] = OpSsePunpckhqdq, [0x16E] = OpMov0f6e, [0x16F] = OpMov0f6f, [0x170] = OpShuffle, [0x171] = Op171, [0x172] = Op172, [0x173] = Op173, [0x174] = OpSsePcmpeqb, [0x175] = OpSsePcmpeqw, [0x176] = OpSsePcmpeqd, [0x177] = OpEmms, [0x178] = OpUd, [0x179] = OpUd, [0x17A] = OpUd, [0x17B] = OpUd, [0x17C] = OpHaddpsd, [0x17D] = OpHsubpsd, [0x17E] = OpMov0f7e, [0x17F] = OpMov0f7f, [0x180] = OpJo, [0x181] = OpJno, [0x182] = OpJb, [0x183] = OpJae, [0x184] = OpJe, [0x185] = OpJne, [0x186] = OpJbe, [0x187] = OpJa, [0x188] = OpJs, [0x189] = OpJns, [0x18A] = OpJp, [0x18B] = OpJnp, [0x18C] = OpJl, [0x18D] = OpJge, [0x18E] = OpJle, [0x18F] = OpJg, [0x190] = OpSeto, [0x191] = OpSetno, [0x192] = OpSetb, [0x193] = OpSetae, [0x194] = OpSete, [0x195] = OpSetne, [0x196] = OpSetbe, [0x197] = OpSeta, [0x198] = OpSets, [0x199] = OpSetns, [0x19A] = OpSetp, [0x19B] = OpSetnp, [0x19C] = OpSetl, [0x19D] = OpSetge, [0x19E] = OpSetle, [0x19F] = OpSetg, [0x1A0] = OpPushSeg, [0x1A1] = OpPopSeg, [0x1A2] = OpCpuid, [0x1A3] = OpBit, [0x1A4] = OpDoubleShift, [0x1A5] = OpDoubleShift, [0x1A6] = OpUd, [0x1A7] = OpUd, [0x1A8] = OpPushSeg, [0x1A9] = OpPopSeg, [0x1AA] = OpUd, [0x1AB] = OpBit, [0x1AC] = OpDoubleShift, [0x1AD] = OpDoubleShift, [0x1AE] = Op1ae, [0x1AF] = OpImulGvqpEvqp, [0x1B0] = OpCmpxchgEbAlGb, [0x1B1] = OpCmpxchgEvqpRaxGvqp, [0x1B2] = OpUd, [0x1B3] = OpBit, [0x1B4] = OpUd, [0x1B5] = OpUd, [0x1B6] = OpMovzbGvqpEb, [0x1B7] = OpMovzwGvqpEw, [0x1B8] = Op1b8, [0x1B9] = OpUd, [0x1BA] = OpBit, [0x1BB] = OpBit, [0x1BC] = OpBsf, [0x1BD] = OpBsr, [0x1BE] = OpMovsbGvqpEb, [0x1BF] = OpMovswGvqpEw, [0x1C0] = OpXaddEbGb, [0x1C1] = OpXaddEvqpGvqp, [0x1C2] = OpCmppsd, [0x1C3] = OpMovntiMdqpGdqp, [0x1C4] = OpPinsrwVdqEwIb, [0x1C5] = OpPextrwGdqpUdqIb, [0x1C6] = OpShufpsd, [0x1C7] = Op1c7, [0x1C8] = OpBswapZvqp, [0x1C9] = OpBswapZvqp, [0x1CA] = OpBswapZvqp, [0x1CB] = OpBswapZvqp, [0x1CC] = OpBswapZvqp, [0x1CD] = OpBswapZvqp, [0x1CE] = OpBswapZvqp, [0x1CF] = OpBswapZvqp, [0x1D0] = OpAddsubpsd, [0x1D1] = OpSsePsrlwv, [0x1D2] = OpSsePsrldv, [0x1D3] = OpSsePsrlqv, [0x1D4] = OpSsePaddq, [0x1D5] = OpSsePmullw, [0x1D6] = OpMov0fD6, [0x1D7] = OpPmovmskbGdqpNqUdq, [0x1D8] = OpSsePsubusb, [0x1D9] = OpSsePsubusw, [0x1DA] = OpSsePminub, [0x1DB] = OpSsePand, [0x1DC] = OpSsePaddusb, [0x1DD] = OpSsePaddusw, [0x1DE] = OpSsePmaxub, [0x1DF] = OpSsePandn, [0x1E0] = OpSsePavgb, [0x1E1] = OpSsePsrawv, [0x1E2] = OpSsePsradv, [0x1E3] = OpSsePavgw, [0x1E4] = OpSsePmulhuw, [0x1E5] = OpSsePmulhw, [0x1E6] = OpCvt0fE6, [0x1E7] = OpMov0fE7, [0x1E8] = OpSsePsubsb, [0x1E9] = OpSsePsubsw, [0x1EA] = OpSsePminsw, [0x1EB] = OpSsePor, [0x1EC] = OpSsePaddsb, [0x1ED] = OpSsePaddsw, [0x1EE] = OpSsePmaxsw, [0x1EF] = OpSsePxor, [0x1F0] = OpLddquVdqMdq, [0x1F1] = OpSsePsllwv, [0x1F2] = OpSsePslldv, [0x1F3] = OpSsePsllqv, [0x1F4] = OpSsePmuludq, [0x1F5] = OpSsePmaddwd, [0x1F6] = OpSsePsadbw, [0x1F7] = OpMaskMovDiXmmRegXmmRm, [0x1F8] = OpSsePsubb, [0x1F9] = OpSsePsubw, [0x1FA] = OpSsePsubd, [0x1FB] = OpSsePsubq, [0x1FC] = OpSsePaddb, [0x1FD] = OpSsePaddw, [0x1FE] = OpSsePaddd, [0x1FF] = OpUd, [0x200] = OpSsePshufb, [0x201] = OpSsePhaddw, [0x202] = OpSsePhaddd, [0x203] = OpSsePhaddsw, [0x204] = OpSsePmaddubsw, [0x205] = OpSsePhsubw, [0x206] = OpSsePhsubd, [0x207] = OpSsePhsubsw, [0x208] = OpSsePsignb, [0x209] = OpSsePsignw, [0x20A] = OpSsePsignd, [0x20B] = OpSsePmulhrsw, }; void ExecuteSparseInstruction(struct Machine *m, uint32_t rde, uint32_t d) { switch (d) { CASE(0x21c, OpSsePabsb(m, rde)); CASE(0x21d, OpSsePabsw(m, rde)); CASE(0x21e, OpSsePabsd(m, rde)); CASE(0x22a, OpMovntdqaVdqMdq(m, rde)); CASE(0x240, OpSsePmulld(m, rde)); CASE(0x30f, OpSsePalignr(m, rde)); CASE(0x344, OpSsePclmulqdq(m, rde)); default: OpUd(m, rde); } } void ExecuteInstruction(struct Machine *m) { m->ip += m->xedd->length; if (m->xedd->op.dispatch < ARRAYLEN(kNexgen32e)) { kNexgen32e[m->xedd->op.dispatch](m, m->xedd->op.rde); } else { ExecuteSparseInstruction(m, m->xedd->op.rde, m->xedd->op.dispatch); } if (m->stashaddr) { VirtualRecv(m, m->stashaddr, m->stash, m->stashsize); m->stashaddr = 0; } }
57,202
2,246
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/modrm.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_MODRM_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_MODRM_H_ #include "tool/build/lib/abp.h" #include "tool/build/lib/machine.h" #define Rex(x) ((x & 000000000020) >> 004) #define Osz(x) ((x & 000000000040) >> 005) #define Rep(x) ((x & 030000000000) >> 036) #define Rexr(x) ((x & 000000000010) >> 003) #define Rexw(x) ((x & 000000000100) >> 006) #define Rexb(x) ((x & 000000002000) >> 012) #define Sego(x) ((x & 000007000000) >> 022) #define Mode(x) ((x & 001400000000) >> 032) #define Eamode(x) ((x & 000300000000) >> 030) #define RexbRm(x) ((x & 000000003600) >> 007) #define RexrReg(x) ((x & 000000000017) >> 000) #define RegLog2(x) ((x & 006000000000) >> 034) #define ModrmRm(x) ((x & 000000001600) >> 007) #define ModrmReg(x) ((x & 000000000007) >> 000) #define ModrmSrm(x) ((x & 000000070000) >> 014) #define ModrmMod(x) ((x & 000060000000) >> 026) #define Modrm(x) (ModrmMod(x) << 6 | ModrmReg(x) << 3 | ModrmRm(x)) #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define RexbBase(m, x) (Rexb(x) << 3 | m->xedd->op.base) #define AddrByteReg(m, k) ((uint8_t *)m->reg + kByteReg[k]) #define ByteRexrReg(m, x) AddrByteReg(m, (x & 00000000037) >> 0) #define ByteRexbRm(m, x) AddrByteReg(m, (x & 00000007600) >> 7) #define ByteRexbSrm(m, x) AddrByteReg(m, (x & 00000370000) >> 12) #define RegSrm(m, x) Abp8(m->reg[(x & 00000070000) >> 12]) #define RegRexbRm(m, x) Abp8(m->reg[RexbRm(x)]) #define RegRexbSrm(m, x) Abp8(m->reg[(x & 00000170000) >> 12]) #define RegRexrReg(m, x) Abp8(m->reg[RexrReg(x)]) #define RegRexbBase(m, x) Abp8(m->reg[RexbBase(m, x)]) #define RegRexxIndex(m) Abp8(m->reg[m->xedd->op.rexx << 3 | m->xedd->op.index]) #define MmRm(m, x) Abp16(m->xmm[(x & 00000001600) >> 7]) #define MmReg(m, x) Abp16(m->xmm[(x & 00000000007) >> 0]) #define XmmRexbRm(m, x) Abp16(m->xmm[RexbRm(x)]) #define XmmRexrReg(m, x) Abp16(m->xmm[RexrReg(x)]) #define Rexx(m) m->op.rexx #define SibBase(m) m->op.base #define SibIndex(m) m->op.index #define SibExists(x) (ModrmRm(x) == 4) #define IsModrmRegister(x) (ModrmMod(x) == 3) #define SibHasIndex(x) (SibIndex(x) != 4 || Rexx(x)) #define SibHasBase(x, r) (SibBase(x) != 5 || ModrmMod(r)) #define SibIsAbsolute(x, r) (!SibHasBase(x, r) && !SibHasIndex(x)) #define IsRipRelative(x) (Eamode(x) && ModrmRm(x) == 5 && !ModrmMod(x)) struct AddrSeg { int64_t addr; uint8_t *seg; }; extern const uint8_t kByteReg[32]; uint32_t EncodeRde(struct XedDecodedInst *); int64_t ComputeAddress(const struct Machine *, uint32_t); struct AddrSeg LoadEffectiveAddress(const struct Machine *, uint32_t); void *ComputeReserveAddressRead(struct Machine *, uint32_t, size_t); void *ComputeReserveAddressRead1(struct Machine *, uint32_t); void *ComputeReserveAddressRead4(struct Machine *, uint32_t); void *ComputeReserveAddressRead8(struct Machine *, uint32_t); void *ComputeReserveAddressWrite(struct Machine *, uint32_t, size_t); void *ComputeReserveAddressWrite1(struct Machine *, uint32_t); void *ComputeReserveAddressWrite4(struct Machine *, uint32_t); void *ComputeReserveAddressWrite8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterBytePointerRead(struct Machine *, uint32_t); uint8_t *GetModrmRegisterBytePointerWrite(struct Machine *, uint32_t); uint8_t *GetModrmRegisterMmPointerRead(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterMmPointerRead8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterMmPointerWrite(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterMmPointerWrite8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerRead(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterWordPointerRead2(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerRead4(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerRead8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerReadOsz(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerReadOszRexw(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerWrite(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterWordPointerWrite2(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerWrite4(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerWrite8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerWriteOsz(struct Machine *, uint32_t); uint8_t *GetModrmRegisterWordPointerWriteOszRexw(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerRead(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterXmmPointerRead16(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerRead4(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerRead8(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerWrite(struct Machine *, uint32_t, size_t); uint8_t *GetModrmRegisterXmmPointerWrite16(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerWrite4(struct Machine *, uint32_t); uint8_t *GetModrmRegisterXmmPointerWrite8(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_MODRM_H_ */
5,243
101
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ssefloat.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_SSEFLOAT_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_SSEFLOAT_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef float float_v _Vector_size(16) forcealign(16); typedef double double_v _Vector_size(16) forcealign(16); void OpUnpcklpsd(struct Machine *, uint32_t); void OpUnpckhpsd(struct Machine *, uint32_t); void OpPextrwGdqpUdqIb(struct Machine *, uint32_t); void OpPinsrwVdqEwIb(struct Machine *, uint32_t); void OpShuffle(struct Machine *, uint32_t); void OpShufpsd(struct Machine *, uint32_t); void OpSqrtpsd(struct Machine *, uint32_t); void OpRsqrtps(struct Machine *, uint32_t); void OpRcpps(struct Machine *, uint32_t); void OpComissVsWs(struct Machine *, uint32_t); void OpAddpsd(struct Machine *, uint32_t); void OpMulpsd(struct Machine *, uint32_t); void OpSubpsd(struct Machine *, uint32_t); void OpDivpsd(struct Machine *, uint32_t); void OpMinpsd(struct Machine *, uint32_t); void OpMaxpsd(struct Machine *, uint32_t); void OpCmppsd(struct Machine *, uint32_t); void OpAndpsd(struct Machine *, uint32_t); void OpAndnpsd(struct Machine *, uint32_t); void OpOrpsd(struct Machine *, uint32_t); void OpXorpsd(struct Machine *, uint32_t); void OpHaddpsd(struct Machine *, uint32_t); void OpHsubpsd(struct Machine *, uint32_t); void OpAddsubpsd(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_SSEFLOAT_H_ */
1,493
38
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pml4tfmt.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/log/check.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/x/x.h" #include "tool/build/lib/buffer.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/pml4t.h" struct Pml4tFormatter { bool t; int64_t start; struct Buffer b; long lines; }; static int64_t MakeAddress(unsigned short a[4]) { uint64_t x; x = 0; x |= a[0]; x <<= 9; x |= a[1]; x <<= 9; x |= a[2]; x <<= 9; x |= a[3]; x <<= 12; return x; } static void FormatStartPage(struct Pml4tFormatter *pp, int64_t start) { pp->t = true; pp->start = start; if (pp->lines++) AppendChar(&pp->b, '\n'); AppendFmt(&pp->b, "%012lx-", start); } static void FormatEndPage(struct Pml4tFormatter *pp, int64_t end) { int64_t size; pp->t = false; size = end - pp->start; AppendFmt(&pp->b, "%012lx %012lx %,ld bytes", end - 1, size, size); } static void *GetPt(struct Machine *m, uint64_t r) { CHECK_LE(r + 0x1000, m->real.n); return m->real.p + r; } char *FormatPml4t(struct Machine *m) { uint64_t *pd[4]; unsigned short i, a[4]; struct Pml4tFormatter pp = {0}; unsigned short range[][2] = {{256, 512}, {0, 256}}; if ((m->mode & 3) != XED_MODE_LONG) return strdup(""); pd[0] = GetPt(m, m->cr3); for (i = 0; i < ARRAYLEN(range); ++i) { a[0] = range[i][0]; do { a[1] = a[2] = a[3] = 0; if (!IsValidPage(pd[0][a[0]])) { if (pp.t) FormatEndPage(&pp, MakeAddress(a)); } else { pd[1] = GetPt(m, UnmaskPageAddr(pd[0][a[0]])); do { a[2] = a[3] = 0; if (!IsValidPage(pd[1][a[1]])) { if (pp.t) FormatEndPage(&pp, MakeAddress(a)); } else { pd[2] = GetPt(m, UnmaskPageAddr(pd[1][a[1]])); do { a[3] = 0; if (!IsValidPage(pd[2][a[2]])) { if (pp.t) FormatEndPage(&pp, MakeAddress(a)); } else { pd[3] = GetPt(m, UnmaskPageAddr(pd[2][a[2]])); do { if (!IsValidPage(pd[3][a[3]])) { if (pp.t) FormatEndPage(&pp, MakeAddress(a)); } else { if (!pp.t) { FormatStartPage(&pp, MakeAddress(a)); } } } while (++a[3] != 512); } } while (++a[2] != 512); } } while (++a[1] != 512); } } while (++a[0] != range[i][1]); } if (pp.t) { FormatEndPage(&pp, 0x800000000000); } if (pp.b.p) { return xrealloc(pp.b.p, pp.b.i + 1); } else { return strdup(""); } }
4,457
119
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/sse.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_SSE_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_SSE_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void Op171(struct Machine *, uint32_t); void Op172(struct Machine *, uint32_t); void Op173(struct Machine *, uint32_t); void OpSsePabsb(struct Machine *, uint32_t); void OpSsePabsd(struct Machine *, uint32_t); void OpSsePabsw(struct Machine *, uint32_t); void OpSsePackssdw(struct Machine *, uint32_t); void OpSsePacksswb(struct Machine *, uint32_t); void OpSsePackuswb(struct Machine *, uint32_t); void OpSsePaddb(struct Machine *, uint32_t); void OpSsePaddd(struct Machine *, uint32_t); void OpSsePaddq(struct Machine *, uint32_t); void OpSsePaddsb(struct Machine *, uint32_t); void OpSsePaddsw(struct Machine *, uint32_t); void OpSsePaddusb(struct Machine *, uint32_t); void OpSsePaddusw(struct Machine *, uint32_t); void OpSsePaddw(struct Machine *, uint32_t); void OpSsePalignr(struct Machine *, uint32_t); void OpSsePand(struct Machine *, uint32_t); void OpSsePandn(struct Machine *, uint32_t); void OpSsePavgb(struct Machine *, uint32_t); void OpSsePavgw(struct Machine *, uint32_t); void OpSsePcmpeqb(struct Machine *, uint32_t); void OpSsePcmpeqd(struct Machine *, uint32_t); void OpSsePcmpeqw(struct Machine *, uint32_t); void OpSsePcmpgtb(struct Machine *, uint32_t); void OpSsePcmpgtd(struct Machine *, uint32_t); void OpSsePcmpgtw(struct Machine *, uint32_t); void OpSsePhaddd(struct Machine *, uint32_t); void OpSsePhaddsw(struct Machine *, uint32_t); void OpSsePhaddw(struct Machine *, uint32_t); void OpSsePhsubd(struct Machine *, uint32_t); void OpSsePhsubsw(struct Machine *, uint32_t); void OpSsePhsubw(struct Machine *, uint32_t); void OpSsePmaddubsw(struct Machine *, uint32_t); void OpSsePmaddwd(struct Machine *, uint32_t); void OpSsePmaxsw(struct Machine *, uint32_t); void OpSsePmaxub(struct Machine *, uint32_t); void OpSsePminsw(struct Machine *, uint32_t); void OpSsePminub(struct Machine *, uint32_t); void OpSsePmulhrsw(struct Machine *, uint32_t); void OpSsePmulhuw(struct Machine *, uint32_t); void OpSsePmulhw(struct Machine *, uint32_t); void OpSsePmulld(struct Machine *, uint32_t); void OpSsePmullw(struct Machine *, uint32_t); void OpSsePmuludq(struct Machine *, uint32_t); void OpSsePor(struct Machine *, uint32_t); void OpSsePsadbw(struct Machine *, uint32_t); void OpSsePshufb(struct Machine *, uint32_t); void OpSsePsignb(struct Machine *, uint32_t); void OpSsePsignd(struct Machine *, uint32_t); void OpSsePsignw(struct Machine *, uint32_t); void OpSsePslldv(struct Machine *, uint32_t); void OpSsePsllqv(struct Machine *, uint32_t); void OpSsePsllwv(struct Machine *, uint32_t); void OpSsePsradv(struct Machine *, uint32_t); void OpSsePsrawv(struct Machine *, uint32_t); void OpSsePsrldv(struct Machine *, uint32_t); void OpSsePsrlqv(struct Machine *, uint32_t); void OpSsePsrlwv(struct Machine *, uint32_t); void OpSsePsubb(struct Machine *, uint32_t); void OpSsePsubd(struct Machine *, uint32_t); void OpSsePsubq(struct Machine *, uint32_t); void OpSsePsubsb(struct Machine *, uint32_t); void OpSsePsubsw(struct Machine *, uint32_t); void OpSsePsubusb(struct Machine *, uint32_t); void OpSsePsubusw(struct Machine *, uint32_t); void OpSsePsubw(struct Machine *, uint32_t); void OpSsePunpckhbw(struct Machine *, uint32_t); void OpSsePunpckhdq(struct Machine *, uint32_t); void OpSsePunpckhqdq(struct Machine *, uint32_t); void OpSsePunpckhwd(struct Machine *, uint32_t); void OpSsePunpcklbw(struct Machine *, uint32_t); void OpSsePunpckldq(struct Machine *, uint32_t); void OpSsePunpcklqdq(struct Machine *, uint32_t); void OpSsePunpcklwd(struct Machine *, uint32_t); void OpSsePxor(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_SSE_H_ */
3,855
88
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/argv.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/log/check.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "libc/str/str.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #define STACKALIGN 16 #define LINUX_AT_EXECFN 31 static size_t GetArgListLen(char **p) { size_t n; for (n = 0; *p; ++p) ++n; return n; } static int64_t PushString(struct Machine *m, const char *s) { size_t n; int64_t sp; n = strlen(s) + 1; sp = Read64(m->sp); sp -= n; Write64(m->sp, sp); VirtualRecv(m, sp, s, n); return sp; } void LoadArgv(struct Machine *m, const char *prog, char **args, char **vars) { int64_t i, n, sp, *p, *bloc; size_t narg, nenv, naux, nall; DCHECK_NOTNULL(prog); DCHECK_NOTNULL(args); DCHECK_NOTNULL(vars); naux = 1; nenv = GetArgListLen(vars); narg = GetArgListLen(args); nall = 1 + 1 + narg + 1 + nenv + 1 + (naux + 1) * 2; bloc = gc(malloc(sizeof(int64_t) * nall)); p = bloc + nall; *--p = 0; *--p = 0; *--p = PushString(m, prog); *--p = LINUX_AT_EXECFN; for (*--p = 0, i = nenv; i--;) *--p = PushString(m, vars[i]); for (*--p = 0, i = narg; i--;) *--p = PushString(m, args[i]); *--p = PushString(m, prog); *--p = 1 + narg; DCHECK_EQ(bloc, p); sp = Read64(m->sp); while ((sp - nall * sizeof(int64_t)) & (STACKALIGN - 1)) --sp; sp -= nall * sizeof(int64_t); DCHECK_EQ(0, sp % STACKALIGN); Write64(m->sp, sp); Write64(m->di, 0); /* or ape detects freebsd */ VirtualRecv(m, sp, bloc, sizeof(int64_t) * nall); }
3,378
76
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/asmdown.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/mem/alg.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "tool/build/lib/asmdown.h" #include "tool/build/lib/javadown.h" static bool IsSymbolChar1(char c) { return (c & 0x80) || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '$' || c == '_'; } static bool IsSymbolChar2(char c) { return (c & 0x80) || ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '$' || c == '_'; } static bool IsSymbolString(const char *s) { int i; if (!IsSymbolChar1(*s++)) return false; while (*s) { if (!IsSymbolChar2(*s++)) return false; } return true; } /** * Extracts symbols and docstrings from .S file. * * Docstrings are multiline Fortran-style AT&T assembly comments * preceding a symbol that have at least one @tag line. * * @param code is contents of .S file * @param size is byte length of code * @return object that needs to be FreeAsmdown()'d * @note this function assumes canonical unix newlines */ struct Asmdown *ParseAsmdown(const char *code, size_t size) { struct Asmdown *ad; char *p1, *p2, *p3, *symbol, *alias; enum { BOL, COM, SYM, OTHER } state; int i, j, line, start_line, start_docstring, end_docstring, start_symbol; ad = calloc(1, sizeof(struct Asmdown)); line = 1; start_line = 1; state = BOL; start_docstring = 0; end_docstring = 0; start_symbol = 0; for (i = 0; i < size; ++i) { switch (state) { case BOL: if (code[i] == '/') { start_line = line; start_docstring = i; state = COM; } else if (IsSymbolChar1(code[i])) { start_symbol = i; state = SYM; } else if (code[i] == '\n') { ++line; } else if (i + 8 < size && !memcmp(code + i, "\t.alias\t", 8)) { p1 = code + i + 8; if ((p2 = strchr(p1, ',')) && (p3 = strchr(p2, '\n'))) { symbol = strndup(p1, p2 - p1); alias = strndup(p2 + 1, p3 - (p2 + 1)); if (IsSymbolString(symbol) && IsSymbolString(alias)) { for (j = 0; j < ad->symbols.n; ++j) { if (!strcmp(ad->symbols.p[j].name, symbol)) { ad->symbols.p = realloc( ad->symbols.p, ++ad->symbols.n * sizeof(*ad->symbols.p)); ad->symbols.p[ad->symbols.n - 1].line = ad->symbols.p[j].line; ad->symbols.p[ad->symbols.n - 1].name = strdup(alias); ad->symbols.p[ad->symbols.n - 1].is_alias = true; ad->symbols.p[ad->symbols.n - 1].javadown = ad->symbols.p[j].javadown; break; } } } free(symbol); free(alias); } state = OTHER; } else { state = OTHER; } break; case COM: if (code[i] == '\n') { ++line; if (i + 1 < size && code[i + 1] != '/') { state = BOL; end_docstring = i + 1; if (!memmem(code + start_docstring, end_docstring - start_docstring, "/\t@", 3)) { start_docstring = 0; end_docstring = 0; } } } break; case SYM: if (code[i] == ':' && end_docstring > start_docstring) { ad->symbols.p = realloc(ad->symbols.p, ++ad->symbols.n * sizeof(*ad->symbols.p)); ad->symbols.p[ad->symbols.n - 1].line = start_line; ad->symbols.p[ad->symbols.n - 1].name = strndup(code + start_symbol, i - start_symbol); ad->symbols.p[ad->symbols.n - 1].is_alias = false; ad->symbols.p[ad->symbols.n - 1].javadown = ParseJavadown( code + start_docstring, end_docstring - start_docstring); end_docstring = 0; start_docstring = 0; state = OTHER; } else if (code[i] == '\n') { ++line; state = BOL; } else if (!IsSymbolChar2(code[i])) { state = OTHER; } break; case OTHER: if (code[i] == '\n') { ++line; state = BOL; } break; default: unreachable; } } return ad; } /** * Frees object returned by ParseAsmdown(). */ void FreeAsmdown(struct Asmdown *ad) { int i; if (ad) { for (i = 0; i < ad->symbols.n; ++i) { free(ad->symbols.p[i].name); if (!ad->symbols.p[i].is_alias) { FreeJavadown(ad->symbols.p[i].javadown); } } free(ad->symbols.p); free(ad); } }
6,449
169
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/iovs.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/mem/mem.h" #include "libc/str/str.h" #include "tool/build/lib/iovs.h" void InitIovs(struct Iovs *ib) { ib->p = ib->init; ib->i = 0; ib->n = ARRAYLEN(ib->init); } void FreeIovs(struct Iovs *ib) { if (ib->p != ib->init) { free(ib->p); } } /** * Appends memory region to i/o vector builder. */ int AppendIovs(struct Iovs *ib, void *base, size_t len) { unsigned i, n; struct iovec *p; if (len) { p = ib->p; i = ib->i; n = ib->n; if (i && (intptr_t)base == (intptr_t)p[i - 1].iov_base + p[i - 1].iov_len) { p[i - 1].iov_len += len; } else { if (__builtin_expect(i == n, 0)) { n += n >> 1; if (p == ib->init) { if (!(p = malloc(sizeof(struct iovec) * n))) return -1; memcpy(p, ib->init, sizeof(ib->init)); } else { if (!(p = realloc(p, sizeof(struct iovec) * n))) return -1; } ib->p = p; ib->n = n; } p[i].iov_base = base; p[i].iov_len = len; ++ib->i; } } return 0; }
2,914
67
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/diself.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/elf/elf.h" #include "libc/elf/struct/sym.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/mem/mem.h" #include "libc/runtime/memtrack.internal.h" #include "libc/str/str.h" #include "tool/build/lib/dis.h" bool g_disisprog_disable; static int DisSymCompare(const struct DisSym *a, const struct DisSym *b) { if (a->addr != b->addr) { if (a->addr < b->addr) return -1; if (a->addr > b->addr) return +1; } if (a->rank != b->rank) { if (a->rank > b->rank) return -1; if (a->rank < b->rank) return +1; } if (a->unique != b->unique) { if (a->unique < b->unique) return -1; if (a->unique > b->unique) return +1; } return 0; } static void DisLoadElfLoads(struct Dis *d, struct Elf *elf) { long i, j, n; int64_t addr; uint64_t size; Elf64_Phdr *phdr; j = 0; n = elf->ehdr->e_phnum; if (d->loads.n < n) { d->loads.n = n; d->loads.p = realloc(d->loads.p, d->loads.n * sizeof(*d->loads.p)); CHECK_NOTNULL(d->loads.p); } for (i = 0; i < n; ++i) { phdr = GetElfSegmentHeaderAddress(elf->ehdr, elf->size, i); if (phdr->p_type != PT_LOAD) continue; d->loads.p[j].addr = phdr->p_vaddr; d->loads.p[j].size = phdr->p_memsz; d->loads.p[j].istext = (phdr->p_flags & PF_X) == PF_X; ++j; } d->loads.i = j; } static void DisLoadElfSyms(struct Dis *d, struct Elf *elf) { size_t i, j, n; int64_t stablen; const Elf64_Sym *st, *sym; bool isabs, iscode, isweak, islocal, ishidden, isprotected, isfunc, isobject; j = 0; if ((d->syms.stab = GetElfStringTable(elf->ehdr, elf->size)) && (st = GetElfSymbolTable(elf->ehdr, elf->size, &n))) { stablen = (intptr_t)elf->ehdr + elf->size - (intptr_t)d->syms.stab; if (d->syms.n < n) { d->syms.n = n; d->syms.p = realloc(d->syms.p, d->syms.n * sizeof(*d->syms.p)); CHECK_NOTNULL(d->syms.p); } for (i = 0; i < n; ++i) { if (ELF64_ST_TYPE(st[i].st_info) == STT_SECTION || ELF64_ST_TYPE(st[i].st_info) == STT_FILE || !st[i].st_name || _startswith(d->syms.stab + st[i].st_name, "v_") || !(0 <= st[i].st_name && st[i].st_name < stablen) || !st[i].st_value || !IsLegalPointer(st[i].st_value)) { continue; } isabs = st[i].st_shndx == SHN_ABS; isweak = ELF64_ST_BIND(st[i].st_info) == STB_WEAK; islocal = ELF64_ST_BIND(st[i].st_info) == STB_LOCAL; ishidden = st[i].st_other == STV_HIDDEN; isprotected = st[i].st_other == STV_PROTECTED; isfunc = ELF64_ST_TYPE(st[i].st_info) == STT_FUNC; isobject = ELF64_ST_TYPE(st[i].st_info) == STT_OBJECT; d->syms.p[j].unique = i; d->syms.p[j].size = st[i].st_size; d->syms.p[j].name = st[i].st_name; CHECK_GE(st[i].st_value, 0); d->syms.p[j].addr = st[i].st_value; d->syms.p[j].rank = -islocal + -isweak + -isabs + isprotected + isobject + isfunc; d->syms.p[j].iscode = DisIsText(d, st[i].st_value) ? !isobject : isfunc; d->syms.p[j].isabs = isabs; ++j; } } d->syms.i = j; } static void DisSortSyms(struct Dis *d) { size_t i, j; qsort(d->syms.p, d->syms.i, sizeof(struct DisSym), (void *)DisSymCompare); for (i = 0; i < d->syms.i; ++i) { if (!strcmp("_end", d->syms.stab + d->syms.p[i].name)) { d->syms.i = i; break; } } } static void DisCanonizeSyms(struct Dis *d) { int64_t i, j, a; if (d->syms.i) { i = 1; j = 1; a = d->syms.p[0].addr; do { if (d->syms.p[j].addr > a) { a = d->syms.p[j].addr; if (j > i) { d->syms.p[i] = d->syms.p[j]; } ++i; } ++j; } while (j < d->syms.i); d->syms.p = realloc(d->syms.p, sizeof(*d->syms.p) * i); d->syms.i = i; d->syms.n = i; } for (i = 0; i < d->syms.i; ++i) { DEBUGF("%012lx-%012lx %s", d->syms.p[i].addr, d->syms.p[i].addr + (d->syms.p[i].size ? d->syms.p[i].size - 1 : 0), d->syms.stab + d->syms.p[i].name); } } bool DisIsProg(struct Dis *d, int64_t addr) { long i; if (g_disisprog_disable) return true; for (i = 0; i < d->loads.i; ++i) { if (addr >= d->loads.p[i].addr && addr < d->loads.p[i].addr + d->loads.p[i].size) { return true; } } return false; } bool DisIsText(struct Dis *d, int64_t addr) { long i; for (i = 0; i < d->loads.i; ++i) { if (addr >= d->loads.p[i].addr && addr < d->loads.p[i].addr + d->loads.p[i].size) { return d->loads.p[i].istext; } } return false; } long DisFindSym(struct Dis *d, int64_t addr) { long l, r, m, n; if (DisIsProg(d, addr)) { l = 0; r = d->syms.i; while (l < r) { m = (l + r) >> 1; if (d->syms.p[m].addr > addr) { r = m; } else { l = m + 1; } } // TODO(jart): This was <256 but that broke SectorLISP debugging // Why did the Cosmo binbase bootloader need this? if (r && d->syms.p[r - 1].addr < 32) { return -1; } if (r && (addr == d->syms.p[r - 1].addr || (addr > d->syms.p[r - 1].addr && (addr <= d->syms.p[r - 1].addr + d->syms.p[r - 1].size || !d->syms.p[r - 1].size)))) { return r - 1; } } return -1; } long DisFindSymByName(struct Dis *d, const char *s) { long i; for (i = 0; i < d->syms.i; ++i) { if (strcmp(s, d->syms.stab + d->syms.p[i].name) == 0) { return i; } } return -1; } void DisLoadElf(struct Dis *d, struct Elf *elf) { if (!elf || !elf->ehdr) return; DisLoadElfLoads(d, elf); DisLoadElfSyms(d, elf); DisSortSyms(d); /* DisCanonizeSyms(d); */ }
7,556
221
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stack.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/log/check.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "tool/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/stack.h" #include "tool/build/lib/throw.h" static const uint8_t kStackOsz[2][3] = { [0][XED_MODE_REAL] = 2, [0][XED_MODE_LEGACY] = 4, [0][XED_MODE_LONG] = 8, [1][XED_MODE_REAL] = 4, [1][XED_MODE_LEGACY] = 2, [1][XED_MODE_LONG] = 2, }; static const uint8_t kCallOsz[2][3] = { [0][XED_MODE_REAL] = 2, [0][XED_MODE_LEGACY] = 4, [0][XED_MODE_LONG] = 8, [1][XED_MODE_REAL] = 4, [1][XED_MODE_LEGACY] = 2, [1][XED_MODE_LONG] = 8, }; static void WriteStackWord(uint8_t *p, uint32_t rde, uint32_t osz, uint64_t x) { if (osz == 8) { Write64(p, x); } else if (osz == 2) { Write16(p, x); } else { Write32(p, x); } } static uint64_t ReadStackWord(uint8_t *p, uint32_t osz) { if (osz == 8) { return Read64(p); } else if (osz == 2) { return Read16(p); } else { return Read32(p); } } static void PushN(struct Machine *m, uint32_t rde, uint64_t x, unsigned osz) { uint64_t v; void *p[2]; uint8_t b[8]; switch (Eamode(rde)) { case XED_MODE_REAL: v = (Read32(m->sp) - osz) & 0xffff; Write16(m->sp, v); v += Read64(m->ss); break; case XED_MODE_LEGACY: v = (Read32(m->sp) - osz) & 0xffffffff; Write64(m->sp, v); v += Read64(m->ss); break; case XED_MODE_LONG: v = (Read64(m->sp) - osz) & 0xffffffffffffffff; Write64(m->sp, v); break; default: unreachable; } WriteStackWord(AccessRam(m, v, osz, p, b, false), rde, osz, x); EndStore(m, v, osz, p, b); } void Push(struct Machine *m, uint32_t rde, uint64_t x) { PushN(m, rde, x, kStackOsz[m->xedd->op.osz][Mode(rde)]); } void OpPushZvq(struct Machine *m, uint32_t rde) { unsigned osz; osz = kStackOsz[m->xedd->op.osz][Mode(rde)]; PushN(m, rde, ReadStackWord(RegRexbSrm(m, rde), osz), osz); } static uint64_t PopN(struct Machine *m, uint32_t rde, uint16_t extra, unsigned osz) { uint64_t v; void *p[2]; uint8_t b[8]; switch (Eamode(rde)) { case XED_MODE_LONG: v = Read64(m->sp); Write64(m->sp, v + osz + extra); break; case XED_MODE_LEGACY: v = Read32(m->sp); Write64(m->sp, (v + osz + extra) & 0xffffffff); v += Read64(m->ss); break; case XED_MODE_REAL: v = Read32(m->sp); Write16(m->sp, v + osz + extra); v += Read64(m->ss); break; default: unreachable; } return ReadStackWord(AccessRam(m, v, osz, p, b, true), osz); } uint64_t Pop(struct Machine *m, uint32_t rde, uint16_t extra) { return PopN(m, rde, extra, kStackOsz[m->xedd->op.osz][Mode(rde)]); } void OpPopZvq(struct Machine *m, uint32_t rde) { uint64_t x; unsigned osz; osz = kStackOsz[m->xedd->op.osz][Mode(rde)]; x = PopN(m, rde, 0, osz); switch (osz) { case 8: case 4: Write64(RegRexbSrm(m, rde), x); break; case 2: Write16(RegRexbSrm(m, rde), x); break; default: unreachable; } } static void OpCall(struct Machine *m, uint32_t rde, uint64_t func) { if (!func) { /* * call null is technically possible but too fringe and disastrous * to accommodate at least until our debugger has rewind capability */ HaltMachine(m, kMachineProtectionFault); } Push(m, rde, m->ip); m->ip = func; } void OpCallJvds(struct Machine *m, uint32_t rde) { OpCall(m, rde, m->ip + m->xedd->op.disp); } static uint64_t LoadAddressFromMemory(struct Machine *m, uint32_t rde) { unsigned osz; osz = kCallOsz[m->xedd->op.osz][Mode(rde)]; return ReadStackWord(GetModrmRegisterWordPointerRead(m, rde, osz), osz); } void OpCallEq(struct Machine *m, uint32_t rde) { OpCall(m, rde, LoadAddressFromMemory(m, rde)); } void OpJmpEq(struct Machine *m, uint32_t rde) { m->ip = LoadAddressFromMemory(m, rde); } void OpLeave(struct Machine *m, uint32_t rde) { switch (Eamode(rde)) { case XED_MODE_LONG: Write64(m->sp, Read64(m->bp)); Write64(m->bp, Pop(m, rde, 0)); break; case XED_MODE_LEGACY: Write64(m->sp, Read32(m->bp)); Write64(m->bp, Pop(m, rde, 0)); break; case XED_MODE_REAL: Write16(m->sp, Read16(m->bp)); Write16(m->bp, Pop(m, rde, 0)); break; default: unreachable; } } void OpRet(struct Machine *m, uint32_t rde) { m->ip = Pop(m, rde, m->xedd->op.uimm0); } void OpPushEvq(struct Machine *m, uint32_t rde) { unsigned osz; osz = kStackOsz[m->xedd->op.osz][Mode(rde)]; Push(m, rde, ReadStackWord(GetModrmRegisterWordPointerRead(m, rde, osz), osz)); } void OpPopEvq(struct Machine *m, uint32_t rde) { unsigned osz; osz = kStackOsz[m->xedd->op.osz][Mode(rde)]; WriteStackWord(GetModrmRegisterWordPointerWrite(m, rde, osz), rde, osz, Pop(m, rde, 0)); } static relegated void Pushaw(struct Machine *m, uint32_t rde) { uint16_t v; uint8_t b[8][2]; memcpy(b[0], m->di, 2); memcpy(b[1], m->si, 2); memcpy(b[2], m->bp, 2); memcpy(b[3], m->sp, 2); memcpy(b[4], m->bx, 2); memcpy(b[5], m->dx, 2); memcpy(b[6], m->cx, 2); memcpy(b[7], m->ax, 2); Write16(m->sp, (v = (Read16(m->sp) - sizeof(b)) & 0xffff)); VirtualRecv(m, Read64(m->ss) + v, b, sizeof(b)); } static relegated void Pushad(struct Machine *m, uint32_t rde) { uint32_t v; uint8_t b[8][4]; memcpy(b[0], m->di, 4); memcpy(b[1], m->si, 4); memcpy(b[2], m->bp, 4); memcpy(b[3], m->sp, 4); memcpy(b[4], m->bx, 4); memcpy(b[5], m->dx, 4); memcpy(b[6], m->cx, 4); memcpy(b[7], m->ax, 4); Write64(m->sp, (v = (Read32(m->sp) - sizeof(b)) & 0xffffffff)); VirtualRecv(m, Read64(m->ss) + v, b, sizeof(b)); } static relegated void Popaw(struct Machine *m, uint32_t rde) { uint8_t b[8][2]; VirtualSend(m, b, Read64(m->ss) + Read16(m->sp), sizeof(b)); Write16(m->sp, (Read32(m->sp) + sizeof(b)) & 0xffff); memcpy(m->di, b[0], 2); memcpy(m->si, b[1], 2); memcpy(m->bp, b[2], 2); memcpy(m->sp, b[3], 2); memcpy(m->bx, b[4], 2); memcpy(m->dx, b[5], 2); memcpy(m->cx, b[6], 2); memcpy(m->ax, b[7], 2); } static relegated void Popad(struct Machine *m, uint32_t rde) { uint8_t b[8][4]; VirtualSend(m, b, Read64(m->ss) + Read32(m->sp), sizeof(b)); Write64(m->sp, (Read32(m->sp) + sizeof(b)) & 0xffffffff); memcpy(m->di, b[0], 4); memcpy(m->si, b[1], 4); memcpy(m->bp, b[2], 4); memcpy(m->sp, b[3], 4); memcpy(m->bx, b[4], 4); memcpy(m->dx, b[5], 4); memcpy(m->cx, b[6], 4); memcpy(m->ax, b[7], 4); } relegated void OpPusha(struct Machine *m, uint32_t rde) { switch (Eamode(rde)) { case XED_MODE_REAL: Pushaw(m, rde); break; case XED_MODE_LEGACY: Pushad(m, rde); break; case XED_MODE_LONG: OpUd(m, rde); default: unreachable; } } relegated void OpPopa(struct Machine *m, uint32_t rde) { switch (Eamode(rde)) { case XED_MODE_REAL: Popaw(m, rde); break; case XED_MODE_LEGACY: Popad(m, rde); break; case XED_MODE_LONG: OpUd(m, rde); default: unreachable; } } relegated void OpCallf(struct Machine *m, uint32_t rde) { Push(m, rde, Read64(m->cs) >> 4); Push(m, rde, m->ip); Write64(m->cs, m->xedd->op.uimm0 << 4); m->ip = m->xedd->op.disp & (Osz(rde) ? 0xffff : 0xffffffff); if (m->onlongbranch) { m->onlongbranch(m); } } relegated void OpRetf(struct Machine *m, uint32_t rde) { m->ip = Pop(m, rde, 0); Write64(m->cs, Pop(m, rde, m->xedd->op.uimm0) << 4); if (m->onlongbranch) { m->onlongbranch(m); } }
9,533
315
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/demangle.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_DEMANGLE_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_DEMANGLE_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ char *Demangle(char *, const char *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_DEMANGLE_H_ */
324
11
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/getargs.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/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.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/sysv/errfuns.h" #include "tool/build/lib/getargs.h" /** * @fileoverview Fast Command Line Argument Ingestion. * * The purpose of this library is to be able to have build commands with * huge argument lists. The way we do that is by replacing commands like * * foo.com lots of args * * with this * * echo of args >args * foo.com lots @args * * This iterator abstracts the process of reading the special `@` * prefixed args. In order to do that quickly and easily, we make the * following assumptions: * * 1. Arguments don't have whitespace. * 2. Files have a trailing whitespace. * * We need (1) so GNU Make can go faster. Assume we tokenized based on * newlines. We would would write that in our Makefile as follows: * * # don't do this * target: thousands of args * $(file >[email protected]) $(foreach x,$^,$(file >>[email protected],$(x))) * tool.com -o $@ @[email protected] * * That is slow because it needs to open and close the args file * thousands of times. If we trade away filenames with spaces then the * following will only require a couple system calls: * * # do this * target: thousands of args * $(file >[email protected],$^) * tool.com -o $@ @[email protected] * * We need (2) because it make the code in this file simpler and avoids * a malloc() dependency. Having that trailing character means argument * parsing from files can be a zero-copy operation. */ #define IsSpace(c) ((255 & (c)) <= ' ') /** * Zeroes GetArgs object and sets its fields. * @param args is borrowed for the lifetime of the GetArgs object */ void getargs_init(struct GetArgs *ga, char **args) { assert(args); bzero(ga, sizeof(*ga)); ga->args = args; } /** * Releases memory associated with GetArgs object and zeroes it. */ void getargs_destroy(struct GetArgs *ga) { if (ga->map) munmap(ga->map, ga->mapsize); bzero(ga, sizeof(*ga)); } /** * Gets next argument, e.g. * * const char *s; * while ((s = getargs_next(&ga))) { * printf("%s\n", s); * } * * @return NUL-terminated string; it should not be freed; it should be * assumed that it stays in scope until the next getargs_next call */ const char *getargs_next(struct GetArgs *ga) { int fd; char *p; size_t k; unsigned m; struct stat st; do { if (ga->map) { for (; ga->j < ga->mapsize; ++ga->j) { if (!IsSpace(ga->map[ga->j])) { break; } } k = 0; #if defined(__SSE2__) && defined(__GNUC__) && !defined(__STRICT_ANSI__) typedef unsigned char xmm_t __attribute__((__vector_size__(16), __aligned__(1))); for (; ga->j + k + 16 <= ga->mapsize; k += 16) { if ((m = __builtin_ia32_pmovmskb128( *(const xmm_t *)(ga->map + ga->j + k) > (xmm_t){' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}) ^ 0xffff)) { k += __builtin_ctzl(m); break; } } #endif for (; ga->j + k < ga->mapsize; ++k) { if (IsSpace(ga->map[ga->j + k])) { break; } } if (k) { if (ga->j + k < ga->mapsize) { ga->map[ga->j + k] = 0; p = ga->map + ga->j; ga->j += ++k; return p; } else { eio(); break; } } if (munmap(ga->map, ga->mapsize) == -1) break; ga->map = 0; ga->mapsize = 0; ga->j = 0; } if (!(p = ga->args[ga->i])) return 0; ++ga->i; if (*p != '@') return p; ++p; if ((fd = open((ga->path = p), O_RDONLY)) != -1) { fstat(fd, &st); if ((p = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) != MAP_FAILED) { ga->map = p; ga->mapsize = st.st_size; } close(fd); } } while (ga->map); perror(ga->path); exit(1); }
6,060
170
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/xlaterrno.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/errno.h" #include "libc/mem/mem.h" struct thatispacked LinuxErrno { int32_t local; uint8_t linux; }; extern const struct LinuxErrno kLinuxErrnos[]; /** * Turns local errno into Linux errno. */ int XlatErrno(int local) { int i; for (i = 0; kLinuxErrnos[i].local; ++i) { if (local == *(int *)((intptr_t)kLinuxErrnos + kLinuxErrnos[i].local)) { return kLinuxErrnos[i].linux; } } return ENOSYS; }
2,275
41
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/elfwriter_yoink.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 "tool/build/lib/elfwriter.h" void elfwriter_yoink(struct ElfWriter *elf, const char *symbol, int stb) { unsigned char *p; struct ElfWriterSymRef sym; const unsigned char kNopl[8] = "\017\037\004\045\000\000\000\000"; p = elfwriter_reserve(elf, 8); memcpy(p, kNopl, sizeof(kNopl)); sym = elfwriter_linksym(elf, symbol, ELF64_ST_INFO(stb, STT_OBJECT), STV_HIDDEN); elfwriter_appendrela(elf, sizeof(kNopl) - 4, sym, elfwriter_relatype_abs32(elf), 0); elfwriter_commit(elf, sizeof(kNopl)); }
2,425
34
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/eztls.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_EZTLS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_EZTLS_H_ #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/x509_crt.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct EzTlsBio { int fd, c; unsigned a, b; unsigned char t[4000]; unsigned char u[1430]; }; extern struct EzTlsBio ezbio; extern mbedtls_ssl_config ezconf; extern mbedtls_ssl_context ezssl; extern mbedtls_ctr_drbg_context ezrng; void EzFd(int); void EzHandshake(void); int EzHandshake2(void); void EzSetup(char[32]); void EzInitialize(void); int EzTlsFlush(struct EzTlsBio *, const unsigned char *, size_t); /* * openssl s_client -connect 127.0.0.1:31337 \ * -psk $(hex <~/.runit.psk) \ * -psk_identity runit */ forceinline void SetupPresharedKeySsl(int endpoint, char psk[32]) { EzInitialize(); mbedtls_ssl_config_defaults(&ezconf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_SUITEC); EzSetup(psk); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_EZTLS_H_ */
1,177
43
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/lines.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 "tool/build/lib/lines.h" struct Lines *NewLines(void) { return calloc(1, sizeof(struct Lines)); } void FreeLines(struct Lines *lines) { size_t i; for (i = 0; i < lines->n; ++i) { free(lines->p[i]); } free(lines); } void AppendLine(struct Lines *lines, const char *s, size_t n) { lines->p = realloc(lines->p, ++lines->n * sizeof(*lines->p)); lines->p[lines->n - 1] = strndup(s, n); } void AppendLines(struct Lines *lines, const char *s) { const char *p; for (;;) { p = strchr(s, '\n'); if (p) { AppendLine(lines, s, p - s); s = p + 1; } else { if (*s) { AppendLine(lines, s, -1); } break; } } }
2,573
55
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/xmmtype.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 "tool/build/lib/modrm.h" #include "tool/build/lib/xmmtype.h" static void UpdateXmmTypes(struct Machine *m, struct XmmType *xt, int regtype, int rmtype) { xt->type[RexrReg(m->xedd->op.rde)] = regtype; if (IsModrmRegister(m->xedd->op.rde)) { xt->type[RexbRm(m->xedd->op.rde)] = rmtype; } } static void UpdateXmmSizes(struct Machine *m, struct XmmType *xt, int regsize, int rmsize) { xt->size[RexrReg(m->xedd->op.rde)] = regsize; if (IsModrmRegister(m->xedd->op.rde)) { xt->size[RexbRm(m->xedd->op.rde)] = rmsize; } } void UpdateXmmType(struct Machine *m, struct XmmType *xt) { switch (m->xedd->op.dispatch) { case 0x110: case 0x111: // MOVSS,MOVSD if (Rep(m->xedd->op.rde) == 3) { UpdateXmmTypes(m, xt, kXmmFloat, kXmmFloat); } else if (Rep(m->xedd->op.rde) == 2) { UpdateXmmTypes(m, xt, kXmmDouble, kXmmDouble); } break; case 0x12E: // UCOMIS case 0x12F: // COMIS case 0x151: // SQRT case 0x152: // RSQRT case 0x153: // RCP case 0x158: // ADD case 0x159: // MUL case 0x15C: // SUB case 0x15D: // MIN case 0x15E: // DIV case 0x15F: // MAX case 0x1C2: // CMP if (Osz(m->xedd->op.rde) || Rep(m->xedd->op.rde) == 2) { UpdateXmmTypes(m, xt, kXmmDouble, kXmmDouble); } else { UpdateXmmTypes(m, xt, kXmmFloat, kXmmFloat); } break; case 0x12A: // CVTPI2PS,CVTSI2SS,CVTPI2PD,CVTSI2SD if (Osz(m->xedd->op.rde) || Rep(m->xedd->op.rde) == 2) { UpdateXmmSizes(m, xt, 8, 4); UpdateXmmTypes(m, xt, kXmmDouble, kXmmIntegral); } else { UpdateXmmSizes(m, xt, 4, 4); UpdateXmmTypes(m, xt, kXmmFloat, kXmmIntegral); } break; case 0x15A: // CVT{P,S}{S,D}2{P,S}{S,D} if (Osz(m->xedd->op.rde) || Rep(m->xedd->op.rde) == 2) { UpdateXmmTypes(m, xt, kXmmFloat, kXmmDouble); } else { UpdateXmmTypes(m, xt, kXmmDouble, kXmmFloat); } break; case 0x15B: // CVT{,T}{DQ,PS}2{PS,DQ} UpdateXmmSizes(m, xt, 4, 4); if (Osz(m->xedd->op.rde) || Rep(m->xedd->op.rde) == 3) { UpdateXmmTypes(m, xt, kXmmIntegral, kXmmFloat); } else { UpdateXmmTypes(m, xt, kXmmFloat, kXmmIntegral); } break; case 0x17C: // HADD case 0x17D: // HSUB case 0x1D0: // ADDSUB if (Osz(m->xedd->op.rde)) { UpdateXmmTypes(m, xt, kXmmDouble, kXmmDouble); } else { UpdateXmmTypes(m, xt, kXmmFloat, kXmmFloat); } break; case 0x164: // PCMPGTB case 0x174: // PCMPEQB case 0x1D8: // PSUBUSB case 0x1DA: // PMINUB case 0x1DC: // PADDUSB case 0x1DE: // PMAXUB case 0x1E0: // PAVGB case 0x1E8: // PSUBSB case 0x1EC: // PADDSB case 0x1F8: // PSUBB case 0x1FC: // PADDB UpdateXmmSizes(m, xt, 1, 1); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x165: // PCMPGTW case 0x175: // PCMPEQW case 0x171: // PSRLW,PSRAW,PSLLW case 0x1D1: // PSRLW case 0x1D5: // PMULLW case 0x1D9: // PSUBUSW case 0x1DD: // PADDUSW case 0x1E1: // PSRAW case 0x1E3: // PAVGW case 0x1E4: // PMULHUW case 0x1E5: // PMULHW case 0x1E9: // PSUBSW case 0x1EA: // PMINSW case 0x1ED: // PADDSW case 0x1EE: // PMAXSW case 0x1F1: // PSLLW case 0x1F6: // PSADBW case 0x1F9: // PSUBW case 0x1FD: // PADDW UpdateXmmSizes(m, xt, 2, 2); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x166: // PCMPGTD case 0x176: // PCMPEQD case 0x172: // PSRLD,PSRAD,PSLLD case 0x1D2: // PSRLD case 0x1E2: // PSRAD case 0x1F2: // PSLLD case 0x1FA: // PSUBD case 0x1FE: // PADDD UpdateXmmSizes(m, xt, 4, 4); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x173: // PSRLQ,PSRLQ,PSRLDQ,PSLLQ,PSLLDQ case 0x1D3: // PSRLQ case 0x1D4: // PADDQ case 0x1F3: // PSLLQ case 0x1F4: // PMULUDQ case 0x1FB: // PSUBQ UpdateXmmSizes(m, xt, 8, 8); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x16B: // PACKSSDW case 0x1F5: // PMADDWD UpdateXmmSizes(m, xt, 4, 2); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x163: // PACKSSWB case 0x167: // PACKUSWB UpdateXmmSizes(m, xt, 1, 2); UpdateXmmTypes(m, xt, kXmmIntegral, kXmmIntegral); break; case 0x128: // MOVAPS Vps Wps if (IsModrmRegister(m->xedd->op.rde)) { xt->type[RexrReg(m->xedd->op.rde)] = xt->type[RexbRm(m->xedd->op.rde)]; xt->size[RexrReg(m->xedd->op.rde)] = xt->size[RexbRm(m->xedd->op.rde)]; } break; case 0x129: // MOVAPS Wps Vps if (IsModrmRegister(m->xedd->op.rde)) { xt->type[RexbRm(m->xedd->op.rde)] = xt->type[RexrReg(m->xedd->op.rde)]; xt->size[RexbRm(m->xedd->op.rde)] = xt->size[RexrReg(m->xedd->op.rde)]; } break; case 0x16F: // MOVDQA Vdq Wdq if (Osz(m->xedd->op.rde) && IsModrmRegister(m->xedd->op.rde)) { xt->type[RexrReg(m->xedd->op.rde)] = xt->type[RexbRm(m->xedd->op.rde)]; xt->size[RexrReg(m->xedd->op.rde)] = xt->size[RexbRm(m->xedd->op.rde)]; } break; default: return; } }
7,251
187
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/buildlib.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 += TOOL_BUILD_LIB TOOL_BUILD_LIB_ARTIFACTS += TOOL_BUILD_LIB_A TOOL_BUILD_LIB = $(TOOL_BUILD_LIB_A_DEPS) $(TOOL_BUILD_LIB_A) TOOL_BUILD_LIB_A = o/$(MODE)/tool/build/lib/buildlib.a TOOL_BUILD_LIB_A_FILES := $(wildcard tool/build/lib/*) TOOL_BUILD_LIB_A_HDRS = $(filter %.h,$(TOOL_BUILD_LIB_A_FILES)) TOOL_BUILD_LIB_A_SRCS_S = $(filter %.S,$(TOOL_BUILD_LIB_A_FILES)) TOOL_BUILD_LIB_A_SRCS_C = \ $(filter-out tool/build/lib/apetest.c,$(filter %.c,$(TOOL_BUILD_LIB_A_FILES))) TOOL_BUILD_LIB_A_CHECKS = \ $(TOOL_BUILD_LIB_A_HDRS:%=o/$(MODE)/%.ok) \ $(TOOL_BUILD_LIB_A).pkg TOOL_BUILD_LIB_A_SRCS = \ $(TOOL_BUILD_LIB_A_SRCS_S) \ $(TOOL_BUILD_LIB_A_SRCS_C) TOOL_BUILD_LIB_COMS = \ o/$(MODE)/tool/build/lib/apetest.com \ o/$(MODE)/tool/build/lib/apetest2.com TOOL_BUILD_LIB_A_OBJS = \ $(TOOL_BUILD_LIB_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(TOOL_BUILD_LIB_A_SRCS_C:%.c=o/$(MODE)/%.o) \ o/$(MODE)/tool/build/lib/apetest.com.zip.o \ o/$(MODE)/tool/build/lib/apetest2.com.zip.o TOOL_BUILD_LIB_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_ELF \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_X \ NET_HTTP \ NET_HTTPS \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_MBEDTLS \ THIRD_PARTY_XED \ THIRD_PARTY_ZLIB TOOL_BUILD_LIB_A_DEPS := \ $(call uniq,$(foreach x,$(TOOL_BUILD_LIB_A_DIRECTDEPS),$($(x)))) $(TOOL_BUILD_LIB_A): \ tool/build/lib/ \ $(TOOL_BUILD_LIB_A).pkg \ $(TOOL_BUILD_LIB_A_OBJS) $(TOOL_BUILD_LIB_A).pkg: \ $(TOOL_BUILD_LIB_A_OBJS) \ $(foreach x,$(TOOL_BUILD_LIB_A_DIRECTDEPS),$($(x)_A).pkg) ifeq ($(ARCH), x86_64) o/$(MODE)/tool/build/lib/ssefloat.o: private \ TARGET_ARCH += \ -msse3 endif o/$(MODE)/tool/build/lib/apetest.com.dbg: \ $(TOOL_BUILD_LIB_A_DEPS) \ o/$(MODE)/tool/build/lib/apetest.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/build/lib/apetest2.com.dbg: \ $(TOOL_BUILD_LIB_A_DEPS) \ o/$(MODE)/tool/build/lib/apetest.o \ $(CRT) \ $(APE_COPY_SELF) @$(APELINK) o/$(MODE)/tool/build/lib/apetest.com.zip.o \ o/$(MODE)/tool/build/lib/apetest2.com.zip.o: private \ ZIPOBJ_FLAGS += \ -B o/$(MODE)/tool/build/lib/apetest.o: \ tool/build/lib/apetest.c \ libc/calls/calls.h # these assembly files are safe to build on aarch64 o/$(MODE)/tool/build/lib/errnos.o: tool/build/lib/errnos.S @$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $< TOOL_BUILD_LIB_LIBS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x))) TOOL_BUILD_LIB_SRCS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_SRCS)) TOOL_BUILD_LIB_HDRS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_HDRS)) TOOL_BUILD_LIB_BINS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_BINS)) TOOL_BUILD_LIB_CHECKS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_CHECKS)) TOOL_BUILD_LIB_OBJS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_OBJS)) TOOL_BUILD_LIB_TESTS = $(foreach x,$(TOOL_BUILD_LIB_ARTIFACTS),$($(x)_TESTS)) .PHONY: o/$(MODE)/tool/build/lib o/$(MODE)/tool/build/lib: \ $(TOOL_BUILD_LIB_COMS) \ $(TOOL_BUILD_LIB_CHECKS) \ $(TOOL_BUILD_LIB_A)
3,521
117
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/bitscan.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 "tool/build/lib/bitscan.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/modrm.h" uint64_t AluPopcnt(struct Machine *m, uint32_t rde, uint64_t x) { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_SF, false); m->flags = SetFlag(m->flags, FLAGS_OF, false); m->flags = SetFlag(m->flags, FLAGS_PF, false); x = x - ((x >> 1) & 0x5555555555555555); x = ((x >> 2) & 0x3333333333333333) + (x & 0x3333333333333333); x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f; x = (x + (x >> 32)) & 0xffffffff; x = x + (x >> 16); x = (x + (x >> 8)) & 0x7f; return x; } uint64_t AluBsr(struct Machine *m, uint32_t rde, uint64_t x) { unsigned i; if (Rexw(rde)) { x &= 0xffffffffffffffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 64; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x == 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } return 63 ^ __builtin_clzll(x); } else if (!Osz(rde)) { x &= 0xffffffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 32; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x == 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } return 31 ^ __builtin_clz(x); } else { x &= 0xffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 16; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x == 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } for (i = 15; !(x & 0x8000); --i) x <<= 1; return i; } } uint64_t AluBsf(struct Machine *m, uint32_t rde, uint64_t x) { unsigned i; if (Rexw(rde)) { x &= 0xffffffffffffffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 64; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x & 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } return __builtin_ctzll(x); } else if (!Osz(rde)) { x &= 0xffffffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 32; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x & 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } return __builtin_ctz(x); } else { x &= 0xffff; if (Rep(rde) == 3) { if (!x) { m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_ZF, false); return 16; } else { m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, x & 1); } } else { m->flags = SetFlag(m->flags, FLAGS_ZF, !x); if (!x) return 0; } for (i = 0; !(x & 1); ++i) x >>= 1; return i; } }
5,568
146
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/asmdown.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ASMDOWN_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ASMDOWN_H_ #include "tool/build/lib/javadown.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Asmdown { struct AsmdownSymbols { size_t n; struct AsmdownSymbol { int line; char *name; bool is_alias; struct Javadown *javadown; } * p; } symbols; }; struct Asmdown *ParseAsmdown(const char *, size_t); void FreeAsmdown(struct Asmdown *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ASMDOWN_H_ */
600
25
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ioports.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/nexgen32e/uart.internal.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/poll.h" #include "tool/build/lib/ioports.h" static int OpE9Read(struct Machine *m) { int fd; uint8_t b; fd = STDIN_FILENO; if (fd >= m->fds.i) return -1; if (!m->fds.p[fd].cb) return -1; if (m->fds.p[fd].cb->readv(m->fds.p[fd].fd, &(struct iovec){&b, 1}, 1) == 1) { return b; } else { return -1; } } static void OpE9Write(struct Machine *m, uint8_t b) { int fd; fd = STDOUT_FILENO; if (fd >= m->fds.i) return; if (!m->fds.p[fd].cb) return; m->fds.p[fd].cb->writev(m->fds.p[fd].fd, &(struct iovec){&b, 1}, 1); } static int OpE9Poll(struct Machine *m) { int fd, rc; struct pollfd pf; fd = STDIN_FILENO; if (fd >= m->fds.i) return -1; if (!m->fds.p[fd].cb) return -1; pf.fd = m->fds.p[fd].fd; pf.events = POLLIN | POLLOUT; rc = m->fds.p[fd].cb->poll(&pf, 1, 20); if (rc <= 0) return rc; return pf.revents; } static int OpSerialIn(struct Machine *m, int r) { int p, s; switch (r) { case UART_DLL: if (!m->dlab) { return OpE9Read(m); } else { return 0x01; } case UART_LSR: if ((p = OpE9Poll(m)) == -1) return -1; s = UART_TTYIDL; if (p & POLLIN) s |= UART_TTYDA; if (p & POLLOUT) s |= UART_TTYTXR; return s; default: return 0; } } static void OpSerialOut(struct Machine *m, int r, uint32_t x) { switch (r) { case UART_DLL: if (!m->dlab) { return OpE9Write(m, x); } break; case UART_LCR: m->dlab = !!(x & UART_DLAB); break; default: break; } } uint64_t OpIn(struct Machine *m, uint16_t p) { switch (p) { case 0xE9: return OpE9Read(m); case 0x3F8 ... 0x3FF: return OpSerialIn(m, p - 0x3F8); default: return -1; } } void OpOut(struct Machine *m, uint16_t p, uint32_t x) { switch (p) { case 0xE9: OpE9Write(m, x); break; case 0x3F8 ... 0x3FF: OpSerialOut(m, p - 0x3F8, x); break; default: break; } }
3,922
116
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/time.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_TIME_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_TIME_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpPause(struct Machine *, uint32_t); void OpRdtsc(struct Machine *, uint32_t); void OpRdtscp(struct Machine *, uint32_t); void OpRdpid(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_TIME_H_ */
471
15
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/word.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_WORD_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_WORD_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void SetMemoryShort(struct Machine *, int64_t, int16_t); void SetMemoryInt(struct Machine *, int64_t, int32_t); void SetMemoryLong(struct Machine *, int64_t, int64_t); void SetMemoryFloat(struct Machine *, int64_t, float); void SetMemoryDouble(struct Machine *, int64_t, double); void SetMemoryLdbl(struct Machine *, int64_t, long double); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_WORD_H_ */
642
17
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/instruction.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/bsf.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "third_party/xed/x86.h" #include "tool/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/stats.h" #include "tool/build/lib/throw.h" static bool IsOpcodeEqual(struct XedDecodedInst *xedd, uint8_t *a) { uint64_t w; if (xedd->length) { if (xedd->length <= 7) { w = Read64(a) ^ Read64(xedd->bytes); return !w || _bsfl(w) >= (xedd->length << 3); } else { return memcmp(a, xedd->bytes, xedd->length) == 0; } } else { return false; } } static void DecodeInstruction(struct Machine *m, uint8_t *p, unsigned n) { struct XedDecodedInst xedd[1]; xed_decoded_inst_zero_set_mode(xedd, m->mode); if (!xed_instruction_length_decode(xedd, p, n)) { xedd->op.rde = EncodeRde(xedd); memcpy(m->xedd, xedd, sizeof(m->icache[0])); } else { HaltMachine(m, kMachineDecodeError); } } static dontinline void LoadInstructionSlow(struct Machine *m, uint64_t ip) { unsigned i; uint8_t *addr; uint8_t copy[15], *toil; i = 0x1000 - (ip & 0xfff); addr = ResolveAddress(m, ip); if ((toil = FindReal(m, ip + i))) { memcpy(copy, addr, i); memcpy(copy + i, toil, 15 - i); DecodeInstruction(m, copy, 15); } else { DecodeInstruction(m, addr, i); } } void LoadInstruction(struct Machine *m) { uint64_t ip; unsigned key; uint8_t *addr; ip = Read64(m->cs) + MaskAddress(m->mode & 3, m->ip); key = ip & (ARRAYLEN(m->icache) - 1); m->xedd = (struct XedDecodedInst *)m->icache[key]; if ((ip & 0xfff) < 0x1000 - 15) { if (ip - (ip & 0xfff) == m->codevirt && m->codehost) { addr = m->codehost + (ip & 0xfff); } else { m->codevirt = ip - (ip & 0xfff); m->codehost = ResolveAddress(m, m->codevirt); addr = m->codehost + (ip & 0xfff); } if (!IsOpcodeEqual(m->xedd, addr)) { DecodeInstruction(m, addr, 15); } } else { LoadInstructionSlow(m, ip); } }
3,942
93
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/high.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_HIGH_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_HIGH_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct High { bool active; uint8_t keyword; uint8_t reg; uint8_t literal; uint8_t label; uint8_t comment; uint8_t quote; }; extern struct High g_high; char *HighStart(char *, int); char *HighEnd(char *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_HIGH_H_ */
486
24
jart/cosmopolitan
false
cosmopolitan/tool/build/emucrt/emucrt.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 += TOOL_BUILD_EMUCRT TOOL_BUILD_EMUCRT = \ o/$(MODE)/tool/build/emucrt/emucrt.o \ o/$(MODE)/tool/build/emucrt/emucrt.lds o/$(MODE)/tool/build/emucrt/emucrt.o: \ tool/build/emucrt/emucrt.S \ libc/macros.internal.h \ libc/intrin/asancodes.h \ ape/relocations.h .PHONY: o/$(MODE)/tool/build/emucrt o/$(MODE)/tool/build/emucrt: \ $(TOOL_BUILD_EMUCRT)
576
19
jart/cosmopolitan
false
cosmopolitan/tool/build/emucrt/real.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ ENTRY(_start) SECTIONS { .text 0x7c00 : { *(.start) *(.text .text.*) *(.rodata .rodata.*) *(.data .data.*) . = 0x1fe; SHORT(0xaa55); *(.bss .bss.*) *(COMMON) } /DISCARD/ : { *(.*) } }
2,068
39
jart/cosmopolitan
false
cosmopolitan/tool/build/emucrt/emucrt.lds
/*-*- mode: ld-script; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-│ │vi: set et sts=2 tw=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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ ENTRY(_start) SECTIONS { .text IMAGE_BASE_VIRTUAL : { *(.start) KEEP(*(.initprologue)) KEEP(*(SORT_BY_NAME(.init.*))) KEEP(*(SORT_NONE(.init))) KEEP(*(.initepilogue)) *(.text .text.*) *(.privileged) *(.rodata .rodata.*) KEEP(*(.initroprologue)) KEEP(*(SORT_BY_NAME(.initro.*))) KEEP(*(.initroepilogue)) *(.ubsan.types) *(.ubsan.data) *(.data .data.*) *(.bss .bss.*) *(COMMON) } .gnu_debuglink 0 : { *(.gnu_debuglink) } .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } .stab.excl 0 : { *(.stab.excl) } .stab.exclstr 0 : { *(.stab.exclstr) } .stab.index 0 : { *(.stab.index) } .stab.indexstr 0 : { *(.stab.indexstr) } .debug 0 : { *(.debug) } .line 0 : { *(.line) } .debug_srcinfo 0 : { *(.debug_srcinfo) } .debug_sfnames 0 : { *(.debug_sfnames) } .debug_aranges 0 : { *(.debug_aranges) } .debug_pubnames 0 : { *(.debug_pubnames) } .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } .debug_abbrev 0 : { *(.debug_abbrev) } .debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end ) } .debug_frame 0 : { *(.debug_frame) } .debug_str 0 : { *(.debug_str) } .debug_loc 0 : { *(.debug_loc) } .debug_macinfo 0 : { *(.debug_macinfo) } .debug_weaknames 0 : { *(.debug_weaknames) } .debug_funcnames 0 : { *(.debug_funcnames) } .debug_typenames 0 : { *(.debug_typenames) } .debug_varnames 0 : { *(.debug_varnames) } .debug_pubtypes 0 : { *(.debug_pubtypes) } .debug_ranges 0 : { *(.debug_ranges) } .debug_macro 0 : { *(.debug_macro) } .debug_addr 0 : { *(.debug_addr) } .gnu.attributes 0 : { KEEP(*(.gnu.attributes)) } /DISCARD/ : { *(.GCC.command.line) *(.comment) *(.discard) *(.yoink) *(.*) } }
3,727
81
jart/cosmopolitan
false
cosmopolitan/tool/build/emucrt/emucrt.S
/*-*- mode:asm; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 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" .section .start,"ax",@progbits emucrt: bofram 9f movslq (%rsp),%rdi # argc lea 8(%rsp),%rsi # argv lea 24(%rsp,%rdi,8),%rdx # envp .weak main call main movzbl %al,%edi mov $0xE7,%eax syscall 9: .endfn emucrt,globl
2,099
32
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/real.h
#ifndef COSMOPOLITAN_TOOL_BUILD_EMUBIN_REAL_H_ #define COSMOPOLITAN_TOOL_BUILD_EMUBIN_REAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline void SetEs(int base) { asm volatile("mov%z0\t%0,%%es" : /* no outputs */ : "r"(base)); } forceinline void SetVideoMode(int mode) { asm volatile("int\t$0x10" : /* no outputs */ : "a"(mode)); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_EMUBIN_REAL_H_ */
514
19
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/realstart.inc
asm(".section .start,\"ax\",@progbits\n\t" ".globl\t_start\n" "_start:\n\t" "jmp\t1f\n1:\t" "call\tmain\n\t" "nop\n\t" ".previous");
157
8
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/linmap.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/linux/exit.h" #include "libc/linux/fstat.h" #include "libc/linux/mmap.h" #include "libc/linux/open.h" struct stat st; void _start(void) { long fd = LinuxOpen("/etc/passwd", 0, 0); LinuxFstat(fd, &st); LinuxMmap((void *)0x000000000000, st.st_size, 1, 2, fd, 0); LinuxExit(0); }
2,138
32
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/prime.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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ dontinline bool IsPrime(int i) { int j, n; for (j = 3, n = VEIL("r", 3); j <= n; j += 2) { if (VEIL("r", i) % VEIL("r", j) == 0) { return false; } } return true; } /** * Places 10th prime number in RAX. */ int main(int argc, char *argv[]) { int i, c; for (c = i = 0; c < VEIL("r", 10); ++i) { if (IsPrime(i)) { ++c; } } return i; }
2,216
42
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/metalsha256.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 "tool/build/emubin/metalsha256.h" #include "libc/intrin/repstosb.h" #define ROTR(a, b) (((a) >> (b)) | ((a) << (32 - (b)))) #define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z))) #define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define EP0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) #define EP1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) #define SIG0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ ((x) >> 3)) #define SIG1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ ((x) >> 10)) const uint32_t kMetalSha256Tab[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, }; void MetalSha256Cleanup(struct MetalSha256Ctx *ctx) { repstosb(ctx, 0, sizeof(*ctx)); asm("pxor\t%xmm0,%xmm0\n\t" "pxor\t%xmm1,%xmm1\n\t" "pxor\t%xmm2,%xmm2\n\t" "pxor\t%xmm3,%xmm3\n\t" "pxor\t%xmm4,%xmm4\n\t" "pxor\t%xmm5,%xmm5\n\t" "pxor\t%xmm6,%xmm6\n\t" "pxor\t%xmm7,%xmm7"); } void MetalSha256Transform(uint32_t state[8], const uint8_t data[64]) { unsigned i; uint32_t a, b, c, d, e, f, g, h, t1, t2, m[64]; for (i = 0; i < 16; ++i, data += 4) { m[i] = (uint32_t)data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; } for (; i < 64; ++i) { m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; } a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; f = state[5]; g = state[6]; h = state[7]; for (i = 0; i < 64; ++i) { t1 = h + EP1(e) + CH(e, f, g) + kMetalSha256Tab[i] + m[i]; t2 = EP0(a) + MAJ(a, b, c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; state[5] += f; state[6] += g; state[7] += h; } void MetalSha256Init(struct MetalSha256Ctx *ctx) { ctx->datalen = 0; ctx->bitlen = 0; ctx->state[0] = 0x6a09e667; ctx->state[1] = 0xbb67ae85; ctx->state[2] = 0x3c6ef372; ctx->state[3] = 0xa54ff53a; ctx->state[4] = 0x510e527f; ctx->state[5] = 0x9b05688c; ctx->state[6] = 0x1f83d9ab; ctx->state[7] = 0x5be0cd19; } void MetalSha256Update(struct MetalSha256Ctx *ctx, const uint8_t *data, long size) { long i; for (i = 0; i < size; ++i) { ctx->data[ctx->datalen] = data[i]; ctx->datalen++; if (ctx->datalen == 64) { MetalSha256Transform(ctx->state, ctx->data); ctx->bitlen += 512; ctx->datalen = 0; } } } void MetalSha256Final(struct MetalSha256Ctx *ctx, uint8_t *hash) { long i; i = ctx->datalen; ctx->data[i++] = 0x80; if (ctx->datalen < 56) { repstosb(ctx->data + i, 0, 56 - i); } else { repstosb(ctx->data + i, 0, 64 - i); MetalSha256Transform(ctx->state, ctx->data); repstosb(ctx->data, 0, 56); } ctx->bitlen += ctx->datalen * 8; ctx->data[63] = ctx->bitlen; ctx->data[62] = ctx->bitlen >> 8; ctx->data[61] = ctx->bitlen >> 16; ctx->data[60] = ctx->bitlen >> 24; ctx->data[59] = ctx->bitlen >> 32; ctx->data[58] = ctx->bitlen >> 40; ctx->data[57] = ctx->bitlen >> 48; ctx->data[56] = ctx->bitlen >> 56; MetalSha256Transform(ctx->state, ctx->data); for (i = 0; i < 4; ++i) { hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0xff; hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0xff; hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0xff; hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0xff; hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0xff; hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0xff; hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0xff; hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0xff; } MetalSha256Cleanup(ctx); }
6,271
155
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/mdatest.real.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 "tool/build/emubin/poke.h" #include "tool/build/emubin/real.h" #include "tool/build/emubin/realstart.inc" /* m=tiny; make -j12 MODE=$m o/$m/tool/build/{tinyemu,emulator}.com \ o/$m/tool/build/emubin/mdatest.bin && o/$m/tool/build/emulator.com \ -rt o/$m/tool/build/emubin/mdatest.bin */ static void MdaTest(uint16_t p[25][80]) { int i, y, x; for (i = 0; i < 256; ++i) { y = i / 16; x = i % 16 * 3; POKE(p[y][x + 0], i << 8 | "0123456789abcdef"[(i & 0xf0) >> 4]); POKE(p[y][x + 1], i << 8 | "0123456789abcdef"[(i & 0x0f) >> 0]); } } int main() { SetVideoMode(7); SetEs(0xb0000 >> 4); MdaTest((void *)0); for (;;) __builtin_ia32_pause(); }
2,518
45
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/emubin.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 += TOOL_BUILD_EMUBIN TOOL_BUILD_EMUBIN_BINS = \ o/$(MODE)/tool/build/emubin/sha256.bin \ o/$(MODE)/tool/build/emubin/sha256.bin.dbg \ o/$(MODE)/tool/build/emubin/mips.bin \ o/$(MODE)/tool/build/emubin/mips.bin.dbg \ o/$(MODE)/tool/build/emubin/prime.bin \ o/$(MODE)/tool/build/emubin/prime.bin.dbg \ o/$(MODE)/tool/build/emubin/pi.bin \ o/$(MODE)/tool/build/emubin/pi.bin.dbg TOOL_BUILD_EMUBIN_A = o/$(MODE)/tool/build/emubin/emubin.a TOOL_BUILD_EMUBIN_FILES := $(wildcard tool/build/emubin/*) TOOL_BUILD_EMUBIN_SRCS = $(filter %.c,$(TOOL_BUILD_EMUBIN_FILES)) TOOL_BUILD_EMUBIN_HDRS = $(filter %.h,$(TOOL_BUILD_EMUBIN_FILES)) TOOL_BUILD_EMUBIN_OBJS = \ $(TOOL_BUILD_EMUBIN_SRCS:%.c=o/$(MODE)/%.o) TOOL_BUILD_EMUBIN_CHECKS = \ $(TOOL_BUILD_EMUBIN_HDRS:%=o/$(MODE)/%.ok) TOOL_BUILD_EMUBIN_DIRECTDEPS = \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_STUBS \ LIBC_TINYMATH TOOL_BUILD_EMUBIN_DEPS := \ $(call uniq,$(foreach x,$(TOOL_BUILD_EMUBIN_DIRECTDEPS),$($(x)))) $(TOOL_BUILD_EMUBIN_A): \ tool/build/emubin/ \ $(TOOL_BUILD_EMUBIN_A).pkg \ $(TOOL_BUILD_EMUBIN_OBJS) $(TOOL_BUILD_EMUBIN_A).pkg: \ $(TOOL_BUILD_EMUBIN_OBJS) \ $(foreach x,$(TOOL_BUILD_EMUBIN_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/build/emubin/%.bin.dbg: \ $(TOOL_BUILD_EMUCRT) \ $(TOOL_BUILD_EMUBIN_DEPS) \ $(TOOL_BUILD_EMUBIN_A) \ o/$(MODE)/tool/build/emubin/%.o \ $(TOOL_BUILD_EMUBIN_A).pkg @$(ELFLINK) -e emucrt -z max-page-size=0x10 o/tiny/tool/build/emubin/spiral.bin.dbg: \ $(TOOL_BUILD_EMUBIN_DEPS) \ o/tiny/tool/build/emubin/spiral.real.o @$(ELFLINK) -z max-page-size=0x10 -T tool/build/emucrt/real.lds o/tiny/tool/build/emubin/mdatest.bin.dbg: \ $(TOOL_BUILD_EMUBIN_DEPS) \ o/tiny/tool/build/emubin/mdatest.real.o @$(ELFLINK) -z max-page-size=0x10 -T tool/build/emucrt/real.lds $(TOOL_BUILD_EMUBIN_OBJS): private \ OVERRIDE_CFLAGS += \ $(NO_MAGIC) .PHONY: o/$(MODE)/tool/build/emubin o/$(MODE)/tool/build/emubin:
2,208
69
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/sha256.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 "tool/build/emubin/metalsha256.h" #define SHA256_BLOCK_SIZE 32 #define OUTB(PORT, BYTE) asm volatile("outb\t%b1,%0" : : "N"(PORT), "a"(BYTE)) #define INW(PORT) \ ({ \ int Word; \ asm volatile("in\t%1,%0" : "=a"(Word) : "N"(PORT)); \ Word; \ }) static void PrintHexBytes(int n, const uint8_t p[n]) { int i; for (i = 0; i < n; ++i) { OUTB(0xE9, "0123456789abcdef"[(p[i] >> 4) & 15]); OUTB(0xE9, "0123456789abcdef"[(p[i] >> 0) & 15]); } OUTB(0xE9, '\n'); } int main(int argc, char *argv[]) { int rc; uint8_t hash[32], buf[1]; struct MetalSha256Ctx ctx; MetalSha256Init(&ctx); while ((rc = INW(0xE9)) != -1) { buf[0] = rc; MetalSha256Update(&ctx, buf, sizeof(buf)); } MetalSha256Final(&ctx, hash); PrintHexBytes(sizeof(hash), hash); return 0; }
2,825
53
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/pi.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/math.h" #if 1 #define FLOAT long double #define SQRT sqrtl #else #define FLOAT float #define SQRT sqrt #endif /** * Computes π w/ François Viète method. * * make -j8 MODE=tiny * o/tiny/tool/build/emulator.com.dbg -t o/tiny/tool/build/pi.bin * */ FLOAT Main(void) { long i, n; FLOAT pi, q, t; n = VEIL("r", 10); q = 0; t = 1; for (i = 0; i < n; ++i) { q += 2; q = SQRT(q); t *= q / 2; } return 2 / t; } volatile FLOAT st0; int main(int argc, char *argv[]) { st0 = Main(); return 0; }
2,385
56
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/mips.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 "tool/build/emubin/metalsha256.h" //#define DISINGENUOUS /* 100 million NOPs is still 100 MIPS lool */ static void Print(uint8_t c) { asm volatile("out\t%0,$0xE9" : /* no outputs */ : "a"(c) : "memory"); } int main(int argc, char *argv[]) { int i; #ifdef DISINGENUOUS for (i = 0; i < 150 * 1000 * 1000 / 3; ++i) asm("nop"); #else size_t size; struct MetalSha256Ctx ctx; unsigned char hash[32], *data; data = (void *)0x7fffffff0000; size = 0x10000; MetalSha256Init(&ctx); for (i = 0; i < 10; ++i) { MetalSha256Update(&ctx, data, size); } MetalSha256Final(&ctx, hash); for (i = 0; i < sizeof(hash); ++i) { Print("0123456789abcdef"[(hash[i] >> 4) & 15]); Print("0123456789abcdef"[(hash[i] >> 0) & 15]); } Print('\n'); #endif return 0; }
2,626
50
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/poke.h
#ifndef COSMOPOLITAN_TOOL_BUILD_EMUBIN_POKE_H_ #define COSMOPOLITAN_TOOL_BUILD_EMUBIN_POKE_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define POKE(MEM, VAL) \ asm volatile("mov%z0\t%1,%%es:%0" : "=m"(MEM) : "Qi"((typeof(MEM))(VAL))) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_EMUBIN_POKE_H_ */
376
12
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/spiral.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 "tool/build/emubin/poke.h" #include "tool/build/emubin/real.h" #include "tool/build/emubin/realstart.inc" #define signbit(x) __builtin_signbit(x) static const unsigned char kBlocks[] = { [0b1111] = 0xdb, // █ [0b0110] = 0xdb, // █ [0b1001] = 0xdb, // █ [0b0111] = 0xdb, // █ [0b1011] = 0xdb, // █ [0b1110] = 0xdb, // █ [0b1101] = 0xdb, // █ [0b1100] = 0xdc, // ▄ [0b0100] = 0xdc, // ▄ [0b1000] = 0xdc, // ▄ [0b0101] = 0xdd, // ▌ [0b1010] = 0xde, // ▐ [0b0011] = 0xdf, // ▀ [0b0010] = 0xdf, // ▀ [0b0001] = 0xdf, // ▀ }; forceinline void *SetMemory(void *di, int al, unsigned long cx) { asm("rep stosb" : "=D"(di), "=c"(cx), "=m"(*(char(*)[cx])di) : "0"(di), "1"(cx), "a"(al)); return di; } forceinline long double pi(void) { long double x; asm("fldpi" : "=t"(x)); return x; } forceinline long double tau(void) { return pi() * 2; } forceinline void sincosl_(long double x, long double *sin, long double *cos) { asm("fsincos" : "=t"(*sin), "=u"(*cos) : "0"(x)); } forceinline long double atan2l_(long double x, long double y) { asm("fpatan" : "+t"(x) : "u"(y) : "st(1)"); return x; } forceinline long lrintl_(long double x) { long i; asm("fistp%z0\t%0" : "=m"(i) : "t"(x) : "st"); return i; } forceinline long double truncl_(long double x) { asm("frndint" : "+t"(x)); return x; } forceinline long double fabsl_(long double x) { asm("fabs" : "+t"(x)); return x; } forceinline long lroundl_(long double x) { int s = signbit(x); x = truncl_(fabsl_(x) + .5); if (s) x = -x; return lrintl_(x); } static unsigned short GetFpuControlWord(void) { unsigned short cw; asm("fnstcw\t%0" : "=m"(cw)); return cw; } static void SetFpuControlWord(unsigned short cw) { asm volatile("fldcw\t%0" : /* no outputs */ : "m"(cw)); } static void InitializeFpu(void) { asm("fninit"); } static void SetTruncationRounding(void) { SetFpuControlWord(GetFpuControlWord() | 0x0c00); } static void spiral(unsigned char p[25][80][2], unsigned char B[25][80], int g) { int i, x, y; long double a, b, u, v, h; for (a = b = i = 0; i < 1000; ++i) { sincosl_(a, &u, &v); h = atan2l_(u, v) - .333L * g; x = lroundl_(80 + u * b); y = lroundl_(25 + v * b * (1. / ((266 / 64.) * (900 / 1600.)))); B[y >> 1][x >> 1] |= 1 << ((y & 1) << 1 | (x & 1)); POKE(p[y >> 1][x >> 1][0], kBlocks[B[y >> 1][x >> 1]]); POKE(p[y >> 1][x >> 1][1], (lrintl_((h + tau()) * (8 / tau())) & 7) + 8); a += .05; b += .05; } } int main() { int g; InitializeFpu(); SetTruncationRounding(); SetVideoMode(3); for (g = 0;; ++g) { SetEs(0); SetMemory((void *)(0x7c00 + 512), 0, 25 * 80); SetEs(0xb8000 >> 4); /* SetMemory((void *)0, 0, 25 * 80 * 2); */ spiral((void *)0, (void *)(0x7c00 + 512), g); } }
4,737
139
jart/cosmopolitan
false
cosmopolitan/tool/build/emubin/metalsha256.h
#ifndef COSMOPOLITAN_TOOL_BUILD_EMUBIN_METALSHA256_H_ #define COSMOPOLITAN_TOOL_BUILD_EMUBIN_METALSHA256_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct MetalSha256Ctx { uint8_t data[64]; uint32_t datalen; uint64_t bitlen; uint32_t state[8]; }; void MetalSha256Init(struct MetalSha256Ctx *); void MetalSha256Update(struct MetalSha256Ctx *, const uint8_t *, long); void MetalSha256Final(struct MetalSha256Ctx *, uint8_t *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_EMUBIN_METALSHA256_H_ */
582
20
jart/cosmopolitan
false
cosmopolitan/tool/net/ljson.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 "tool/net/ljson.h" #include "libc/intrin/bits.h" #include "libc/intrin/likely.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/stack.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/str/utf16.h" #include "third_party/double-conversion/wrapper.h" #include "third_party/lua/cosmo.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/ltests.h" #include "third_party/lua/lua.h" #define KEY 1 #define COMMA 2 #define COLON 4 #define ARRAY 8 #define OBJECT 16 #define DEPTH 64 #define ASCII 0 #define C0 1 #define DQUOTE 2 #define BACKSLASH 3 #define UTF8_2 4 #define UTF8_3 5 #define UTF8_4 6 #define C1 7 #define UTF8_3_E0 8 #define UTF8_3_ED 9 #define UTF8_4_F0 10 #define BADUTF8 11 #define EVILUTF8 12 static const char kJsonStr[256] = { 1, 1, 1, 1, 1, 1, 1, 1, // 0000 ascii (0) 1, 1, 1, 1, 1, 1, 1, 1, // 0010 1, 1, 1, 1, 1, 1, 1, 1, // 0020 c0 (1) 1, 1, 1, 1, 1, 1, 1, 1, // 0030 0, 0, 2, 0, 0, 0, 0, 0, // 0040 dquote (2) 0, 0, 0, 0, 0, 0, 0, 0, // 0050 0, 0, 0, 0, 0, 0, 0, 0, // 0060 0, 0, 0, 0, 0, 0, 0, 0, // 0070 0, 0, 0, 0, 0, 0, 0, 0, // 0100 0, 0, 0, 0, 0, 0, 0, 0, // 0110 0, 0, 0, 0, 0, 0, 0, 0, // 0120 0, 0, 0, 0, 3, 0, 0, 0, // 0130 backslash (3) 0, 0, 0, 0, 0, 0, 0, 0, // 0140 0, 0, 0, 0, 0, 0, 0, 0, // 0150 0, 0, 0, 0, 0, 0, 0, 0, // 0160 0, 0, 0, 0, 0, 0, 0, 0, // 0170 7, 7, 7, 7, 7, 7, 7, 7, // 0200 c1 (8) 7, 7, 7, 7, 7, 7, 7, 7, // 0210 7, 7, 7, 7, 7, 7, 7, 7, // 0220 7, 7, 7, 7, 7, 7, 7, 7, // 0230 11, 11, 11, 11, 11, 11, 11, 11, // 0240 latin1 (4) 11, 11, 11, 11, 11, 11, 11, 11, // 0250 11, 11, 11, 11, 11, 11, 11, 11, // 0260 11, 11, 11, 11, 11, 11, 11, 11, // 0270 12, 12, 4, 4, 4, 4, 4, 4, // 0300 utf8-2 (5) 4, 4, 4, 4, 4, 4, 4, 4, // 0310 4, 4, 4, 4, 4, 4, 4, 4, // 0320 utf8-2 4, 4, 4, 4, 4, 4, 4, 4, // 0330 8, 5, 5, 5, 5, 5, 5, 5, // 0340 utf8-3 (6) 5, 5, 5, 5, 5, 9, 5, 5, // 0350 10, 6, 6, 6, 6, 11, 11, 11, // 0360 utf8-4 (7) 11, 11, 11, 11, 11, 11, 11, 11, // 0370 }; static struct DecodeJson Parse(struct lua_State *L, const char *p, const char *e, int context, int depth) { long x; char w[4]; luaL_Buffer b; struct DecodeJson r; const char *a, *reason; int A, B, C, D, c, d, i, u; if (UNLIKELY(!depth)) { return (struct DecodeJson){-1, "maximum depth exceeded"}; } if (UNLIKELY(!HaveStackMemory(GUARDSIZE))) { return (struct DecodeJson){-1, "out of stack"}; } for (a = p, d = +1; p < e;) { switch ((c = *p++ & 255)) { case ' ': // spaces case '\n': case '\r': case '\t': a = p; break; case ',': // present in list and object if (context & COMMA) { context = 0; a = p; break; } else { return (struct DecodeJson){-1, "unexpected ','"}; } case ':': // present only in object after key if (context & COLON) { context = 0; a = p; break; } else { return (struct DecodeJson){-1, "unexpected ':'"}; } case 'n': // null if (context & (KEY | COLON | COMMA)) goto OnColonCommaKey; if (p + 3 <= e && READ32LE(p - 1) == READ32LE("null")) { lua_pushnil(L); return (struct DecodeJson){1, p + 3}; } else { goto IllegalCharacter; } case 'f': // false if (context & (KEY | COLON | COMMA)) goto OnColonCommaKey; if (p + 4 <= e && READ32LE(p) == READ32LE("alse")) { lua_pushboolean(L, false); return (struct DecodeJson){1, p + 4}; } else { goto IllegalCharacter; } case 't': // true if (context & (KEY | COLON | COMMA)) goto OnColonCommaKey; if (p + 3 <= e && READ32LE(p - 1) == READ32LE("true")) { lua_pushboolean(L, true); return (struct DecodeJson){1, p + 3}; } else { goto IllegalCharacter; } default: IllegalCharacter: return (struct DecodeJson){-1, "illegal character"}; OnColonCommaKey: if (context & KEY) goto BadObjectKey; OnColonComma: if (context & COLON) goto MissingColon; return (struct DecodeJson){-1, "missing ','"}; MissingColon: return (struct DecodeJson){-1, "missing ':'"}; BadObjectKey: return (struct DecodeJson){-1, "object key must be string"}; case '-': // negative if (context & (COLON | COMMA | KEY)) goto OnColonCommaKey; if (p < e && isdigit(*p)) { d = -1; break; } else { return (struct DecodeJson){-1, "bad negative"}; } case '0': // zero or number if (context & (COLON | COMMA | KEY)) goto OnColonCommaKey; if (p < e) { if (*p == '.') { if (p + 1 == e || !isdigit(p[1])) { return (struct DecodeJson){-1, "bad double"}; } goto UseDubble; } else if (*p == 'e' || *p == 'E') { goto UseDubble; } else if (isdigit(*p)) { return (struct DecodeJson){-1, "unexpected octal"}; } } lua_pushinteger(L, 0); return (struct DecodeJson){1, p}; case '1' ... '9': // integer if (context & (COLON | COMMA | KEY)) goto OnColonCommaKey; for (x = (c - '0') * d; p < e; ++p) { c = *p & 255; if (isdigit(c)) { if (__builtin_mul_overflow(x, 10, &x) || __builtin_add_overflow(x, (c - '0') * d, &x)) { goto UseDubble; } } else if (c == '.') { if (p + 1 == e || !isdigit(p[1])) { return (struct DecodeJson){-1, "bad double"}; } goto UseDubble; } else if (c == 'e' || c == 'E') { goto UseDubble; } else { break; } } lua_pushinteger(L, x); return (struct DecodeJson){1, p}; UseDubble: // number lua_pushnumber(L, StringToDouble(a, e - a, &c)); DCHECK(c > 0, "paranoid avoiding infinite loop"); if (a + c < e && (a[c] == 'e' || a[c] == 'E')) { return (struct DecodeJson){-1, "bad exponent"}; } return (struct DecodeJson){1, a + c}; case '[': // Array if (context & (COLON | COMMA | KEY)) goto OnColonCommaKey; lua_newtable(L); // +1 for (context = ARRAY, i = 0;;) { r = Parse(L, p, e, context, depth - 1); // +2 if (UNLIKELY(r.rc == -1)) { lua_pop(L, 1); return r; } p = r.p; if (!r.rc) { break; } lua_rawseti(L, -2, i++ + 1); context = ARRAY | COMMA; } if (!i) { // we need this kludge so `[]` won't round-trip as `{}` lua_pushboolean(L, false); // +2 lua_rawseti(L, -2, 0); } return (struct DecodeJson){1, p}; case ']': if (context & ARRAY) { return (struct DecodeJson){0, p}; } else { return (struct DecodeJson){-1, "unexpected ']'"}; } case '}': if (context & OBJECT) { return (struct DecodeJson){0, p}; } else { return (struct DecodeJson){-1, "unexpected '}'"}; } case '{': // Object if (context & (COLON | COMMA | KEY)) goto OnColonCommaKey; lua_newtable(L); // +1 context = KEY | OBJECT; for (;;) { r = Parse(L, p, e, context, depth - 1); // +2 if (r.rc == -1) { lua_pop(L, 1); return r; } p = r.p; if (!r.rc) { return (struct DecodeJson){1, p}; } r = Parse(L, p, e, COLON, depth - 1); // +3 if (r.rc == -1) { lua_pop(L, 2); return r; } if (!r.rc) { lua_pop(L, 2); return (struct DecodeJson){-1, "unexpected eof in object"}; } p = r.p; lua_settable(L, -3); context = KEY | COMMA | OBJECT; } case '"': // string if (context & (COLON | COMMA)) goto OnColonComma; luaL_buffinit(L, &b); for (;;) { if (UNLIKELY(p >= e)) { UnexpectedEofString: reason = "unexpected eof in string"; goto StringFailureWithReason; } switch (kJsonStr[(c = *p++ & 255)]) { case ASCII: luaL_addchar(&b, c); break; case DQUOTE: luaL_pushresult(&b); return (struct DecodeJson){1, p}; case BACKSLASH: if (p >= e) { goto UnexpectedEofString; } switch ((c = *p++ & 255)) { case '"': case '/': case '\\': luaL_addchar(&b, c); break; case 'b': luaL_addchar(&b, '\b'); break; case 'f': luaL_addchar(&b, '\f'); break; case 'n': luaL_addchar(&b, '\n'); break; case 'r': luaL_addchar(&b, '\r'); break; case 't': luaL_addchar(&b, '\t'); break; case 'x': if (p + 2 <= e && // (A = kHexToInt[p[0] & 255]) != -1 && // HEX (B = kHexToInt[p[1] & 255]) != -1) { // c = A << 4 | B; if (!(0x20 <= c && c <= 0x7E)) { reason = "hex escape not printable"; goto StringFailureWithReason; } p += 2; luaL_addchar(&b, c); break; } else { reason = "invalid hex escape"; goto StringFailureWithReason; } case 'u': if (p + 4 <= e && // (A = kHexToInt[p[0] & 255]) != -1 && // (B = kHexToInt[p[1] & 255]) != -1 && // UCS-2 (C = kHexToInt[p[2] & 255]) != -1 && // (D = kHexToInt[p[3] & 255]) != -1) { // c = A << 12 | B << 8 | C << 4 | D; if (!IsSurrogate(c)) { p += 4; } else if (IsHighSurrogate(c)) { if (p + 4 + 6 <= e && // p[4] == '\\' && // p[5] == 'u' && // (A = kHexToInt[p[6] & 255]) != -1 && // UTF-16 (B = kHexToInt[p[7] & 255]) != -1 && // (C = kHexToInt[p[8] & 255]) != -1 && // (D = kHexToInt[p[9] & 255]) != -1) { // u = A << 12 | B << 8 | C << 4 | D; if (IsLowSurrogate(u)) { p += 4 + 6; c = MergeUtf16(c, u); } else { goto BadUnicode; } } else { goto BadUnicode; } } else { goto BadUnicode; } // UTF-8 EncodeUtf8: if (c <= 0x7f) { w[0] = c; i = 1; } else if (c <= 0x7ff) { w[0] = 0300 | (c >> 6); w[1] = 0200 | (c & 077); i = 2; } else if (c <= 0xffff) { if (IsSurrogate(c)) { ReplacementCharacter: c = 0xfffd; } w[0] = 0340 | (c >> 12); w[1] = 0200 | ((c >> 6) & 077); w[2] = 0200 | (c & 077); i = 3; } else if (~(c >> 18) & 007) { w[0] = 0360 | (c >> 18); w[1] = 0200 | ((c >> 12) & 077); w[2] = 0200 | ((c >> 6) & 077); w[3] = 0200 | (c & 077); i = 4; } else { goto ReplacementCharacter; } luaL_addlstring(&b, w, i); } else { reason = "invalid unicode escape"; goto StringFailureWithReason; BadUnicode: // Echo invalid \uXXXX sequences // Rather than corrupting UTF-8! luaL_addstring(&b, "\\u"); } break; default: reason = "invalid escape character"; goto StringFailureWithReason; } break; case UTF8_2: if (p < e && // (p[0] & 0300) == 0200) { // c = (c & 037) << 6 | // (p[0] & 077); // p += 1; goto EncodeUtf8; } else { reason = "malformed utf-8"; goto StringFailureWithReason; } case UTF8_3_E0: if (p + 2 <= e && // (p[0] & 0377) < 0240 && // (p[0] & 0300) == 0200 && // (p[1] & 0300) == 0200) { reason = "overlong utf-8 0..0x7ff"; goto StringFailureWithReason; } // fallthrough case UTF8_3: ThreeUtf8: if (p + 2 <= e && // (p[0] & 0300) == 0200 && // (p[1] & 0300) == 0200) { // c = (c & 017) << 12 | // (p[0] & 077) << 6 | // (p[1] & 077); // p += 2; goto EncodeUtf8; } else { reason = "malformed utf-8"; goto StringFailureWithReason; } case UTF8_3_ED: if (p + 2 <= e && // (p[0] & 0377) >= 0240) { // if (p + 5 <= e && // (p[0] & 0377) >= 0256 && // (p[1] & 0300) == 0200 && // (p[2] & 0377) == 0355 && // (p[3] & 0377) >= 0260 && // (p[4] & 0300) == 0200) { // A = (0355 & 017) << 12 | // CESU-8 (p[0] & 077) << 6 | // (p[1] & 077); // B = (0355 & 017) << 12 | // (p[3] & 077) << 6 | // (p[4] & 077); // c = ((A - 0xDB80) << 10) + // ((B - 0xDC00) + 0x10000); // goto EncodeUtf8; } else if ((p[0] & 0300) == 0200 && // (p[1] & 0300) == 0200) { // reason = "utf-16 surrogate in utf-8"; goto StringFailureWithReason; } else { reason = "malformed utf-8"; goto StringFailureWithReason; } } goto ThreeUtf8; case UTF8_4_F0: if (p + 3 <= e && (p[0] & 0377) < 0220 && (((uint32_t)(p[+2] & 0377) << 030 | (uint32_t)(p[+1] & 0377) << 020 | (uint32_t)(p[+0] & 0377) << 010 | (uint32_t)(p[-1] & 0377) << 000) & 0xC0C0C000) == 0x80808000) { reason = "overlong utf-8 0..0xffff"; goto StringFailureWithReason; } // fallthrough case UTF8_4: if (p + 3 <= e && // ((A = ((uint32_t)(p[+2] & 0377) << 030 | // (uint32_t)(p[+1] & 0377) << 020 | // (uint32_t)(p[+0] & 0377) << 010 | // (uint32_t)(p[-1] & 0377) << 000)) & // 0xC0C0C000) == 0x80808000) { // A = (A & 7) << 18 | // (A & (077 << 010)) << (12 - 010) | // (A & (077 << 020)) >> -(6 - 020) | // (A & (077 << 030)) >> 030; // if (A <= 0x10FFFF) { c = A; p += 3; goto EncodeUtf8; } else { reason = "utf-8 exceeds utf-16 range"; goto StringFailureWithReason; } } else { reason = "malformed utf-8"; goto StringFailureWithReason; } case EVILUTF8: if (p < e && // (p[0] & 0300) == 0200) { // reason = "overlong ascii"; goto StringFailureWithReason; } // fallthrough case BADUTF8: reason = "illegal utf-8 character"; goto StringFailureWithReason; case C0: reason = "non-del c0 control code in string"; goto StringFailureWithReason; case C1: reason = "c1 control code in string"; goto StringFailureWithReason; default: unreachable; } } unreachable; StringFailureWithReason: luaL_pushresultsize(&b, 0); lua_pop(L, 1); return (struct DecodeJson){-1, reason}; } } if (depth == DEPTH) { return (struct DecodeJson){0, 0}; } else { return (struct DecodeJson){-1, "unexpected eof"}; } } /** * Parses JSON data structure string into Lua data structure. * * This function returns the number of items pushed to the Lua stack, * which should be 1, unless no parseable JSON content was found, in * which case this will return 0. On error -1 is returned. There's * currently no error return condition. This function doesn't do JSON * validity enforcement. * * JSON UTF-16 strings are re-encoded as valid UTF-8. 64-bit integers * are supported. If an integer overflows during parsing, it'll be * converted to a floating-point number instead. Invalid surrogate * escape sequences in strings won't be decoded. * * @param L is Lua interpreter state * @param p is input string * @param n is byte length of `p` or -1 for automatic strlen() * @return r.rc is 1 if value is pushed on lua stack * @return r.rc is 0 on eof * @return r.rc is -1 on error * @return r.p is is advanced `p` pointer if `rc ≥ 0` * @return r.p is string describing error if `rc < 0` */ struct DecodeJson DecodeJson(struct lua_State *L, const char *p, size_t n) { if (n == -1) n = p ? strlen(p) : 0; if (lua_checkstack(L, DEPTH * 3 + LUA_MINSTACK)) { return Parse(L, p, p + n, 0, DEPTH); } else { return (struct DecodeJson){-1, "can't set stack depth"}; } }
21,952
594
jart/cosmopolitan
false
cosmopolitan/tool/net/lpath.h
#ifndef COSMOPOLITAN_TOOL_NET_LPATH_H_ #define COSMOPOLITAN_TOOL_NET_LPATH_H_ #include "third_party/lua/lauxlib.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int LuaPath(lua_State *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_NET_LPATH_H_ */
314
12
jart/cosmopolitan
false
cosmopolitan/tool/net/fetch.inc
#define FetchHasHeader(H) (!!msg.headers[H].a) #define FetchHeaderData(H) (inbuf.p + msg.headers[H].a) #define FetchHeaderLength(H) (msg.headers[H].b - msg.headers[H].a) #define FetchHeaderEqualCase(H, S) \ SlicesEqualCase(S, strlen(S), FetchHeaderData(H), FetchHeaderLength(H)) #define kaNONE 0 #define kaOPEN 1 #define kaKEEP 2 #define kaCLOSE 3 static int LuaFetch(lua_State *L) { #define ssl nope // TODO(jart): make this file less huge char *p; ssize_t rc; bool usingssl; uint32_t ip; struct Url url; int t, ret, sock = -1, methodidx, hdridx; char *host, *port, *request; struct TlsBio *bio; struct addrinfo *addr; struct Buffer inbuf; // shadowing intentional struct HttpMessage msg; // shadowing intentional struct HttpUnchunker u; const char *urlarg, *body, *method; char *conlenhdr = ""; char *headers = 0; char *hosthdr = 0; char *connhdr = 0; char *agenthdr = brand; char *key, *val, *hdr; size_t keylen, vallen; size_t urlarglen, requestlen, paylen, bodylen; size_t i, g, n, hdrsize; int keepalive = kaNONE; int imethod, numredirects = 0, maxredirects = 5; bool followredirect = true; struct addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_STREAM, .ai_protocol = IPPROTO_TCP, .ai_flags = AI_NUMERICSERV}; /* * Get args: url [, body | {method = "PUT", body = "..."}] */ urlarg = luaL_checklstring(L, 1, &urlarglen); if (lua_istable(L, 2)) { lua_settop(L, 2); // discard any extra arguments lua_getfield(L, 2, "body"); body = luaL_optlstring(L, -1, "", &bodylen); lua_getfield(L, 2, "method"); // use GET by default if no method is provided method = luaL_optstring(L, -1, kHttpMethod[kHttpGet]); if ((imethod = GetHttpMethod(method, -1))) { method = kHttpMethod[imethod]; } else { return LuaNilError(L, "bad method"); } lua_getfield(L, 2, "followredirect"); if (lua_isboolean(L, -1)) followredirect = lua_toboolean(L, -1); lua_getfield(L, 2, "maxredirects"); maxredirects = luaL_optinteger(L, -1, maxredirects); lua_getfield(L, 2, "numredirects"); numredirects = luaL_optinteger(L, -1, numredirects); lua_getfield(L, 2, "keepalive"); if (!lua_isnil(L, -1)) { if (lua_istable(L, -1)) { keepalive = kaOPEN; // will be updated based on host later } else if (lua_isboolean(L, -1)) { keepalive = lua_toboolean(L, -1) ? kaOPEN : kaNONE; if (keepalive) { lua_createtable(L, 0, 1); lua_setfield(L, 2, "keepalive"); } } else { return luaL_argerror(L, 2, "invalid keepalive value;" " boolean or table expected"); } } lua_getfield(L, 2, "headers"); if (!lua_isnil(L, -1)) { if (!lua_istable(L, -1)) return luaL_argerror(L, 2, "invalid headers value; table expected"); lua_pushnil(L); while (lua_next(L, -2)) { if (lua_type(L, -2) == LUA_TSTRING) { // skip any non-string keys key = lua_tolstring(L, -2, &keylen); if (!IsValidHttpToken(key, keylen)) return LuaNilError(L, "invalid header name: %s", key); val = lua_tolstring(L, -1, &vallen); if (!(hdr = _gc(EncodeHttpHeaderValue(val, vallen, 0)))) return LuaNilError(L, "invalid header %s value encoding", key); // Content-Length will be overwritten; skip it to avoid duplicates; // also allow unknown headers if ((hdridx = GetHttpHeader(key, keylen)) == -1 || hdridx != kHttpContentLength) { if (hdridx == kHttpUserAgent) { agenthdr = hdr; } else if (hdridx == kHttpHost) { hosthdr = hdr; } else if (hdridx == kHttpConnection) { connhdr = hdr; } else { appendd(&headers, key, keylen); appendw(&headers, READ16LE(": ")); appends(&headers, hdr); appendw(&headers, READ16LE("\r\n")); } } } lua_pop(L, 1); // pop the value, keep the key for the next iteration } } lua_settop(L, 2); // drop all added elements to keep the stack balanced } else if (lua_isnoneornil(L, 2)) { body = ""; bodylen = 0; method = kHttpMethod[kHttpGet]; } else { body = luaL_checklstring(L, 2, &bodylen); method = kHttpMethod[kHttpPost]; } // provide Content-Length header unless it's zero and not expected methodidx = GetHttpMethod(method, -1); if (bodylen > 0 || !(methodidx == kHttpGet || methodidx == kHttpHead || methodidx == kHttpTrace || methodidx == kHttpDelete || methodidx == kHttpConnect)) { conlenhdr = _gc(xasprintf("Content-Length: %zu\r\n", bodylen)); } /* * Parse URL. */ _gc(ParseUrl(urlarg, urlarglen, &url, true)); _gc(url.params.p); usingssl = false; if (url.scheme.n) { #ifndef UNSECURE if (!unsecure && url.scheme.n == 5 && !memcasecmp(url.scheme.p, "https", 5)) { usingssl = true; } else #endif if (!(url.scheme.n == 4 && !memcasecmp(url.scheme.p, "http", 4))) { return LuaNilError(L, "bad scheme"); } } #ifndef UNSECURE if (usingssl) keepalive = kaNONE; if (usingssl && !sslinitialized) TlsInit(); #endif if (url.host.n) { host = _gc(strndup(url.host.p, url.host.n)); if (url.port.n) { port = _gc(strndup(url.port.p, url.port.n)); #ifndef UNSECURE } else if (usingssl) { port = "443"; #endif } else { port = "80"; } } else if ((ip = ParseIp(urlarg, -1)) != -1) { host = urlarg; port = "80"; } else { return LuaNilError(L, "invalid host"); } if (!IsAcceptableHost(host, -1)) { return LuaNilError(L, "invalid host"); } if (!hosthdr) hosthdr = _gc(xasprintf("%s:%s", host, port)); // check if hosthdr is in keepalive table if (keepalive && lua_istable(L, 2)) { lua_getfield(L, 2, "keepalive"); lua_getfield(L, -1, "close"); // aft: -2=tbl, -1=close lua_getfield(L, -2, hosthdr); // aft: -3=tbl, -2=close, -1=hosthdr if (lua_isinteger(L, -1)) { sock = lua_tointeger(L, -1); keepalive = lua_toboolean(L, -2) ? kaCLOSE : kaKEEP; // remove host mapping, as the socket is ether being closed // (so needs to be removed) or will be added after the request is done; // this also helps to keep the mapping clean in case of an error lua_pushnil(L); // aft: -4=tbl, -3=close, -2=hosthdr, -1=nil lua_setfield(L, -4, hosthdr); VERBOSEF("(ftch) reuse socket %d for host %s (and %s)", sock, hosthdr, keepalive == kaCLOSE ? "close" : "keep"); } lua_settop(L, 2); // drop all added elements to keep the stack balanced } url.fragment.p = 0, url.fragment.n = 0; url.scheme.p = 0, url.scheme.n = 0; url.user.p = 0, url.user.n = 0; url.pass.p = 0, url.pass.n = 0; url.host.p = 0, url.host.n = 0; url.port.p = 0, url.port.n = 0; if (!url.path.n || url.path.p[0] != '/') { p = _gc(xmalloc(1 + url.path.n)); mempcpy(mempcpy(p, "/", 1), url.path.p, url.path.n); url.path.p = p; ++url.path.n; } /* * Create HTTP message. */ request = 0; appendf(&request, "%s %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: %s\r\n" "User-Agent: %s\r\n" "%s%s" "\r\n", method, _gc(EncodeUrl(&url, 0)), hosthdr, (keepalive == kaNONE || keepalive == kaCLOSE) ? "close" : (connhdr ? connhdr : "keep-alive"), agenthdr, conlenhdr, headers ? headers : ""); appendd(&request, body, bodylen); requestlen = appendz(request).i; _gc(request); if (keepalive == kaNONE || keepalive == kaOPEN) { /* * Perform DNS lookup. */ DEBUGF("(ftch) client resolving %s", host); if ((rc = getaddrinfo(host, port, &hints, &addr)) != EAI_SUCCESS) { return LuaNilError(L, "getaddrinfo(%s:%s) error: EAI_%s %s", host, port, gai_strerror(rc), strerror(errno)); } /* * Connect to server. */ ip = ntohl(((struct sockaddr_in *)addr->ai_addr)->sin_addr.s_addr); DEBUGF("(ftch) client connecting %hhu.%hhu.%hhu.%hhu:%d", ip >> 24, ip >> 16, ip >> 8, ip, ntohs(((struct sockaddr_in *)addr->ai_addr)->sin_port)); CHECK_NE(-1, (sock = GoodSocket(addr->ai_family, addr->ai_socktype, addr->ai_protocol, false, &timeout))); rc = connect(sock, addr->ai_addr, addr->ai_addrlen); freeaddrinfo(addr), addr = 0; if (rc == -1) { close(sock); return LuaNilError(L, "connect(%s:%s) error: %s", host, port, strerror(errno)); } } #ifndef UNSECURE if (usingssl) { if (sslcliused) { mbedtls_ssl_session_reset(&sslcli); } else { ReseedRng(&rngcli, "child"); } sslcliused = true; DEBUGF("(ftch) client handshaking %`'s", host); if (!evadedragnetsurveillance) { mbedtls_ssl_set_hostname(&sslcli, host); } bio = _gc(malloc(sizeof(struct TlsBio))); bio->fd = sock; bio->a = 0; bio->b = 0; bio->c = -1; mbedtls_ssl_set_bio(&sslcli, bio, TlsSend, 0, TlsRecvImpl); while ((ret = mbedtls_ssl_handshake(&sslcli))) { switch (ret) { case MBEDTLS_ERR_SSL_WANT_READ: break; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: goto VerifyFailed; default: close(sock); return LuaNilTlsError(L, "handshake", ret); } } LockInc(&shared->c.sslhandshakes); VERBOSEF("(ftch) shaken %s:%s %s %s", host, port, mbedtls_ssl_get_ciphersuite(&sslcli), mbedtls_ssl_get_version(&sslcli)); } #endif /* UNSECURE */ /* * Send HTTP Message. */ DEBUGF("(ftch) client sending %s request", method); for (i = 0; i < requestlen; i += rc) { #ifndef UNSECURE if (usingssl) { rc = mbedtls_ssl_write(&sslcli, request + i, requestlen - i); if (rc <= 0) { if (rc == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) goto VerifyFailed; close(sock); return LuaNilTlsError(L, "write", rc); } } else #endif if ((rc = WRITE(sock, request + i, requestlen - i)) <= 0) { close(sock); return LuaNilError(L, "write error: %s", strerror(errno)); } } if (logmessages) { LogMessage("sent", request, requestlen); } /* * Handle response. */ bzero(&inbuf, sizeof(inbuf)); InitHttpMessage(&msg, kHttpResponse); for (hdrsize = paylen = t = 0;;) { if (inbuf.n == inbuf.c) { inbuf.c += 1000; inbuf.c += inbuf.c >> 1; inbuf.p = realloc(inbuf.p, inbuf.c); } NOISEF("(ftch) client reading"); #ifndef UNSECURE if (usingssl) { if ((rc = mbedtls_ssl_read(&sslcli, inbuf.p + inbuf.n, inbuf.c - inbuf.n)) < 0) { if (rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { rc = 0; } else { close(sock); free(inbuf.p); DestroyHttpMessage(&msg); return LuaNilTlsError(L, "read", rc); } } } else #endif if ((rc = READ(sock, inbuf.p + inbuf.n, inbuf.c - inbuf.n)) == -1) { close(sock); free(inbuf.p); DestroyHttpMessage(&msg); return LuaNilError(L, "read error: %s", strerror(errno)); } g = rc; inbuf.n += g; switch (t) { case kHttpClientStateHeaders: if (!g) { WARNF("(ftch) HTTP client %s error", "EOF headers"); goto TransportError; } rc = ParseHttpMessage(&msg, inbuf.p, inbuf.n); if (rc == -1) { WARNF("(ftch) HTTP client %s error", "ParseHttpMessage"); goto TransportError; } if (rc) { DEBUGF("(ftch) content-length is %`'.*s", FetchHeaderLength(kHttpContentLength), FetchHeaderData(kHttpContentLength)); hdrsize = rc; if (logmessages) { LogMessage("received", inbuf.p, hdrsize); } if (100 <= msg.status && msg.status <= 199) { if ((FetchHasHeader(kHttpContentLength) && !FetchHeaderEqualCase(kHttpContentLength, "0")) || (FetchHasHeader(kHttpTransferEncoding) && !FetchHeaderEqualCase(kHttpTransferEncoding, "identity"))) { WARNF("(ftch) HTTP client %s error", "Content-Length #1"); goto TransportError; } DestroyHttpMessage(&msg); InitHttpMessage(&msg, kHttpResponse); memmove(inbuf.p, inbuf.p + hdrsize, inbuf.n - hdrsize); inbuf.n -= hdrsize; break; } if (msg.status == 204 || msg.status == 304) { goto Finished; } if (FetchHasHeader(kHttpTransferEncoding) && !FetchHeaderEqualCase(kHttpTransferEncoding, "identity")) { if (FetchHeaderEqualCase(kHttpTransferEncoding, "chunked")) { t = kHttpClientStateBodyChunked; bzero(&u, sizeof(u)); goto Chunked; } else { WARNF("(ftch) HTTP client %s error", "Transfer-Encoding"); goto TransportError; } } else if (FetchHasHeader(kHttpContentLength)) { rc = ParseContentLength(FetchHeaderData(kHttpContentLength), FetchHeaderLength(kHttpContentLength)); if (rc == -1) { WARNF("(ftch) ParseContentLength(%`'.*s) failed", FetchHeaderLength(kHttpContentLength), FetchHeaderData(kHttpContentLength)); goto TransportError; } if ((paylen = rc) <= inbuf.n - hdrsize) { goto Finished; } else { t = kHttpClientStateBodyLengthed; } } else { t = kHttpClientStateBody; } } break; case kHttpClientStateBody: if (!g) { paylen = inbuf.n - hdrsize; goto Finished; } break; case kHttpClientStateBodyLengthed: if (!g) { WARNF("(ftch) HTTP client %s error", "EOF body"); goto TransportError; } if (inbuf.n - hdrsize >= paylen) { goto Finished; } break; case kHttpClientStateBodyChunked: Chunked: rc = Unchunk(&u, inbuf.p + hdrsize, inbuf.n - hdrsize, &paylen); if (rc == -1) { WARNF("(ftch) HTTP client %s error", "Unchunk"); goto TransportError; } if (rc) goto Finished; break; default: unreachable; } } Finished: if (paylen && logbodies) LogBody("received", inbuf.p + hdrsize, paylen); VERBOSEF("(ftch) completed %s HTTP%02d %d %s %`'.*s", method, msg.version, msg.status, urlarg, FetchHeaderLength(kHttpServer), FetchHeaderData(kHttpServer)); // check if the server has requested to close the connection // https://www.rfc-editor.org/rfc/rfc2616#section-14.10 if (keepalive && keepalive != kaCLOSE && FetchHasHeader(kHttpConnection) && FetchHeaderEqualCase(kHttpConnection, "close")) { VERBOSEF("(ftch) close keepalive on server request"); keepalive = kaCLOSE; } // need to save updated sock for keepalive if (keepalive && keepalive != kaCLOSE && lua_istable(L, 2)) { lua_getfield(L, 2, "keepalive"); lua_pushinteger(L, sock); lua_setfield(L, -2, hosthdr); lua_pop(L, 1); } if (followredirect && FetchHasHeader(kHttpLocation) && (msg.status == 301 || msg.status == 308 || // permanent redirects msg.status == 302 || msg.status == 307 || // temporary redirects msg.status == 303 /* see other; non-GET changes to GET, body lost */) && numredirects < maxredirects) { // if 303, then remove body and set method to GET if (msg.status == 303) { body = ""; bodylen = 0; method = kHttpMethod[kHttpGet]; } // create table if needed if (!lua_istable(L, 2)) { lua_settop(L, 1); // pop body if present lua_createtable(L, 0, 3); // body, method, numredirects } lua_pushlstring(L, body, bodylen); lua_setfield(L, -2, "body"); lua_pushstring(L, method); lua_setfield(L, -2, "method"); lua_pushinteger(L, numredirects + 1); lua_setfield(L, -2, "numredirects"); // replace URL with Location header lua_pushlstring(L, FetchHeaderData(kHttpLocation), FetchHeaderLength(kHttpLocation)); lua_replace(L, -3); DestroyHttpMessage(&msg); free(inbuf.p); if (!keepalive || keepalive == kaCLOSE) close(sock); return LuaFetch(L); } else { lua_pushinteger(L, msg.status); LuaPushHeaders(L, &msg, inbuf.p); lua_pushlstring(L, inbuf.p + hdrsize, paylen); DestroyHttpMessage(&msg); free(inbuf.p); if (!keepalive || keepalive == kaCLOSE) close(sock); return 3; } TransportError: DestroyHttpMessage(&msg); free(inbuf.p); close(sock); return LuaNilError(L, "transport error"); #ifndef UNSECURE VerifyFailed: LockInc(&shared->c.sslverifyfailed); close(sock); return LuaNilTlsError( L, _gc(DescribeSslVerifyFailure(sslcli.session_negotiate->verify_result)), ret); #endif #undef ssl }
17,531
526
jart/cosmopolitan
false
cosmopolitan/tool/net/lpath.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/calls/struct/stat.h" #include "libc/errno.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/s.h" #include "third_party/lua/lauxlib.h" /** * @fileoverview redbean unix path manipulation module */ // path.basename(str) // └─→ str static int LuaPathBasename(lua_State *L) { size_t i, n; const char *p; if ((p = luaL_optlstring(L, 1, 0, &n)) && n) { while (n > 1 && p[n - 1] == '/') --n; i = n - 1; while (i && p[i - 1] != '/') --i; lua_pushlstring(L, p + i, n - i); } else { lua_pushlstring(L, ".", 1); } return 1; } // path.dirname(str) // └─→ str static int LuaPathDirname(lua_State *L) { size_t n; const char *p; if ((p = luaL_optlstring(L, 1, 0, &n)) && n--) { for (; p[n] == '/'; n--) { if (!n) goto ReturnSlash; } for (; p[n] != '/'; n--) { if (!n) goto ReturnDot; } for (; p[n] == '/'; n--) { if (!n) goto ReturnSlash; } lua_pushlstring(L, p, n + 1); return 1; } ReturnDot: lua_pushlstring(L, ".", 1); return 1; ReturnSlash: lua_pushlstring(L, "/", 1); return 1; } // path.join(str, ...) // └─→ str static int LuaPathJoin(lua_State *L) { int i, n; size_t z; bool gotstr; const char *c; luaL_Buffer b; bool needslash; if ((n = lua_gettop(L))) { luaL_buffinit(L, &b); gotstr = false; needslash = false; for (i = 1; i <= n; ++i) { if (lua_isnoneornil(L, i)) continue; gotstr = true; c = luaL_checklstring(L, i, &z); if (z) { if (c[0] == '/') { luaL_buffsub(&b, luaL_bufflen(&b)); } else if (needslash) { luaL_addchar(&b, '/'); } luaL_addlstring(&b, c, z); needslash = c[z - 1] != '/'; } else if (needslash) { luaL_addchar(&b, '/'); needslash = false; } } if (gotstr) { luaL_pushresult(&b); } else { lua_pushnil(L); } return 1; } else { luaL_error(L, "missing argument"); unreachable; } } static int CheckPath(lua_State *L, int type, int flags) { int olderr; struct stat st; const char *path; path = luaL_checkstring(L, 1); olderr = errno; if (fstatat(AT_FDCWD, path, &st, flags) != -1) { lua_pushboolean(L, !type || (st.st_mode & S_IFMT) == type); } else { errno = olderr; lua_pushboolean(L, false); } return 1; } // path.exists(str) // └─→ bool static int LuaPathExists(lua_State *L) { return CheckPath(L, 0, 0); } // path.isfile(str) // └─→ bool static int LuaPathIsfile(lua_State *L) { return CheckPath(L, S_IFREG, AT_SYMLINK_NOFOLLOW); } // path.islink(str) // └─→ bool static int LuaPathIslink(lua_State *L) { return CheckPath(L, S_IFLNK, AT_SYMLINK_NOFOLLOW); } // path.isdir(str) // └─→ bool static int LuaPathIsdir(lua_State *L) { return CheckPath(L, S_IFDIR, AT_SYMLINK_NOFOLLOW); } static const luaL_Reg kLuaPath[] = { {"basename", LuaPathBasename}, // {"dirname", LuaPathDirname}, // {"exists", LuaPathExists}, // {"isdir", LuaPathIsdir}, // {"isfile", LuaPathIsfile}, // {"islink", LuaPathIslink}, // {"join", LuaPathJoin}, // {0}, // }; int LuaPath(lua_State *L) { luaL_newlib(L, kLuaPath); return 1; }
5,184
167
jart/cosmopolitan
false
cosmopolitan/tool/net/ljson.h
#ifndef COSMOPOLITAN_TOOL_NET_LJSON_H_ #define COSMOPOLITAN_TOOL_NET_LJSON_H_ #include "third_party/lua/lauxlib.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct DecodeJson { int rc; const char *p; }; struct DecodeJson DecodeJson(struct lua_State *, const char *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_NET_LJSON_H_ */
411
17
jart/cosmopolitan
false
cosmopolitan/tool/net/net.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 += TOOL_NET TOOL_NET_FILES := $(wildcard tool/net/*) TOOL_NET_SRCS = $(filter %.c,$(TOOL_NET_FILES)) TOOL_NET_HDRS = $(filter %.h,$(TOOL_NET_FILES)) TOOL_NET_OBJS = \ $(TOOL_NET_SRCS:%.c=o/$(MODE)/%.o) TOOL_NET_BINS = \ $(TOOL_NET_COMS) \ $(TOOL_NET_COMS:%=%.dbg) TOOL_NET_COMS = \ o/$(MODE)/tool/net/dig.com \ o/$(MODE)/tool/net/redbean.com \ o/$(MODE)/tool/net/redbean-demo.com \ o/$(MODE)/tool/net/redbean-static.com \ o/$(MODE)/tool/net/redbean-unsecure.com \ o/$(MODE)/tool/net/redbean-original.com \ o/$(MODE)/tool/net/wb.com TOOL_NET_CHECKS = \ o/$(MODE)/tool/net/net.pkg \ $(TOOL_NET_HDRS:%=o/$(MODE)/%.ok) TOOL_NET_DIRECTDEPS = \ DSP_SCALE \ LIBC_CALLS \ LIBC_DNS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_IPHLPAPI \ LIBC_NT_KERNEL32 \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_THREAD \ LIBC_TINYMATH \ LIBC_X \ LIBC_ZIPOS \ NET_FINGER \ NET_HTTP \ NET_HTTPS \ THIRD_PARTY_ARGON2 \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_GDTOA \ THIRD_PARTY_GETOPT \ THIRD_PARTY_LINENOISE \ THIRD_PARTY_LUA \ THIRD_PARTY_LUA_UNIX \ THIRD_PARTY_MAXMIND \ THIRD_PARTY_MBEDTLS \ THIRD_PARTY_REGEX \ THIRD_PARTY_SQLITE3 \ THIRD_PARTY_ZLIB \ TOOL_ARGS \ TOOL_BUILD_LIB \ TOOL_DECODE_LIB \ THIRD_PARTY_DOUBLECONVERSION TOOL_NET_DEPS := \ $(call uniq,$(foreach x,$(TOOL_NET_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/net/net.pkg: \ $(TOOL_NET_OBJS) \ $(foreach x,$(TOOL_NET_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/net/%.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/%.o \ o/$(MODE)/tool/net/net.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) # REDBEAN.COM # # The little web server that could! TOOL_NET_REDBEAN_LUA_MODULES = \ o/$(MODE)/tool/net/lfuncs.o \ o/$(MODE)/tool/net/lpath.o \ o/$(MODE)/tool/net/lfinger.o \ o/$(MODE)/tool/net/lre.o \ o/$(MODE)/tool/net/ljson.o \ o/$(MODE)/tool/net/lmaxmind.o \ o/$(MODE)/tool/net/lsqlite3.o \ o/$(MODE)/tool/net/largon2.o TOOL_NET_REDBEAN_STANDARD_ASSETS = \ tool/net/.init.lua \ tool/net/favicon.ico \ tool/net/redbean.png \ tool/net/help.txt TOOL_NET_REDBEAN_STANDARD_ASSETS_ZIP = \ $(COMPILE) -AZIP -T$@ \ $(VM) o/$(MODE)/third_party/zip/zip.com -b$(TMPDIR) -9qj $@ \ $(TOOL_NET_REDBEAN_STANDARD_ASSETS) o/$(MODE)/tool/net/redbean.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean.o \ $(TOOL_NET_REDBEAN_LUA_MODULES) \ o/$(MODE)/tool/net/net.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/net/redbean.com: \ o/$(MODE)/tool/net/redbean.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(TOOL_NET_REDBEAN_STANDARD_ASSETS) \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) @$(TOOL_NET_REDBEAN_STANDARD_ASSETS_ZIP) o/$(MODE)/tool/net/lsqlite3.o: private \ OVERRIDE_CFLAGS += \ -DSQLITE_ENABLE_SESSION # REDBEAN-DEMO.COM # # This redbean-demo.com program is the same as redbean.com except it # bundles a bunch of example code and there's a live of it available # online at http://redbean.justine.lol/ o/$(MODE)/tool/net/.init.lua.zip.o \ o/$(MODE)/tool/net/demo/.init.lua.zip.o \ o/$(MODE)/tool/net/demo/.reload.lua.zip.o \ o/$(MODE)/tool/net/demo/sql.lua.zip.o \ o/$(MODE)/tool/net/demo/sql-backup.lua.zip.o \ o/$(MODE)/tool/net/demo/sql-backupstore.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-unix.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-rawsocket.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-subprocess.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-webserver.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-dir.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-info.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-finger.lua.zip.o \ o/$(MODE)/tool/net/demo/fetch.lua.zip.o \ o/$(MODE)/tool/net/demo/finger.lua.zip.o \ o/$(MODE)/tool/net/demo/call-lua-module.lua.zip.o \ o/$(MODE)/tool/net/demo/store-asset.lua.zip.o \ o/$(MODE)/tool/net/demo/maxmind.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean.lua.zip.o \ o/$(MODE)/tool/net/demo/opensource.lua.zip.o \ o/$(MODE)/tool/net/demo/hitcounter.lua.zip.o \ o/$(MODE)/tool/net/demo/binarytrees.lua.zip.o \ o/$(MODE)/tool/net/demo/crashreport.lua.zip.o \ o/$(MODE)/tool/net/demo/closedsource.lua.zip.o \ o/$(MODE)/tool/net/demo/printpayload.lua.zip.o \ o/$(MODE)/tool/net/demo/gensvg.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean-form.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean-xhr.lua.zip.o \ o/$(MODE)/tool/net/redbean.png.zip.o \ o/$(MODE)/tool/net/favicon.ico.zip.o \ o/$(MODE)/tool/net/help.txt.zip.o \ o/$(MODE)/tool/net/demo/404.html.zip.o: private \ ZIPOBJ_FLAGS += \ -B o/$(MODE)/tool/net/demo/.lua/.zip.o \ o/$(MODE)/tool/net/demo/.lua/mymodule.lua.zip.o: private \ ZIPOBJ_FLAGS += \ -C3 o/$(MODE)/tool/net/demo/seekable.txt.zip.o: private \ ZIPOBJ_FLAGS += \ -B \ -0 o/$(MODE)/tool/net/redbean-demo.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean.o \ $(TOOL_NET_REDBEAN_LUA_MODULES) \ o/$(MODE)/tool/net/net.pkg \ o/$(MODE)/tool/net/demo/sql.lua.zip.o \ o/$(MODE)/tool/net/demo/sql-backup.lua.zip.o \ o/$(MODE)/tool/net/demo/sql-backupstore.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-unix.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-rawsocket.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-subprocess.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-webserver.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-dir.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-info.lua.zip.o \ o/$(MODE)/tool/net/demo/unix-finger.lua.zip.o \ o/$(MODE)/tool/net/demo/fetch.lua.zip.o \ o/$(MODE)/tool/net/demo/finger.lua.zip.o \ o/$(MODE)/tool/net/demo/store-asset.lua.zip.o \ o/$(MODE)/tool/net/demo/call-lua-module.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean.lua.zip.o \ o/$(MODE)/tool/net/demo/maxmind.lua.zip.o \ o/$(MODE)/tool/net/demo/opensource.lua.zip.o \ o/$(MODE)/tool/net/demo/hitcounter.lua.zip.o \ o/$(MODE)/tool/net/demo/binarytrees.lua.zip.o \ o/$(MODE)/tool/net/demo/crashreport.lua.zip.o \ o/$(MODE)/tool/net/demo/closedsource.lua.zip.o \ o/$(MODE)/tool/net/demo/printpayload.lua.zip.o \ o/$(MODE)/tool/net/demo/gensvg.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean-form.lua.zip.o \ o/$(MODE)/tool/net/demo/redbean-xhr.lua.zip.o \ o/$(MODE)/tool/.zip.o \ o/$(MODE)/tool/net/.zip.o \ o/$(MODE)/tool/net/demo/.zip.o \ o/$(MODE)/tool/net/demo/index.html.zip.o \ o/$(MODE)/tool/net/demo/redbean.css.zip.o \ o/$(MODE)/tool/net/redbean.png.zip.o \ o/$(MODE)/tool/net/favicon.ico.zip.o \ o/$(MODE)/tool/net/demo/404.html.zip.o \ o/$(MODE)/tool/net/demo/seekable.txt.zip.o \ o/$(MODE)/tool/net/demo/.lua/.zip.o \ o/$(MODE)/tool/net/demo/.lua/mymodule.lua.zip.o \ o/$(MODE)/tool/net/demo/.reload.lua.zip.o \ o/$(MODE)/tool/net/demo/.init.lua.zip.o \ o/$(MODE)/tool/net/help.txt.zip.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/net/redbean-demo.com: \ o/$(MODE)/tool/net/redbean-demo.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) # REDBEAN-STATIC.COM # # Passing the -DSTATIC causes Lua and SQLite to be removed. This reduces # the binary size from roughly 1500 kb to 500 kb. It still supports SSL. o/$(MODE)/tool/net/redbean-static.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean-static.o \ o/$(MODE)/tool/net/net.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/net/redbean-static.com: \ o/$(MODE)/tool/net/redbean-static.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(TOOL_NET_REDBEAN_STANDARD_ASSETS) \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) @$(TOOL_NET_REDBEAN_STANDARD_ASSETS_ZIP) # REDBEAN-UNSECURE.COM # # Passing the -DUNSECURE will cause the TLS security code to be removed. # That doesn't mean redbean becomes insecure. It just reduces complexity # in situations where you'd rather have SSL be handled in an edge proxy. o/$(MODE)/tool/net/redbean-unsecure.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean-unsecure.o \ $(TOOL_NET_REDBEAN_LUA_MODULES) \ o/$(MODE)/tool/net/net.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/net/redbean-unsecure.com: \ o/$(MODE)/tool/net/redbean-unsecure.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(TOOL_NET_REDBEAN_STANDARD_ASSETS) \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) @$(TOOL_NET_REDBEAN_STANDARD_ASSETS_ZIP) # REDBEAN-ORIGINAL.COM # # Passing the -DSTATIC and -DUNSECURE flags together w/ MODE=tiny will # produce 200kb binary that's very similar to redbean as it existed on # Hacker News the day it went viral. o/$(MODE)/tool/net/redbean-original.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean-original.o \ o/$(MODE)/tool/net/net.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/net/redbean-original.com: \ o/$(MODE)/tool/net/redbean-original.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(TOOL_NET_REDBEAN_STANDARD_ASSETS) \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) @$(TOOL_NET_REDBEAN_STANDARD_ASSETS_ZIP) o/$(MODE)/tool/net/demo/.lua/.zip.o: \ tool/net/demo/.lua o/$(MODE)/tool/net/demo/.zip.o: \ tool/net/demo o/$(MODE)/tool/net/.zip.o: \ tool/net o/$(MODE)/tool/.zip.o: \ tool .PHONY: o/$(MODE)/tool/net o/$(MODE)/tool/net: \ $(TOOL_NET_BINS) \ $(TOOL_NET_CHECKS)
10,716
333
jart/cosmopolitan
false
cosmopolitan/tool/net/redbean-original.c
#define STATIC #define UNSECURE #define REDBEAN "redbean-original" #include "tool/net/redbean.c"
97
5
jart/cosmopolitan
false
cosmopolitan/tool/net/dig.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/dns/dns.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sock.h" #include "tool/decode/lib/flagger.h" #include "tool/decode/lib/idname.h" #include "tool/decode/lib/socknames.h" void lookup(const char *name) { int rc; struct addrinfo *ai = NULL; struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP}; switch ((rc = getaddrinfo(name, "80", &hint, &ai))) { case EAI_SUCCESS: break; case EAI_SYSTEM: perror("getaddrinfo"); exit(1); default: fprintf(stderr, "getaddrinfo failed: %d (EAI_%s)\n", rc, gai_strerror(rc)); exit(1); } if (ai) { for (struct addrinfo *addr = ai; addr; addr = addr->ai_next) { const unsigned char *ip = addr->ai_family == AF_INET ? (const unsigned char *)&((struct sockaddr_in *)addr->ai_addr) ->sin_addr : (const unsigned char *)"\0\0\0\0"; printf("%-12s = %s\n", "ai_flags", RecreateFlags(kAddrInfoFlagNames, addr->ai_flags), addr->ai_flags); printf("%-12s = %s (%d)\n", "ai_family", findnamebyid(kAddressFamilyNames, addr->ai_family), addr->ai_family); printf("%-12s = %s (%d)\n", "ai_socktype", findnamebyid(kSockTypeNames, addr->ai_socktype), addr->ai_socktype); printf("%-12s = %s (%d)\n", "ai_protocol", findnamebyid(kProtocolNames, addr->ai_protocol), addr->ai_protocol); printf("%-12s = %d\n", "ai_addrlen", addr->ai_addrlen); printf("%-12s = %hhu.%hhu.%hhu.%hhu\n", "ai_addr", ip[0], ip[1], ip[2], ip[3]); printf("%-12s = %s\n", "ai_canonname", addr->ai_canonname); } freeaddrinfo(ai); } else { fprintf(stderr, "%s: %s\n", name, "no results"); } } int main(int argc, char *argv[]) { int i; ShowCrashReports(); for (i = 1; i < argc; ++i) lookup(argv[i]); return 0; }
3,972
82
jart/cosmopolitan
false
cosmopolitan/tool/net/lfuncs.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 "tool/net/lfuncs.h" #include "dsp/scale/cdecimate2xuint8x8.h" #include "libc/calls/calls.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/stat.h" #include "libc/dns/dns.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/fmt/leb128.h" #include "libc/intrin/bits.h" #include "libc/intrin/bsf.h" #include "libc/intrin/bsr.h" #include "libc/intrin/popcnt.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/bench.h" #include "libc/nexgen32e/crc32.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/rdtscp.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/rusage.h" #include "libc/sysv/consts/sock.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "net/http/escape.h" #include "net/http/http.h" #include "net/http/ip.h" #include "net/http/url.h" #include "third_party/lua/cosmo.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/lua.h" #include "third_party/lua/luaconf.h" #include "third_party/lua/lunix.h" #include "third_party/mbedtls/md.h" #include "third_party/mbedtls/md5.h" #include "third_party/mbedtls/platform.h" #include "third_party/mbedtls/sha1.h" #include "third_party/mbedtls/sha256.h" #include "third_party/mbedtls/sha512.h" #include "third_party/zlib/zlib.h" static int Rdpid(void) { #ifdef __x86_64__ return rdpid(); #else return -1; #endif } int LuaHex(lua_State *L) { char b[19]; uint64_t x; x = luaL_checkinteger(L, 1); FormatHex64(b, x, true); lua_pushstring(L, b); return 1; } int LuaOct(lua_State *L) { char b[24]; uint64_t x; x = luaL_checkinteger(L, 1); FormatOctal64(b, x, true); lua_pushstring(L, b); return 1; } int LuaBin(lua_State *L) { char b[67]; uint64_t x; x = luaL_checkinteger(L, 1); FormatBinary64(b, x, 2); lua_pushstring(L, b); return 1; } int LuaGetTime(lua_State *L) { lua_pushnumber(L, nowl()); return 1; } int LuaSleep(lua_State *L) { usleep(1e6 * luaL_checknumber(L, 1)); return 0; } int LuaRdtsc(lua_State *L) { lua_pushinteger(L, rdtsc()); return 1; } int LuaGetCpuNode(lua_State *L) { lua_pushinteger(L, TSC_AUX_NODE(Rdpid())); return 1; } int LuaGetCpuCore(lua_State *L) { lua_pushinteger(L, TSC_AUX_CORE(Rdpid())); return 1; } int LuaGetCpuCount(lua_State *L) { lua_pushinteger(L, _getcpucount()); return 1; } int LuaGetLogLevel(lua_State *L) { lua_pushinteger(L, __log_level); return 1; } int LuaSetLogLevel(lua_State *L) { __log_level = luaL_checkinteger(L, 1); return 0; } static int LuaRand(lua_State *L, uint64_t impl(void)) { lua_pushinteger(L, impl()); return 1; } int LuaLemur64(lua_State *L) { return LuaRand(L, lemur64); } int LuaRand64(lua_State *L) { return LuaRand(L, _rand64); } int LuaRdrand(lua_State *L) { return LuaRand(L, rdrand); } int LuaRdseed(lua_State *L) { return LuaRand(L, rdseed); } int LuaDecimate(lua_State *L) { char *p; size_t n, m; const char *s; luaL_Buffer buf; s = luaL_checklstring(L, 1, &n); m = ROUNDUP(n, 16); p = luaL_buffinitsize(L, &buf, m); memcpy(p, s, n); bzero(p + n, m - n); cDecimate2xUint8x8(m, (unsigned char *)p, (signed char[8]){-1, -3, 3, 17, 17, 3, -3, -1}); luaL_pushresultsize(&buf, (n + 1) >> 1); return 1; } int LuaMeasureEntropy(lua_State *L) { size_t n; const char *s; s = luaL_checklstring(L, 1, &n); lua_pushnumber(L, MeasureEntropy(s, n)); return 1; } int LuaGetHostOs(lua_State *L) { const char *s = NULL; if (IsLinux()) { s = "LINUX"; } else if (IsMetal()) { s = "METAL"; } else if (IsWindows()) { s = "WINDOWS"; } else if (IsXnu()) { s = "XNU"; } else if (IsOpenbsd()) { s = "OPENBSD"; } else if (IsFreebsd()) { s = "FREEBSD"; } else if (IsNetbsd()) { s = "NETBSD"; } if (s) { lua_pushstring(L, s); } else { lua_pushnil(L); } return 1; } int LuaGetHostIsa(lua_State *L) { const char *s; #ifdef __x86_64__ s = "X86_64"; #elif defined(__aarch64__) s = "AARCH64"; #elif defined(__powerpc64__) s = "POWERPC64"; #elif defined(__s390x__) s = "S390X"; #else #error "unsupported architecture" #endif lua_pushstring(L, s); return 1; } int LuaFormatIp(lua_State *L) { char b[16]; uint32_t ip; ip = htonl(luaL_checkinteger(L, 1)); inet_ntop(AF_INET, &ip, b, sizeof(b)); lua_pushstring(L, b); return 1; } int LuaParseIp(lua_State *L) { size_t n; const char *s; s = luaL_checklstring(L, 1, &n); lua_pushinteger(L, ParseIp(s, n)); return 1; } static int LuaIsIp(lua_State *L, bool IsIp(uint32_t)) { lua_pushboolean(L, IsIp(luaL_checkinteger(L, 1))); return 1; } int LuaIsPublicIp(lua_State *L) { return LuaIsIp(L, IsPublicIp); } int LuaIsPrivateIp(lua_State *L) { return LuaIsIp(L, IsPrivateIp); } int LuaIsLoopbackIp(lua_State *L) { return LuaIsIp(L, IsLoopbackIp); } int LuaCategorizeIp(lua_State *L) { lua_pushstring(L, GetIpCategoryName(CategorizeIp(luaL_checkinteger(L, 1)))); return 1; } int LuaFormatHttpDateTime(lua_State *L) { char buf[30]; lua_pushstring(L, FormatUnixHttpDateTime(buf, luaL_checkinteger(L, 1))); return 1; } int LuaParseHttpDateTime(lua_State *L) { size_t n; const char *s; s = luaL_checklstring(L, 1, &n); lua_pushinteger(L, ParseHttpDateTime(s, n)); return 1; } int LuaParseParams(lua_State *L) { void *m; size_t size; const char *data; struct UrlParams h; if (!lua_isnoneornil(L, 1)) { data = luaL_checklstring(L, 1, &size); bzero(&h, sizeof(h)); if ((m = ParseParams(data, size, &h))) { LuaPushUrlParams(L, &h); free(h.p); free(m); return 1; } else { luaL_error(L, "out of memory"); unreachable; } } else { return lua_gettop(L); } } int LuaParseHost(lua_State *L) { void *m; size_t n; struct Url h; const char *p; if (!lua_isnoneornil(L, 1)) { bzero(&h, sizeof(h)); p = luaL_checklstring(L, 1, &n); if ((m = ParseHost(p, n, &h))) { lua_newtable(L); LuaPushUrlView(L, &h.host); LuaPushUrlView(L, &h.port); free(m); return 1; } else { luaL_error(L, "out of memory"); unreachable; } } else { return lua_gettop(L); } } int LuaPopcnt(lua_State *L) { lua_pushinteger(L, popcnt(luaL_checkinteger(L, 1))); return 1; } int LuaBsr(lua_State *L) { long x; if ((x = luaL_checkinteger(L, 1))) { lua_pushinteger(L, _bsrl(x)); return 1; } else { luaL_argerror(L, 1, "zero"); unreachable; } } int LuaBsf(lua_State *L) { long x; if ((x = luaL_checkinteger(L, 1))) { lua_pushinteger(L, _bsfl(x)); return 1; } else { luaL_argerror(L, 1, "zero"); unreachable; } } static int LuaHash(lua_State *L, uint32_t H(uint32_t, const void *, size_t)) { long i; size_t n; const char *p; i = luaL_checkinteger(L, 1); p = luaL_checklstring(L, 2, &n); lua_pushinteger(L, H(i, p, n)); return 1; } int LuaCrc32(lua_State *L) { return LuaHash(L, crc32_z); } int LuaCrc32c(lua_State *L) { return LuaHash(L, crc32c); } int LuaIndentLines(lua_State *L) { void *p; size_t n, j; if (!lua_isnoneornil(L, 1)) { p = luaL_checklstring(L, 1, &n); j = luaL_optinteger(L, 2, 1); if (!(0 <= j && j <= 65535)) { luaL_argerror(L, 2, "not in range 0..65535"); unreachable; } p = IndentLines(p, n, &n, j); lua_pushlstring(L, p, n); free(p); return 1; } else { return lua_gettop(L); } } int LuaGetMonospaceWidth(lua_State *L) { int w; if (lua_isnumber(L, 1)) { w = wcwidth(lua_tointeger(L, 1)); } else if (lua_isstring(L, 1)) { w = strwidth(luaL_checkstring(L, 1), luaL_optinteger(L, 2, 0) & 7); } else { luaL_argerror(L, 1, "not integer or string"); unreachable; } lua_pushinteger(L, w); return 1; } // Slurp(path:str[, i:int[, j:int]]) // ├─→ data:str // └─→ nil, unix.Errno int LuaSlurp(lua_State *L) { ssize_t rc; char tb[2048]; luaL_Buffer b; struct stat st; int fd, olderr; bool shouldpread; lua_Integer i, j, got; olderr = errno; if (lua_isnoneornil(L, 2)) { i = 1; } else { i = luaL_checkinteger(L, 2); } if (lua_isnoneornil(L, 3)) { j = LUA_MAXINTEGER; } else { j = luaL_checkinteger(L, 3); } luaL_buffinit(L, &b); if ((fd = open(luaL_checkstring(L, 1), O_RDONLY | O_SEQUENTIAL)) == -1) { return LuaUnixSysretErrno(L, "open", olderr); } if (i < 0 || j < 0) { if (fstat(fd, &st) == -1) { close(fd); return LuaUnixSysretErrno(L, "fstat", olderr); } if (i < 0) { i = st.st_size + (i + 1); } if (j < 0) { j = st.st_size + (j + 1); } } if (i < 1) { i = 1; } shouldpread = i > 1; for (; i <= j; i += got) { if (shouldpread) { rc = pread(fd, tb, MIN(j - i + 1, sizeof(tb)), i - 1); } else { rc = read(fd, tb, MIN(j - i + 1, sizeof(tb))); } if (rc != -1) { got = rc; if (!got) break; luaL_addlstring(&b, tb, got); } else if (errno == EINTR) { errno = olderr; got = 0; } else { close(fd); return LuaUnixSysretErrno(L, "read", olderr); } } if (close(fd) == -1) { return LuaUnixSysretErrno(L, "close", olderr); } luaL_pushresult(&b); return 1; } // Barf(path:str, data:str[, mode:int[, flags:int[, offset:int]]]) // ├─→ true // └─→ nil, unix.Errno int LuaBarf(lua_State *L) { char *data; ssize_t rc; lua_Number offset; size_t i, n, wrote; int fd, mode, flags, olderr; olderr = errno; data = luaL_checklstring(L, 2, &n); if (lua_isnoneornil(L, 5)) { offset = 0; } else { offset = luaL_checkinteger(L, 5); if (offset < 1) { luaL_error(L, "offset must be >= 1"); unreachable; } --offset; } mode = luaL_optinteger(L, 3, 0644); flags = O_WRONLY | O_SEQUENTIAL | luaL_optinteger(L, 4, O_TRUNC | O_CREAT); if (flags & O_NONBLOCK) { luaL_error(L, "O_NONBLOCK not allowed"); unreachable; } if ((flags & O_APPEND) && offset) { luaL_error(L, "O_APPEND with offset not possible"); unreachable; } if ((fd = open(luaL_checkstring(L, 1), flags, mode)) == -1) { return LuaUnixSysretErrno(L, "open", olderr); } for (i = 0; i < n; i += wrote) { if (offset) { rc = pwrite(fd, data + i, n - i, offset + i); } else { rc = write(fd, data + i, n - i); } if (rc != -1) { wrote = rc; } else if (errno == EINTR) { errno = olderr; wrote = 0; } else { close(fd); return LuaUnixSysretErrno(L, "write", olderr); } } if (close(fd) == -1) { return LuaUnixSysretErrno(L, "close", olderr); } lua_pushboolean(L, true); return 1; } int LuaResolveIp(lua_State *L) { ssize_t rc; int64_t ip; const char *host; struct addrinfo *ai = NULL; struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP}; host = luaL_checkstring(L, 1); if ((ip = ParseIp(host, -1)) != -1) { lua_pushinteger(L, ip); return 1; } else if ((rc = getaddrinfo(host, "0", &hint, &ai)) == EAI_SUCCESS) { lua_pushinteger(L, ntohl(ai->ai_addr4->sin_addr.s_addr)); freeaddrinfo(ai); return 1; } else { lua_pushnil(L); lua_pushfstring(L, "%s: DNS lookup failed: EAI_%s", host, gai_strerror(rc)); return 2; } } static int LuaCheckControlFlags(lua_State *L, int idx) { int f = luaL_optinteger(L, idx, 0); if (f & ~(kControlWs | kControlC0 | kControlC1)) { luaL_argerror(L, idx, "invalid control flags"); unreachable; } return f; } int LuaHasControlCodes(lua_State *L) { int f; size_t n; const char *p; p = luaL_checklstring(L, 1, &n); f = LuaCheckControlFlags(L, 2); lua_pushboolean(L, HasControlCodes(p, n, f) != -1); return 1; } int LuaEncodeLatin1(lua_State *L) { int f; char *p; size_t n; p = luaL_checklstring(L, 1, &n); f = LuaCheckControlFlags(L, 2); if ((p = EncodeLatin1(p, n, &n, f))) { lua_pushlstring(L, p, n); free(p); return 1; } else { luaL_error(L, "out of memory"); unreachable; } } int LuaGetRandomBytes(lua_State *L) { size_t n; luaL_Buffer buf; n = luaL_optinteger(L, 1, 16); if (!(n > 0 && n <= 256)) { luaL_argerror(L, 1, "not in range 1..256"); unreachable; } CHECK_EQ(n, getrandom(luaL_buffinitsize(L, &buf, n), n, 0)); luaL_pushresultsize(&buf, n); return 1; } int LuaGetHttpReason(lua_State *L) { lua_pushstring(L, GetHttpReason(luaL_checkinteger(L, 1))); return 1; } int LuaGetCryptoHash(lua_State *L) { size_t hl, pl, kl; uint8_t d[64]; mbedtls_md_context_t ctx; // get hash name, payload, and key void *h = luaL_checklstring(L, 1, &hl); void *p = luaL_checklstring(L, 2, &pl); void *k = luaL_optlstring(L, 3, "", &kl); const mbedtls_md_info_t *digest = mbedtls_md_info_from_string(h); if (!digest) return luaL_argerror(L, 1, "unknown hash type"); if (kl == 0) { // no key provided, run generic hash function if ((digest->f_md)(p, pl, d)) return luaL_error(L, "bad input data"); } else if (mbedtls_md_hmac(digest, k, kl, p, pl, d)) { return luaL_error(L, "bad input data"); } lua_pushlstring(L, (void *)d, digest->size); mbedtls_platform_zeroize(d, sizeof(d)); return 1; } static dontinline int LuaIsValid(lua_State *L, bool V(const char *, size_t)) { size_t size; const char *data; data = luaL_checklstring(L, 1, &size); lua_pushboolean(L, V(data, size)); return 1; } int LuaIsValidHttpToken(lua_State *L) { return LuaIsValid(L, IsValidHttpToken); } int LuaIsAcceptablePath(lua_State *L) { return LuaIsValid(L, IsAcceptablePath); } int LuaIsReasonablePath(lua_State *L) { return LuaIsValid(L, IsReasonablePath); } int LuaIsAcceptableHost(lua_State *L) { return LuaIsValid(L, IsAcceptableHost); } int LuaIsAcceptablePort(lua_State *L) { return LuaIsValid(L, IsAcceptablePort); } static dontinline int LuaCoderImpl(lua_State *L, char *C(const char *, size_t, size_t *)) { void *p; size_t n; if (!lua_isnoneornil(L, 1)) { p = luaL_checklstring(L, 1, &n); if ((p = C(p, n, &n))) { lua_pushlstring(L, p, n); free(p); } else { luaL_error(L, "out of memory"); unreachable; } return 1; } else { return lua_gettop(L); } } static dontinline int LuaCoder(lua_State *L, char *C(const char *, size_t, size_t *)) { return LuaCoderImpl(L, C); } int LuaUnderlong(lua_State *L) { return LuaCoder(L, Underlong); } int LuaEncodeBase64(lua_State *L) { return LuaCoder(L, EncodeBase64); } int LuaDecodeBase64(lua_State *L) { return LuaCoder(L, DecodeBase64); } int LuaDecodeLatin1(lua_State *L) { return LuaCoder(L, DecodeLatin1); } int LuaEscapeHtml(lua_State *L) { return LuaCoder(L, EscapeHtml); } int LuaEscapeParam(lua_State *L) { return LuaCoder(L, EscapeParam); } int LuaEscapePath(lua_State *L) { return LuaCoder(L, EscapePath); } int LuaEscapeHost(lua_State *L) { return LuaCoder(L, EscapeHost); } int LuaEscapeIp(lua_State *L) { return LuaCoder(L, EscapeIp); } int LuaEscapeUser(lua_State *L) { return LuaCoder(L, EscapeUser); } int LuaEscapePass(lua_State *L) { return LuaCoder(L, EscapePass); } int LuaEscapeSegment(lua_State *L) { return LuaCoder(L, EscapeSegment); } int LuaEscapeFragment(lua_State *L) { return LuaCoder(L, EscapeFragment); } int LuaEscapeLiteral(lua_State *L) { char *p, *q = 0; size_t n, y = 0; p = luaL_checklstring(L, 1, &n); if ((p = EscapeJsStringLiteral(&q, &y, p, n, &n))) { lua_pushlstring(L, p, n); free(q); return 1; } else { luaL_error(L, "out of memory"); unreachable; } } int LuaVisualizeControlCodes(lua_State *L) { return LuaCoder(L, VisualizeControlCodes); } static dontinline int LuaHasherImpl(lua_State *L, size_t k, int H(const void *, size_t, uint8_t *)) { void *p; size_t n; uint8_t d[64]; if (!lua_isnoneornil(L, 1)) { p = luaL_checklstring(L, 1, &n); H(p, n, d); lua_pushlstring(L, (void *)d, k); mbedtls_platform_zeroize(d, sizeof(d)); return 1; } else { return lua_gettop(L); } } static dontinline int LuaHasher(lua_State *L, size_t k, int H(const void *, size_t, uint8_t *)) { return LuaHasherImpl(L, k, H); } int LuaMd5(lua_State *L) { return LuaHasher(L, 16, mbedtls_md5_ret); } int LuaSha1(lua_State *L) { return LuaHasher(L, 20, mbedtls_sha1_ret); } int LuaSha224(lua_State *L) { return LuaHasher(L, 28, mbedtls_sha256_ret_224); } int LuaSha256(lua_State *L) { return LuaHasher(L, 32, mbedtls_sha256_ret_256); } int LuaSha384(lua_State *L) { return LuaHasher(L, 48, mbedtls_sha512_ret_384); } int LuaSha512(lua_State *L) { return LuaHasher(L, 64, mbedtls_sha512_ret_512); } int LuaIsHeaderRepeatable(lua_State *L) { int h; bool r; size_t n; const char *s; s = luaL_checklstring(L, 1, &n); if ((h = GetHttpHeader(s, n)) != -1) { r = kHttpRepeatable[h]; } else { r = false; } lua_pushboolean(L, r); return 1; } void LuaPushUrlView(lua_State *L, struct UrlView *v) { if (v->p) { lua_pushlstring(L, v->p, v->n); } else { lua_pushnil(L); } } static int64_t GetInterrupts(void) { struct rusage ru; if (!getrusage(RUSAGE_SELF, &ru)) { return ru.ru_nivcsw; } else { return 0; } } static int DoNothing(lua_State *L) { return 0; } int LuaBenchmark(lua_State *L) { uint64_t t1, t2; int64_t interrupts; double avgticks, overhead; int core, iter, count, tries, attempts, maxattempts; luaL_checktype(L, 1, LUA_TFUNCTION); count = luaL_optinteger(L, 2, 100); maxattempts = luaL_optinteger(L, 3, 10); __warn_if_powersave(); lua_gc(L, LUA_GCSTOP); for (attempts = 0;;) { lua_gc(L, LUA_GCCOLLECT); sched_yield(); core = TSC_AUX_CORE(Rdpid()); interrupts = GetInterrupts(); for (avgticks = iter = 1; iter < count; ++iter) { lua_pushcfunction(L, DoNothing); t1 = __startbench_m(); lua_call(L, 0, 0); t2 = __endbench_m(); avgticks += 1. / iter * ((int)(t2 - t1) - avgticks); } ++attempts; if (TSC_AUX_CORE(Rdpid()) == core && GetInterrupts() == interrupts) { break; } else if (attempts >= maxattempts) { luaL_error(L, "system is under too much load to run benchmark"); unreachable; } } overhead = avgticks; for (attempts = 0;;) { lua_gc(L, LUA_GCCOLLECT); sched_yield(); core = TSC_AUX_CORE(Rdpid()); interrupts = GetInterrupts(); for (avgticks = iter = 1; iter < count; ++iter) { lua_pushvalue(L, 1); t1 = __startbench_m(); lua_call(L, 0, 0); t2 = __endbench_m(); avgticks += 1. / iter * ((int)(t2 - t1) - avgticks); } ++attempts; if (TSC_AUX_CORE(Rdpid()) == core && GetInterrupts() == interrupts) { break; } else if (attempts >= maxattempts) { luaL_error(L, "system is under too much load to run benchmark"); unreachable; } } avgticks = MAX(avgticks - overhead, 0); lua_gc(L, LUA_GCRESTART); lua_pushinteger(L, ConvertTicksToNanos(round(avgticks))); lua_pushinteger(L, round(avgticks)); lua_pushinteger(L, round(overhead)); lua_pushinteger(L, attempts); return 4; } static void LuaCompress2(lua_State *L, void *dest, size_t *destLen, const void *source, size_t sourceLen, int level) { switch (compress2(dest, destLen, source, sourceLen, level)) { case Z_OK: break; case Z_BUF_ERROR: luaL_error(L, "out of memory"); unreachable; case Z_STREAM_ERROR: luaL_error(L, "invalid level"); unreachable; default: unreachable; } } // VERY DEPRECATED - PLEASE DO NOT USE int LuaCompress(lua_State *L) { size_t n, m; char *q, *e; uint32_t crc; const char *p; luaL_Buffer buf; int level, hdrlen; p = luaL_checklstring(L, 1, &n); level = luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION); m = compressBound(n); if (lua_toboolean(L, 3)) { // raw mode q = luaL_buffinitsize(L, &buf, m); LuaCompress2(L, q, &m, p, n, level); } else { // easy mode q = luaL_buffinitsize(L, &buf, 10 + 4 + m); crc = crc32_z(0, p, n); e = uleb64(q, n); e = WRITE32LE(e, crc); hdrlen = e - q; LuaCompress2(L, q + hdrlen, &m, p, n, level); m += hdrlen; } luaL_pushresultsize(&buf, m); return 1; } // VERY DEPRECATED - PLEASE DO NOT USE int LuaUncompress(lua_State *L) { int rc; char *q; uint32_t crc; const char *p; luaL_Buffer buf; size_t n, m, len; p = luaL_checklstring(L, 1, &n); if (lua_isnoneornil(L, 2)) { if ((rc = unuleb64(p, n, &m)) == -1 || n < rc + 4) { luaL_error(L, "compressed value too short to be valid"); unreachable; } len = m; crc = READ32LE(p + rc); q = luaL_buffinitsize(L, &buf, m); if (uncompress((void *)q, &m, (unsigned char *)p + rc + 4, n) != Z_OK || m != len || crc32_z(0, q, m) != crc) { luaL_error(L, "compressed value is corrupted"); unreachable; } } else { len = m = luaL_checkinteger(L, 2); q = luaL_buffinitsize(L, &buf, m); if (uncompress((void *)q, &m, (void *)p, n) != Z_OK || m != len) { luaL_error(L, "compressed value is corrupted"); unreachable; } } luaL_pushresultsize(&buf, m); return 1; } // unix.deflate(uncompressed:str[, level:int]) // ├─→ compressed:str // └─→ nil, error:str int LuaDeflate(lua_State *L) { char *out; z_stream zs; int rc, level; const char *in; luaL_Buffer buf; size_t insize, outsize, actualoutsize; in = luaL_checklstring(L, 1, &insize); level = luaL_optinteger(L, 2, Z_DEFAULT_COMPRESSION); outsize = compressBound(insize); out = luaL_buffinitsize(L, &buf, outsize); zs.next_in = (const uint8_t *)in; zs.avail_in = insize; zs.next_out = (uint8_t *)out; zs.avail_out = outsize; zs.zalloc = Z_NULL; zs.zfree = Z_NULL; if ((rc = deflateInit2(&zs, level, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) != Z_OK) { lua_pushnil(L); lua_pushfstring(L, "%s() failed: %d", "deflateInit2", rc); return 2; } rc = deflate(&zs, Z_FINISH); actualoutsize = outsize - zs.avail_out; deflateEnd(&zs); if (rc != Z_STREAM_END) { lua_pushnil(L); lua_pushfstring(L, "%s() failed: %d", "deflate", rc); return 2; } luaL_pushresultsize(&buf, actualoutsize); return 1; } // unix.inflate(compressed:str, maxoutsize:int) // ├─→ uncompressed:str // └─→ nil, error:str int LuaInflate(lua_State *L) { int rc; char *out; z_stream zs; const char *in; luaL_Buffer buf; size_t insize, outsize, actualoutsize; in = luaL_checklstring(L, 1, &insize); outsize = luaL_checkinteger(L, 2); out = luaL_buffinitsize(L, &buf, outsize); zs.next_in = (const uint8_t *)in; zs.avail_in = insize; zs.total_in = insize; zs.next_out = (uint8_t *)out; zs.avail_out = outsize; zs.total_out = outsize; zs.zalloc = Z_NULL; zs.zfree = Z_NULL; if ((rc = inflateInit2(&zs, -MAX_WBITS)) != Z_OK) { lua_pushnil(L); lua_pushfstring(L, "%s() failed: %d", "inflateInit2", rc); return 2; } rc = inflate(&zs, Z_FINISH); actualoutsize = outsize - zs.avail_out; inflateEnd(&zs); if (rc != Z_STREAM_END) { lua_pushnil(L); lua_pushfstring(L, "%s() failed: %d", "inflate", rc); return 2; } luaL_pushresultsize(&buf, actualoutsize); return 1; }
25,751
1,058
jart/cosmopolitan
false
cosmopolitan/tool/net/lfuncs.h
#ifndef COSMOPOLITAN_TOOL_NET_LFUNCS_H_ #define COSMOPOLITAN_TOOL_NET_LFUNCS_H_ #include "net/http/url.h" #include "third_party/lua/lua.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int LuaMaxmind(lua_State *); int LuaRe(lua_State *); int luaopen_argon2(lua_State *); int luaopen_lsqlite3(lua_State *); int LuaBarf(lua_State *); int LuaBenchmark(lua_State *); int LuaBin(lua_State *); int LuaBsf(lua_State *); int LuaBsr(lua_State *); int LuaCategorizeIp(lua_State *); int LuaCompress(lua_State *); int LuaCrc32(lua_State *); int LuaCrc32c(lua_State *); int LuaDecimate(lua_State *); int LuaDecodeBase64(lua_State *); int LuaDecodeLatin1(lua_State *); int LuaDeflate(lua_State *); int LuaEncodeBase64(lua_State *); int LuaEncodeLatin1(lua_State *); int LuaEscapeFragment(lua_State *); int LuaEscapeHost(lua_State *); int LuaEscapeHtml(lua_State *); int LuaEscapeIp(lua_State *); int LuaEscapeLiteral(lua_State *); int LuaEscapeParam(lua_State *); int LuaEscapePass(lua_State *); int LuaEscapePath(lua_State *); int LuaEscapeSegment(lua_State *); int LuaEscapeUser(lua_State *); int LuaFormatHttpDateTime(lua_State *); int LuaFormatIp(lua_State *); int LuaGetCpuCore(lua_State *); int LuaGetCpuCount(lua_State *); int LuaGetCpuNode(lua_State *); int LuaGetCryptoHash(lua_State *); int LuaGetHostIsa(lua_State *); int LuaGetHostOs(lua_State *); int LuaGetHttpReason(lua_State *); int LuaGetLogLevel(lua_State *); int LuaGetMonospaceWidth(lua_State *); int LuaGetRandomBytes(lua_State *); int LuaGetTime(lua_State *); int LuaHasControlCodes(lua_State *); int LuaHex(lua_State *); int LuaIndentLines(lua_State *); int LuaInflate(lua_State *); int LuaIsAcceptableHost(lua_State *); int LuaIsAcceptablePath(lua_State *); int LuaIsAcceptablePort(lua_State *); int LuaIsHeaderRepeatable(lua_State *); int LuaIsLoopbackIp(lua_State *); int LuaIsPrivateIp(lua_State *); int LuaIsPublicIp(lua_State *); int LuaIsReasonablePath(lua_State *); int LuaIsValidHttpToken(lua_State *); int LuaLemur64(lua_State *); int LuaMd5(lua_State *); int LuaMeasureEntropy(lua_State *); int LuaOct(lua_State *); int LuaParseHost(lua_State *); int LuaParseHttpDateTime(lua_State *); int LuaParseIp(lua_State *); int LuaParseParams(lua_State *); int LuaPopcnt(lua_State *); int LuaRand64(lua_State *); int LuaRdrand(lua_State *); int LuaRdseed(lua_State *); int LuaRdtsc(lua_State *); int LuaResolveIp(lua_State *); int LuaSetLogLevel(lua_State *); int LuaSha1(lua_State *); int LuaSha224(lua_State *); int LuaSha256(lua_State *); int LuaSha384(lua_State *); int LuaSha512(lua_State *); int LuaSleep(lua_State *); int LuaSlurp(lua_State *); int LuaUncompress(lua_State *); int LuaUnderlong(lua_State *); int LuaVisualizeControlCodes(lua_State *); void LuaPushUrlView(lua_State *, struct UrlView *); char *FormatUnixHttpDateTime(char *, int64_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_NET_LFUNCS_H_ */
2,948
96
jart/cosmopolitan
false
cosmopolitan/tool/net/help.txt
SYNOPSIS redbean.com [-?BVabdfghjkmsuvz] [-p PORT] [-D DIR] [-- SCRIPTARGS...] DESCRIPTION redbean - single-file distributable web server OVERVIEW redbean makes it possible to share web applications that run offline as a single-file Actually Portable Executable PKZIP archive which contains your assets. All you need to do is download the redbean.com program below, change the filename to .zip, add your content in a zip editing tool, and then change the extension back to .com. redbean can serve 1 million+ gzip encoded responses per second on a cheap personal computer. That performance is thanks to zip and gzip using the same compression format, which enables kernelspace copies. Another reason redbean goes fast is that it's a tiny static binary, which makes fork memory paging nearly free. redbean is also easy to modify to suit your own needs. The program itself is written as a single .c file. It embeds the Lua programming language and SQLite which let you write dynamic pages. FEATURES - Lua v5.4 - SQLite 3.35.5 - TLS v1.2 / v1.1 / v1.0 - HTTP v1.1 / v1.0 / v0.9 - Chromium-Zlib Compression - Statusz Monitoring Statistics - Self-Modifying PKZIP Object Store - Linux + Windows + Mac + FreeBSD + OpenBSD + NetBSD FLAGS -h or -? help -d daemonize -u uniprocess -z print port -m log messages -i interpreter mode -b log message bodies -a log resource usage -g log handler latency -E show crash reports to public ips -j enable ssl client verify -k disable ssl fetch verify -Z log worker system calls -f log worker function calls -B only use stronger cryptography -X disable ssl server and client support -* permit self-modification of executable -J disable non-ssl server and client support -% hasten startup by not generating an rsa key -s increase silence [repeatable] -v increase verbosity [repeatable] -V increase ssl verbosity [repeatable] -S increase pledge sandboxing [repeatable] -e CODE eval Lua code in arg [repeatable] -F PATH eval Lua code in file [repeatable] -H K:V sets http header globally [repeatable] -D DIR overlay assets in local directory [repeatable] -r /X=/Y redirect X to Y [repeatable] -R /X=/Y rewrites X to Y [repeatable] -K PATH tls private key path [repeatable] -C PATH tls certificate(s) path [repeatable] -A PATH add assets with path (recursive) [repeatable] -M INT tunes max message payload size [def. 65536] -t INT timeout ms or keepalive sec if <0 [def. 60000] -p PORT listen port [def. 8080; repeatable] -l ADDR listen addr [def. 0.0.0.0; repeatable] -c SEC configures static cache-control -W TTY use tty path to monitor memory pages -L PATH log file location -P PATH pid file location -U INT daemon set user id -G INT daemon set group id -w PATH launch browser on startup --strace enables system call tracing (see also -Z) --ftrace enables function call tracing (see also -f) KEYBOARD CTRL-D EXIT CTRL-C CTRL-C EXIT CTRL-E END CTRL-A START CTRL-B BACK CTRL-F FORWARD CTRL-L CLEAR CTRL-H BACKSPACE CTRL-D DELETE CTRL-N NEXT HISTORY CTRL-P PREVIOUS HISTORY CTRL-R SEARCH HISTORY CTRL-G CANCEL SEARCH ALT-< BEGINNING OF HISTORY ALT-> END OF HISTORY ALT-F FORWARD WORD ALT-B BACKWARD WORD CTRL-RIGHT FORWARD WORD CTRL-LEFT BACKWARD WORD CTRL-K KILL LINE FORWARDS CTRL-U KILL LINE BACKWARDS ALT-H KILL WORD BACKWARDS CTRL-W KILL WORD BACKWARDS CTRL-ALT-H KILL WORD BACKWARDS ALT-D KILL WORD FORWARDS CTRL-Y YANK ALT-Y ROTATE KILL RING AND YANK AGAIN CTRL-T TRANSPOSE ALT-T TRANSPOSE WORD ALT-U UPPERCASE WORD ALT-L LOWERCASE WORD ALT-C CAPITALIZE WORD CTRL-\ QUIT PROCESS CTRL-S PAUSE OUTPUT CTRL-Q UNPAUSE OUTPUT (IF PAUSED) CTRL-Q ESCAPED INSERT CTRL-ALT-F FORWARD EXPR CTRL-ALT-B BACKWARD EXPR ALT-RIGHT FORWARD EXPR ALT-LEFT BACKWARD EXPR ALT-SHIFT-B BARF EXPR ALT-SHIFT-S SLURP EXPR CTRL-SPACE SET MARK CTRL-X CTRL-X GOTO MARK CTRL-Z SUSPEND PROCESS ALT-\ SQUEEZE ADJACENT WHITESPACE PROTIP REMAP CAPS LOCK TO CTRL ──────────────────────────────────────────────────────────────────────────────── USAGE This executable is also a ZIP file that contains static assets. You can run redbean interactively in your terminal as follows: ./redbean.com -vvvmbag # starts server verbosely open http://127.0.0.1:8080/ # shows zip listing page CTRL-C # 1x: graceful shutdown CTRL-C # 2x: forceful shutdown You can override the default listing page by adding: zip redbean.com index.lua # lua server pages take priority zip redbean.com index.html # default page for directory The listing page only applies to the root directory. However the default index page applies to subdirectories too. In order for it to work, there needs to be an empty directory entry in the zip. That should already be the default practice of your zip editor. wget \ --mirror \ --convert-links \ --adjust-extension \ --page-requisites \ --no-parent \ --no-if-modified-since \ http://a.example/index.html zip -r redbean.com a.example/ # default page for directory redbean normalizes the trailing slash for you automatically: $ printf 'GET /a.example HTTP/1.0\n\n' | nc 127.0.0.1 8080 HTTP/1.0 307 Temporary Redirect Location: /a.example/ Virtual hosting is accomplished this way too. The Host is simply prepended to the path, and if it doesn't exist, it gets removed. $ printf 'GET / HTTP/1.1\nHost:a.example\n\n' | nc 127.0.0.1 8080 HTTP/1.1 200 OK Link: <http://127.0.0.1/a.example/index.html>; rel="canonical" If you mirror a lot of websites within your redbean then you can actually tell your browser that redbean is your proxy server, in which redbean will act as your private version of the Internet. $ printf 'GET http://a.example HTTP/1.0\n\n' | nc 127.0.0.1 8080 HTTP/1.0 200 OK Link: <http://127.0.0.1/a.example/index.html>; rel="canonical" If you use a reverse proxy, then redbean recognizes the following provided that the proxy forwards requests over the local network: X-Forwarded-For: 203.0.113.42:31337 X-Forwarded-Host: foo.example:80 There's a text/plain statistics page called /statusz that makes it easy to track and monitor the health of your redbean: printf 'GET /statusz\n\n' | nc 127.0.0.1 8080 redbean will display an error page using the /redbean.png logo by default, embedded as a bas64 data uri. You can override the custom page for various errors by adding files to the zip root. zip redbean.com 404.html # custom not found page Audio video content should not be compressed in your ZIP files. Uncompressed assets enable browsers to send Range HTTP request. On the other hand compressed assets are best for gzip encoding. zip redbean.com index.html # adds file zip -0 redbean.com video.mp4 # adds without compression You can have redbean run as a daemon by doing the following: sudo ./redbean.com -vvdp80 -p443 -L redbean.log -P redbean.pid kill -TERM $(cat redbean.pid) # 1x: graceful shutdown kill -TERM $(cat redbean.pid) # 2x: forceful shutdown redbean currently has a 32kb limit on request messages and 64kb including the payload. redbean will grow to whatever the system limits allow. Should fork() or accept() fail redbean will react by going into "meltdown mode" which closes lingering workers. You can trigger this at any time using: kill -USR2 $(cat redbean.pid) Another failure condition is running out of disk space in which case redbean reacts by truncating the log file. Lastly, redbean does the best job possible reporting on resource usage when the logger is in debug mode noting that NetBSD is the best at this. Your redbean is an actually portable executable, that's able to run on six different operating systems. To do that, it needs to extract a 4kb loader program to ${TMPDIR:-${HOME:-.}}/.ape that'll map your redbean into memory. It does however check to see if `ape` is on the system path beforehand. You can also "assimilate" any redbean into the platform-local executable format by running: $ file redbean.com redbean.com: DOS/MBR boot sector $ ./redbean.com --assimilate $ file redbean.com redbean.com: ELF 64-bit LSB executable ──────────────────────────────────────────────────────────────────────────────── SECURITY redbean uses a protocol polyglot for serving HTTP and HTTPS on the same port numbers. For example, both of these are valid: http://127.0.0.1:8080/ https://127.0.0.1:8080/ SSL verbosity is controlled as follows for troubleshooting: -V log ssl errors -VV log ssl state changes too -VVV log ssl informational messages too -VVVV log ssl verbose details too redbean provides hardened ASAN (Address Sanitizer) builds that proactively guard against any potential memory weaknesses that may be discovered, such as buffer overruns, use after free, etc. MDOE=asan is recomended when serving on the public Internet. redbean also supports robust sandboxing on Linux Kernel 5.13+ and OpenBSD. The recommended way to harden your redbean is to call the pledge() and unveil() functions. For example, if you have a SQLite app then the key to using these features is to connect to the db first: function OnWorkerStart() db = sqlite3.open("db.sqlite3") db:busy_timeout(1000) db:exec[[PRAGMA journal_mode=WAL]] db:exec[[PRAGMA synchronous=NORMAL]] db:exec[[SELECT x FROM warmup WHERE x = 1]] assert(unix.setrlimit(unix.RLIMIT_RSS, 100 * 1024 * 1024)) assert(unix.setrlimit(unix.RLIMIT_CPU, 4)) assert(unix.unveil("/var/tmp", "rwc")) assert(unix.unveil("/tmp", "rwc")) assert(unix.unveil(nil, nil)) assert(unix.pledge("stdio flock rpath wpath cpath", nil, unix.PLEDGE_PENALTY_RETURN_EPERM)) end What makes this technique interesting is redbean doesn't have file system access to the database file, and instead uses an inherited file descriptor that was opened beforehand. With SQLite the tmp access is only needed to support things like covering indexes. The -Z flag is also helpful to see where things go wrong, so you know which promises are needed to support your use case. pledge() will work on all Linux kernels since RHEL6 since it uses SECCOMP BPF filtering. On the other hand, unveil() requires Landlock LSM which was only introduced in 2021. If you need unveil() then be sure to test the restrictions work. Most environments don't support unveil(), so it's designed to be a no-op in unsupported environments. Alternatively, there's CLI flags which make it simple to get started: -S (online policy) This causes unix.pledge("stdio rpath inet dns id") to be called on workers after fork() is called. This permits read-only operations and APIs like Fetch() that let workers send and receive data with private and public Internet hosts. Access to the unix module is somewhat restricted, disallowing its more powerful APIs like exec. -SS (offline policy) This causes unix.pledge("stdio rpath id") to be called on workers after after fork() is called. This prevents workers from talking to the network (other than the client) and allows read-only file system access (e.g. `-D DIR` flag). The `id` group helps you to call other functions important to redbean security, such as the unix.setrlimit() function. -SSS (contained policy) This causes unix.pledge("stdio") to be called on workers after after fork() is called. This prevents workers from communicating with the network (other than the client connection) and prevents file system access (with some exceptions like logging). Redbean should only be able to serve from its own zip file in this mode. Lua script access to the unix module is highly restricted. Unlike the unix.pledge() function, these sandboxing flags use a more permissive policy on Linux. Rather than killing the process, they'll cause system calls to fail with EPERM instead. Therefore these flags should be gentler when you want security errors to be recoverable. See http://redbean.dev for further details. ──────────────────────────────────────────────────────────────────────────────── LUA SERVER PAGES Any files with the extension .lua will be dynamically served by redbean. Here's the simplest possible example: Write('<b>Hello World</b>') The Lua Server Page above should be able to perform at 700,000 responses per second on a Core i9, without any sort of caching. If you want a Lua handler that can do 1,000,000 responses per second, then try adding the following global handler to your /.init.lua file: function OnHttpRequest() Write('<b>Hello World</b>') end Here's an example of a more typical workflow for Lua Server Pages using the redbean API: SetStatus(200) SetHeader('Content-Type', 'text/plain; charset=utf-8') Write('<p>Hello ') Write(EscapeHtml(GetParam('name'))) We didn't need the first two lines in the previous example, because they're implied by redbean automatically if you don't set them. Responses are also buffered until the script finishes executing. That enables redbean to make HTTP as easy as possible. In the future, API capabilities will be expanded to make possible things like websockets. redbean embeds the Lua standard library. You can use packages such as io to persist and share state across requests and connections, as well as the StoreAsset function, and the lsqlite3 module. Your Lua interpreter begins its life in the main process at startup in the .init.lua, which is likely where you'll want to perform all your expensive one-time operations like importing modules. Then, as requests roll in, isolated processes are cloned from the blueprint you created. ──────────────────────────────────────────────────────────────────────────────── REPL Your redbean displays a Read-Eval-Print-Loop that lets you modify the state of the main server process while your server is running. Any changes will propagate into forked clients. Your REPL is displayed only when redbean is run as a non-daemon in a Unix terminal or the Windows 10 command prompt or PowerShell. Since the REPL is a Lua REPL it's not included in a redbean-static builds. redbean uses the same keyboard shortcuts as GNU Readline and Emacs. Some of its keyboard commands (listed in a previous section) were inspired by Paredit. A history of your commands is saved to `~/.redbean_history`. If you love the redbean repl and want to use it as your language interpreter then you can pass the `-i` flag to put redbean into interpreter mode. redbean.com -i binarytrees.lua 15 When the `-i` flag is passed (for interpreter mode), redbean won't start a web server and instead functions like the `lua` command. The first command line argument becomes the script you want to run. If you don't supply a script, then the repl without a web server is displayed. This is useful for testing since redbean extensions and modules for the Lua language, are still made available. You can also write redbean scripts with shebang lines: #!/usr/bin/redbean -i print('hello world') However UNIX operating systems usually require that interpreters be encoded in its preferred executable format. You can assimilate your redbean into the local format using the following commands: $ file redbean.com redbean.com: DOS/MBR boot sector $ ./redbean.com --assimilate $ file redbean.com redbean.com: ELF 64-bit LSB executable $ sudo cp redbean.com /usr/bin/redbean By following the above steps, redbean can be installed systemwide for multiple user accounts. It's also possible to chmod the binary to have setuid privileges. Please note that, if you do this, the UNIX section provides further details on APIs like `unix.setuid` that will help you remove root privileges from the process in the appropriate manner. ──────────────────────────────────────────────────────────────────────────────── LUA ENHANCEMENTS We've made some enhancements to the Lua language that should make it more comfortable for C/C++ and Python developers. Some of these - redbean supports a printf modulus operator, like Python. For example, you can say `"hello %s" % {"world"}` instead of `string.format("hello %s", "world")`. - redbean supports a string multiply operator, like Python. For example, you can say `"hi" * 2` instead of `string.rep("hi", 2)`. - redbean supports octal (base 8) integer literals. For example `0644 == 420` is the case in redbean, whereas in upstream Lua `0644 == 644` would be the case. - redbean supports binary (base 2) integer literals. For example `0b1010 == 10` is the case in redbean, whereas in upstream Lua `0b1010` would result in an error. - redbean supports the GNU syntax for the ASCII ESC character in string literals. For example, `"\e"` is the same as `"\x1b"`. ──────────────────────────────────────────────────────────────────────────────── GLOBALS arg: array[str] Array of command line arguments, excluding those parsed by getopt() in the C code, which stops parsing at the first non-hyphenated arg. In some cases you can use the magic -- argument to delimit C from Lua arguments. For example, if you launch your redbean as follows: redbean.com -v arg1 arg2 Then your `/.init.lua` file will have the `arg` array like: arg[-1] = '/usr/bin/redbean.com' arg[ 0] = '/zip/.init.lua' arg[ 1] = 'arg1' arg[ 2] = 'arg2' If you launch redbean in interpreter mode (rather than web server) mode, then an invocation like this: ./redbean.com -i script.lua arg1 arg2 Would have an `arg` array like this: arg[-1] = './redbean.com' arg[ 0] = 'script.lua' arg[ 1] = 'arg1' arg[ 2] = 'arg2' ──────────────────────────────────────────────────────────────────────────────── SPECIAL PATHS / redbean will generate a zip central directory listing for this page, and this page only, but only if there isn't an /index.lua or /index.html file defined. /.init.lua This script is run once in the main process at startup. This lets you modify the state of the Lua interpreter before connection processes are forked off. For example, it's a good idea to do expensive one-time computations here. You can also use this file to call the ProgramFOO() functions below. The init module load happens after redbean's arguments and zip assets have been parsed, but before calling functions like socket() and fork(). Note that this path is a hidden file so that it can't be unintentionally run by the network client. /.reload.lua This script is run from the main process when SIGHUP is received. This only applies to redbean when running in daemon mode. Any changes that are made to the Lua interpreter state will be inherited by future forked connection processes. Note that this path is a hidden file so that it can't be unintentionally run by the network client. /.lua/... Your Lua modules go in this directory. The way it works is redbean sets Lua's package.path to /zip/.lua/?.lua;/zip/.lua/?/init.lua by default. Cosmopolitan Libc lets system calls like open read from the ZIP structure, if the filename is prefixed with /zip/. So this works like magic. /redbean.png If it exists, it'll be used as the / listing page icon, embedded as a base64 URI. /usr/share/zoneinfo This directory contains a subset of the timezone database. Your `TZ` environment variable controls which one of these files is used by functions such as unix.localtime(). /usr/share/ssl/root This directory contains your root certificate authorities. It is needed so the Fetch() HTTPS client API can verify that a remote certificate was signed by a third party. You can add your own certificate files to this directory within the ZIP executable. If you enable HTTPS client verification then redbean will check that HTTPS clients (a) have a certificate and (b) it was signed. /.args Specifies default command-line arguments. There's one argument per line. Trailing newline is ignored. If the special argument `...` is *not* encountered, then the replacement will only happen if *no* CLI args are specified. If the special argument `...` *is* encountered, then it'll be replaced with whatever CLI args were specified by the user. For example, you might want to use redbean.com in interpreter mode, where your script file is inside the zip. Then, if your redbean is run, what you want is to have the default behavior be running your script. In that case, you might: $ cat <<'EOF' >.args -i /zip/hello.lua EOF $ cat <<'EOF' >hello.lua print("hello world") EOF $ zip redbean.com .args hello.lua $ ./redbean.com hello world Please note that if you ran: $ ./redbean.com -vv Then the default mode of redbean will kick back in. To prevent that from happening, simply add the magic arg `...` to the end of your `.args` file. ──────────────────────────────────────────────────────────────────────────────── HOOKS OnHttpRequest() If this function is defined in the global scope by your /.init.lua then redbean will call it at the earliest possible moment to hand over control for all messages (with the exception of OPTIONS *). See functions like Route which asks redbean to do its default thing from the handler. OnClientConnection(ip:int, port:int, serverip:int, serverport:int) → bool If this function is defined it'll be called from the main process each time redbean accepts a new client connection. If it returns `true`, redbean will close the connection without calling fork. OnLogLatency(reqtimeus:int, contimeus:int) If this function is defined it'll be called from the main process each time redbean completes handling of a request, but before the response is sent. The handler received the time (in µs) since the request handling and connection handling started. OnProcessCreate(pid:int, ip:int, port:int, serverip:int, serverport:int) If this function is defined it'll be called from the main process each time redbean forks a connection handler worker process. The ip/port of the remote client is provided, along with the ip/port of the listening interface that accepted the connection. This may be used to create a server activity dashboard, in which case the data provider handler should set SetHeader('Connection','Close'). This won't be called in uniprocess mode. OnProcessDestroy(pid:int) If this function is defined it'll be called from the main process each time redbean reaps a child connection process using wait4(). This won't be called in uniprocess mode. OnServerHeartbeat() If this function is defined it'll be called from the main process on each server heartbeat. The heartbeat interval is configurable with ProgramHeartbeatInterval. OnServerListen(socketdescriptor:int,serverip:int,serverport:int) → bool If this function is defined it'll be called from the main process before redbean starts listening on a port. This hook can be used to modify socket configuration to set `SO_REUSEPORT`, for example. If it returns `true`, redbean will not listen to that ip/port. OnServerStart() If this function is defined it'll be called from the main process right before the main event loop starts. OnServerStop() If this function is defined it'll be called from the main process after all the connection processes have been reaped and exit() is ready to be called. OnWorkerStart() If this function is defined it'll be called from the child worker process after it's been forked and before messages are handled. This won't be called in uniprocess mode. OnWorkerStop() If this function is defined it'll be called from the child worker process once _exit() is ready to be called. This won't be called in uniprocess mode. ──────────────────────────────────────────────────────────────────────────────── FUNCTIONS Write(data:str) Appends data to HTTP response payload buffer. This is buffered independently of headers. SetStatus(code:int[, reason:str]) Starts an HTTP response, specifying the parameters on its first line. reason is optional since redbean can fill in the appropriate text for well-known magic numbers, e.g. 200, 404, etc. This method will reset the response and is therefore mutually exclusive with ServeAsset and other Serve* functions. If this function isn't called, then the default behavior is to send 200 OK. SetHeader(name:str, value:str) Appends HTTP header to response header buffer. name is case-insensitive and restricted to non-space ASCII. value is a UTF-8 string that must be encodable as ISO-8859-1. Leading and trailing whitespace is trimmed automatically. Overlong characters are canonicalized. C0 and C1 control codes are forbidden, with the exception of tab. This function automatically calls SetStatus(200, "OK") if a status has not yet been set. As SetStatus and Serve* functions reset the response, SetHeader needs to be called after SetStatus and Serve* functions are called. The header buffer is independent of the payload buffer. Neither is written to the wire until the Lua Server Page has finished executing. This function disallows the setting of certain headers such as Content-Range and Date, which are abstracted by the transport layer. In such cases, consider calling ServeAsset. SetCookie(name:str, value:str[, options:table]) Appends Set-Cookie HTTP header to the response header buffer. Several Set-Cookie headers can be added to the same response. __Host- and __Secure- prefixes are supported and may set or overwrite some of the options (for example, specifying __Host- prefix sets the Secure option to true, sets the path to "/", and removes the Domain option). The following options can be used (their lowercase equivalents are supported as well): - Expires: sets the maximum lifetime of the cookie as an HTTP-date timestamp. Can be specified as a Date in the RFC1123 (string) format or as a UNIX timestamp (number of seconds). - MaxAge: sets number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and MaxAge are set, MaxAge has precedence. - Domain: sets the host to which the cookie will be sent. - Path: sets the path that must be present in the request URL, or the client will not send the Cookie header. - Secure: (bool) requests the cookie to be only send to the server when a request is made with the https: scheme. - HttpOnly: (bool) forbids JavaScript from accessing the cookie. - SameSite: (Strict, Lax, or None) controls whether a cookie is sent with cross-origin requests, providing some protection against cross-site request forgery attacks. GetParam(name:str) → value:str Returns first value associated with name. name is handled in a case-sensitive manner. This function checks Request-URL parameters first. Then it checks application/x-www-form-urlencoded from the message body, if it exists, which is common for HTML forms sending POST requests. If a parameter is supplied matching name that has no value, e.g. foo in ?foo&bar=value, then the returned value will be nil, whereas for ?foo=&bar=value it would be "". To differentiate between no-equal and absent, use the HasParam function. The returned value is decoded from ISO-8859-1 (only in the case of Request-URL) and we assume that percent-encoded characters were supplied by the client as UTF-8 sequences, which are returned exactly as the client supplied them, and may therefore may contain overlong sequences, control codes, NUL characters, and even numbers which have been banned by the IETF. It is the responsibility of the caller to impose further restrictions on validity, if they're desired. EscapeHtml(str) → str Escapes HTML entities: The set of entities is &><"' which become &amp;&gt;&lt;&quot;&#39;. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See escapehtml.c. LaunchBrowser([path:str]) Launches web browser on local machine with URL to this redbean server. It is the responsibility of the caller to escape the path with EscapePath if needed, as it's not escaped automatically. This function may be called from /.init.lua. CategorizeIp(ip:uint32) → str Returns a string describing an IP address. This is currently Class A granular. It can tell you if traffic originated from private networks, ARIN, APNIC, DOD, etc. DecodeBase64(ascii:str) → binary:str Turns ASCII into binary, in a permissive way that ignores characters outside the base64 alphabet, such as whitespace. See decodebase64.c. DecodeLatin1(iso-8859-1:str) → utf-8:str Turns ISO-8859-1 string into UTF-8. EncodeBase64(binary:str) → ascii:str Turns binary into ASCII. This can be used to create HTML data: URIs that do things like embed a PNG file in a web page. See encodebase64.c. DecodeJson(input:str) ├─→ int64 ├─→ string ├─→ double ├─→ array ├─→ object ├─→ false ├─→ true ├─→ nil └─→ nil, error:str Turns JSON string into a Lua data structure. This is a generally permissive parser, in the sense that like v8, it permits scalars as top-level values. Therefore we must note that this API can be thought of as special, in the sense val = assert(DecodeJson(str)) will usually do the right thing, except in cases where false or null are the top-level value. In those cases, it's needed to check the second value too in order to discern from error val, err = DecodeJson(str) if not val then if err then print('bad json', err) elseif val == nil then print('val is null') elseif val == false then print('val is false') end end This parser supports 64-bit signed integers. If an overflow happens, then the integer is silently coerced to double, as consistent with v8. If a double overflows into Infinity, we coerce it to `null` since that's what v8 does, and the same goes for underflows which, like v8, are coerced to 0.0. When objects are parsed, your Lua object can't preserve the the original ordering of fields. As such, they'll be sorted by EncodeJson() and may not round-trip with original intent This parser has perfect conformance with JSONTestSuite. This parser validates utf-8 and utf-16. EncodeJson(value[, options:table]) ├─→ json:str ├─→ true [if useoutput] └─→ nil, error:str Turns Lua data structure into JSON string. Since Lua tables are both hashmaps and arrays, we use a simple fast algorithm for telling the two apart. Tables with non-zero length (as reported by `#`) are encoded as arrays, and any non-array elements are ignored. For example: >: EncodeJson({2}) "[2]" >: EncodeJson({[1]=2, ["hi"]=1}) "[2]" If there are holes in your array, then the serialized array will exclude everything after the first hole. If the beginning of your array is a hole, then an error is returned. >: EncodeJson({[1]=1, [3]=3}) "[1]" >: EncodeJson({[2]=1, [3]=3}) "[]" >: EncodeJson({[2]=1, [3]=3}) nil "json objects must only use string keys" If the raw length of a table is reported as zero, then we check for the magic element `[0]=false`. If it's present, then your table will be serialized as empty array `[]`. An entry is inserted by DecodeJson() automatically, only when encountering empty arrays, and it's necessary in order to make empty arrays round-trip. If raw length is zero and `[0]=false` is absent, then your table will be serialized as an iterated object. >: EncodeJson({}) "{}" >: EncodeJson({[0]=false}) "[]" >: EncodeJson({["hi"]=1}) "{\"hi\":1}" >: EncodeJson({["hi"]=1, [0]=false}) "[]" >: EncodeJson({["hi"]=1, [7]=false}) nil "json objects must only use string keys" The following options may be used: - useoutput: (bool=false) encodes the result directly to the output buffer and returns `true` value. This option is ignored if used outside of request handling code. - sorted: (bool=true) Lua uses hash tables so the order of object keys is lost in a Lua table. So, by default, we use `strcmp` to impose a deterministic output order. If you don't care about ordering then setting `sorted=false` should yield a performance boost in serialization. - pretty: (bool=false) Setting this option to `true` will cause tables with more than one entry to be formatted across multiple lines for readability. - indent: (str=" ") This option controls the indentation of pretty formatting. This field is ignored if `pretty` isn't `true`. - maxdepth: (int=64) This option controls the maximum amount of recursion the serializer is allowed to perform. The max is 32767. You might not be able to set it that high if there isn't enough C stack memory. Your serializer checks for this and will return an error rather than crashing. This function will return an error if: - `value` is cyclic - `value` has depth greater than 64 - `value` contains functions, user data, or threads - `value` is table that blends string / non-string keys - Your serializer runs out of C heap memory (setrlimit) We assume strings in `value` contain UTF-8. This serializer currently does not produce UTF-8 output. The output format is right now ASCII. Your UTF-8 data will be safely transcoded to \uXXXX sequences which are UTF-16. Overlong encodings in your input strings will be canonicalized rather than validated. NaNs are serialized as `null` and Infinities are `null` which is consistent with the v8 behavior. EncodeLua(value[, options:table]) ├─→ luacode:str ├─→ true [if useoutput] └─→ nil, error:str Turns Lua data structure into Lua code string. Since Lua uses tables as both hashmaps and arrays, tables will only be serialized as an array with determinate order, if it's an array in the strictest possible sense. 1. for all 𝑘=𝑣 in table, 𝑘 is an integer ≥1 2. no holes exist between MIN(𝑘) and MAX(𝑘) 3. if non-empty, MIN(𝑘) is 1 In all other cases, your table will be serialized as an object which is iterated and displayed as a list of (possibly) sorted entries that have equal signs. >: EncodeLua({3, 2}) "{3, 2}" >: EncodeLua({[1]=3, [2]=3}) "{3, 2}" >: EncodeLua({[1]=3, [3]=3}) "{[1]=3, [3]=3}" >: EncodeLua({["hi"]=1, [1]=2}) "{[1]=2, hi=1}" The following options may be used: - useoutput: (bool=false) encodes the result directly to the output buffer and returns `true` value. This option is ignored if used outside of request handling code. - sorted: (bool=true) Lua uses hash tables so the order of object keys is lost in a Lua table. So, by default, we use `strcmp` to impose a deterministic output order. If you don't care about ordering then setting `sorted=false` should yield a performance boost in serialization. - pretty: (bool=false) Setting this option to `true` will cause tables with more than one entry to be formatted across multiple lines for readability. - indent: (str=" ") This option controls the indentation of pretty formatting. This field is ignored if `pretty` isn't `true`. - maxdepth: (int=64) This option controls the maximum amount of recursion the serializer is allowed to perform. The max is 32767. You might not be able to set it that high if there isn't enough C stack memory. Your serializer checks for this and will return an error rather than crashing. If a user data object has a `__repr` or `__tostring` meta method, then that'll be used to encode the Lua code. This serializer is designed primarily to describe data. For example, it's used by the REPL where we need to be able to ignore errors when displaying data structures, since showing most things imperfectly is better than crashing. Therefore this isn't the kind of serializer you'd want to use to persist data in prod. Try using the JSON serializer for that purpose. Non-encodable value types (e.g. threads, functions) will be represented as a string literal with the type name and pointer address. The string description is of an unspecified format that could most likely change. This encoder detects cyclic tables; however instead of failing, it embeds a string of unspecified layout describing the cycle. Integer literals are encoded as decimal. However if the int64 number is ≥256 and has a population count of 1 then we switch to representing the number in hexadecimal, for readability. Hex numbers have leading zeroes added in order to visualize whether the number fits in a uint16, uint32, or int64. Also some numbers can only be encoded expressionally. For example, NaNs are serialized as `0/0`, and Infinity is `math.huge`. >: 7000 7000 >: 0x100 0x0100 >: 0x10000 0x00010000 >: 0x100000000 0x0000000100000000 >: 0/0 0/0 >: 1.5e+9999 math.huge >: -9223372036854775807 - 1 -9223372036854775807 - 1 The only failure return condition currently implemented is when C runs out of heap memory. EncodeLatin1(utf-8:str[, flags:int]) → iso-8859-1:str Turns UTF-8 into ISO-8859-1 string. EscapeFragment(str) → str Escapes URL #fragment. The allowed characters are -/?.~_@:!$&'()*+,;=0-9A-Za-z and everything else gets %XX encoded. Please note that '& can still break HTML and that '() can still break CSS URLs. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See kescapefragment.S. EscapeHost(str) → str Escapes URL host. See kescapeauthority.S EscapeLiteral(str) → str Escapes JavaScript or JSON string literal content. The caller is responsible for adding the surrounding quotation marks. This implementation \uxxxx sequences for all non-ASCII sequences. HTML entities are also encoded, so the output doesn't need EscapeHtml. This function assumes UTF-8 input. Overlong encodings are canonicalized. Invalid input sequences are assumed to be ISO-8859-1. The output is UTF-16 since that's what JavaScript uses. For example, some individual codepoints such as emoji characters will encode as multiple \uxxxx sequences. Ints that are impossible to encode as UTF-16 are substituted with the \xFFFD replacement character. See escapejsstringliteral.c. EscapeParam(str) → str Escapes URL parameter name or value. The allowed characters are -.*_0-9A-Za-z and everything else gets %XX encoded. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See kescapeparam.S. EscapePass(str) → str Escapes URL password. See kescapeauthority.S. EscapePath(str) → str Escapes URL path. This is the same as EscapeSegment except slash is allowed. The allowed characters are -.~_@:!$&'()*+,;=0-9A-Za-z/ and everything else gets %XX encoded. Please note that '& can still break HTML, so the output may need EscapeHtml too. Also note that '() can still break CSS URLs. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See kescapepath.S. EscapeSegment(str) → str Escapes URL path segment. This is the same as EscapePath except slash isn't allowed. The allowed characters are -.~_@:!$&'()*+,;=0-9A-Za-z and everything else gets %XX encoded. Please note that '& can still break HTML, so the output may need EscapeHtml too. Also note that '() can still break CSS URLs. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See kescapesegment.S. EscapeUser(str) → str Escapes URL username. See kescapeauthority.S. EvadeDragnetSurveillance(bool) If this option is programmed then redbean will not transmit a Server Name Indicator (SNI) when performing Fetch() requests. This function is not available in unsecure mode. Fetch(url:str[,body:str|{method=value:str,body=value:str,headers=table,...}]) ├─→ status:int, {header:str=value:str,...}, body:str └─→ nil, error:str Sends an HTTP/HTTPS request to the specified URL. If only the URL is provided, then a GET request is sent. If both URL and body parameters are specified, then a POST request is sent. If any other method needs to be specified (for example, PUT or DELETE), then passing a table as the second value allows setting request method, body, and headers, as well as some other options: - method (default = "GET"): sets the method to be used for the request. The specified method is converted to uppercase. - body (default = ""): sets the body value to be sent. - headers: sets headers for the request using the key/value pairs from this table. Only string keys are used and all the values are converted to strings. - followredirect (default = true): forces temporary and permanent redirects to be followed. This behavior can be disabled by passing `false`. - maxredirects (default = 5): sets the number of allowed redirects to minimize looping due to misconfigured servers. When the number is exceeded, the last response is returned. - keepalive (default = false): configures each request to keep the connection open (unless closed by the server) and reuse for the next request to the same host. This option is disabled when SSL connection is used. The mapping of hosts and their sockets is stored in a table assigned to the `keepalive` field itself, so it can be passed to the next call. If the table includes the `close` field set to a true value, then the connection is closed after the request is made and the host is removed from the mapping table. When the redirect is being followed, the same method and body values are being sent in all cases except when 303 status is returned. In that case the method is set to GET and the body is removed before the redirect is followed. Note that if these (method/body) values are provided as table fields, they will be modified in place. FormatHttpDateTime(seconds:int) → rfc1123:str Converts UNIX timestamp to an RFC1123 string that looks like this: Mon, 29 Mar 2021 15:37:13 GMT. See formathttpdatetime.c. FormatIp(uint32) → str Turns integer like 0x01020304 into a string like 1.2.3.4. See also ParseIp for the inverse operation. GetAssetComment(path:str) → str Returns comment text associated with asset in the ZIP central directory. Also available as GetComment (deprecated). GetAssetLastModifiedTime(path:str) → seconds:number Returns UNIX timestamp for modification time of a ZIP asset (or local file if the -D flag is used). If both a file and a ZIP asset are present, then the file is used. Also available as GetLastModifiedTime (deprecated). GetAssetMode(path:str) → int Returns UNIX-style octal mode for ZIP asset (or local file if the -D flag is used). If both a file and a ZIP asset are present, then the file is used. GetAssetSize(path:str) → int Returns byte size of uncompressed contents of ZIP asset (or local file if the -D flag is used). If both a file and a ZIP asset are present, then the file is used. GetBody() → str Returns the request message body if present or an empty string. Also available as GetPayload (deprecated). GetCookie(name:str) → str Returns cookie value. GetCryptoHash(name:str,payload:str[,key:str]) → str Returns value of the specified cryptographic hash function. If the key is provided, then HMAC value of the same function is returned. The name can be one of the following strings: MD5, SHA1, SHA224, SHA256, SHA384, SHA512, and BLAKE2B256. GetRemoteAddr() → ip:uint32,port:uint16 Returns client ip4 address and port, e.g. 0x01020304,31337 would represent 1.2.3.4:31337. This is the same as GetClientAddr except it will use the ip:port from the X-Forwarded-For header, only if IsPrivateIp or IsLoopbackIp return true. When multiple addresses are present in the header, the last/right-most address is used. GetResponseBody() ├─→ body:str └─→ nil, error:str Returns the (uncompressed) response message body if present or an empty string. May also return a partial or empty string during streaming, as the full content may not be known at the call time. Returns an error when decompression fails. GetClientAddr() → ip:uint32,port:uint16 Returns client socket ip4 address and port, e.g. 0x01020304,31337 would represent 1.2.3.4:31337. Please consider using GetRemoteAddr instead, since the latter takes into consideration reverse proxy scenarios. GetClientFd() → int Returns file descriptor being used for client connection. This is useful for scripts that want to use unix:fork(). IsClientUsingSsl() → bool Returns true if client connection has begun being managed by the MbedTLS security layer. This is an important thing to consider if a script is taking control of GetClientFd() GetServerAddr() → ip:uint32,port:uint16 Returns address to which listening server socket is bound, e.g. 0x01020304,8080 would represent 1.2.3.4:8080. If -p 0 was supplied as the listening port, then the port in this string will be whatever number the operating system assigned. GetDate() → seconds:int Returns date associated with request that's used to generate the Date header, which is now, give or take a second. The returned value is a UNIX timestamp. GetHeader(name:str) → value:str Returns HTTP header. name is case-insensitive. The header value is returned as a canonical UTF-8 string, with leading and trailing whitespace trimmed, which was decoded from ISO-8859-1, which is guaranteed to not have C0/C1 control sequences, with the exception of the tab character. Leading and trailing whitespace is automatically removed. In the event that the client suplies raw UTF-8 in the HTTP message headers, the original UTF-8 sequence can be losslessly restored by counter-intuitively recoding the returned string back to Latin1. If the requested header is defined by the RFCs as storing comma-separated values (e.g. Allow, Accept-Encoding) and the field name occurs multiple times in the message, then this function will fold those multiple entries into a single string. GetHeaders() → {name:str=value:str,...} Returns HTTP headers as dictionary mapping header key strings to their UTF-8 decoded values. The ordering of headers from the request message is not preserved. Whether or not the same key can repeat depends on whether or not it's a standard header, and if so, if it's one of the ones that the RFCs define as repeatable. See khttprepeatable.c. Those headers will not be folded. Standard headers which aren't on that list, will be overwritten with the last-occurring one during parsing. Extended headers are always passed through exactly as they're received. Please consider using GetHeader API if possible since it does a better job abstracting these issues. GetLogLevel() → int Returns logger verbosity level. Likely return values are kLogDebug > kLogVerbose > kLogInfo > kLogWarn > kLogError > kLogFatal. GetHost() → str Returns host associated with request. This will be the Host header, if it's supplied. Otherwise it's the bind address. GetHostOs() → str Returns string that describes the host OS. This can return: - `"LINUX"` - `"METAL"` - `"WINDOWS"` - `"XNU"` - `"NETBSD"` - `"FREEBSD"` - `"OPENBSD"` GetHostIsa() → str Returns string describing host instruction set architecture. This can return: - `"X86_64"` for Intel and AMD systems - `"AARCH64"` for ARM64, M1, and Raspberry Pi systems - `"POWERPC64"` for OpenPOWER Raptor Computing Systems GetMonospaceWidth(str|char) → int Returns monospace display width of string. This is useful for fixed-width formatting. For example, CJK characters typically take up two cells. This function takes into consideration combining characters, which are discounted, as well as control codes and ANSI escape sequences. GetMethod() → str Returns HTTP method. Normally this will be GET, HEAD, or POST in which case redbean normalizes this value to its uppercase form. Anything else that the RFC classifies as a "token" string is accepted too, which might contain characters like &". GetParams() → {{name:str[,value:str]},...} Returns name=value parameters from Request-URL and application/x-www-form-urlencoded message body in the order they were received. This may contain duplicates. The inner array will have either one or two items, depending on whether or not the equals sign was used. GetPath() → str Returns the Request-URL path. This is guaranteed to begin with "/". It is further guaranteed that no "//" or "/." exists in the path. The returned value is returned as a UTF-8 string which was decoded from ISO-8859-1. We assume that percent-encoded characters were supplied by the client as UTF-8 sequences, which are returned exactly as the client supplied them, and may therefore may contain overlong sequences, control codes, NUL characters, and even numbers which have been banned by the IETF. redbean takes those things into consideration when performing path safety checks. It is the responsibility of the caller to impose further restrictions on validity, if they're desired. GetEffectivePath() → str Returns path as it was resolved by the routing algorithms, which might contain the virtual host prepended if used. GetScheme() → str Returns scheme from Request-URL, if any. GetSslIdentity() → str Returns certificate subject or PSK identity from the current SSL session. `nil` is returned for regular (non-SSL) connections. GetStatus() → int Returns current status (as set by an earlier SetStatus call) or `nil` if the status hasn't been set yet. GetTime() → seconds:number Returns current time as a UNIX timestamp with 0.0001s precision. GetUrl() → str Returns the effective Request-URL as an ASCII string, where illegal characters or UTF-8 is guaranteed to be percent encoded, and has been normalized to include either the Host or X-Forwarded-Host headers, if they exist, and possibly a scheme too if redbean is being used as an HTTP proxy server. In the future this API might change to return an object instead. GetHttpVersion() → int Returns the request HTTP protocol version, which can be 9 for HTTP/0.9, 10 for HTTP/1.0, or 11 for HTTP/1.1. Also available as GetVersion (deprecated). GetHttpReason(code:int) → str Returns a string describing the HTTP reason phrase. See gethttpreason.c GetRandomBytes([length:int]) → str Returns string with the specified number of random bytes (1..256). If no length is specified, then a string of length 16 is returned. GetRedbeanVersion() → int Returns the Redbean version in the format 0xMMmmpp, with major (MM), minor (mm), and patch (pp) versions encoded. The version value 1.4 would be represented as 0x010400. GetZipPaths([prefix:str]) → {path:str,...} Returns paths of all assets in the zip central directory, prefixed by a slash. If prefix parameter is provided, then only paths that start with the prefix (case sensitive) are returned. HasParam(name:str) → bool Returns true if parameter with name was supplied in either the Request-URL or an application/x-www-form-urlencoded message body. HidePath(prefix:str) Programs redbean / listing page to not display any paths beginning with prefix. This function should only be called from /.init.lua. IsHiddenPath(path:str) → bool Returns true if the prefix of the given path is set with HidePath. IsPublicIp(uint32) → bool Returns true if IP address is not a private network (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and is not localhost (127.0.0.0/8). Note: we intentionally regard TEST-NET IPs as public. IsPrivateIp(uint32) → bool Returns true if IP address is part of a private network (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). IsLoopbackIp(uint32) → bool Returns true if IP address is part of the localhost network (127.0.0.0/8). IsAssetCompressed(path:str) → bool Returns true if ZIP artifact at path is stored on disk using DEFLATE compression. Also available as IsCompressed (deprecated). IndentLines(str[, int]) → str Adds spaces to beginnings of multiline string. If the int parameter is not supplied then 1 space will be added. LoadAsset(path:str) → str Returns contents of file as string. The asset may be sourced from either the zip (decompressed) or the local filesystem if the -D flag was used. If slurping large file into memory is a concern, then consider using ServeAsset which can serve directly off disk. StoreAsset(path:str, data:str[, mode:int]) Stores asset to executable's ZIP central directory. This currently happens in an append-only fashion and is still largely in the proof-of-concept stages. Currently only supported on Linux, XNU, and FreeBSD. In order to use this feature, the -* flag must be passed. Log(level:int, message:str) Emits message string to log, if level is less than or equal to GetLogLevel. If redbean is running in interactive mode, then this will log to the console. If redbean is running as a daemon or the -L LOGFILE flag is passed, then this will log to the file. Reasonable values for level are kLogDebug > kLogVerbose > kLogInfo > kLogWarn > kLogError > kLogFatal. The logger emits timestamps in the local timezone with microsecond precision. If log entries are emitted more frequently than once per second, then the log entry will display a delta timestamp, showing how much time has elapsed since the previous log entry. This behavior is useful for quickly measuring how long various portions of your code take to execute. ParseHttpDateTime(rfc1123:str) → seconds:int Converts RFC1123 string that looks like this: Mon, 29 Mar 2021 15:37:13 GMT to a UNIX timestamp. See parsehttpdatetime.c. ParseUrl(url:str[, flags:int]) → URL Parses URL. An object containing the following fields is returned: - `scheme` is a string, e.g. `"http"` - `user` is the username string, or nil if absent - `pass` is the password string, or nil if absent - `host` is the hostname string, or nil if `url` was a path - `port` is the port string, or nil if absent - `path` is the path string, or nil if absent - `params` is the URL paramaters, e.g. `/?a=b&c` would be represented as the data structure `{{"a", "b"}, {"c"}, ...}` - `fragment` is the stuff after the `#` character `flags` may have: - `kUrlPlus` to turn `+` into space - `kUrlLatin1` to transcode ISO-8859-1 input into UTF-8 This parser is charset agnostic. Percent encoded bytes are decoded for all fields. 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 data 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 data:opaque, better in fact than most things which claim to be URI parsers. IsAcceptablePath(str) → bool Returns true if path doesn't contain ".", ".." or "//" segments See isacceptablepath.c IsReasonablePath(str) → bool Returns true if path doesn't contain "." or ".." segments. See isreasonablepath.c EncodeUrl(URL) → str This function is the inverse of ParseUrl. The output will always be correctly formatted. The exception is if illegal characters are supplied in the scheme field, since there's no way of escaping those. Opaque parts are escaped as though they were paths, since many URI parsers won't understand things like an unescaped question mark in path. ParseIp(str) → int Converts IPv4 address string to integer, e.g. "1.2.3.4" → 0x01020304, or returns -1 for invalid inputs. See also FormatIp for the inverse operation. ProgramAddr(ip:int) ProgramAddr(host:str) Configures the address on which to listen. This can be called multiple times to set more than one address. If an integer is provided then it should be a word-encoded IPv4 address, such as the ones returned by ResolveIp(). If a string is provided, it will first be passed to ParseIp() to see if it's an IPv4 address. If it isn't, then a HOSTS.TXT lookup is performed, with fallback to the system-configured DNS resolution service. Please note that in MODE=tiny the HOSTS.TXT and DNS resolution isn't included, and therefore an IP must be provided. ProgramBrand(str) Changes HTTP Server header, as well as the <h1> title on the / listing page. The brand string needs to be a UTF-8 value that's encodable as ISO-8859-1. If the brand is changed to something other than redbean, then the promotional links will be removed from the listing page too. This function should only be called from /.init.lua. ProgramCache(seconds:int[, directive:string]) Configures Cache-Control and Expires header generation for static asset serving. A negative value will disable the headers. Zero means don't cache. Greater than zero asks public proxies and browsers to cache for a given number of seconds. The directive value is added to the Cache-Control header when specified (with "must-revalidate" provided by default) and can be set to an empty string to remove the default value. This function should only be called from /.init.lua. ProgramCertificate(pem:str) Same as the -C flag if called from .init.lua, e.g. ProgramCertificate(LoadAsset("/.sign.crt")) for zip loading or ProgramCertificate(Slurp("/etc/letsencrypt.lol/fullchain.pem")) for local file system only. ProgramContentType(ext:str[, contenttype:str]) → str Sets or returns content type associated with a file extension. ProgramHeader(name:str, value:str) Appends HTTP header to the header buffer for all responses (whereas SetHeader only appends a header to the current response buffer). name is case-insensitive and restricted to non-space ASCII. value is a UTF-8 string that must be encodable as ISO-8859-1. Leading and trailing whitespace is trimmed automatically. Overlong characters are canonicalized. C0 and C1 control codes are forbidden, with the exception of tab. The header buffer is independent of the payload buffer. This function disallows the setting of certain headers such as Content-Range and Date, which are abstracted by the transport layer. ProgramHeartbeatInterval([milliseconds:int]) Sets the heartbeat interval (in milliseconds). 5000ms is the default and 100ms is the minimum. If `milliseconds` is not specified, then the current interval is returned. ProgramTimeout(milliseconds:int|seconds:int) Default timeout is 60000ms. Minimal value of timeout is 10(ms). Negative values (<0) sets the keepalive in seconds. This function should only be called from /.init.lua. ProgramPort(uint16) Hard-codes the port number on which to listen, which can be any number in the range 1..65535, or alternatively 0 to ask the operating system to choose a port, which may be revealed later on by GetServerAddr or the -z flag to stdout. ProgramMaxPayloadSize(int) Sets the maximum HTTP message payload size in bytes. The default is very conservatively set to 65536 so this is something many people will want to increase. This limit is enforced at the transport layer, before any Lua code is called, because right now redbean stores and forwards messages. (Use the UNIX API for raw socket streaming.) Setting this to a very high value can be useful if you're less concerned about rogue clients and would rather have your Lua code be granted more control to bounce unreasonable messages. If a value less than 1450 is supplied, it'll automatically be increased to 1450, since that's the size of ethernet frames. This function can only be called from .init.lua. ProgramMaxWorkers(int) Limits the number of workers forked by redbean. If that number is reached, the server continues polling until the number of workers is reduced or the value is updated. Setting it to 0 removes the limit (this is the default). ProgramPrivateKey(pem:str) Same as the -K flag if called from .init.lua, e.g. ProgramPrivateKey(LoadAsset("/.sign.key")) for zip loading or ProgramPrivateKey(Slurp("/etc/letsencrypt/privkey.pem")) for local file system only. ProgramRedirect(code:int, src:str, location:str) Configures fallback routing for paths which would otherwise return 404 Not Found. If code is 0 then the path is rewritten internally as an accelerated redirect. If code is 301, 302, 307, or 308 then a redirect response will be sent to the client. This function should only be called from /.init.lua. ProgramSslTicketLifetime(seconds:int) Defaults to 86400 (24 hours). This may be set to ≤0 to disable SSL tickets. It's a good idea to use these since it increases handshake performance 10x and eliminates a network round trip. This function is not available in unsecure mode. ProgramSslPresharedKey(key:str, identity:str) This function can be used to enable the PSK ciphersuites which simplify SSL and enhance its performance in controlled environments. `key` may contain 1..32 bytes of random binary data and identity is usually a short plaintext string. The first time this function is called, the preshared key will be added to both the client and the server SSL configs. If it's called multiple times, then the remaining keys will be added to the server, which is useful if you want to assign separate keys to each client, each of which needs a separate identity too. If this function is called multiple times with the same identity string, then the latter call will overwrite the prior. If a preshared key is supplied and no certificates or key-signing-keys are programmed, then redbean won't bother auto-generating any serving certificates and will instead use only PSK ciphersuites. This function is not available in unsecure mode. ProgramSslFetchVerify(enabled:bool) May be used to disable the verification of certificates for remote hosts when using the Fetch() API. This function is not available in unsecure mode. ProgramSslClientVerify(enabled:bool) Enables the verification of certificates supplied by the HTTP clients that connect to your redbean. This has the same effect as the `-j` flag. Tuning this option alone does not preclude the possibility of unsecured HTTP clients, which can be disabled using ProgramSslRequired(). This function can only be called from `.init.lua`. This function is not available in unsecure mode. ProgramSslRequired(mandatory:str) Enables the blocking of HTTP so that all inbound clients and must use the TLS transport layer. This has the same effect as the `-J` flag. Fetch() is still allowed to make outbound HTTP requests. This function can only be called from `.init.lua`. This function is not available in unsecure mode. ProgramSslCiphersuite(name:str) See https://redbean.dev/ for further details. IsDaemon() → bool Returns true if -d flag was passed to redbean. ProgramUid(int) Same as the -U flag if called from .init.lua for setuid() ProgramGid(int) Same as the -G flag if called from .init.lua for setgid() ProgramDirectory(str) Same as the -D flag if called from .init.lua for overlaying local file system directories. This may be called multiple times. The first directory programmed is preferred. These currently do not show up in the index page listing. ProgramLogMessages(bool) Same as the -m flag if called from .init.lua for logging message headers only. ProgramLogBodies(bool) Same as the -b flag if called from .init.lua for logging message bodies as part of POST / PUT / etc. requests. ProgramLogPath(str) Same as the -L flag if called from .init.lua for setting the log file path on the local file system. It's created if it doesn't exist. This is called before de-escalating the user / group id. The file is opened in append only mode. If the disk runs out of space then redbean will truncate the log file if has access to change the log file after daemonizing. ProgramPidPath(str) Same as the -P flag if called from .init.lua for setting the pid file path on the local file system. It's useful for reloading daemonized redbean using `kill -HUP $(cat /var/run/redbean.pid)` or terminating redbean with `kill $(cat /var/run/redbean.pid)` which will gracefully terminate all clients. Sending the TERM signal twice will cause a forceful shutdown, which might make someone with a slow internet connection who's downloading big files unhappy. ProgramUniprocess([bool]) → bool Same as the -u flag if called from .init.lua. Can be used to configure the uniprocess mode. The current value is returned. Slurp(filename:str[, i:int[, j:int]]) ├─→ data:str └─→ nil, unix.Errno Reads all data from file the easy way. This function reads file data from local file system. Zip file assets can be accessed using the `/zip/...` prefix. `i` and `j` may be used to slice a substring in `filename`. These parameters are 1-indexed and behave consistently with Lua's string.sub() API. For example: assert(Barf('x.txt', 'abc123')) assert(assert(Slurp('x.txt', 2, 3)) == 'bc') This function is uninterruptible so `unix.EINTR` errors will be ignored. This should only be a concern if you've installed signal handlers. Use the UNIX API if you need to react to it. Barf(filename:str, data:str[, mode:int[, flags:int[, offset:int]]]) ├─→ true └─→ nil, unix.Errno Writes all data to file the easy way. This function writes to the local file system. `mode` defaults to `0644`. This parameter is ignored when `flags` doesn't have `unix.O_CREAT`. `flags` defaults to `unix.O_TRUNC | unix.O_CREAT`. `offset` is 1-indexed and may be used to overwrite arbitrary slices within a file when used in conjunction with `flags=0`. For example: assert(Barf('x.txt', 'abc123')) assert(Barf('x.txt', 'XX', 0, 0, 3)) assert(assert(Slurp('x.txt', 1, 6)) == 'abXX23') Sleep(seconds:number) Sleeps the specified number of seconds (can be fractional). The smallest interval is a microsecond. Route([host:str[, path:str]]) Instructs redbean to follow the normal HTTP serving path. This function is useful when writing an OnHttpRequest handler, since that overrides the serving path entirely. So if the handler decides it doesn't want to do anything, it can simply call this function, to hand over control back to the redbean core. By default, the host and path arguments are supplied from the resolved GetUrl value. This handler always resolves, since it will generate a 404 Not Found response if redbean couldn't find an appropriate endpoint. RouteHost([host:str[, path:str]]) → bool This is the same as Route, except it only implements the subset of request routing needed for serving virtual-hosted assets, where redbean tries to prefix the path with the hostname when looking up a file. This function returns true if the request was resolved. If it was resolved, then your OnHttpRequest request handler can still set additional headers. RoutePath([path:str]) → bool This is the same as Route, except it only implements the subset of request routing needed for serving assets. This function returns true if the request was resolved. If it was resolved, then your OnHttpRequest request handler can still set additional headers. Note that the asset needs to have "read other" permissions; otherwise this function logs a warning and returns 403 Forbidden. If this is undesirable, use GetAssetMode and ServeAsset to bypass the check. ServeAsset(path:str) Instructs redbean to serve static asset at path. This function causes what would normally happen outside a dynamic handler to happen. The asset can be sourced from either the zip or local filesystem if -D is used. This function is mutually exclusive with SetStatus and other Serve* functions. ServeError(code:int[, reason:str]) Instructs redbean to serve a boilerplate error page. This takes care of logging the error, setting the reason phrase, and adding a payload. This function is mutually exclusive with SetStatus and other Serve* functions. ServeRedirect(code:int, location:str) Instructs redbean to return the specified redirect code along with the Location header set. This function is mutually exclusive with SetStatus and other Serve* functions. SetLogLevel(level:int) Sets logger verbosity. Reasonable values for level are kLogDebug > kLogVerbose > kLogInfo > kLogWarn > kLogError > kLogFatal. This is reset at the end of the http request, so it can be used to disable access log and message logging. VisualizeControlCodes(str) → str Replaces C0 control codes and trojan source characters with descriptive UNICODE pictorial representation. This function also canonicalizes overlong encodings. C1 control codes are replaced with a JavaScript-like escape sequence. Underlong(str) → str Canonicalizes overlong encodings. Crc32(initial:int, data:str) → int Computes 32-bit CRC-32 used by zip/zlib/gzip/etc. Crc32c(initial:int, data:str) → int Computes 32-bit Castagnoli Cyclic Redundancy Check. Md5(str) → str Computes MD5 checksum, returning 16 bytes of binary. Sha1(str) → str Computes SHA1 checksum, returning 20 bytes of binary. Sha224(str) → str Computes SHA224 checksum, returning 28 bytes of binary. Sha256(str) → str Computes SHA256 checksum, returning 32 bytes of binary. Sha384(str) → str Computes SHA384 checksum, returning 48 bytes of binary. Sha512(str) → str Computes SHA512 checksum, returning 64 bytes of binary. Bsf(x:int) → int Returns position of first bit set. Passing 0 will raise an error. Same as the Intel x86 instruction BSF. Bsr(x:int) → int Returns binary logarithm of 𝑥. Passing 0 will raise an error. Same as the Intel x86 instruction BSR. Popcnt(x:int) → int Returns number of bits set in integer. Rdtsc() → int Returns CPU timestamp counter. Lemur64() → int Returns fastest pseudorandom non-cryptographic random number. This linear congruential generator passes practrand and bigcrush. Rand64() → int Returns nondeterministic pseudorandom non-cryptographic number. This linear congruential generator passes practrand and bigcrush. This generator is safe across fork(), threads, and signal handlers. Rdrand() → int Returns 64-bit hardware random integer from RDRND instruction, with automatic fallback to getrandom() if not available. Rdseed() → int Returns 64-bit hardware random integer from RDSEED instruction, with automatic fallback to RDRND and getrandom() if not available. GetCpuCount() → int Returns CPU core count or 0 if it couldn't be determined. GetCpuCore() → int Returns 0-indexed CPU core on which process is currently scheduled. GetCpuNode() → int Returns 0-indexed NUMA node on which process is currently scheduled. Decimate(str) → str Shrinks byte buffer in half using John Costella's magic kernel. This downscales data 2x using an eight-tap convolution, e.g. >: Decimate('\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00') "\xff\x00\xff\x00\xff\x00" This is very fast if SSSE3 is available (Intel 2004+ / AMD 2011+). MeasureEntropy(data) → float Returns Shannon entropy of array. This gives you an idea of the density of information. Cryptographic random should be in the ballpark of 7.9 whereas plaintext will be more like 4.5. Deflate(uncompressed:str[, level:int]) ├─→ compressed:str └─→ nil, error:str Compresses data. >: Deflate("hello") "\xcbH\xcd\xc9\xc9\x07\x00" >: Inflate("\xcbH\xcd\xc9\xc9\x07\x00", 5) "hello" The output format is raw DEFLATE that's suitable for embedding into formats like a ZIP file. It's recommended that, like ZIP, you also store separately a Crc32() checksum in addition to the original uncompressed size. `level` is the compression level, which defaults to 7. The max is 9. Lower numbers go faster (4 for instance is a sweet spot) and higher numbers go slower but have better compression. Inflate(compressed:str, maxoutsize:int) ├─→ uncompressed:str └─→ nil, error:str Decompresses data. This function performs the inverse of Deflate(). It's recommended that you perform a Crc32() check on the output string after this function succeeds. `maxoutsize` is the uncompressed size, which should be known. However, it is permissable (although not advised) to specify some large number in which case (on success) the byte length of the output string may be less than `maxoutsize`. Benchmark(func[, count[, maxattempts]]) └─→ nanos:real, ticks:int, overhead-ticks:int, tries:int Performs microbenchmark. The first value returned is the average number of nanoseconds that `func` needed to execute. Nanoseconds are computed from RDTSC tick counts, using an approximation that's measured beforehand with the unix.clock_gettime() function. The `ticks` result is the canonical average number of clock ticks. This subroutine will subtract whatever the overhead happens to be for benchmarking a function that does nothing. This overhead value will be reported in the result. `tries` indicates if your microbenchmark needed to be repeated, possibly because your system is under load and the benchmark was preempted by the operating system, or moved to a different core. oct(int) └─→ str Formats string as octal integer literal string. If the provided value is zero, the result will be `"0"`. Otherwise the resulting value will be the zero-prefixed octal string. The result is currently modulo 2^64. Negative numbers are converted to unsigned. hex(int) └─→ str Formats string as hexadecimal integer literal string. If the provided value is zero, the result will be `"0"`. Otherwise the resulting value will be the `"0x"`-prefixed hex string. The result is currently modulo 2^64. Negative numbers are converted to unsigned. bin(int) └─→ str Formats string as binary integer literal string. If the provided value is zero, the result will be `"0"`. Otherwise the resulting value will be the `"0b"`-prefixed binary str. The result is currently modulo 2^64. Negative numbers are converted to unsigned. ResolveIp(hostname:str) ├─→ ip:uint32 └─→ nil, error:str Gets IP address associated with hostname. This function first checks if hostname is already an IP address, in which case it returns the result of `ParseIp`. Otherwise, it checks HOSTS.TXT on the local system and returns the first IPv4 address associated with hostname. If no such entry is found, a DNS lookup is performed using the system configured (e.g. /etc/resolv.conf) DNS resolution service. If the service returns multiple IN A records then only the first one is returned. The returned address is word-encoded in host endian order. For example, 1.2.3.4 is encoded as 0x01020304. The `FormatIp` function may be used to turn this value back into a string. If no IP address could be found, then nil is returned alongside a string of unspecified format describing the error. Calls to this function may be wrapped in assert() if an exception is desired. IsTrustedIp(ip:int) └─→ bool Returns true if IP address is trustworthy. If the ProgramTrustedIp() function has NOT been called then redbean will consider the networks 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16 to be trustworthy too. If ProgramTrustedIp() HAS been called at some point earlier in your redbean's lifecycle, then it'll trust the IPs and network subnets you specify instead. The network interface addresses used by the host machine are always considered trustworthy, e.g. 127.0.0.1. This may change soon, if we decide to export a GetHostIps() API which queries your NIC devices. ProgramTrustedIp(ip:int[, cidr:int]) Trusts an IP address or network. This function may be used to configure the IsTrustedIp() function which is how redbean determines if a client is allowed to send us headers like X-Forwarded-For (cf GetRemoteAddr vs. GetClientAddr) without them being ignored. Trusted IPs is also how redbean turns off token bucket rate limiting selectively, so be careful. Here's an example of how you could trust all of Cloudflare's IPs: ProgramTrustedIp(ParseIp("103.21.244.0"), 22); ProgramTrustedIp(ParseIp("103.22.200.0"), 22); ProgramTrustedIp(ParseIp("103.31.4.0"), 22); ProgramTrustedIp(ParseIp("104.16.0.0"), 13); ProgramTrustedIp(ParseIp("104.24.0.0"), 14); ProgramTrustedIp(ParseIp("108.162.192.0"), 18); ProgramTrustedIp(ParseIp("131.0.72.0"), 22); ProgramTrustedIp(ParseIp("141.101.64.0"), 18); ProgramTrustedIp(ParseIp("162.158.0.0"), 15); ProgramTrustedIp(ParseIp("172.64.0.0"), 13); ProgramTrustedIp(ParseIp("173.245.48.0"), 20); ProgramTrustedIp(ParseIp("188.114.96.0"), 20); ProgramTrustedIp(ParseIp("190.93.240.0"), 20); ProgramTrustedIp(ParseIp("197.234.240.0"), 22); ProgramTrustedIp(ParseIp("198.41.128.0"), 17); Although you might want consider trusting redbean's open source freedom embracing solution to DDOS protection instead! ProgramTokenBucket( [replenish:num[, cidr:int[, reject:int[, ignore:int[, ban:int]]]]]) Enables DDOS protection. Imagine you have 2**32 buckets, one for each IP address. Each bucket can hold about 127 tokens. Every second a background worker puts one token in each bucket. When a TCP client socket is opened, it takes a token from its bucket, and then proceeds. If the bucket holds only a third of its original tokens, then redbean sends them a 429 warning. If the client ignores this warning and keeps sending requests, until there's no tokens left, then the banhammer finally comes down. function OnServerStart() ProgramTokenBucket() ProgramTrustedIp(ParseIp('x.x.x.x'), 32) assert(unix.setrlimit(unix.RLIMIT_NPROC, 1000, 1000)) end This model of network rate limiting generously lets people "burst" a tiny bit. For example someone might get a strong craving for content and smash the reload button in Chrome 64 times in a few seconds. But since the client only get 1 new token per second, they'd better cool their heels for a few minutes after doing that. This amount of burst can be altered by choosing the `reject` / `ignore` / `ban` threshold arguments. For example, if the `reject` parameter is set to 126 then no bursting is allowed, which probably isn't a good idea. redbean is programmed to acquire a token immediately after accept() is called from the main server process, which is well before fork() or read() or any Lua code happens. redbean then takes action, based on the token count, which can be accept / reject / ignore / ban. If redbean determines a ban is warrented, then 4-byte datagram is sent to the unix domain socket `/var/run/blackhole.sock` which should be operated using the blackholed program we distribute separately. The trick redbean uses on Linux for example is insert rules in your raw prerouting table. redbean is very fast at the application layer so the biggest issue we've encountered in production is are kernels themselves, and programming the raw prerouting table dynamically is how we solved that. `replenish` is the number of times per second a token should be added to each bucket. The default value is 1 which means one token is granted per second to all buckets. The minimum value is 1/3600 which means once per hour. The maximum value for this setting is 1e6, which means once every microsecond. `cidr` is the specificity of judgement. Since creating 2^32 buckets would need 4GB of RAM, redbean defaults this value to 24 which means filtering applies to class c network blocks (i.e. x.x.x.*), and your token buckets only take up 2^24 bytes of RAM (16MB). This can be set to any number on the inclusive interval [8,32], where having a lower number means you use less ram/cpu, but splash damage applies more to your clients; whereas higher numbers means more ram/cpu usage, while ensuring rate limiting only applies to specific compromised actors. `reject` is the token count or treshold at which redbean should send 429 Too Many Request warnings to the client. Permitted values can be anywhere between -1 and 126 inclusively. The default value is 30 and -1 means to disable (assuming AcquireToken() will be used). `ignore` is the token count or treshold, at which redbean should try simply ignoring clients and close the connection without logging any kind of warning, and without sending any response. The default value for this setting is `MIN(reject / 2, 15)`. This must be less than or equal to the `reject` setting. Allowed values are [-1,126] where you can use -1 as a means of disabling `ignore`. `ban` is the token count at which redbean should report IP addresses to the blackhole daemon via a unix-domain socket datagram so they'll get banned in the kernel routing tables. redbean's default value for this setting is `MIN(ignore / 10, 1)`. Permitted values are [-1,126] where -1 may be used as a means of disabling the `ban` feature. This function throws an exception if the constraints described above are not the case. Warnings are logged should redbean fail to connect to the blackhole daemon, assuming it hasn't been disabled. It's safe to use load balancing tools when banning is enabled, since you can't accidentally ban your own network interface addresses, loopback ips, or ProgramTrustedIp() addresses where these rate limits don't apply. It's assumed will be called from the .init.lua global scope although it could be used in interpreter mode, or from a forked child process in which case the only processes that'll have ability to use it will be that same process, and any descendent processes. This function is only able to be called once. This feature is not available in unsecure mode. AcquireToken([ip:uint32]) └─→ int8 Atomically acquires token. This routine atomically acquires a single token for an `ip` address. The return value is the token count before the subtraction happened. No action is taken based on the count, since the caller will decide. `ip` should be an IPv4 address and this defaults to GetClientAddr(), although other interpretations of its meaning are possible. Your token buckets are stored in shared memory so this can be called from multiple forked processes. which operate on the same values. CountTokens([ip:uint32]) └─→ int8 Counts number of tokens in bucket. This function is the same as AcquireToken() except no subtraction is performed, i.e. no token is taken. `ip` should be an IPv4 address and this defaults to GetClientAddr(), although other interpretations of its meaning are possible. Blackhole(ip:uint32) └─→ bool Sends IP address to blackholed service. ProgramTokenBucket() needs to be called beforehand. The default settings will blackhole automatically, during the accept() loop based on the banned threshold. However if your Lua code calls AcquireToken() manually, then you'll need this function to take action on the returned values. This function returns true if a datagram could be sent sucessfully. Otherwise false is returned, which can happen if blackholed isn't running, or if a lot of processes are sending messages to it and the operation would have blocked. It's assumed that the blackholed service is running locally in the background. ──────────────────────────────────────────────────────────────────────────────── CONSTANTS kLogDebug Integer for debug logging level. See Log. kLogVerbose Integer for verbose logging level, which is less than kLogDebug. kLogInfo Integer for info logging level, which is less than kLogVerbose. kLogWarn Integer for warn logging level, which is less than kLogVerbose. kLogError Integer for error logging level, which is less than kLogWarn. kLogFatal Integer for fatal logging level, which is less than kLogError. Logging anything at this level will result in a backtrace and process exit. ──────────────────────────────────────────────────────────────────────────────── LSQLITE3 MODULE Please refer to the LuaSQLite3 Documentation. For example, you could put the following in your /.init.lua file: sqlite3 = require "lsqlite3" db = sqlite3.open_memory() db:exec[[ CREATE TABLE test ( id INTEGER PRIMARY KEY, content TEXT ); INSERT INTO test (content) VALUES ('Hello World'); INSERT INTO test (content) VALUES ('Hello Lua'); INSERT INTO test (content) VALUES ('Hello Sqlite3'); ]] Then, your Lua server pages or OnHttpRequest handler may perform SQL queries by accessing the db global. The performance is good too, at about 400k qps. for row in db:nrows("SELECT * FROM test") do Write(row.id.." "..row.content.."<br>") end redbean supports a subset of what's defined in the upstream LuaSQLite3 project. Most of the unsupported APIs relate to pointers and database notification hooks. ──────────────────────────────────────────────────────────────────────────────── RE MODULE This module exposes an API for POSIX regular expressions which enable you to validate input, search for substrings, extract pieces of strings, etc. Here's a usage example: # Example IPv4 Address Regular Expression (see also ParseIP) p = re.compile([[^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$]]) m,a,b,c,d = assert(p:search(𝑠)) if m then print("ok", tonumber(a), tonumber(b), tonumber(c), tonumber(d)) else print("not ok") end re.search(regex:str, text:str[, flags:int]) ├─→ match:str[, group1:str, ...] └─→ nil, re.Errno Searches for regular expression match in text. This is a shorthand notation roughly equivalent to: preg = re.compile(regex) patt = preg:search(re, text) `flags` defaults to zero and may have any of: - `re.BASIC` - `re.ICASE` - `re.NEWLINE` - `re.NOSUB` - `re.NOTBOL` - `re.NOTEOL` This has exponential complexity. Please use re.compile() to compile your regular expressions once from `/.init.lua`. This API exists for convenience. This isn't recommended for prod. This uses POSIX extended syntax by default. re.compile(regex:str[, flags:int]) → re.Regex ├─→ preg:re.Regex └─→ nil, re.Errno Compiles regular expression. `flags` defaults to zero and may have any of: - `re.BASIC` - `re.ICASE` - `re.NEWLINE` - `re.NOSUB` This has an O(2^𝑛) cost. Consider compiling regular expressions once from your `/.init.lua` file. If `regex` is an untrusted user value, then `unix.setrlimit` should be used to impose cpu and memory quotas for security. This uses POSIX extended syntax by default. ──────────────────────────────────────────────────────────────────────────────── RE REGEX OBJECT re.Regex:search(text:str[, flags:int]) ├─→ match:str[, group1:str, ...] └─→ nil, re.Errno Executes precompiled regular expression. Returns nothing (nil) if the pattern doesn't match anything. Otherwise it pushes the matched substring and any parenthesis-captured values too. Flags may contain re.NOTBOL or re.NOTEOL to indicate whether or not text should be considered at the start and/or end of a line. `flags` defaults to zero and may have any of: - `re.NOTBOL` - `re.NOTEOL` This has an O(𝑛) cost. ──────────────────────────────────────────────────────────────────────────────── RE ERRNO OBJECT re.Errno:errno() └─→ errno:int Returns regex error number. re.Errno:doc() └─→ description:str Returns English string describing error code. re.Errno:__tostring() └─→ str Delegates to re.Errno:doc() ──────────────────────────────────────────────────────────────────────────────── RE ERRORS re.NOMATCH No match re.BADPAT Invalid regex re.ECOLLATE Unknown collating element re.ECTYPE Unknown character class name re.EESCAPE Trailing backslash re.ESUBREG Invalid back reference re.EBRACK Missing `]` re.EPAREN Missing `)` re.EBRACE Missing `}` re.BADBR Invalid contents of `{}` re.ERANGE Invalid character range. re.ESPACE Out of memory re.BADRPT Repetition not preceded by valid expression ──────────────────────────────────────────────────────────────────────────────── RE FLAGS re.BASIC Use this flag if you prefer the default POSIX regex syntax. We use extended regex notation by default. For example, an extended regular expression for matching an IP address might look like ([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*) whereas with basic syntax it would look like \([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\). This flag may only be used with re.compile and re.search. re.ICASE Use this flag to make your pattern case ASCII case-insensitive. This means [a-z] will mean the same thing as [A-Za-z]. This flag may only be used with re.compile and re.search. re.NEWLINE Use this flag to change the handling of NEWLINE (\x0a) characters. When this flag is set, (1) a NEWLINE shall not be matched by a "." or any form of a non-matching list, (2) a "^" shall match the zero-length string immediately after a NEWLINE (regardless of re.NOTBOL), and (3) a "$" shall match the zero-length string immediately before a NEWLINE (regardless of re.NOTEOL). re.NOSUB Causes re.search to only report success and failure. This is reported via the API by returning empty string for success. This flag may only be used with re.compile and re.search. re.NOTBOL The first character of the string pointed to by string is not the beginning of the line. This flag may only be used with re.search and re.Regex:search. re.NOTEOL The last character of the string pointed to by string is not the end of the line. This flag may only be used with re.search and re.Regex:search. ──────────────────────────────────────────────────────────────────────────────── PATH MODULE The path module may be used to manipulate unix paths. Note that we use unix paths on Windows. For example, if you have a path like C:\foo\bar then it should be /c/foo/bar with redbean. It should also be noted the unix module is more permissive when using Windows paths, where translation to win32 is very light. path.dirname(str) └─→ str Strips final component of path, e.g. path │ dirname ─────────────────── . │ . .. │ . / │ / usr │ . /usr/ │ / /usr/lib │ /usr /usr/lib/ │ /usr path.basename(path:str) └─→ str Returns final component of path, e.g. path │ basename ───────────────────── . │ . .. │ .. / │ / usr │ usr /usr/ │ usr /usr/lib │ lib /usr/lib/ │ lib path.join(str, ...) └─→ str Concatenates path components, e.g. x │ y │ joined ───────────────────────────────── / │ / │ / /usr │ lib │ /usr/lib /usr/ │ lib │ /usr/lib /usr/lib │ /lib │ /lib You may specify 1+ arguments. Specifying no arguments will raise an error. If nil arguments are specified, then they're skipped over. If exclusively nil arguments are passed, then nil is returned. Empty strings behave similarly to nil, but unlike nil may coerce a trailing slash. path.exists(path:str) └─→ bool Returns true if path exists. This function is inclusive of regular files, directories, and special files. Symbolic links are followed are resolved. On error, false is returned. path.isfile(path:str) └─→ bool Returns true if path exists and is regular file. Symbolic links are not followed. On error, false is returned. path.isdir(path:str) └─→ bool Returns true if path exists and is directory. Symbolic links are not followed. On error, false is returned. path.islink(path:str) └─→ bool Returns true if path exists and is symbolic link. Symbolic links are not followed. On error, false is returned. ──────────────────────────────────────────────────────────────────────────────── MAXMIND MODULE This module may be used to get city/country/asn/etc from IPs, e.g. -- .init.lua maxmind = require 'maxmind' asndb = maxmind.open('/usr/local/share/maxmind/GeoLite2-ASN.mmdb') -- request handler as = asndb:lookup(GetRemoteAddr()) if as then asnum = as:get('autonomous_system_number') asorg = as:get('autonomous_system_organization') Write(EscapeHtml(asnum)) Write(' ') Write(EscapeHtml(asorg)) end For further details, please see maxmind.lua in redbean-demo.com. ──────────────────────────────────────────────────────────────────────────────── FINGER MODULE This is an experimental module that, like the maxmind module, gives you insight into what kind of device is connecting to your redbean. This module can help you protect your redbean because it provides tools for identifying clients that misrepresent themselves. For example the User-Agent header might report itself as a Windows computer when the SYN packet says it's a Linux computer. function OnServerListen(fd, ip, port) unix.setsockopt(fd, unix.SOL_TCP, unix.TCP_SAVE_SYN, true) return false end function OnClientConnection(ip, port, serverip, serverport) fd = GetClientFd() syn = unix.getsockopt(fd, unix.SOL_TCP, unix.TCP_SAVED_SYN) end function OnHttpRequest() Log(kLogInfo, "client is running %s and reports %s" % { finger.GetSynFingerOs(finger.FingerSyn(syn)), GetHeader('User-Agent')}) Route() end The following functions are provided. finger.FingerSyn(syn_packet_bytes:str) ├─→ synfinger:uint32 └─→ nil, error:str Fingerprints 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. We make no guarantees this hashing algorithm won't change as we learn more about the optimal way to fingerprint, so be sure to save your syn packets too if you're using this feature, in case they need to be rehashed in the future. This function is nil/error propagating. finger.GetSynFingerOs(synfinger:uint32) ├─→ osname:str └─→ nil, error:str Fingerprints IP+TCP SYN packet. If `synfinger` is a known hard-coded magic number, then one of the following strings may be returned: - `"LINUX"` - `"WINDOWS"` - `"XNU"` - `"NETBSD"` - `"FREEBSD"` - `"OPENBSD"` If this function returns nil, then one thing you can do to help is file an issue and share with us your SYN packet specimens. The way we prefer to receive them is in EncodeLua(syn_packet_bytes) format along with details on the operating system which you must know. finger.DescribeSyn(syn_packet_bytes:str) ├─→ description:str └─→ nil, error:str Describes IP+TCP SYN packet. The layout looks as follows: TTL:OPTIONS:WSIZE:MSS The `TTL`, `WSIZE`, and `MSS` fields are unsigned decimal fields. The `OPTIONS` field communicates the ordering of the commonly used subset of tcp options. The following character mappings are defined. TCP options not on this list will be ignored. - E: End of Option list - N: No-Operation - M: Maxmimum Segment Size - K: Window Scale - O: SACK Permitted - A: SACK - e: Echo (obsolete) - r: Echo reply (obsolete) - T: Timestamps This function is nil/error propagating. ──────────────────────────────────────────────────────────────────────────────── ARGON2 MODULE This module implements a password hashing algorithm based on blake2b that won the Password Hashing Competition. It can be used to securely store user passwords in your SQLite database, in a way that destroys the password, but can be verified by regenerating the hash again the next time the user logs in. Destroying the password is important, since if your database is compromised, the bad guys won't be able to use rainbow tables to recover the plain text of the passwords. Argon2 achieves this security by being expensive to compute. Care should be taken in choosing parameters, since an HTTP endpoint that uses Argon2 can just as easily become a denial of service vector. For example, you may want to consider throttling your login endpoint. argon2.hash_encoded(pass:str, salt:str[, config:table]) ├─→ ascii:str └─→ nil, error:str Hashes password. This is consistent with the README of the reference implementation: >: assert(argon2.hash_encoded("password", "somesalt", { variant = argon2.variants.argon2_i, m_cost = 65536, hash_len = 24, parallelism = 4, t_cost = 2, })) "$argon2i$v=19$m=65536,t=2,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG" `pass` is the secret value to be encoded. `salt` is a nonce value used to hash the string. `config.m_cost` is the memory hardness in kibibytes, which defaults to 4096 (4 mibibytes). It's recommended that this be tuned upwards. `config.t_cost` is the number of iterations, which defaults to 3. `config.parallelism` is the parallelism factor, which defaults to 1. `config.hash_len` is the number of desired bytes in hash output, which defaults to 32. `config.variant` may be: - `argon2.variants.argon2_id` blend of other two methods [default] - `argon2.variants.argon2_i` maximize resistance to side-channel attacks - `argon2.variants.argon2_d` maximize resistance to gpu cracking attacks argon2.verify(encoded:str, pass:str) ├─→ ok:bool └─→ nil, error:str Verifies password, e.g. >: argon2.verify( "$argon2i$v=19$m=65536,t=2," .. "p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG", "password") true ──────────────────────────────────────────────────────────────────────────────── UNIX MODULE This module exposes the low-level System Five system call interface. This module works on all supported platforms, including Windows NT. unix.open(path:str, flags:int[, mode:int[, dirfd:int]]) ├─→ fd:int └─→ nil, unix.Errno Opens file. Returns a file descriptor integer that needs to be closed, e.g. fd = assert(unix.open("/etc/passwd", unix.O_RDONLY)) print(unix.read(fd)) unix.close(fd) `flags` should have one of: - `O_RDONLY`: open for reading (default) - `O_WRONLY`: open for writing - `O_RDWR`: open for reading and writing The following values may also be OR'd into `flags`: - `O_CREAT` create file if it doesn't exist - `O_TRUNC` automatic ftruncate(fd,0) if exists - `O_CLOEXEC` automatic close() upon execve() - `O_EXCL` exclusive access (see below) - `O_APPEND` open file for append only - `O_NONBLOCK` asks read/write to fail with EAGAIN rather than block - `O_DIRECT` it's complicated (not supported on Apple and OpenBSD) - `O_DIRECTORY` useful for stat'ing (hint on UNIX but required on NT) - `O_NOFOLLOW` fail if it's a symlink (zero on Windows) - `O_DSYNC` it's complicated (zero on non-Linux/Apple) - `O_RSYNC` it's complicated (zero on non-Linux/Apple) - `O_PATH` it's complicated (zero on non-Linux) - `O_VERIFY` it's complicated (zero on non-FreeBSD) - `O_SHLOCK` it's complicated (zero on non-BSD) - `O_EXLOCK` it's complicated (zero on non-BSD) - `O_NOATIME` don't record access time (zero on non-Linux) - `O_RANDOM` hint random access intent (zero on non-Windows) - `O_SEQUENTIAL` hint sequential access intent (zero on non-Windows) - `O_COMPRESSED` ask fs to abstract compression (zero on non-Windows) - `O_INDEXED` turns on that slow performance (zero on non-Windows) There are three regular combinations for the above flags: - `O_RDONLY`: Opens existing file for reading. If it doesn't exist then nil is returned and errno will be `ENOENT` (or in some other cases `ENOTDIR`). - `O_WRONLY|O_CREAT|O_TRUNC`: Creates file. If it already exists, then the existing copy is destroyed and the opened file will start off with a length of zero. This is the behavior of the traditional creat() system call. - `O_WRONLY|O_CREAT|O_EXCL`: Create file only if doesn't exist already. If it does exist then `nil` is returned along with `errno` set to `EEXIST`. `dirfd` defaults to to `unix.AT_FDCWD` and may optionally be set to a directory file descriptor to which `path` is relative. Returns `ENOENT` if `path` doesn't exist. Returns `ENOTDIR` if `path` contained a directory component that wasn't a directory. unix.close(fd:int) ├─→ true └─→ nil, unix.Errno Closes file descriptor. This function should never be called twice for the same file descriptor, regardless of whether or not an error happened. The file descriptor is always gone after close is called. So it technically always succeeds, but that doesn't mean an error should be ignored. For example, on NFS a close failure could indicate data loss. Closing does not mean that scheduled i/o operations have been completed. You'd need to use fsync() or fdatasync() beforehand to ensure that. You shouldn't need to do that normally, because our close implementation guarantees a consistent view, since on systems where it isn't guaranteed (like Windows) close will implicitly sync. File descriptors are automatically closed on exit(). Returns `EBADF` if `fd` wasn't valid. Returns `EINTR` possibly maybe. Returns `EIO` if an i/o error occurred. unix.read(fd:int[, bufsiz:str[, offset:int]]) ├─→ data:str └─→ nil, unix.Errno Reads from file descriptor. This function returns empty string on end of file. The exception is if `bufsiz` is zero, in which case an empty returned string means the file descriptor works. unix.write(fd:int, data:str[, offset:int]) ├─→ wrotebytes:int └─→ nil, unix.Errno Writes to file descriptor. unix.exit([exitcode:int]) └─→ ⊥ Invokes `_Exit(exitcode)` on the process. This will immediately halt the current process. Memory will be freed. File descriptors will be closed. Any open connections it owns will be reset. This function never returns. unix.environ() └─→ {str,...} Returns raw environment variables. This allocates and constructs the C/C++ `environ` variable as a Lua table consisting of string keys and string values. This data structure preserves casing. On Windows NT, by convention, environment variable keys are treated in a case-insensitive way. It is the responsibility of the caller to consider this. This data structure preserves valueless variables. It's possible on both UNIX and Windows to have an environment variable without an equals, even though it's unusual. This data structure preserves duplicates. For example, on Windows, there's some irregular uses of environment variables such as how the command prompt inserts multiple environment variables with empty string as keys, for its internal bookkeeping. unix.fork() ├─┬─→ 0 │ └─→ childpid:int └─→ nil, unix.Errno Creates a new process mitosis style. This system call returns twice. The parent process gets the nonzero pid. The child gets zero. Here's a simple usage example of creating subprocesses, where we fork off a child worker from a main process hook callback to do some independent chores, such as sending an HTTP request back to redbean. -- as soon as server starts, make a fetch to the server -- then signal redbean to shutdown when fetch is complete local onServerStart = function() if assert(unix.fork()) == 0 then local ok, headers, body = Fetch('http://127.0.0.1:8080/test') unix.kill(unix.getppid(), unix.SIGTERM) unix.exit(0) end end OnServerStart = onServerStart We didn't need to use wait() here, because (a) we want redbean to go back to what it was doing before as the Fetch() completes, and (b) redbean's main process already has a zombie collector. However it's a moot point, since once the fetch is done, the child process then asks redbean to gracefully shutdown by sending SIGTERM its parent. This is actually a situation where we *must* use fork, because the purpose of the main redbean process is to call accept() and create workers. So if we programmed redbean to use the main process to send a blocking request to itself instead, then redbean would deadlock and never be able to accept() the client. While deadlocking is an extreme example, the truth is that latency issues can crop up for the same reason that just cause jitter instead, and as such, can easily go unnoticed. For example, if you do something that takes longer than a few milliseconds from inside your redbean heartbeat, then that's a few milliseconds in which redbean is no longer concurrent, and tail latency is being added to its ability to accept new connections. fork() does a great job at solving this. If you're not sure how long something will take, then when in doubt, fork off a process. You can then report its completion to something like SQLite. Redbean makes having lots of processes cheap. On Linux they're about as lightweight as what heavyweight environments call greenlets. You can easily have 10,000 Redbean workers on one PC. Here's some benchmarks for fork() performance across platforms: Linux 5.4 fork l: 97,200𝑐 31,395𝑛𝑠 [metal] FreeBSD 12 fork l: 236,089𝑐 78,841𝑛𝑠 [vmware] Darwin 20.6 fork l: 295,325𝑐 81,738𝑛𝑠 [metal] NetBSD 9 fork l: 5,832,027𝑐 1,947,899𝑛𝑠 [vmware] OpenBSD 6.8 fork l: 13,241,940𝑐 4,422,103𝑛𝑠 [vmware] Windows10 fork l: 18,802,239𝑐 6,360,271𝑛𝑠 [metal] One of the benefits of using fork() is it creates an isolation barrier between the different parts of your app. This can lead to enhanced reliability and security. For example, redbean uses fork so it can wipe your ssl keys from memory before handing over control to request handlers that process untrusted input. It also ensures that if your Lua app crashes, it won't take down the server as a whole. Hence it should come as no surprise that fork() would go slower on operating systems that have more security features. So depending on your use case, you can choose the operating system that suits you. unix.commandv(prog:str) ├─→ path:str └─→ nil, unix.Errno Performs `$PATH` lookup of executable. unix = require 'unix' prog = assert(unix.commandv('ls')) unix.execve(prog, {prog, '-hal', '.'}, {'PATH=/bin'}) unix.exit(127) We automatically suffix `.com` and `.exe` for all platforms when path searching. By default, the current directory is not on the path. If `prog` is an absolute path, then it's returned as-is. If `prog` contains slashes then it's not path searched either and will be returned if it exists. unix.execve(prog:str[, args:List<*>, env:List<*>]) └─→ nil, unix.Errno Exits current process, replacing it with a new instance of the specified program. `prog` needs to be an absolute path, see commandv(). `env` defaults to to the current `environ`. Here's a basic usage example: unix.execve("/bin/ls", {"/bin/ls", "-hal"}, {"PATH=/bin"}) unix.exit(127) `prog` needs to be the resolved pathname of your executable. You can use commandv() to search your `PATH`. `args` is a string list table. The first element in `args` should be `prog`. Values are coerced to strings. This parameter defaults to `{prog}`. `env` is a string list table. Values are coerced to strings. No ordering requirement is imposed. By convention, each string has its key and value separated by an equals sign without spaces. If this parameter is not specified, it'll default to the C/C++ `environ` variable which is inherited from the shell that launched redbean. It's the responsibility of the user to supply a sanitized environ when spawning untrusted processes. execve() is normally called after fork() returns 0. If that isn't the case, then your redbean worker will be destroyed. This function never returns on success. `EAGAIN` is returned if you've enforced a max number of processes using `setrlimit(RLIMIT_NPROC)`. unix.dup(oldfd:int[, newfd:int[, flags:int[, lowest:int]]]) ├─→ newfd:int └─→ nil, unix.Errno Duplicates file descriptor. `newfd` may be specified to choose a specific number for the new file descriptor. If it's already open, then the preexisting one will be silently closed. `EINVAL` is returned if `newfd` equals `oldfd`. `flags` can have `O_CLOEXEC` which means the returned file descriptors will be automatically closed upon execve(). `lowest` defaults to zero and defines the lowest numbered file descriptor that's acceptable to use. If `newfd` is specified then `lowest` is ignored. For example, if you wanted to duplicate standard input, then: stdin2 = assert(unix.dup(0, nil, unix.O_CLOEXEC, 3)) Will ensure that, in the rare event standard output or standard error are closed, you won't accidentally duplicate standard input to those numbers. unix.pipe([flags:int]) ├─→ reader:int, writer:int └─→ nil, unix.Errno Creates fifo which enables communication between processes. `flags` may have any combination (using bitwise OR) of: - `O_CLOEXEC`: Automatically close file descriptor upon execve() - `O_NONBLOCK`: Request `EAGAIN` be raised rather than blocking - `O_DIRECT`: Enable packet mode w/ atomic reads and writes, so long as they're no larger than `PIPE_BUF` (guaranteed to be 512+ bytes) with support limited to Linux, Windows NT, FreeBSD, and NetBSD. Returns two file descriptors: one for reading and one for writing. Here's an example of how pipe(), fork(), dup(), etc. may be used to serve an HTTP response containing the output of a subprocess. local unix = require "unix" ls = assert(unix.commandv("ls")) reader, writer = assert(unix.pipe()) if assert(unix.fork()) == 0 then unix.close(1) unix.dup(writer) unix.close(writer) unix.close(reader) unix.execve(ls, {ls, "-Shal"}) unix.exit(127) else unix.close(writer) SetHeader('Content-Type', 'text/plain') while true do data, err = unix.read(reader) if data then if data ~= "" then Write(data) else break end elseif err:errno() ~= EINTR then Log(kLogWarn, tostring(err)) break end end assert(unix.close(reader)) assert(unix.wait()) end unix.wait([pid:int[, options:int]]) ├─→ pid:int, wstatus:int, unix.Rusage └─→ nil, unix.Errno Waits for subprocess to terminate. `pid` defaults to `-1` which means any child process. Setting `pid` to `0` is equivalent to `-getpid()`. If `pid < -1` then that means wait for any pid in the process group `-pid`. Then lastly if `pid > 0` then this waits for a specific process id Options may have `WNOHANG` which means don't block, check for the existence of processes that are already dead (technically speaking zombies) and if so harvest them immediately. Returns the process id of the child that terminated. In other cases, the returned `pid` is nil and `errno` is non-nil. The returned `wstatus` contains information about the process exit status. It's a complicated integer and there's functions that can help interpret it. For example: -- wait for zombies -- traditional technique for SIGCHLD handlers while true do pid, status = unix.wait(-1, unix.WNOHANG) if pid then if unix.WIFEXITED(status) then print('child', pid, 'exited with', unix.WEXITSTATUS(status)) elseif unix.WIFSIGNALED(status) then print('child', pid, 'crashed with', unix.strsignal(unix.WTERMSIG(status))) end elseif status:errno() == unix.ECHILD then Log(kLogDebug, 'no more zombies') break else Log(kLogWarn, tostring(err)) break end end unix.WIFEXITED(wstatus:int) └─→ bool Returns true if process exited cleanly. unix.WEXITSTATUS(wstatus:int) └─→ exitcode:uint8 Returns code passed to exit() assuming `WIFEXITED(wstatus)` is true. unix.WIFSIGNALED(wstatus:int) └─→ bool Returns true if process terminated due to a signal. unix.WTERMSIG(wstatus:int) └─→ sig:uint8 Returns signal that caused process to terminate assuming `WIFSIGNALED(wstatus)` is true. unix.getpid() └─→ pid:int Returns process id of current process. This function does not fail. unix.getppid() └─→ pid:int Returns process id of parent process. This function does not fail. unix.kill(pid:int, sig:int) ├─→ true └─→ nil, unix.Errno Sends signal to process(es). The impact of this action can be terminating the process, or interrupting it to request something happen. `pid` can be: - `pid > 0` signals one process by id - `== 0` signals all processes in current process group - `-1` signals all processes possible (except init) - `< -1` signals all processes in -pid process group `sig` can be: - `0` checks both if pid exists and we can signal it - `SIGINT` sends ctrl-c keyboard interrupt - `SIGQUIT` sends backtrace and exit signal - `SIGTERM` sends shutdown signal - etc. Windows NT only supports the kill() signals required by the ANSI C89 standard, which are `SIGINT` and `SIGQUIT`. All other signals on the Windows platform that are sent to another process via kill() will be treated like `SIGKILL`. unix.raise(sig:int) ├─→ rc:int └─→ nil, unix.Errno Triggers signal in current process. This is pretty much the same as `kill(getpid(), sig)`. unix.access(path:str, how:int[, flags:int[, dirfd:int]]) ├─→ true └─→ nil, unix.Errno Checks if effective user of current process has permission to access file. `how` can be `R_OK`, `W_OK`, `X_OK`, or `F_OK` to check for read, write, execute, and existence respectively. `flags` may have any of: - `AT_SYMLINK_NOFOLLOW`: do not follow symbolic links. unix.mkdir(path:str[, mode:int[, dirfd:int]]) ├─→ true └─→ nil, unix.Errno Makes directory. `path` is the path of the directory you wish to create. `mode` is octal permission bits, e.g. `0755`. Fails with `EEXIST` if `path` already exists, whether it be a directory or a file. Fails with `ENOENT` if the parent directory of the directory you want to create doesn't exist. For making `a/really/long/path/` consider using makedirs() instead. Fails with `ENOTDIR` if a parent directory component existed that wasn't a directory. Fails with `EACCES` if the parent directory doesn't grant write permission to the current user. Fails with `ENAMETOOLONG` if the path is too long. unix.makedirs(path:str[, mode:int]) ├─→ true └─→ nil, unix.Errno Makes directories. Unlike mkdir() this convenience wrapper will automatically create parent parent directories as needed. If the directory already exists then, unlike mkdir() which returns EEXIST, the makedirs() function will return success. `path` is the path of the directory you wish to create. `mode` is octal permission bits, e.g. `0755`. unix.chdir(path:str) ├─→ true └─→ nil, unix.Errno Changes current directory to `path`. unix.unlink(path:str[, dirfd:int]) ├─→ true └─→ nil, unix.Errno Removes file at `path`. If `path` refers to a symbolic link, the link is removed. Returns `EISDIR` if `path` refers to a directory. See rmdir(). unix.rmdir(path:str[, dirfd:int]) ├─→ true └─→ nil, unix.Errno Removes empty directory at `path`. Returns `ENOTDIR` if `path` isn't a directory, or a path component in `path` exists yet wasn't a directory. unix.rename(oldpath:str, newpath:str[, olddirfd:int, newdirfd:int]) ├─→ true └─→ nil, unix.Errno Renames file or directory. unix.link(existingpath:str, newpath:str[, flags:int[, olddirfd, newdirfd]]) ├─→ true └─→ nil, unix.Errno Creates hard link, so your underlying inode has two names. unix.symlink(target:str, linkpath:str[, newdirfd:int]) ├─→ true └─→ nil, unix.Errno Creates symbolic link. On Windows NT a symbolic link is called a "reparse point" and can only be created from an administrator account. Your redbean will automatically request the appropriate permissions. unix.readlink(path:str[, dirfd:int]) ├─→ content:str └─→ nil, unix.Errno Reads contents of symbolic link. Note that broken links are supported on all platforms. A symbolic link can contain just about anything. It's important to not assume that `content` will be a valid filename. On Windows NT, this function transliterates `\` to `/` and furthermore prefixes `//?/` to WIN32 DOS-style absolute paths, thereby assisting with simple absolute filename checks in addition to enabling one to exceed the traditional 260 character limit. unix.realpath(path:str) ├─→ path:str └─→ nil, unix.Errno Returns absolute path of filename, with `.` and `..` components removed, and symlinks will be resolved. unix.utimensat(path[, asecs, ananos, msecs, mnanos[, dirfd[, flags]]]) ├─→ 0 └─→ nil, unix.Errno Changes access and/or modified timestamps on file. `path` is a string with the name of the file. The `asecs` and `ananos` parameters set the access time. If they're none or nil, the current time will be used. The `msecs` and `mnanos` parameters set the modified time. If they're none or nil, the current time will be used. The nanosecond parameters (`ananos` and `mnanos`) must be on the interval [0,1000000000) or `unix.EINVAL` is raised. On XNU this is truncated to microsecond precision. On Windows NT, it's truncated to hectonanosecond precision. These nanosecond parameters may also be set to one of the following special values: - `unix.UTIME_NOW`: Fill this timestamp with current time. This feature is not available on old versions of Linux, e.g. RHEL5. - `unix.UTIME_OMIT`: Do not alter this timestamp. This feature is not available on old versions of Linux, e.g. RHEL5. `dirfd` is a file descriptor integer opened with `O_DIRECTORY` that's used for relative path names. It defaults to `unix.AT_FDCWD`. `flags` may have have any of the following flags bitwise or'd - `AT_SYMLINK_NOFOLLOW`: Do not follow symbolic links. This makes it possible to edit the timestamps on the symbolic link itself, rather than the file it points to. unix.futimens(fd:int[, asecs, ananos, msecs, mnanos]) ├─→ 0 └─→ nil, unix.Errno Changes access and/or modified timestamps on file descriptor. `fd` is the file descriptor of a file opened with `unix.open`. The `asecs` and `ananos` parameters set the access time. If they're none or nil, the current time will be used. The `msecs` and `mnanos` parameters set the modified time. If they're none or nil, the current time will be used. The nanosecond parameters (`ananos` and `mnanos`) must be on the interval [0,1000000000) or `unix.EINVAL` is raised. On XNU this is truncated to microsecond precision. On Windows NT, it's truncated to hectonanosecond precision. These nanosecond parameters may also be set to one of the following special values: - `unix.UTIME_NOW`: Fill this timestamp with current time. - `unix.UTIME_OMIT`: Do not alter this timestamp. This system call is currently not available on very old versions of Linux, e.g. RHEL5. unix.chown(path:str, uid:int, gid:int[, flags:int[, dirfd:int]]) ├─→ true └─→ nil, unix.Errno Changes user and group on file. Returns `ENOSYS` on Windows NT. unix.chmod(path:str, mode:int[, flags:int[, dirfd:int]]) ├─→ true └─→ nil, unix.Errno Changes mode bits on file. On Windows NT the chmod system call only changes the read-only status of a file. unix.getcwd() ├─→ path:str └─→ nil, unix.Errno Returns current working directory. On Windows NT, this function transliterates `\` to `/` and furthermore prefixes `//?/` to WIN32 DOS-style absolute paths, thereby assisting with simple absolute filename checks in addition to enabling one to exceed the traditional 260 character limit. unix.rmrf(path:str) ├─→ true └─→ nil, unix.Errno Recursively removes filesystem path. Like unix.makedirs() this function isn't actually a system call but rather is a Libc convenience wrapper. It's intended to be equivalent to using the UNIX shell's `rm -rf path` command. `path` is the file or directory path you wish to destroy. unix.fcntl(fd:int, unix.F_GETFD) ├─→ flags:int └─→ nil, unix.Errno Returns file descriptor flags. The returned `flags` may include any of: - `unix.FD_CLOEXEC` if `fd` was opened with `unix.O_CLOEXEC`. Returns `EBADF` if `fd` isn't open. unix.fcntl(fd:int, unix.F_SETFD, flags:int) ├─→ true └─→ nil, unix.Errno Sets file descriptor flags. `flags` may include any of: - `unix.FD_CLOEXEC` to re-open `fd` with `unix.O_CLOEXEC`. Returns `EBADF` if `fd` isn't open. unix.fcntl(fd:int, unix.F_GETFL) ├─→ flags:int └─→ nil, unix.Errno Returns file descriptor status flags. `flags & unix.O_ACCMODE` includes one of: - `O_RDONLY` - `O_WRONLY` - `O_RDWR` Examples of values `flags & ~unix.O_ACCMODE` may include: - `O_NONBLOCK` - `O_APPEND` - `O_SYNC` - `O_ASYNC` - `O_NOATIME` on Linux - `O_RANDOM` on Windows - `O_SEQUENTIAL` on Windows - `O_DIRECT` on Linux/FreeBSD/NetBSD/Windows Examples of values `flags & ~unix.O_ACCMODE` won't include: - `O_CREAT` - `O_TRUNC` - `O_EXCL` - `O_NOCTTY` Returns `EBADF` if `fd` isn't open. unix.fcntl(fd:int, unix.F_SETFL, flags:int) ├─→ true └─→ nil, unix.Errno Changes file descriptor status flags. Examples of values `flags` may include: - `O_NONBLOCK` - `O_APPEND` - `O_SYNC` - `O_ASYNC` - `O_NOATIME` on Linux - `O_RANDOM` on Windows - `O_SEQUENTIAL` on Windows - `O_DIRECT` on Linux/FreeBSD/NetBSD/Windows These values should be ignored: - `O_RDONLY`, `O_WRONLY`, `O_RDWR` - `O_CREAT`, `O_TRUNC`, `O_EXCL` - `O_NOCTTY` Returns `EBADF` if `fd` isn't open. unix.fcntl(fd:int, unix.F_SETLK[, type[, start[, len[, whence]]]]) unix.fcntl(fd:int, unix.F_SETLKW[, type[, start[, len[, whence]]]]) ├─→ true └─→ nil, unix.Errno Acquires lock on file interval. POSIX Advisory Locks allow multiple processes to leave voluntary hints to each other about which portions of a file they're using. The command may be: - `F_SETLK` to acquire lock if possible - `F_SETLKW` to wait for lock if necessary `fd` is file descriptor of open() file. `type` may be one of: - `F_RDLCK` for read lock (default) - `F_WRLCK` for read/write lock - `F_UNLCK` to unlock `start` is 0-indexed byte offset into file. The default is zero. `len` is byte length of interval. Zero is the default and it means until the end of the file. `whence` may be one of: - `SEEK_SET` start from beginning (default) - `SEEK_CUR` start from current position - `SEEK_END` start from end Returns `EAGAIN` if lock couldn't be acquired. POSIX says this theoretically could also be `EACCES` but we haven't seen this behavior on any of our supported platforms. Returns `EBADF` if `fd` wasn't open. unix.fcntl(fd:int, unix.F_GETLK[, type[, start[, len[, whence]]]]) ├─→ unix.F_UNLCK ├─→ type, start, len, whence, pid └─→ nil, unix.Errno Acquires information about POSIX advisory lock on file. This function accepts the same parameters as fcntl(F_SETLK) and tells you if the lock acquisition would be successful for a given range of bytes. If locking would have succeeded, then F_UNLCK is returned. If the lock would not have succeeded, then information about a conflicting lock is returned. Returned `type` may be `F_RDLCK` or `F_WRLCK`. Returned `pid` is the process id of the current lock owner. This function is currently not supported on Windows. Returns `EBADF` if `fd` wasn't open. unix.getsid(pid:int) ├─→ sid:int └─→ nil, unix.Errno Gets session id. unix.getpgrp() ├─→ pgid:int └─→ nil, unix.Errno Gets process group id. unix.setpgrp() ├─→ pgid:int └─→ nil, unix.Errno Sets process group id. This is the same as `setpgid(0,0)`. unix.setpgid(pid:int, pgid:int) ├─→ true └─→ nil, unix.Errno Sets process group id the modern way. unix.getpgid(pid:int) ├─→ pgid:int └─→ nil, unix.Errno Gets process group id the modern way. unix.setsid() ├─→ sid:int └─→ nil, unix.Errno Sets session id. This function can be used to create daemons. Fails with `ENOSYS` on Windows NT. unix.getuid() └─→ uid:int Gets real user id. On Windows this system call is polyfilled by running GetUserNameW() through Knuth's multiplicative hash. This function does not fail. unix.getgid() └─→ gid:int Sets real group id. On Windows this system call is polyfilled as getuid(). This function does not fail. unix.geteuid() └─→ uid:int Gets effective user id. For example, if your redbean is a setuid binary, then getuid() will return the uid of the user running the program, and geteuid() shall return zero which means root, assuming that's the file owning user. On Windows this system call is polyfilled as getuid(). This function does not fail. unix.getegid() └─→ gid:int Gets effective group id. On Windows this system call is polyfilled as getuid(). This function does not fail. unix.chroot(path:str) ├─→ true └─→ nil, unix.Errno Changes root directory. Returns `ENOSYS` on Windows NT. unix.setuid(uid:int) ├─→ true └─→ nil, unix.Errno Sets user id. One use case for this function is dropping root privileges. Should you ever choose to run redbean as root and decide not to use the `-G` and `-U` flags, you can replicate that behavior in the Lua processes you spawn as follows: ok, err = unix.setgid(1000) -- check your /etc/groups if not ok then Log(kLogFatal, tostring(err)) end ok, err = unix.setuid(1000) -- check your /etc/passwd if not ok then Log(kLogFatal, tostring(err)) end If your goal is to relinquish privileges because redbean is a setuid binary, then things are more straightforward: ok, err = unix.setgid(unix.getgid()) if not ok then Log(kLogFatal, tostring(err)) end ok, err = unix.setuid(unix.getuid()) if not ok then Log(kLogFatal, tostring(err)) end See also the setresuid() function and be sure to refer to your local system manual about the subtleties of changing user id in a way that isn't restorable. Returns `ENOSYS` on Windows NT if `uid` isn't `getuid()`. unix.setfsuid(uid:int) ├─→ true └─→ nil, unix.Errno Sets user id for file system ops. unix.setgid(gid:int) ├─→ true └─→ nil, unix.Errno Sets group id. Returns `ENOSYS` on Windows NT if `gid` isn't `getgid()`. unix.setresuid(real:int, effective:int, saved:int) ├─→ true └─→ nil, unix.Errno Sets real, effective, and saved user ids. If any of the above parameters are -1, then it's a no-op. Returns `ENOSYS` on Windows NT. Returns `ENOSYS` on Macintosh and NetBSD if `saved` isn't -1. unix.setresgid(real:int, effective:int, saved:int) ├─→ true └─→ nil, unix.Errno Sets real, effective, and saved group ids. If any of the above parameters are -1, then it's a no-op. Returns `ENOSYS` on Windows NT. Returns `ENOSYS` on Macintosh and NetBSD if `saved` isn't -1. unix.umask(newmask:int) └─→ oldmask:int Sets file permission mask and returns the old one. This is used to remove bits from the `mode` parameter of functions like open() and mkdir(). The masks typically used are 027 and 022. Those masks ensure that, even if a file is created with 0666 bits, it'll be turned into 0640 or 0644 so that users other than the owner can't modify it. To read the mask without changing it, try doing this: mask = unix.umask(027) unix.umask(mask) On Windows NT this is a no-op and `mask` is returned. This function does not fail. unix.syslog(priority:int, msg:str) Generates a log message, which will be distributed by syslogd. `priority` is a bitmask containing the facility value and the level value. If no facility value is ORed into priority, then the default value set by openlog() is used. If set to NULL, the program name is used. Level is one of `LOG_EMERG`, `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`, `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`. This function currently works on Linux, Windows, and NetBSD. On WIN32 it uses the ReportEvent() facility. unix.clock_gettime([clock:int]) ├─→ seconds:int, nanos:int └─→ nil, unix.Errno Returns nanosecond precision timestamp from system, e.g. >: unix.clock_gettime() 1651137352 774458779 >: Benchmark(unix.clock_gettime) 126 393 571 1 `clock` can be any one of of: - `CLOCK_REALTIME`: universally supported - `CLOCK_REALTIME_FAST`: ditto but faster on freebsd - `CLOCK_REALTIME_PRECISE`: ditto but better on freebsd - `CLOCK_REALTIME_COARSE`: : like `CLOCK_REALTIME_FAST` but needs Linux 2.6.32+ - `CLOCK_MONOTONIC`: universally supported - `CLOCK_MONOTONIC_FAST`: ditto but faster on freebsd - `CLOCK_MONOTONIC_PRECISE`: ditto but better on freebsd - `CLOCK_MONOTONIC_COARSE`: : like `CLOCK_MONOTONIC_FAST` but needs Linux 2.6.32+ - `CLOCK_MONOTONIC_RAW`: is actually monotonic but needs Linux 2.6.28+ - `CLOCK_PROCESS_CPUTIME_ID`: linux and bsd - `CLOCK_THREAD_CPUTIME_ID`: linux and bsd - `CLOCK_MONOTONIC_COARSE`: linux, freebsd - `CLOCK_PROF`: linux and netbsd - `CLOCK_BOOTTIME`: linux and openbsd - `CLOCK_REALTIME_ALARM`: linux-only - `CLOCK_BOOTTIME_ALARM`: linux-only - `CLOCK_TAI`: linux-only Returns `EINVAL` if clock isn't supported on platform. This function only fails if `clock` is invalid. This function goes fastest on Linux and Windows. unix.nanosleep(seconds:int[, nanos:int]) ├─→ remseconds:int, remnanos:int └─→ nil, unix.Errno Sleeps with nanosecond precision. Returns `EINTR` if a signal was received while waiting. unix.sync() unix.fsync(fd:int) ├─→ true └─→ nil, unix.Errno unix.fdatasync(fd:int) ├─→ true └─→ nil, unix.Errno These functions are used to make programs slower by asking the operating system to flush data to the physical medium. unix.lseek(fd:int, offset:int[, whence:int]) ├─→ newposbytes:int └─→ nil, unix.Errno Seeks to file position. `whence` can be one of: - `SEEK_SET`: Sets the file position to `offset` [default] - `SEEK_CUR`: Sets the file position to `position + offset` - `SEEK_END`: Sets the file position to `filesize + offset` Returns the new position relative to the start of the file. unix.truncate(path:str[, length:int]) ├─→ true └─→ nil, unix.Errno Reduces or extends underlying physical medium of file. If file was originally larger, content >length is lost. `length` defaults to zero. unix.ftruncate(fd:int[, length:int]) ├─→ true └─→ nil, unix.Errno Reduces or extends underlying physical medium of open file. If file was originally larger, content >length is lost. `length` defaults to zero. unix.socket([family:int[, type:int[, protocol:int]]]) ├─→ fd:int └─→ nil, unix.Errno Creates socket endpoint for process communication. `family` defaults to `AF_INET` and can be: - `AF_INET`: Creates Internet Protocol Version 4 (IPv4) socket. - `AF_UNIX`: Creates local UNIX domain socket. On the New Technology this requires Windows 10 and only works with `SOCK_STREAM`. `type` defaults to `SOCK_STREAM` and can be: - `SOCK_STREAM` - `SOCK_DGRAM` - `SOCK_RAW` - `SOCK_RDM` - `SOCK_SEQPACKET` You may bitwise OR any of the following into `type`: - `SOCK_CLOEXEC` - `SOCK_NONBLOCK` `protocol` may be any of: - `0` to let kernel choose [default] - `IPPROTO_TCP` - `IPPROTO_UDP` - `IPPROTO_RAW` - `IPPROTO_IP` - `IPPROTO_ICMP` unix.socketpair([family:int[, type:int[, protocol:int]]]) ├─→ fd1:int, fd2:int └─→ nil, unix.Errno Creates bidirectional pipe. `family` defaults to `AF_UNIX`. `type` defaults to `SOCK_STREAM` and can be: - `SOCK_STREAM` - `SOCK_DGRAM` - `SOCK_SEQPACKET` You may bitwise OR any of the following into `type`: - `SOCK_CLOEXEC` - `SOCK_NONBLOCK` `protocol` defaults to `0`. unix.bind(fd:int[, ip:uint32, port:uint16]) unix.bind(fd:int[, unixpath:str]) ├─→ true └─→ nil, unix.Errno Binds socket. `ip` and `port` are in host endian order. For example, if you wanted to listen on `1.2.3.4:31337` you could do any of these unix.bind(sock, 0x01020304, 31337) unix.bind(sock, ParseIp('1.2.3.4'), 31337) unix.bind(sock, 1 << 24 | 0 << 16 | 0 << 8 | 1, 31337) `ip` and `port` both default to zero. The meaning of bind(0, 0) is to listen on all interfaces with a kernel-assigned ephemeral port number, that can be retrieved and used as follows: sock = assert(unix.socket()) -- create ipv4 tcp socket assert(unix.bind(sock)) -- all interfaces ephemeral port ip, port = assert(unix.getsockname(sock)) print("listening on ip", FormatIp(ip), "port", port) assert(unix.listen(sock)) while true do client, clientip, clientport = assert(unix.accept(sock)) print("got client ip", FormatIp(clientip), "port", clientport) unix.close(client) end Further note that calling `unix.bind(sock)` is equivalent to not calling bind() at all, since the above behavior is the default. unix.siocgifconf() ├─→ {{name:str,ip:uint32,netmask:uint32}, ...} └─→ nil, unix.Errno Returns list of network adapter addresses. unix.getsockopt(fd:int, level:int, optname:int) → ... unix.setsockopt(fd:int, level:int, optname:int, ...) → ok:bool, unix.Errno Tunes networking parameters. `level` and `optname` may be one of the following pairs. The ellipses type signature above changes depending on which options are used. `optname` is the option feature magic number. The constants for these will be set to `0` if the option isn't supported on the host platform. Raises `ENOPROTOOPT` if your `level` / `optname` combination isn't valid, recognized, or supported on the host platform. Raises `ENOTSOCK` if `fd` is valid but isn't a socket. Raises `EBADF` if `fd` isn't valid. unix.getsockopt(fd:int, level:int, optname:int) ├─→ value:int └─→ nil, unix.Errno unix.setsockopt(fd:int, level:int, optname:int, value:bool) ├─→ true └─→ nil, unix.Errno - `SOL_SOCKET`, `SO_TYPE` - `SOL_SOCKET`, `SO_DEBUG` - `SOL_SOCKET`, `SO_ACCEPTCONN` - `SOL_SOCKET`, `SO_BROADCAST` - `SOL_SOCKET`, `SO_REUSEADDR` - `SOL_SOCKET`, `SO_REUSEPORT` - `SOL_SOCKET`, `SO_KEEPALIVE` - `SOL_SOCKET`, `SO_DONTROUTE` - `SOL_TCP`, `TCP_NODELAY` - `SOL_TCP`, `TCP_CORK` - `SOL_TCP`, `TCP_QUICKACK` - `SOL_TCP`, `TCP_FASTOPEN_CONNECT` - `SOL_TCP`, `TCP_DEFER_ACCEPT` - `SOL_IP`, `IP_HDRINCL` unix.getsockopt(fd:int, level:int, optname:int) ├─→ value:int └─→ nil, unix.Errno unix.setsockopt(fd:int, level:int, optname:int, value:int) ├─→ true └─→ nil, unix.Errno - `SOL_SOCKET`, `SO_SNDBUF` - `SOL_SOCKET`, `SO_RCVBUF` - `SOL_SOCKET`, `SO_RCVLOWAT` - `SOL_SOCKET`, `SO_SNDLOWAT` - `SOL_TCP`, `TCP_KEEPIDLE` - `SOL_TCP`, `TCP_KEEPINTVL` - `SOL_TCP`, `TCP_FASTOPEN` - `SOL_TCP`, `TCP_KEEPCNT` - `SOL_TCP`, `TCP_MAXSEG` - `SOL_TCP`, `TCP_SYNCNT` - `SOL_TCP`, `TCP_NOTSENT_LOWAT` - `SOL_TCP`, `TCP_WINDOW_CLAMP` - `SOL_IP`, `IP_TOS` - `SOL_IP`, `IP_MTU` - `SOL_IP`, `IP_TTL` unix.getsockopt(fd:int, level:int, optname:int) ├─→ secs:int, nsecs:int └─→ nil, unix.Errno unix.setsockopt(fd:int, level:int, optname:int, secs:int[, nanos:int]) ├─→ true └─→ nil, unix.Errno - `SOL_SOCKET`, `SO_RCVTIMEO`: If this option is specified then your stream socket will have a read() / recv() timeout. If the specified interval elapses without receiving data, then EAGAIN shall be returned by read. If this option is used on listening sockets, it'll be inherited by accepted sockets. Your redbean already does this for GetClientFd() based on the `-t` flag. - `SOL_SOCKET`, `SO_SNDTIMEO`: This is the same as `SO_RCVTIMEO` but it applies to the write() / send() functions. unix.getsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER) ├─→ seconds:int, enabled:bool └─→ nil, unix.Errno unix.setsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER, secs:int, enabled:bool) ├─→ true └─→ nil, unix.Errno This `SO_LINGER` parameter can be used to make close() a blocking call. Normally when the kernel returns immediately when it receives close(). Sometimes it's desirable to have extra assurance on errors happened, even if it comes at the cost of performance. unix.setsockopt(serverfd:int, unix.SOL_TCP, unix.TCP_SAVE_SYN, enabled:int) ├─→ true └─→ nil, unix.Errno unix.getsockopt(clientfd:int, unix.SOL_TCP, unix.TCP_SAVED_SYN) ├─→ syn_packet_bytes:str └─→ nil, unix.Errno This `TCP_SAVED_SYN` option may be used to retrieve the bytes of the TCP SYN packet that the client sent when the connection for `fd` was opened. In order for this to work, `TCP_SAVE_SYN` must have been set earlier on the listening socket. This is Linux-only. You can use the `OnServerListen` hook to enable SYN saving in your Redbean. When the `TCP_SAVE_SYN` option isn't used, this may return empty string. unix.poll({[fd:int]=events:int, ...}[, timeoutms:int[, mask:unix.Sigset]]) ├─→ {[fd:int]=revents:int, ...} └─→ nil, unix.Errno Checks for events on a set of file descriptors. The table of file descriptors to poll uses sparse integer keys. Any pairs with non-integer keys will be ignored. Pairs with negative keys are ignored by poll(). The returned table will be a subset of the supplied file descriptors. `events` and `revents` may be any combination (using bitwise OR) of: - `POLLIN` (events, revents): There is data to read. - `POLLOUT` (events, revents): Writing is now possible, although may still block if available space in a socket or pipe is exceeded (unless `O_NONBLOCK` is set). - `POLLPRI` (events, revents): There is some exceptional condition (for example, out-of-band data on a TCP socket). - `POLLRDHUP` (events, revents): Stream socket peer closed connection, or shut down writing half of connection. - `POLLERR` (revents): Some error condition. - `POLLHUP` (revents): Hang up. When reading from a channel such as a pipe or a stream socket, this event merely indicates that the peer closed its end of the channel. - `POLLNVAL` (revents): Invalid request. `timeoutms` is the number of milliseconds to block. The default is -1 which means block indefinitely until there's an event or an interrupt. If the timeout elapses without any such events, an empty table is returned. A timeout of zero means non-blocking. `mask` serves the purpose of enabling poll to listen for both file descriptor events and signals. It's equivalent to saying: oldmask = unix.sigprocmask(unix.SIG_SETMASK, mask); unix.poll(fds, timeout); unix.sigprocmask(unix.SIG_SETMASK, oldmask); Except it'll happen atomically on supported platforms. The only exceptions are MacOS and NetBSD where this behavior is simulated by the polyfill. Atomicity is helpful for unit testing signal behavior. `EINTR` is returned if the kernel decided to deliver a signal to a signal handler instead during your call. This is a @norestart system call that always returns `EINTR` even if `SA_RESTART` is in play. unix.gethostname() ├─→ host:str └─→ nil, unix.Errno Returns hostname of system. unix.listen(fd:int[, backlog:int]) ├─→ true └─→ nil, unix.Errno Begins listening for incoming connections on a socket. unix.accept(serverfd:int[, flags:int]) ├─→ clientfd:int, ip:uint32, port:uint16 ├─→ clientfd:int, unixpath:str └─→ nil, unix.Errno Accepts new client socket descriptor for a listening tcp socket. `flags` may have any combination (using bitwise OR) of: - `SOCK_CLOEXEC` - `SOCK_NONBLOCK` unix.connect(fd:int, ip:uint32, port:uint16) unix.connect(fd:int, unixpath:str) ├─→ true └─→ nil, unix.Errno Connects a TCP socket to a remote host. With TCP this is a blocking operation. For a UDP socket it simply remembers the intended address so that send() or write() may be used rather than sendto(). unix.getsockname(fd:int) ├─→ ip:uint32, port:uint16 ├─→ unixpath:str └─→ nil, unix.Errno Retrieves the local address of a socket. unix.getpeername(fd:int) ├─→ ip:uint32, port:uint16 ├─→ unixpath:str └─→ nil, unix.Errno Retrieves the remote address of a socket. This operation will either fail on `AF_UNIX` sockets or return an empty string. unix.recv(fd:int[, bufsiz:int[, flags:int]]) ├─→ data:str └─→ nil, unix.Errno Receives message from a socket. `flags` may have any combination (using bitwise OR) of: - `MSG_WAITALL` - `MSG_DONTROUTE` - `MSG_PEEK` - `MSG_OOB` unix.recvfrom(fd:int[, bufsiz:int[, flags:int]]) ├─→ data:str, ip:uint32, port:uint16 ├─→ data:str, unixpath:str └─→ nil, unix.Errno Receives message from a socket. `flags` may have any combination (using bitwise OR) of: - `MSG_WAITALL` - `MSG_DONTROUTE` - `MSG_PEEK` - `MSG_OOB` unix.send(fd:int, data:str[, flags:int]) ├─→ sent:int └─→ nil, unix.Errno This is the same as `write` except it has a `flags` argument that's intended for sockets. `flags` may have any combination (using bitwise OR) of: - `MSG_NOSIGNAL`: Don't SIGPIPE on EOF - `MSG_OOB`: Send stream data through out of bound channel - `MSG_DONTROUTE`: Don't go through gateway (for diagnostics) - `MSG_MORE`: Manual corking to belay nodelay (0 on non-Linux) unix.sendto(fd:int, data:str, ip:uint32, port:uint16[, flags:int]) unix.sendto(fd:int, data:str, unixpath:str[, flags:int]) ├─→ sent:int └─→ nil, unix.Errno This is useful for sending messages over UDP sockets to specific addresses. `flags` may have any combination (using bitwise OR) of: - `MSG_OOB` - `MSG_DONTROUTE` - `MSG_NOSIGNAL` unix.shutdown(fd:int, how:int) ├─→ true └─→ nil, unix.Errno Partially closes socket. `how` is set to one of: - `SHUT_RD`: sends a tcp half close for reading - `SHUT_WR`: sends a tcp half close for writing - `SHUT_RDWR` This system call currently has issues on Macintosh, so portable code should log rather than assert failures reported by shutdown(). unix.sigprocmask(how:int, newmask:unix.Sigset) ├─→ oldmask:unix.Sigset └─→ nil, unix.Errno Manipulates bitset of signals blocked by process. `how` can be one of: - `SIG_BLOCK`: applies `mask` to set of blocked signals using bitwise OR - `SIG_UNBLOCK`: removes bits in `mask` from set of blocked signals - `SIG_SETMASK`: replaces process signal mask with `mask` `mask` is a unix.Sigset() object (see section below). For example, to temporarily block `SIGTERM` and `SIGINT` so critical work won't be interrupted, sigprocmask() can be used as follows: newmask = unix.Sigset(unix.SIGTERM) oldmask = assert(unix.sigprocmask(unix.SIG_BLOCK, newmask)) -- do something... assert(unix.sigprocmask(unix.SIG_SETMASK, oldmask)) unix.sigaction(sig:int[, handler:func|int[, flags:int[, mask:unix.Sigset]]]) ├─→ oldhandler:func|int, flags:int, mask:unix.Sigset └─→ nil, unix.Errno Changes action taken upon receipt of a specific signal. `sig` can be one of: - `unix.SIGINT` - `unix.SIGQUIT` - `unix.SIGTERM` - etc. `handler` can be: - Lua function - `unix.SIG_IGN` - `unix.SIG_DFL` `flags` can have: - `unix.SA_RESTART`: Enables BSD signal handling semantics. Normally i/o entrypoints check for pending signals to deliver. If one gets delivered during an i/o call, the normal behavior is to cancel the i/o operation and return -1 with `EINTR` in errno. If you use the `SA_RESTART` flag then that behavior changes, so that any function that's been annotated with @restartable will not return `EINTR` and will instead resume the i/o operation. This makes coding easier but it can be an anti-pattern if not used carefully, since poor usage can easily result in latency issues. It also requires one to do more work in signal handlers, so special care needs to be given to which C library functions are @asyncsignalsafe. - `unix.SA_RESETHAND`: Causes signal handler to be single-shot. This means that, upon entry of delivery to a signal handler, it's reset to the `SIG_DFL` handler automatically. You may use the alias `SA_ONESHOT` for this flag, which means the same thing. - `unix.SA_NODEFER`: Disables the reentrancy safety check on your signal handler. Normally that's a good thing, since for instance if your `SIGSEGV` signal handler happens to segfault, you're going to want your process to just crash rather than looping endlessly. But in some cases it's desirable to use `SA_NODEFER` instead, such as at times when you wish to `longjmp()` out of your signal handler and back into your program. This is only safe to do across platforms for non-crashing signals such as `SIGCHLD` and `SIGINT`. Crash handlers should use Xed instead to recover execution, because on Windows a `SIGSEGV` or `SIGTRAP` crash handler might happen on a separate stack and/or a separate thread. You may use the alias `SA_NOMASK` for this flag, which means the same thing. - `unix.SA_NOCLDWAIT`: Changes `SIGCHLD` so the zombie is gone and you can't call wait() anymore; similar but may still deliver the SIGCHLD. - `unix.SA_NOCLDSTOP`: Lets you set `SIGCHLD` handler that's only notified on exit/termination and not notified on `SIGSTOP`, `SIGTSTP`, `SIGTTIN`, `SIGTTOU`, or `SIGCONT`. Example: function OnSigUsr1(sig) gotsigusr1 = true end gotsigusr1 = false oldmask = assert(unix.sigprocmask(unix.SIG_BLOCK, unix.Sigset(unix.SIGUSR1))) assert(unix.sigaction(unix.SIGUSR1, OnSigUsr1)) assert(unix.raise(unix.SIGUSR1)) assert(not gotsigusr1) ok, err = unix.sigsuspend(oldmask) assert(not ok) assert(err:errno() == unix.EINTR) assert(gotsigusr1) assert(unix.sigprocmask(unix.SIG_SETMASK, oldmask)) It's a good idea to not do too much work in a signal handler. unix.sigpending() ├─→ mask:unix.Sigset └─→ nil, unix.Errno Returns the set of signals that are pending for delivery. unix.sigsuspend([mask:unix.Sigset]) └─→ nil, unix.Errno Waits for signal to be delivered. The signal mask is temporarily replaced with `mask` during this system call. `mask` specifies which signals should be blocked. unix.setitimer(which[, intervalsec, intns, valuesec, valuens]) ├─→ intervalsec:int, intervalns:int, valuesec:int, valuens:int └─→ nil, unix.Errno Causes `SIGALRM` signals to be generated at some point(s) in the future. The `which` parameter should be `ITIMER_REAL`. Here's an example of how to create a 400 ms interval timer: ticks = 0 assert(unix.sigaction(unix.SIGALRM, function(sig) print('tick no. %d' % {ticks}) ticks = ticks + 1 end)) assert(unix.setitimer(unix.ITIMER_REAL, 0, 400e6, 0, 400e6)) while true do unix.sigsuspend() end Here's how you'd do a single-shot timeout in 1 second: unix.sigaction(unix.SIGALRM, MyOnSigAlrm, unix.SA_RESETHAND) unix.setitimer(unix.ITIMER_REAL, 0, 0, 1, 0) `intns` needs to be on the interval `[0,1000000000)` `valuens` needs to be on the interval `[0,1000000000)` unix.strsignal(sig:int) → str Turns platform-specific `sig` code into its symbolic name. For example: >: unix.strsignal(9) "SIGKILL" >: unix.strsignal(unix.SIGKILL) "SIGKILL" Please note that signal numbers are normally different across supported platforms, and the constants should be preferred. unix.setrlimit(resource:int, soft:int[, hard:int]) ├─→ true └─→ nil, unix.Errno Changes resource limit. `resource` may be one of: - `RLIMIT_AS` limits the size of the virtual address space. This will work on all platforms. It's emulated on XNU and Windows which means it won't propagate across execve() currently. - `RLIMIT_CPU` causes `SIGXCPU` to be sent to the process when the soft limit on CPU time is exceeded, and the process is destroyed when the hard limit is exceeded. It works everywhere but Windows where it should be possible to poll getrusage() with setitimer(). - `RLIMIT_FSIZE` causes `SIGXFSZ` to sent to the process when the soft limit on file size is exceeded and the process is destroyed when the hard limit is exceeded. It works everywhere but Windows. - `RLIMIT_NPROC` limits the number of simultaneous processes and it should work on all platforms except Windows. Please be advised it limits the process, with respect to the activities of the user id as a whole. - `RLIMIT_NOFILE` limits the number of open file descriptors and it should work on all platforms except Windows (TODO). If a limit isn't supported by the host platform, it'll be set to 127. On most platforms these limits are enforced by the kernel and as such are inherited by subprocesses. `hard` defaults to whatever was specified in `soft`. unix.getrlimit(resource:int) ├─→ soft:int, hard:int └─→ nil, unix.Errno Returns information about resource limits for current process. unix.getrusage([who:int]) ├─→ unix.Rusage └─→ nil, unix.Errno Returns information about resource usage for current process, e.g. >: unix.getrusage() {utime={0, 53644000}, maxrss=44896, minflt=545, oublock=24, nvcsw=9} `who` defaults to `RUSAGE_SELF` and can be any of: - `RUSAGE_SELF`: current process - `RUSAGE_THREAD`: current thread - `RUSAGE_CHILDREN`: not supported on Windows NT - `RUSAGE_BOTH`: not supported on non-Linux See the unix.Rusage section below for details on returned fields. unix.pledge([promises:str[, execpromises:str[, mode:int]]]) ├─→ true └─→ nil, unix.Errno Restrict system operations. This can be used to sandbox your redbean workers. It allows finer customization compared to the `-S` flag. Pledging causes most system calls to become unavailable. If a forbidden system call is used, then the process will be killed. In that case, on OpenBSD, your system log will explain which promise you need. On Linux, we report the promise to stderr, with one exception: reporting is currently not possible if you pledge exec. Using pledge is irreversible. On Linux it causes PR_SET_NO_NEW_PRIVS to be set on your process. By default exit and exit_group are always allowed. This is useful for processes that perform pure computation and interface with the parent via shared memory. Once pledge is in effect, the chmod functions (if allowed) will not permit the sticky/setuid/setgid bits to change. Linux will EPERM here and OpenBSD should ignore those three bits rather than crashing. User and group IDs also can't be changed once pledge is in effect. OpenBSD should ignore the chown functions without crashing. Linux will just EPERM. Root access isn't required. Support is limited to OpenBSD and Linux 2.6.23+ (i.e. RHEL6 c. 2012) so long as Redbean is running directly on the host system, i.e. not running in a userspace emulator like Blink or Qemu. If your environment isn't supported, then pledge() will return 0 and do nothing, rather than raising ENOSYS, so the apps you share with others will err on the side of not breaking. If a functionality check is needed, please use `unix.pledge(nil, nil)` which is a no-op that will fail appropriately when the necessary system support isn't available to impose security restrictions. `promises` is a string that may include any of the following groups delimited by spaces. This list has been curated to focus on the system calls for which this module provides wrappers. See the Cosmopolitan Libc pledge() documentation for a comprehensive and authoritative list of raw system calls. Having the raw system call list may be useful if you're executing foreign programs. stdio Allows read, write, send, recv, recvfrom, close, clock_getres, clock_gettime, dup, fchdir, fstat, fsync, fdatasync, ftruncate, getdents, getegid, getrandom, geteuid, getgid, getgroups, getitimer, getpgid, getpgrp, getpid, hgetppid, getresgid, getresuid, getrlimit, getsid, gettimeofday, getuid, lseek, madvise, brk, mmap/mprotect (PROT_EXEC isn't allowed), msync, munmap, gethostname, nanosleep, pipe, pipe2, poll, setitimer, shutdown, sigaction, sigsuspend, sigprocmask, socketpair, umask, wait4, getrusage, ioctl(FIONREAD), ioctl(FIONBIO), ioctl(FIOCLEX), ioctl(FIONCLEX), fcntl(F_GETFD), fcntl(F_SETFD), fcntl(F_GETFL), fcntl(F_SETFL), raise, kill(getpid()). rpath Allows chdir, getcwd, open, stat, fstat, access, readlink, chmod, chmod, fchmod. wpath Allows getcwd, open, stat, fstat, access, readlink, chmod, fchmod. cpath Allows rename, link, symlink, unlink, mkdir, rmdir. fattr Allows chmod, fchmod, utimensat, futimens. flock Allows flock, fcntl(F_GETLK), fcntl(F_SETLK), fcntl(F_SETLKW). tty Allows isatty, tiocgwinsz, tcgets, tcsets, tcsetsw, tcsetsf. inet Allows socket (AF_INET), listen, bind, connect, accept, getpeername, getsockname, setsockopt, getsockopt. anet Allows socket (AF_INET), listen, bind, accept, getpeername, getsockname, setsockopt, getsockopt. unix Allows socket (AF_UNIX), listen, bind, connect, accept, getpeername, getsockname, setsockopt, getsockopt. dns Allows sendto, recvfrom, socket(AF_INET), connect. recvfd Allows recvmsg, recvmmsg. sendfd Allows sendmsg, sendmmsg. proc Allows fork, vfork, clone, kill, tgkill, getpriority, setpriority, setrlimit, setpgid, setsid. id Allows setuid, setreuid, setresuid, setgid, setregid, setresgid, setgroups, setrlimit, getpriority, setpriority. settime Allows settimeofday and clock_adjtime. chown Allows chown. unveil Allows unveil(). exec Allows execve. If the executable in question needs a loader, then you will need "rpath prot_exec" too. With APE, security is strongest when you assimilate your binaries beforehand, using the --assimilate flag, or the o//tool/build/assimilate.com program. On OpenBSD this is mandatory. prot_exec Allows mmap(PROT_EXEC) and mprotect(PROT_EXEC). This may be needed to launch non-static non-native executables, such as non-assimilated APE binaries, or programs that link dynamic shared objects, i.e. most Linux distro binaries. `execpromises` only matters if "exec" is specified in `promises`. In that case, this specifies the promises that'll apply once execve() happens. If this is NULL then the default is used, which is unrestricted. OpenBSD allows child processes to escape the sandbox (so a pledged OpenSSH server process can do things like spawn a root shell). Linux however requires monotonically decreasing privileges. This function will will perform some validation on Linux to make sure that `execpromises` is a subset of `promises`. Your libc wrapper for execve() will then apply its SECCOMP BPF filter later. Since Linux has to do this before calling sys_execve(), the executed process will be weakened to have execute permissions too. `mode` if specified should specify one penalty: - `unix.PLEDGE_PENALTY_KILL_THREAD` causes the violating thread to be killed. This is the default on Linux. It's effectively the same as killing the process, since redbean has no threads. The termination signal can't be caught and will be either `SIGSYS` or `SIGABRT`. Consider enabling stderr logging below so you'll know why your program failed. Otherwise check the system log. - `unix.PLEDGE_PENALTY_KILL_PROCESS` causes the process and all its threads to be killed. This is always the case on OpenBSD. - `unix.PLEDGE_PENALTY_RETURN_EPERM` causes system calls to just return an `EPERM` error instead of killing. This is a gentler solution that allows code to display a friendly warning. Please note this may lead to weird behaviors if the software being sandboxed is lazy about checking error results. `mode` may optionally bitwise or the following flags: - `unix.PLEDGE_STDERR_LOGGING` enables friendly error message logging letting you know which promises are needed whenever violations occur. Without this, violations will be logged to `dmesg` on Linux if the penalty is to kill the process. You would then need to manually look up the system call number and then cross reference it with the cosmopolitan libc pledge() documentation. You can also use `strace -ff` which is easier. This is ignored OpenBSD, which already has a good system log. Turning on stderr logging (which uses SECCOMP trapping) also means that the `unix.WTERMSIG()` on your killed processes will always be `unix.SIGABRT` on both Linux and OpenBSD. Otherwise, Linux prefers to raise `unix.SIGSYS`. unix.unveil(path:str, permissions:str) ├─→ true └─→ nil, unix.Errno Restricts filesystem operations, e.g. unix.unveil(".", "r"); -- current dir + children visible unix.unveil("/etc", "r"); -- make /etc readable too unix.unveil(nil, nil); -- commit and lock policy Unveiling restricts a thread's view of the filesystem to a set of allowed paths with specific privileges. Once you start using unveil(), the entire file system is considered hidden. You then specify, by repeatedly calling unveil(), which paths should become unhidden. When you're finished, you call `unveil(nil,nil)` which commits your policy, after which further use is forbidden, in the current thread, as well as any threads or processes it spawns. There are some differences between unveil() on Linux versus OpenBSD. 1. Build your policy and lock it in one go. On OpenBSD, policies take effect immediately and may evolve as you continue to call unveil() but only in a more restrictive direction. On Linux, nothing will happen until you call `unveil(nil,nil)` which commits and locks. 2. Try not to overlap directory trees. On OpenBSD, if directory trees overlap, then the most restrictive policy will be used for a given file. On Linux overlapping may result in a less restrictive policy and possibly even undefined behavior. 3. OpenBSD and Linux disagree on error codes. On OpenBSD, accessing paths outside of the allowed set raises ENOENT, and accessing ones with incorrect permissions raises EACCES. On Linux, both these cases raise EACCES. 4. Unlike OpenBSD, Linux does nothing to conceal the existence of paths. Even with an unveil() policy in place, it's still possible to access the metadata of all files using functions like stat() and open(O_PATH), provided you know the path. A sandboxed process can always, for example, determine how many bytes of data are in /etc/passwd, even if the file isn't readable. But it's still not possible to use opendir() and go fishing for paths which weren't previously known. This system call is supported natively on OpenBSD and polyfilled on Linux using the Landlock LSM[1]. This function requires OpenBSD or Linux 5.13+ (2022+). If the kernel support isn't available (or we're in an emulator like Qemu or Blink) then zero is returned and nothing happens (instead of raising ENOSYS) because the files are still unveiled. Use `unix.unveil("", nil)` to feature check the host system, which is defined as a no-op that'll fail if the host system doesn't have the necessary features that allow unix.unveil() impose bona-fide security restrictions. Otherwise, if everything is good, a return value `>=0` is returned, where `0` means OpenBSD, and `>=1` means Linux with Landlock LSM, in which case the return code shall be the maximum supported Landlock ABI version. `path` is the file or directory to unveil `permissions` is a string consisting of zero or more of the following characters: - 'r' makes `path` available for read-only path operations, corresponding to the pledge promise "rpath". - `w` makes `path` available for write operations, corresponding to the pledge promise "wpath". - `x` makes `path` available for execute operations, corresponding to the pledge promises "exec" and "execnative". - `c` allows `path` to be created and removed, corresponding to the pledge promise "cpath". unix.gmtime(unixts:int) ├─→ year,mon,mday,hour,min,sec,gmtoffsec,wday,yday,dst:int,zone:str └─→ nil,unix.Errno Breaks down UNIX timestamp into Zulu Time numbers. - `mon` 1 ≤ mon ≤ 12 - `mday` 1 ≤ mday ≤ 31 - `hour` 0 ≤ hour ≤ 23 - `min` 0 ≤ min ≤ 59 - `sec` 0 ≤ sec ≤ 60 - `gmtoff` ±93600 seconds - `wday` 0 ≤ wday ≤ 6 - `yday` 0 ≤ yday ≤ 365 - `dst` 1 if daylight savings, 0 if not, -1 if not unknown unix.localtime(unixts:int) ├─→ year,mon,mday,hour,min,sec,gmtoffsec,wday,yday,dst:int,zone:str └─→ nil,unix.Errno Breaks down UNIX timestamp into local time numbers, e.g. >: unix.localtime(unix.clock_gettime()) 2022 4 28 2 14 22 -25200 4 117 1 "PDT" This follows the same API as gmtime() which has further details. Your redbean ships with a subset of the time zone database. - `/zip/usr/share/zoneinfo/Honolulu` Z-10 - `/zip/usr/share/zoneinfo/Anchorage` Z -9 - `/zip/usr/share/zoneinfo/GST` Z -8 - `/zip/usr/share/zoneinfo/Boulder` Z -6 - `/zip/usr/share/zoneinfo/Chicago` Z -5 - `/zip/usr/share/zoneinfo/New_York` Z -4 - `/zip/usr/share/zoneinfo/UTC` Z +0 - `/zip/usr/share/zoneinfo/GMT` Z +0 - `/zip/usr/share/zoneinfo/London` Z +1 - `/zip/usr/share/zoneinfo/Berlin` Z +2 - `/zip/usr/share/zoneinfo/Israel` Z +3 - `/zip/usr/share/zoneinfo/India` Z +5 - `/zip/usr/share/zoneinfo/Beijing` Z +8 - `/zip/usr/share/zoneinfo/Japan` Z +9 - `/zip/usr/share/zoneinfo/Sydney` Z+10 You can control which timezone is used using the `TZ` environment variable. If your time zone isn't included in the above list, you can simply copy it inside your redbean. The same is also the case for future updates to the database, which can be swapped out when needed, without having to recompile. unix.stat(path:str[, flags:int[, dirfd:int]]) ├─→ unix.Stat └─→ nil, unix.Errno Gets information about file or directory. `flags` may have any of: - `AT_SYMLINK_NOFOLLOW`: do not follow symbolic links. `dirfd` defaults to to `unix.AT_FDCWD` and may optionally be set to a directory file descriptor to which `path` is relative. unix.fstat(fd:int) ├─→ unix.Stat └─→ nil, unix.Errno Gets information about opened file descriptor. A common use for fstat() is getting the size of a file. For example: fd = assert(unix.open("hello.txt", unix.O_RDONLY)) st = assert(unix.fstat(fd)) Log(kLogInfo, 'hello.txt is %d bytes in size' % {st:size()}) unix.close(fd) unix.statfs(path:str) ├─→ unix.Statfs └─→ nil, unix.Errno Gets information about filesystem. `path` is the path of a file or directory in the mounted filesystem. unix.fstatfs(fd:int) ├─→ unix.Statfs └─→ nil, unix.Errno Gets information about filesystem. `fd` is an open() file descriptor of a file or directory in the mounted filesystem. unix.opendir(path:str) ├─→ state:unix.Dir └─→ nil, unix.Errno Opens directory for listing its contents. For example, to print a simple directory listing: Write('<ul>\r\n') for name, kind, ino, off in assert(unix.opendir(dir)) do if name ~= '.' and name ~= '..' then Write('<li>%s\r\n' % {EscapeHtml(name)}) end end Write('</ul>\r\n') unix.fdopendir(fd:int) ├─→ next:function, state:unix.Dir └─→ nil, unix.Errno Opens directory for listing its contents, via an fd. `fd` should be created by `open(path, O_RDONLY|O_DIRECTORY)`. The returned unix.Dir takes ownership of the file descriptor and will close it automatically when garbage collected. unix.isatty(fd:int) ├─→ true └─→ nil, unix.Errno Returns true if file descriptor is a teletypewriter. Otherwise nil with an Errno object holding one of the following values: - `ENOTTY` if `fd` is valid but not a teletypewriter - `EBADF` if `fd` isn't a valid file descriptor. - `EPERM` if pledge() is used without `tty` in lenient mode No other error numbers are possible. unix.tiocgwinsz(fd:int) ├─→ rows:int, cols:int └─→ nil, unix.Errno Returns cellular dimensions of pseudoteletypewriter display. unix.tmpfd() ├─→ fd:int └─→ nil, unix.Errno Returns file descriptor of open anonymous file. This creates a secure temporary file inside `$TMPDIR`. If it isn't defined, then `/tmp` is used on UNIX and GetTempPath() is used on the New Technology. This resolution of `$TMPDIR` happens once in a ctor, which is copied to the `kTmpDir` global. Once close() is called, the returned file is guaranteed to be deleted automatically. On UNIX the file is unlink()'d before this function returns. On the New Technology it happens upon close(). On the New Technology, temporary files created by this function should have better performance, because `kNtFileAttributeTemporary` asks the kernel to more aggressively cache and reduce i/o ops. unix.sched_yield() Relinquishes scheduled quantum. unix.mapshared(size:int) └─→ unix.Memory() Creates interprocess shared memory mapping. This function allocates special memory that'll be inherited across fork in a shared way. By default all memory in Redbean is "private" memory that's only viewable and editable to the process that owns it. When unix.fork() happens, memory is copied appropriately so that changes to memory made in the child process, don't clobber the memory at those same addresses in the parent process. If you don't want that to happen, and you want the memory to be shared similar to how it would be shared if you were using threads, then you can use this function to achieve just that. The memory object this function returns may be accessed using its methods, which support atomics and futexes. It's very low-level. For example, you can use it to implement scalable mutexes: mem = unix.mapshared(8000 * 8) LOCK = 0 -- pick an arbitrary word index for lock -- From Futexes Are Tricky Version 1.1 § Mutex, Take 3; -- Ulrich Drepper, Red Hat Incorporated, June 27, 2004. function Lock() local ok, old = mem:cmpxchg(LOCK, 0, 1) if not ok then if old == 1 then old = mem:xchg(LOCK, 2) end while old > 0 do mem:wait(LOCK, 2) old = mem:xchg(LOCK, 2) end end end function Unlock() old = mem:fetch_add(LOCK, -1) if old == 2 then mem:store(LOCK, 0) mem:wake(LOCK, 1) end end It's possible to accomplish the same thing as unix.mapshared() using files and unix.fcntl() advisory locks. However this goes significantly faster. For example, that's what SQLite does and we recommend using SQLite for IPC in redbean. But, if your app has thousands of forked processes fighting for a file lock you might need something lower level than file locks, to implement things like throttling. Shared memory is a good way to do that since there's nothing that's faster. The `size` parameter needs to be a multiple of 8. The returned memory is zero initialized. When allocating shared memory, you should try to get as much use out of it as possible, since the overhead of allocating a single shared mapping is 500 words of resident memory and 8000 words of virtual memory. It's because the Cosmopolitan Libc mmap() granularity is 2**16. This system call does not fail. An exception is instead thrown if sufficient memory isn't available. ──────────────────────────────────────────────────────────────────────────────── UNIX MEMORY OBJECT unix.Memory encapsulates memory that's shared across fork() and this module provides the fundamental synchronization primitives Redbean memory maps may be used in two ways: 1. as an array of bytes a.k.a. a string 2. as an array of words a.k.a. integers They're aliased, union, or overlapped views of the same memory. For example if you write a string to your memory region, you'll be able to read it back as an integer. Reads, writes, and word operations will throw an exception if a memory boundary error or overflow occurs. unix.Memory:read([offset:int[, bytes:int]]) └─→ str Reads bytes from memory region `offset` is the starting byte index from which memory is copied, which defaults to zero. If `bytes` is none or nil, then the nul-terminated string at `offset` is returned. You may specify `bytes` to safely read binary data. This operation happens atomically. Each shared mapping has a single lock which is used to synchronize reads and writes to that specific map. To make it scale, create additional maps. unix.Memory:write([offset:int,] data:str[, bytes:int]]) Writes bytes to memory region. `offset` is the starting byte index to which memory is copied, which defaults to zero. If `bytes` is none or nil, then an implicit nil-terminator will be included after your `data` so things like json can be easily serialized to shared memory. This operation happens atomically. Each shared mapping has a single lock which is used to synchronize reads and writes to that specific map. To make it scale, create additional maps. unix.Memory:load(word_index:int) └─→ int Loads word from memory region. This operation is atomic and has relaxed barrier semantics. unix.Memory:store(word_index:int, value:int) Stores word from memory region. This operation is atomic and has relaxed barrier semantics. unix.Memory:xchg(word_index:int, value:int) └─→ int Exchanges value. This sets word at `word_index` to `value` and returns the value previously held within that word. This operation is atomic and provides the same memory barrier semantics as the aligned x86 LOCK XCHG instruction. unix.Memory:cmpxchg(word_index:int, old:int, new:int) └─→ success:bool, old:int Compares and exchanges value. This inspects the word at `word_index` and if its value is the same as `old` then it'll be replaced by the value `new`, in which case true shall be returned alongside `old`. If a different value was held at word, then `false` shall be returned along with its value. This operation happens atomically and provides the same memory barrier semantics as the aligned x86 LOCK CMPXCHG instruction. unix.Memory:fetch_add(word_index:int, value:int) └─→ old:int Fetches then adds value. This method modifies the word at `word_index` to contain the sum of its value and the `value` parameter. This method then returns the value as it existed before the addition was performed. This operation is atomic and provides the same memory barrier semantics as the aligned x86 LOCK XADD instruction. unix.Memory:fetch_and(word_index:int, value:int) └─→ int Fetches and bitwise ands value. This operation happens atomically and provides the same memory barrier ordering semantics as its x86 implementation. unix.Memory:fetch_or(word_index:int, value:int) └─→ int Fetches and bitwise ors value. This operation happens atomically and provides the same memory barrier ordering semantics as its x86 implementation. unix.Memory:fetch_xor(word_index:int, value:int) └─→ int Fetches and bitwise xors value. This operation happens atomically and provides the same memory barrier ordering semantics as its x86 implementation. unix.Memory:wait(word_index:int, expect:int[, abs_deadline:int[, nanos:int]]) ├─→ 0 ├─→ nil, unix.Errno(unix.EINTR) ├─→ nil, unix.Errno(unix.EAGAIN) └─→ nil, unix.Errno(unix.ETIMEDOUT) Waits for word to have a different value. This method asks the kernel to suspend the process until either the absolute deadline expires or we're woken up by another process that calls unix.Memory:wake(). The `expect` parameter is the value you expect the word to have and this function will return if that's not the case. Please note this parameter doesn't imply the kernel will poll the value for you, and you still need to call wake() when you know the memory's changed. The default behavior is to wait until the heat death of the universe if necessary. You may alternatively specify an absolute deadline. If it's less than or equal to the value returned by clock_gettime, then this routine is non-blocking. Otherwise we'll block at most until the current time reaches the absolute deadline. Futexes are supported natively on Linux, FreeBSD, and OpenBSD. When this interface is used on other platforms this method will manually poll the memory location with exponential backoff. Doing this works well enough that we're passing the *NSYNC unit tests, but is not as low latency as having kernel supported futexes. `EINTR` if a signal is delivered while waiting on deadline. Callers should use futexes inside a loop that is able to cope with spurious wakeups. We don't actually guarantee the value at word has in fact changed when this returns. `EAGAIN` is raised if, upon entry, the word at `word_index` had a different value than what's specified at `expect`. `ETIMEDOUT` is raised when the absolute deadline expires. unix.Memory:wake(index:int[, count:int]) └─→ woken:int Wakes other processes waiting on word. This method may be used to signal or broadcast to waiters. The `count` specifies the number of processes that should be woken, which defaults to `INT_MAX`. The return value is the number of processes that were actually woken as a result of the system call. No failure conditions are defined. ──────────────────────────────────────────────────────────────────────────────── UNIX DIR OBJECT unix.Dir objects are created by opendir() or fdopendir(). The following methods are available: unix.Dir:close() ├─→ true └─→ nil, unix.Errno Closes directory stream object and associated its file descriptor. This is called automatically by the garbage collector. This may be called multiple times. unix.Dir:read() ├─→ name:str, kind:int, ino:int, off:int └─→ nil Reads entry from directory stream. Returns `nil` if there are no more entries. On error, `nil` will be returned and `errno` will be non-nil. `kind` can be any of: - `DT_REG`: file is a regular file - `DT_DIR`: file is a directory - `DT_BLK`: file is a block device - `DT_LNK`: file is a symbolic link - `DT_CHR`: file is a character device - `DT_FIFO`: file is a named pipe - `DT_SOCK`: file is a named socket - `DT_UNKNOWN` Note: This function also serves as the `__call` metamethod, so that unix.Dir objects may be used as a for loop iterator. unix.Dir:fd() ├─→ fd:int └─→ nil, unix.Errno Returns file descriptor of open directory object. Returns `EOPNOTSUPP` if using a `/zip/...` path. Returns `EOPNOTSUPP` if using Windows NT. unix.Dir:tell() ├─→ off:int └─→ nil, unix.Errno Returns current arbitrary offset into stream. unix.Dir:rewind() Resets stream back to beginning. ──────────────────────────────────────────────────────────────────────────────── UNIX RUSAGE OBJECT unix.Rusage objects are created by wait() or getrusage(). The following accessor methods are available. unix.Rusage:utime() └─→ seconds:int, nanos:int Returns amount of CPU consumed in userspace. It's always the case that `0 ≤ nanos < 1e9`. On Windows NT this is collected from GetProcessTimes(). unix.Rusage:stime() └─→ seconds:int, nanos:int Returns amount of CPU consumed in kernelspace. It's always the case that `0 ≤ 𝑥 < 1e9`. On Windows NT this is collected from GetProcessTimes(). unix.Rusage:maxrss() └─→ kilobytes:int Returns amount of physical memory used at peak consumption. On Windows NT this is collected from NtProcessMemoryCountersEx::PeakWorkingSetSize / 1024. unix.Rusage:idrss() └─→ integralkilobytes:int Returns integral private memory consumption w.r.t. scheduled ticks. If you chart memory usage over the lifetime of your process, then this would be the space filled in beneath the chart. The frequency of kernel scheduling is defined as unix.CLK_TCK. Each time a tick happens, the kernel samples your process's memory usage, by adding it to this value. You can derive the average consumption from this value by computing how many ticks are in `utime + stime`. Currently only available on FreeBSD and NetBSD. unix.Rusage:ixrss() └─→ integralkilobytes:int Returns integral shared memory consumption w.r.t. scheduled ticks. If you chart memory usage over the lifetime of your process, then this would be the space filled in beneath the chart. The frequency of kernel scheduling is defined as unix.CLK_TCK. Each time a tick happens, the kernel samples your process's memory usage, by adding it to this value. You can derive the average consumption from this value by computing how many ticks are in `utime + stime`. Currently only available on FreeBSD and NetBSD. unix.Rusage:isrss() └─→ integralkilobytes:int Returns integral stack memory consumption w.r.t. scheduled ticks. If you chart memory usage over the lifetime of your process, then this would be the space filled in beneath the chart. The frequency of kernel scheduling is defined as unix.CLK_TCK. Each time a tick happens, the kernel samples your process's memory usage, by adding it to this value. You can derive the average consumption from this value by computing how many ticks are in `utime + stime`. This is only applicable to redbean if its built with MODE=tiny, because redbean likes to allocate its own deterministic stack. Currently only available on FreeBSD and NetBSD. unix.Rusage:minflt() └─→ count:int Returns number of minor page faults. This number indicates how many times redbean was preempted by the kernel to memcpy() a 4096-byte page. This is one of the tradeoffs fork() entails. This number is usually tinier, when your binaries are tinier. Not available on Windows NT. unix.Rusage:majflt() └─→ count:int Returns number of major page faults. This number indicates how many times redbean was preempted by the kernel to perform i/o. For example, you might have used mmap() to load a large file into memory lazily. On Windows NT this is NtProcessMemoryCountersEx::PageFaultCount. unix.Rusage:nswap() └─→ count:int Returns number of swap operations. Operating systems like to reserve hard disk space to back their RAM guarantees, like using a gold standard for fiat currency. When your system is under heavy memory load, swap operations may happen while redbean is working. This number keeps track of them. Not available on Linux, Windows NT. unix.Rusage:inblock() └─→ count:int Returns number of times filesystem had to perform input. On Windows NT this is NtIoCounters::ReadOperationCount. unix.Rusage:oublock() └─→ count:int Returns number of times filesystem had to perform output. On Windows NT this is NtIoCounters::WriteOperationCount. unix.Rusage:msgsnd() └─→ count:int Returns count of ipc messages sent. Not available on Linux, Windows NT. unix.Rusage:msgrcv() └─→ count:int Returns count of ipc messages received. Not available on Linux, Windows NT. unix.Rusage:nsignals() └─→ count:int Returns number of signals received. Not available on Linux. unix.Rusage:nvcsw() └─→ count:int Returns number of voluntary context switches. This number is a good thing. It means your redbean finished its work quickly enough within a time slice that it was able to give back the remaining time to the system. unix.Rusage:nivcsw() └─→ count:int Returns number of non-consensual context switches. This number is a bad thing. It means your redbean was preempted by a higher priority process after failing to finish its work, within the allotted time slice. ──────────────────────────────────────────────────────────────────────────────── UNIX STAT OBJECT unix.Stat objects are created by stat() or fstat(). The following accessor methods are available. unix.Stat:size() └─→ bytes:int Size of file in bytes. unix.Stat:mode() └─→ mode:int Contains file type and permissions. For example, `0010644` is what you might see for a file and `0040755` is what you might see for a directory. To determine the file type: - `unix.S_ISREG(st:mode())` means regular file - `unix.S_ISDIR(st:mode())` means directory - `unix.S_ISLNK(st:mode())` means symbolic link - `unix.S_ISCHR(st:mode())` means character device - `unix.S_ISBLK(st:mode())` means block device - `unix.S_ISFIFO(st:mode())` means fifo or pipe - `unix.S_ISSOCK(st:mode())` means socket unix.Stat:uid() └─→ uid:int User ID of file owner. unix.Stat:gid() └─→ gid:int Group ID of file owner. unix.Stat:birthtim() └─→ unixts:int, nanos:int File birth time. This field should be accurate on Apple, Windows, and BSDs. On Linux this is the minimum of atim/mtim/ctim. On Windows NT nanos is only accurate to hectonanoseconds. Here's an example of how you might print a file timestamp: st = assert(unix.stat('/etc/passwd')) unixts, nanos = st:birthtim() year,mon,mday,hour,min,sec,gmtoffsec = unix.localtime(unixts) Write('%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.9d%+.2d%.2d % { year, mon, mday, hour, min, sec, nanos, gmtoffsec / (60 * 60), math.abs(gmtoffsec) % 60}) unix.Stat:mtim() └─→ unixts:int, nanos:int Last modified time. unix.Stat:atim() └─→ unixts:int, nanos:int Last access time. Please note that file systems are sometimes mounted with `noatime` out of concern for i/o performance. Linux also provides `O_NOATIME` as an option for open(). On Windows NT this is the same as birth time. unix.Stat:ctim() └─→ unixts:int, nanos:int Complicated time. Means time file status was last changed on UNIX. On Windows NT this is the same as birth time. unix.Stat:blocks() └─→ count512:int Number of 512-byte blocks used by storage medium. This provides some indication of how much physical storage a file actually consumes. For example, for small file systems, your system might report this number as being 8, which means 4096 bytes. On Windows NT, if `O_COMPRESSED` is used for a file, then this number will reflect the size *after* compression. you can use: st = assert(unix.stat("moby.txt")) print('file size is %d bytes' % {st:size()}) print('file takes up %d bytes of space' % {st:blocks() * 512}) if GetHostOs() == 'WINDOWS' and st:flags() & 0x800 then print('thanks to file system compression') end To tell if compression is used on a file. unix.Stat:blksize() └─→ bytes:int Block size that underlying device uses. This field might be of assistance in computing optimal i/o sizes. Please note this field has no relationship to blocks, as the latter is fixed at a 512 byte size. unix.Stat:ino() └─→ inode:int Inode number. This can be used to detect some other process used rename() to swap out a file underneath you, so you can do a refresh. redbean does it during each main process heartbeat for its own use cases. On Windows NT this is set to NtByHandleFileInformation::FileIndex. unix.Stat:dev() └─→ dev:int ID of device containing file. On Windows NT this is set to NtByHandleFileInformation::VolumeSerialNumber. unix.Stat:rdev() └─→ rdev:int Information about device type. This value may be set to 0 or -1 for files that aren't devices, depending on the operating system. unix.major() and unix.minor() may be used to extract the device numbers. ──────────────────────────────────────────────────────────────────────────────── UNIX STATFS OBJECT unix.Statfs objects are created by statfs() or fstatfs(). The following accessor methods are available. unix.Statfs:fstypename() └─→ str Type of filesystem. Here's some examples of likely values: - `"ext"` on Linux - `"xfs"` on RHEL7 - `"apfs"` on Apple - `"zfs"` on FreeBSD - `"ffs"` on NetBSD and OpenBSD - `"NTFS"` on Windows unix.Statfs:type() └─→ int Type of filesystem. This is a platform-specific magic number. Consider using the unix.Statfs:fstypename() method instead. On Windows, this will actually be a Knuth multiplicative hash of the name. unix.Statfs:bsize() └─→ int Optimal transfer block size. This field serves two purposes: 1. It tells you how to chunk i/o operations. For local disks, it'll likely be any value between 512 and 4096 depending on the operating system. For network filesystems it will likely be a much larger value, e.g. 512kb. 2. It can be multiplied with the fields `blocks`, `bfree`, and `bavail` to obtain a byte count. unix.Statfs:blocks() └─→ int Total data blocks in filesystem. The size of a block is measured as unix.Statfs:bsize(). unix.Statfs:bfree() └─→ int Total free blocks in filesystem. The size of a block is measured as unix.Statfs:bsize(). unix.Statfs:bavail() └─→ int Total free blocks available in filesystem to unprivileged users. The size of a block is measured as unix.Statfs:bsize(). unix.Statfs:files() └─→ int Total file nodes in filesystem. On Windows this is always the maximum integer value. unix.Statfs:ffree() └─→ int Total free file nodes in filesystem. On Windows this is always the maximum integer value. unix.Statfs:fsid() └─→ int Filesystem id. unix.Statfs:namelen() └─→ int Maximum length of filename components in bytes. unix.Statfs:flags() └─→ int Filesystem flags. The following flags are defined: - `ST_RDONLY`: Read-only filesystem (Linux/Windows/XNU/BSDs) - `ST_NOSUID`: Setuid binaries forbidden (Linux/XNU/BSDs) - `ST_NODEV`: Device files forbidden (Linux/XNU/BSDs) - `ST_NOEXEC`: Execution forbidden (Linux/XNU/BSDs) - `ST_SYNCHRONOUS`: Synchronous (Linux/XNU/BSDs) - `ST_NOATIME`: No access time (Linux/XNU/BSDs) - `ST_RELATIME`: Relative access time (Linux/NetBSD) - `ST_APPEND`: Linux-only - `ST_IMMUTABLE`: Linux-only - `ST_MANDLOCK`: Linux-only - `ST_NODIRATIME`: Linux-only - `ST_WRITE`: Linux-only unix.Statfs:owner() └─→ int User id of owner of filesystem mount. On Linux this is always 0 for root. On Windows this is always 0. ──────────────────────────────────────────────────────────────────────────────── UNIX SIGSET OBJECT The unix.Sigset class defines a mutable bitset that may currently contain 128 entries. See `unix.NSIG` to find out how many signals your operating system actually supports. unix.Sigset(sig:int, ...) └─→ unix.Sigset Constructs new signal bitset object. unix.Sigset:add(sig:int) Adds signal to bitset. unix.Sigset:remove(sig:int) Removes signal from bitset. unix.Sigset:fill() Sets all bits in signal bitset to true. unix.Sigset:clear() Sets all bits in signal bitset to false. unix.Sigset:contains(sig:int) └─→ bool Returns true if `sig` is member of signal bitset. unix.Sigset:__repr() unix.Sigset:__tostring() Returns Lua code string that recreates object. ──────────────────────────────────────────────────────────────────────────────── UNIX SIGNAL MAGNUMS unix.SIGINT Terminal CTRL-C keystroke. unix.SIGQUIT Terminal CTRL-\ keystroke. unix.SIGHUP Terminal hangup or daemon reload; auto-broadcasted to process group. unix.SIGILL Illegal instruction. unix.SIGTRAP INT3 instruction. unix.SIGABRT Process aborted. unix.SIGBUS Valid memory access that went beyond underlying end of file. unix.SIGFPE Illegal math. unix.SIGKILL Terminate with extreme prejudice. unix.SIGUSR1 Do whatever you want. unix.SIGUSR2 Do whatever you want. unix.SIGSEGV Invalid memory access. unix.SIGPIPE Write to closed file descriptor. unix.SIGALRM Sent by setitimer(). unix.SIGTERM Terminate. unix.SIGCHLD Child process exited or terminated and is now a zombie (unless this is SIG_IGN or SA_NOCLDWAIT) or child process stopped due to terminal i/o or profiling/debugging (unless you used SA_NOCLDSTOP) unix.SIGCONT Child process resumed from profiling/debugging. unix.SIGSTOP Child process stopped due to profiling/debugging. unix.SIGTSTP Terminal CTRL-Z keystroke. unix.SIGTTIN Terminal input for background process. unix.SIGTTOU Terminal output for background process. unix.SIGXCPU CPU time limit exceeded. unix.SIGXFSZ File size limit exceeded. unix.SIGVTALRM Virtual alarm clock. unix.SIGPROF Profiling timer expired. unix.SIGWINCH Terminal resized. unix.SIGPWR Not implemented in most community editions of system five. ──────────────────────────────────────────────────────────────────────────────── UNIX ERRNO OBJECT This object is returned by system calls that fail. We prefer returning an object because for many system calls, an error is part their normal operation. For example, it's often desirable to use the errno() method when performing a read() to check for EINTR. unix.Errno:errno() └─→ errno:int Returns error magic number. The error number is always different for different platforms. On UNIX systems, error numbers occupy the range [1,127] in practice. The System V ABI reserves numbers as high as 4095. On Windows NT, error numbers can go up to 65535. unix.Errno:winerr() └─→ errno:int Returns Windows error number. On UNIX systems this is always 0. On Windows NT this will normally be the same as errno(). Because Windows defines so many error codes, there's oftentimes a multimapping between its error codes and System Five. In those cases, this value reflect the GetLastError() result at the time the error occurred. unix.Errno:name() └─→ symbol:str Returns string of symbolic name of System Five error code. For example, this might return `"EINTR"`. unix.Errno:call() └─→ symbol:str Returns name of system call that failed. For example, this might return `"read"` if read() was what failed. unix.Errno:doc() └─→ symbol:str Returns English string describing System Five error code. For example, this might return `"Interrupted system call"`. unix.Errno:__tostring() └─→ str Returns verbose string describing error. Different information components are delimited by slash. For example, this might return `"EINTR/4/Interrupted system call"`. On Windows NT this will include additional information about the Windows error (including FormatMessage() output) if the WIN32 error differs from the System Five error code. ──────────────────────────────────────────────────────────────────────────────── UNIX ERROR MAGNUMS unix.EINVAL Invalid argument. Raised by [pretty much everything]. unix.ENOSYS System call not available on this platform. On Windows this is Raised by chroot, setuid, setgid, getsid, setsid. unix.ENOENT No such file or directory. Raised by access, bind, chdir, chmod, chown, chroot, clock_getres, execve, opendir, inotify_add_watch, link, mkdir, mknod, open, readlink, rename, rmdir, stat, swapon, symlink, truncate, unlink, utime, utimensat. unix.ENOTDIR Not a directory. This means that a directory component in a supplied path *existed* but wasn't a directory. For example, if you try to `open("foo/bar")` and `foo` is a regular file, then `ENOTDIR` will be returned. Raised by open, access, chdir, chroot, execve, link, mkdir, mknod, opendir, readlink, rename, rmdir, stat, symlink, truncate, unlink, utimensat, bind, chmod, chown, fcntl, futimesat, inotify_add_watch. unix.EINTR The greatest of all errnos; crucial for building real time reliable software. Raised by accept, clock_nanosleep, close, connect, dup, fcntl, flock, getrandom, nanosleep, open, pause, poll, ptrace, read, recv, select, send, sigsuspend, sigwaitinfo, truncate, wait, write. unix.EIO Raised by access, acct, chdir, chmod, chown, chroot, close, copy_file_range, execve, fallocate, fsync, ioperm, link, madvise, mbind, pciconfig_read, ptrace, read, readlink, sendfile, statfs, symlink, sync_file_range, truncate, unlink, write. unix.ENXIO No such device or address. Raised by lseek, open, prctl unix.E2BIG Argument list too long. Raised by execve, sched_setattr. unix.ENOEXEC Exec format error. Raised by execve, uselib. unix.ECHILD No child process. Raised by wait, waitpid, waitid, wait3, wait4. unix.ESRCH No such process. Raised by getpriority, getrlimit, getsid, ioprio_set, kill, setpgid, tkill, utimensat. unix.EBADF Bad file descriptor; cf. EBADFD. Raised by accept, access, bind, chdir, chmod, chown, close, connect, copy_file_range, dup, fcntl, flock, fsync, futimesat, opendir, getpeername, getsockname, getsockopt, ioctl, link, listen, lseek, mkdir, mknod, mmap, open, prctl, read, readahead, readlink, recv, rename, select, send, shutdown, splice, stat, symlink, sync, sync_file_range, timerfd_create, truncate, unlink, utimensat, write. unix.EAGAIN Resource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many processes, too much memory locked, read or write with O_NONBLOCK needs polling, etc.). Raised by accept, connect, fcntl, fork, getrandom, mincore, mlock, mmap, mremap, poll, read, select, send, setresuid, setreuid, setuid, sigwaitinfo, splice, tee, timer_create, timerfd_create, tkill, write, unix.EPIPE Broken pipe. Returned by write, send. This happens when you try to write data to a subprocess via a pipe but the reader end has already closed, possibly because the process died. Normally i/o routines only return this if `SIGPIPE` doesn't kill the process. Unlike default UNIX programs, redbean currently ignores `SIGPIPE` by default, so this error code is a distinct possibility when pipes or sockets are being used. unix.ENAMETOOLONG Filename too long. Cosmopolitan Libc currently defines `PATH_MAX` as 1024 characters. On UNIX that limit should only apply to system call wrappers like realpath. On Windows NT it's observed by all system calls that accept a pathname. Raised by access, bind, chdir, chmod, chown, chroot, execve, gethostname, link, mkdir, mknod, open, readlink, rename, rmdir, stat, symlink, truncate, unlink, utimensat. unix.EACCES Permission denied. Raised by access, bind, chdir, chmod, chown, chroot, clock_getres, connect, execve, fcntl, getpriority, link, mkdir, mknod, mmap, mprotect, msgctl, open, prctl, ptrace, readlink, rename, rmdir, semget, send, setpgid, socket, stat, symlink, truncate, unlink, uselib, utime, utimensat. unix.ENOMEM We require more vespene gas. Raised by access, bind, chdir, chmod, chown, chroot, clone, copy_file_range, execve, fanotify_init, fork, getgroups, getrlimit, link, mbind, mincore, mkdir, mknod, mlock, mmap, mprotect, mremap, msync, open, poll, readlink, recv, rename, rmdir, select, send, sigaltstack, splice, stat, subpage_prot, swapon, symlink, sync_file_range, tee, timer_create, timerfd_create, unlink. unix.EPERM Operation not permitted. Raised by accept, chmod, chown, chroot, copy_file_range, execve, fallocate, fanotify_init, fcntl, futex, get_robust_list, getdomainname, getgroups, gethostname, getpriority, getrlimit, getsid, gettimeofday, idle, init_module, io_submit, ioctl_console, ioctl_ficlonerange, ioctl_fideduperange, ioperm, iopl, ioprio_set, keyctl, kill, link, lookup_dcookie, madvise, mbind, membarrier, migrate_pages, mkdir, mknod, mlock, mmap, mount, move_pages, msgctl, nice, open, open_by_handle_at, pciconfig_read, perf_event_open, pidfd_getfd, pidfd_send_signal, pivot_root, prctl, process_vm_readv, ptrace, quotactl, reboot, rename, request_key, rmdir, rt_sigqueueinfo, sched_setaffinity, sched_setattr, sched_setparam, sched_setscheduler, seteuid, setfsgid, setfsuid, setgid, setns, setpgid, setresuid, setreuid, setsid, setuid, setup, setxattr, sigaltstack, spu_create, stime, swapon, symlink, syslog, truncate, unlink, utime, utimensat, write. unix.ENOTBLK Block device required. Raised by umount. unix.EBUSY Device or resource busy. Raised by dup, fcntl, msync, prctl, ptrace, rename, rmdir. unix.EEXIST File exists. Raised by link, mkdir, mknod, mmap, open, rename, rmdir, symlink unix.EXDEV Improper link. Raised by copy_file_range, link, rename. unix.ENODEV No such device. Raised by arch_prctl, mmap, open, prctl, timerfd_create. unix.EISDIR Is a directory. Raised by copy_file_range, execve, open, read, rename, truncate, unlink. unix.ENFILE Too many open files in system. Raised by accept, execve, mmap, open, pipe, socket, socketpair, swapon, timerfd_create, uselib, userfaultfd. unix.EMFILE Too many open files. Raised by accept, dup, execve, fcntl, open, pipe, socket, socketpair, timerfd_create. unix.ENOTTY Inappropriate i/o control operation. Raised by ioctl. unix.ETXTBSY Won't open executable that's executing in write mode. Raised by access, copy_file_range, execve, mmap, open, truncate. unix.EFBIG File too large. Raised by copy_file_range, open, truncate, write. unix.ENOSPC No space left on device. Raised by copy_file_range, fsync, link, mkdir, mknod, open, rename, symlink, sync_file_range, write. unix.EDQUOT Disk quota exceeded. Raised by link, mkdir, mknod, open, rename, symlink, write. unix.ESPIPE Invalid seek. Raised by lseek, splice, sync_file_range. unix.EROFS Read-only filesystem. Raised by access, bind, chmod, chown, link, mkdir, mknod, open, rename, rmdir, symlink, truncate, unlink, utime, utimensat. unix.EMLINK Too many links; raised by link, mkdir, rename. unix.ERANGE Result too large. Raised by prctl. unix.EDEADLK Resource deadlock avoided. Raised by fcntl. unix.ENOLCK No locks available. Raised by fcntl, flock. unix.ENOTEMPTY Directory not empty. Raised by rmdir. unix.ELOOP Too many levels of symbolic links. Raised by access, bind, chdir, chmod, chown, chroot, execve, link, mkdir, mknod, open, readlink, rename, rmdir, stat, symlink, truncate, unlink, utimensat. unix.ENOMSG Raised by msgop. unix.EIDRM Identifier removed. Raised by msgctl. unix.ETIME Timer expired; timer expired. Raised by connect. unix.EPROTO Raised by accept, connect, socket, socketpair. unix.EOVERFLOW Raised by copy_file_range, fanotify_init, lseek, mmap, open, stat, statfs unix.ENOTSOCK Not a socket. Raised by accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, send, shutdown. unix.EDESTADDRREQ Destination address required. Raised by send, write. unix.EMSGSIZE Message too long. Raised by send. unix.EPROTOTYPE Protocol wrong type for socket. Raised by connect. unix.ENOPROTOOPT Protocol not available. Raised by getsockopt, accept. unix.EPROTONOSUPPORT Protocol not supported. Raised by socket, socketpair. unix.ESOCKTNOSUPPORT Socket type not supported. unix.ENOTSUP Operation not supported. Raised by chmod, clock_getres, clock_nanosleep, timer_create. unix.EOPNOTSUPP Socket operation not supported. Raised by accept, listen, mmap, prctl, readv, send, socketpair. unix.EPFNOSUPPORT Protocol family not supported. unix.EAFNOSUPPORT Address family not supported. Raised by connect, socket, socketpair unix.EADDRINUSE Address already in use. Raised by bind, connect, listen unix.EADDRNOTAVAIL Address not available. Raised by bind, connect. unix.ENETDOWN Network is down. Raised by accept unix.ENETUNREACH Host is unreachable. Raised by accept, connect unix.ENETRESET Connection reset by network. unix.ECONNABORTED Connection reset before accept. Raised by accept. unix.ECONNRESET Connection reset by client. Raised by send. unix.ENOBUFS No buffer space available; raised by getpeername, getsockname, send. unix.EISCONN Socket is connected. Raised by connect, send. unix.ENOTCONN Socket is not connected. Raised by getpeername, recv, send, shutdown. unix.ESHUTDOWN Cannot send after transport endpoint shutdown; note that shutdown write is an `EPIPE`. unix.ETOOMANYREFS Too many references: cannot splice. Raised by sendmsg. unix.ETIMEDOUT Connection timed out. Raised by connect. unix.ECONNREFUSED System-imposed limit on the number of threads was encountered. Raised by connect, listen, recv. unix.EHOSTDOWN Host is down. Raised by accept. unix.EHOSTUNREACH Host is unreachable. Raised by accept. unix.EALREADY Connection already in progress. Raised by connect, send. unix.ENODATA No message is available in xsi stream or named pipe is being closed; no data available; barely in posix; returned by ioctl; very close in spirit to EPIPE? ──────────────────────────────────────────────────────────────────────────────── UNIX MISCELLANEOUS MAGNUMS unix.ARG_MAX Returns maximum length of arguments for new processes. This is the character limit when calling execve(). It's the sum of the lengths of `argv` and `envp` including any nul terminators and pointer arrays. For example to see how much your shell `envp` uses $ echo $(($(env | wc -c) + 1 + ($(env | wc -l) + 1) * 8)) 758 POSIX mandates this be 4096 or higher. On Linux this it's 128*1024. On Windows NT it's 32767*2 because CreateProcess lpCommandLine and environment block are separately constrained to 32,767 characters. Most other systems define this limit much higher. unix.BUFSIZ Returns default buffer size. The UNIX module does not perform any buffering between calls. Each time a read or write is performed via the UNIX API your redbean will allocate a buffer of this size by default. This current default would be 4096 across platforms. unix.CLK_TCK Returns the scheduler frequency. This is granularity at which the kernel does work. For example, the Linux kernel normally operates at 100hz so its CLK_TCK will be 100. This value is useful for making sense out of unix.Rusage data. unix.PIPE_BUF Returns maximum size at which pipe i/o is guaranteed atomic. POSIX requires this be at least 512. Linux is more generous and allows 4096. On Windows NT this is currently 4096, and it's the parameter redbean passes to CreateNamedPipe(). unix.PATH_MAX Returns maximum length of file path. This applies to a complete path being passed to system calls. POSIX.1 XSI requires this be at least 1024 so that's what most platforms support. On Windows NT, the limit is technically 260 characters. Your redbean works around that by prefixing `//?/` to your paths as needed. On Linux this limit will be 4096, but that won't be the case for functions such as realpath that are implemented at the C library level; however such functions are the exception rather than the norm, and report enametoolong(), when exceeding the libc limit. unix.NAME_MAX Returns maximum length of file path component. POSIX requires this be at least 14. Most operating systems define it as 255. It's a good idea to not exceed 253 since that's the limit on DNS labels. unix.NSIG Returns maximum number of signals supported by underlying system. The limit for unix.Sigset is 128 to support FreeBSD, but most operating systems define this much lower, like 32. This constant reflects the value chosen by the underlying operating system. ──────────────────────────────────────────────────────────────────────────────── LEGAL redbean contains software licensed ISC, MIT, BSD-2, BSD-3, zlib which makes it a permissively licensed gift to anyone who might find it useful. The transitive closure of legalese can be found inside the binary structure, because notice licenses require we distribute the license along with any software that uses it. By putting them in the binary, compliance in automated and no need for further action on the part of the user who is distributing. ──────────────────────────────────────────────────────────────────────────────── SEE ALSO https://redbean.dev/ https://news.ycombinator.com/item?id=26271117
232,280
6,145
jart/cosmopolitan
false
cosmopolitan/tool/net/redbean-unsecure.c
#define UNSECURE #define REDBEAN "redbean-unsecure" #include "tool/net/redbean.c"
82
4
jart/cosmopolitan
false
cosmopolitan/tool/net/luacheck.h
#ifndef COSMOPOLITAN_TOOL_NET_LUACHECK_H_ #define COSMOPOLITAN_TOOL_NET_LUACHECK_H_ #include "libc/log/log.h" #include "libc/mem/mem.h" #include "third_party/lua/cosmo.h" #include "third_party/lua/lua.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define AssertLuaStackIsAt(L, level) \ do { \ if (lua_gettop(L) > level) { \ char *s = LuaFormatStack(L); \ WARNF("lua stack should be at %d;" \ " extra values ignored:\n%s", \ level, s); \ free(s); \ } \ } while (0) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_NET_LUACHECK_H_ */
790
24
jart/cosmopolitan
false
cosmopolitan/tool/net/sandbox.h
#ifndef COSMOPOLITAN_TOOL_NET_SANDBOX_H_ #define COSMOPOLITAN_TOOL_NET_SANDBOX_H_ #include "libc/calls/struct/bpf.h" #include "libc/calls/struct/filter.h" #include "libc/calls/struct/seccomp.h" #include "libc/sysv/consts/audit.h" // clang-format off #define _SECCOMP_MACHINE(MAGNUM) \ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), \ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MAGNUM, 1, 0), \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS) #define _SECCOMP_LOAD_SYSCALL_NR() \ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)) #define _SECCOMP_ALLOW_SYSCALL(MAGNUM) \ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MAGNUM, 0, 1), \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW) #define _SECCOMP_TRAP_SYSCALL(MAGNUM, DATA) \ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MAGNUM, 0, 1), \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRAP | ((DATA) & SECCOMP_RET_DATA)) #define _SECCOMP_TRACE_SYSCALL(MAGNUM, DATA) \ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, MAGNUM, 0, 1), \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE | ((DATA) & SECCOMP_RET_DATA)) #define _SECCOMP_LOG_AND_RETURN_ERRNO(MAGNUM) \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ((MAGNUM) & SECCOMP_RET_DATA)) #define _SECCOMP_LOG_AND_KILL_PROCESS() \ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | SECCOMP_RET_KILL_PROCESS) #endif /* COSMOPOLITAN_TOOL_NET_SANDBOX_H_ */
1,728
36
jart/cosmopolitan
false
cosmopolitan/tool/net/lfinger.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/finger/finger.h" #include "third_party/lua/lauxlib.h" // finger.DescribeSyn(syn_packet_bytes:str) // ├─→ description:str // └─→ nil, error:str static int LuaDescribeSyn(lua_State *L) { char *q, *r; size_t n, m; const char *p; luaL_Buffer b; if (!lua_isnoneornil(L, 1)) { p = luaL_checklstring(L, 1, &n); m = 128; q = luaL_buffinitsize(L, &b, m); if ((r = DescribeSyn(q, m, p, n))) { luaL_pushresultsize(&b, r - q); return 1; } else { lua_pushnil(L); lua_pushstring(L, "bad syn packet"); return 2; } } else { return lua_gettop(L); } } // finger.FingerSyn(syn_packet_bytes:str) // ├─→ synfinger:uint32 // └─→ nil, error:str static int LuaFingerSyn(lua_State *L) { size_t n; uint32_t x; const char *p; if (!lua_isnoneornil(L, 1)) { p = luaL_checklstring(L, 1, &n); if ((x = FingerSyn(p, n))) { lua_pushinteger(L, x); return 1; } else { lua_pushnil(L); lua_pushstring(L, "bad syn packet"); return 2; } } else { return lua_gettop(L); } } // finger.GetSynFingerOs(synfinger:uint32) // ├─→ osname:str // └─→ nil, error:str static int LuaGetSynFingerOs(lua_State *L) { int os; if (!lua_isnoneornil(L, 1)) { if ((os = GetSynFingerOs(luaL_checkinteger(L, 1)))) { lua_pushstring(L, GetOsName(os)); return 1; } else { lua_pushnil(L); lua_pushstring(L, "unknown syn os fingerprint"); return 2; } } else { return lua_gettop(L); } } static const luaL_Reg kLuaFinger[] = { {"DescribeSyn", LuaDescribeSyn}, // {"FingerSyn", LuaFingerSyn}, // {"GetSynFingerOs", LuaGetSynFingerOs}, // {0}, // }; int LuaFinger(lua_State *L) { luaL_newlib(L, kLuaFinger); return 1; }
3,725
99
jart/cosmopolitan
false
cosmopolitan/tool/net/echo.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/calls/calls.h" #include "libc/fmt/conv.h" #include "libc/intrin/kprintf.h" #include "libc/log/check.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/sockaddr.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sock.h" #include "net/http/http.h" #include "net/http/ip.h" /** * @fileoverview tcp/udp echo servers/clients * use it to fill your network with junk data */ int sock; char buf[1000]; struct sockaddr_in addr = {0}; uint32_t addrsize = sizeof(struct sockaddr_in); void PrintUsage(char **argv) { kprintf("usage: %s udp server [ip port]%n", argv[0]); kprintf(" %s tcp server [ip port]%n", argv[0]); kprintf(" %s udp client [ip port]%n", argv[0]); kprintf(" %s tcp client [ip port]%n", argv[0]); exit(1); } void UdpServer(void) { int ip; ssize_t rc; struct sockaddr_in addr2; uint32_t addrsize2 = sizeof(struct sockaddr_in); CHECK_NE(-1, (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))); CHECK_NE(-1, bind(sock, (struct sockaddr *)&addr, addrsize)); CHECK_NE(-1, getsockname(sock, (struct sockaddr *)&addr2, &addrsize2)); ip = ntohl(addr2.sin_addr.s_addr); kprintf("udp server %hhu.%hhu.%hhu.%hhu %hu%n", ip >> 24, ip >> 16, ip >> 8, ip, ntohs(addr2.sin_port)); for (;;) { CHECK_NE(-1, (rc = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&addr2, &addrsize2))); CHECK_NE(-1, sendto(sock, buf, rc, 0, (struct sockaddr *)&addr2, addrsize2)); } } void UdpClient(void) { CHECK_NE(-1, (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))); CHECK_NE(-1, connect(sock, (struct sockaddr *)&addr, addrsize)); for (;;) { rngset(buf, sizeof(buf), _rand64, -1); CHECK_NE(-1, write(sock, &addr, addrsize)); } } void TcpServer(void) { ssize_t rc; int ip, client; struct sockaddr_in addr2; uint32_t addrsize2 = sizeof(struct sockaddr_in); CHECK_NE(-1, (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))); CHECK_NE(-1, bind(sock, (struct sockaddr *)&addr, addrsize)); CHECK_NE(-1, listen(sock, 10)); CHECK_NE(-1, getsockname(sock, (struct sockaddr *)&addr2, &addrsize2)); ip = ntohl(addr2.sin_addr.s_addr); kprintf("tcp server %hhu.%hhu.%hhu.%hhu %hu%n", ip >> 24, ip >> 16, ip >> 8, ip, ntohs(addr2.sin_port)); for (;;) { addrsize2 = sizeof(struct sockaddr_in); CHECK_NE(-1, (client = accept(sock, (struct sockaddr *)&addr2, &addrsize2))); ip = ntohl(addr2.sin_addr.s_addr); kprintf("got client %hhu.%hhu.%hhu.%hhu %hu%n", ip >> 24, ip >> 16, ip >> 8, ip, ntohs(addr2.sin_port)); for (;;) { CHECK_NE(-1, (rc = read(client, buf, sizeof(buf)))); if (!rc) break; CHECK_NE(-1, write(client, buf, rc)); } } } void TcpClient(void) { CHECK_NE(-1, (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))); CHECK_NE(-1, connect(sock, (struct sockaddr *)&addr, addrsize)); for (;;) { rngset(buf, sizeof(buf), _rand64, -1); CHECK_NE(-1, write(sock, buf, sizeof(buf))); CHECK_NE(-1, read(sock, buf, sizeof(buf))); } } int main(int argc, char *argv[]) { int port = 0; int64_t ip = 0; if (argc < 3) PrintUsage(argv); if (argc >= 4) { if ((ip = ParseIp(argv[3], -1)) == -1) { PrintUsage(argv); } } if (argc >= 5) { port = atoi(argv[4]); if (port & 0xffff0000) { PrintUsage(argv); } } addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(ip); if (!strcmp(argv[1], "udp")) { if (!strcmp(argv[2], "server")) { UdpServer(); } else if (!strcmp(argv[2], "client")) { UdpClient(); } else { PrintUsage(argv); } } else if (!strcmp(argv[1], "tcp")) { if (!strcmp(argv[2], "server")) { TcpServer(); } else if (!strcmp(argv[2], "client")) { TcpClient(); } else { PrintUsage(argv); } } else { PrintUsage(argv); } return 0; }
5,914
156
jart/cosmopolitan
false
cosmopolitan/tool/net/counters.inc
C(accepterrors) C(acceptflakes) C(acceptinterrupts) C(acceptresets) C(accepts) C(badlengths) C(badmessages) C(badmethods) C(badranges) C(bans) C(closeerrors) C(compressedresponses) C(connectionshandled) C(connectsrefused) C(continues) C(decompressedresponses) C(deflates) C(dropped) C(dynamicrequests) C(emfiles) C(enetdowns) C(enfiles) C(enobufs) C(enomems) C(enonets) C(errors) C(expectsrefused) C(failedchildren) C(forbiddens) C(forkerrors) C(frags) C(fumbles) C(handshakeinterrupts) C(http09) C(http10) C(http11) C(http12) C(hugepayloads) C(identityresponses) C(ignores) C(inflates) C(listingrequests) C(loops) C(mapfails) C(maps) C(meltdowns) C(messageshandled) C(missinglengths) C(notfounds) C(notmodifieds) C(openfails) C(partialresponses) C(payloaddisconnects) C(pipelinedrequests) C(pollinterrupts) C(precompressedresponses) C(readerrors) C(readinterrupts) C(readresets) C(readtimeouts) C(redirects) C(reindexes) C(rejects) C(reloads) C(rewrites) C(serveroptions) C(shutdowns) C(slowloris) C(slurps) C(sslcantciphers) C(sslhandshakefails) C(sslhandshakes) C(sslnociphers) C(sslnoclientcert) C(sslnoversion) C(sslshakemacs) C(ssltimeouts) C(sslunknownca) C(sslunknowncert) C(sslupgrades) C(sslverifyfailed) C(stackuse) C(statfails) C(staticrequests) C(stats) C(statuszrequests) C(synchronizationfailures) C(terminatedchildren) C(thiscorruption) C(transfersrefused) C(urisrefused) C(verifies) C(writeerrors) C(writeinterruputs) C(writeresets) C(writetimeouts)
1,467
97
jart/cosmopolitan
false
cosmopolitan/tool/net/wb.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/calls/calls.h" #include "libc/dns/dns.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/sock/goodsocket.internal.h" #include "libc/sock/sock.h" #include "libc/stdio/append.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/slice.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "libc/sysv/consts/tcp.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "libc/x/xsigaction.h" #include "net/http/http.h" #include "net/http/url.h" #include "net/https/https.h" #include "third_party/getopt/getopt.h" #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/error.h" #include "third_party/mbedtls/net_sockets.h" #include "third_party/mbedtls/ssl.h" #define OPTS "BIqksvzX:H:C:m:" #define Micros(t) ((int64_t)((t)*1e6)) #define HasHeader(H) (!!msg.headers[H].a) #define HeaderData(H) (inbuf.p + msg.headers[H].a) #define HeaderLength(H) (msg.headers[H].b - msg.headers[H].a) #define HeaderEqualCase(H, S) \ SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H)) struct Buffer { size_t n, c; char *p; }; struct Headers { size_t n; char **p; } headers; bool suiteb; char *request; bool isdone; char *urlarg; int method = kHttpGet; bool authmode = MBEDTLS_SSL_VERIFY_NONE; char *host; char *port; char *flags; bool usessl; uint32_t ip; struct Url url; struct addrinfo *addr; struct Buffer inbuf; long error_count; long failure_count; long message_count; long connect_count; double *latencies; size_t latencies_n; size_t latencies_c; long double start_run; long double end_run; long double start_fetch; long double end_fetch; long connectionstobemade = 100; long messagesperconnection = 100; mbedtls_x509_crt *cachain; mbedtls_ssl_config conf; mbedtls_ssl_context ssl; mbedtls_ctr_drbg_context drbg; struct addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_STREAM, .ai_protocol = IPPROTO_TCP, .ai_flags = AI_NUMERICSERV}; void OnInt(int sig) { isdone = true; } static int TlsSend(void *c, const unsigned char *p, size_t n) { int rc; if ((rc = write(*(int *)c, p, n)) == -1) { if (errno == EINTR) { return MBEDTLS_ERR_SSL_WANT_WRITE; } else if (errno == EAGAIN) { return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { VERBOSEF("tls write() error %s", strerror(errno)); return MBEDTLS_ERR_NET_RECV_FAILED; } } return rc; } static int TlsRecv(void *c, unsigned char *p, size_t n, uint32_t o) { int r; if ((r = read(*(int *)c, p, n)) == -1) { if (errno == EINTR) { return MBEDTLS_ERR_SSL_WANT_READ; } else if (errno == EAGAIN) { return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { VERBOSEF("tls read() error %s", strerror(errno)); return MBEDTLS_ERR_NET_RECV_FAILED; } } return r; } static wontreturn void PrintUsage(FILE *f, int rc) { fprintf(f, "usage: %s [-%s] URL\n", OPTS, program_invocation_name); fprintf(f, "wb - cosmopolitan http/https benchmark tool\n"); fprintf(f, " -C INT connections to be made\n"); fprintf(f, " -m INT messages per connection\n"); fprintf(f, " -B use suite b ciphersuites\n"); fprintf(f, " -v increase verbosity\n"); fprintf(f, " -H K:V append http header\n"); fprintf(f, " -X NAME specify http method\n"); fprintf(f, " -k verify ssl certs\n"); fprintf(f, " -I same as -X HEAD\n"); fprintf(f, " -z same as -H Accept-Encoding:gzip\n"); fprintf(f, " -h show this help\n"); exit(rc); } int fetch(void) { char *p; int status; ssize_t rc; const char *body; int t, ret, sock; struct TlsBio *bio; long messagesremaining; struct HttpMessage msg; struct HttpUnchunker u; size_t urlarglen, requestlen; size_t g, i, n, hdrsize, paylen; messagesremaining = messagesperconnection; /* * Setup crypto. */ if (usessl) { -mbedtls_ssl_session_reset(&ssl); CHECK_EQ(0, mbedtls_ssl_set_hostname(&ssl, host)); } /* * Connect to server. */ InitHttpMessage(&msg, kHttpResponse); ip = ntohl(((struct sockaddr_in *)addr->ai_addr)->sin_addr.s_addr); CHECK_NE(-1, (sock = GoodSocket(addr->ai_family, addr->ai_socktype, addr->ai_protocol, false, 0))); if (connect(sock, addr->ai_addr, addr->ai_addrlen) == -1) { goto TransportError; } if (usessl) { mbedtls_ssl_set_bio(&ssl, &sock, TlsSend, 0, TlsRecv); if ((ret = mbedtls_ssl_handshake(&ssl))) { goto TransportError; } } SendAnother: /* * Send HTTP Message. */ n = appendz(request).i; if (usessl) { ret = mbedtls_ssl_write(&ssl, request, n); if (ret != n) goto TransportError; } else if (write(sock, request, n) != n) { goto TransportError; } /* * Handle response. */ InitHttpMessage(&msg, kHttpResponse); for (hdrsize = paylen = t = 0;;) { if (inbuf.n == inbuf.c) { inbuf.c += 1000; inbuf.c += inbuf.c >> 1; inbuf.p = realloc(inbuf.p, inbuf.c); } if (usessl) { if ((rc = mbedtls_ssl_read(&ssl, inbuf.p + inbuf.n, inbuf.c - inbuf.n)) < 0) { if (rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { rc = 0; } else { goto TransportError; } } } else if ((rc = read(sock, inbuf.p + inbuf.n, inbuf.c - inbuf.n)) == -1) { goto TransportError; } g = rc; inbuf.n += g; switch (t) { case kHttpClientStateHeaders: if (!g) goto TransportError; rc = ParseHttpMessage(&msg, inbuf.p, inbuf.n); if (rc == -1) goto TransportError; if (rc) { hdrsize = rc; if (100 <= msg.status && msg.status <= 199) { if ((HasHeader(kHttpContentLength) && !HeaderEqualCase(kHttpContentLength, "0")) || (HasHeader(kHttpTransferEncoding) && !HeaderEqualCase(kHttpTransferEncoding, "identity"))) { goto TransportError; } DestroyHttpMessage(&msg); InitHttpMessage(&msg, kHttpResponse); memmove(inbuf.p, inbuf.p + hdrsize, inbuf.n - hdrsize); inbuf.n -= hdrsize; break; } if (msg.status == 204 || msg.status == 304) { goto Finished; } if (HasHeader(kHttpTransferEncoding) && !HeaderEqualCase(kHttpTransferEncoding, "identity")) { if (HeaderEqualCase(kHttpTransferEncoding, "chunked")) { t = kHttpClientStateBodyChunked; bzero(&u, sizeof(u)); goto Chunked; } else { goto TransportError; } } else if (HasHeader(kHttpContentLength)) { rc = ParseContentLength(HeaderData(kHttpContentLength), HeaderLength(kHttpContentLength)); if (rc == -1) goto TransportError; if ((paylen = rc) <= inbuf.n - hdrsize) { goto Finished; } else { t = kHttpClientStateBodyLengthed; } } else { t = kHttpClientStateBody; } } break; case kHttpClientStateBody: if (!g) { paylen = inbuf.n; goto Finished; } break; case kHttpClientStateBodyLengthed: if (!g) goto TransportError; if (inbuf.n - hdrsize >= paylen) goto Finished; break; case kHttpClientStateBodyChunked: Chunked: rc = Unchunk(&u, inbuf.p + hdrsize, inbuf.n - hdrsize, &paylen); if (rc == -1) goto TransportError; if (rc) goto Finished; break; default: unreachable; } } Finished: status = msg.status; DestroyHttpMessage(&msg); if (!isdone && status == 200 && --messagesremaining > 0) { long double now = nowl(); end_fetch = now; ++message_count; latencies = realloc(latencies, ++latencies_n * sizeof(*latencies)); latencies[latencies_n - 1] = end_fetch - start_fetch; start_fetch = now; goto SendAnother; } close(sock); return status; TransportError: close(sock); DestroyHttpMessage(&msg); return 900; } int main(int argc, char *argv[]) { xsigaction(SIGPIPE, SIG_IGN, 0, 0, 0); xsigaction(SIGINT, OnInt, 0, 0, 0); /* * Read flags. */ int opt; __log_level = kLogWarn; while ((opt = getopt(argc, argv, OPTS)) != -1) { switch (opt) { case 's': case 'q': break; case 'B': suiteb = true; appendf(&flags, " -B"); break; case 'v': ++__log_level; break; case 'I': method = kHttpHead; appendf(&flags, " -I"); break; case 'H': headers.p = realloc(headers.p, ++headers.n * sizeof(*headers.p)); headers.p[headers.n - 1] = optarg; appendf(&flags, " -H '%s'", optarg); break; case 'z': headers.p = realloc(headers.p, ++headers.n * sizeof(*headers.p)); headers.p[headers.n - 1] = "Accept-Encoding: gzip"; appendf(&flags, " -z"); break; case 'X': CHECK((method = GetHttpMethod(optarg, strlen(optarg)))); appendf(&flags, " -X %s", optarg); break; case 'k': authmode = MBEDTLS_SSL_VERIFY_REQUIRED; appendf(&flags, " -k"); break; case 'm': messagesperconnection = strtol(optarg, 0, 0); break; case 'C': connectionstobemade = strtol(optarg, 0, 0); break; case 'h': PrintUsage(stdout, EXIT_SUCCESS); default: PrintUsage(stderr, EX_USAGE); } } appendf(&flags, " -m %ld", messagesperconnection); appendf(&flags, " -C %ld", connectionstobemade); if (optind == argc) PrintUsage(stdout, EXIT_SUCCESS); urlarg = argv[optind]; cachain = GetSslRoots(); long connectsremaining = connectionstobemade; /* * Parse URL. */ _gc(ParseUrl(urlarg, -1, &url, kUrlPlus)); _gc(url.params.p); usessl = false; if (url.scheme.n) { if (url.scheme.n == 5 && !memcasecmp(url.scheme.p, "https", 5)) { usessl = true; } else if (!(url.scheme.n == 4 && !memcasecmp(url.scheme.p, "http", 4))) { FATALF("bad scheme"); } } if (url.host.n) { host = _gc(strndup(url.host.p, url.host.n)); if (url.port.n) { port = _gc(strndup(url.port.p, url.port.n)); } else { port = usessl ? "443" : "80"; } } else { host = "127.0.0.1"; port = "80"; } CHECK(IsAcceptableHost(host, -1)); url.fragment.p = 0, url.fragment.n = 0; url.scheme.p = 0, url.scheme.n = 0; url.user.p = 0, url.user.n = 0; url.pass.p = 0, url.pass.n = 0; url.host.p = 0, url.host.n = 0; url.port.p = 0, url.port.n = 0; if (!url.path.n || url.path.p[0] != '/') { char *p = _gc(xmalloc(1 + url.path.n)); mempcpy(mempcpy(p, "/", 1), url.path.p, url.path.n); url.path.p = p; ++url.path.n; } /* * Create HTTP message. */ appendf(&request, "%s %s HTTP/1.1\r\n" "Host: %s:%s\r\n", kHttpMethod[method], _gc(EncodeUrl(&url, 0)), host, port); for (int i = 0; i < headers.n; ++i) { appendf(&request, "%s\r\n", headers.p[i]); } appendf(&request, "\r\n"); /* * Perform DNS lookup. */ int rc; if ((rc = getaddrinfo(host, port, &hints, &addr)) != EAI_SUCCESS) { FATALF("getaddrinfo(%s:%s) failed", host, port); } /* * Setup SSL crypto. */ mbedtls_ssl_init(&ssl); mbedtls_ctr_drbg_init(&drbg); mbedtls_ssl_config_init(&conf); CHECK_EQ(0, mbedtls_ctr_drbg_seed(&drbg, GetEntropy, 0, "justine", 7)); CHECK_EQ(0, mbedtls_ssl_config_defaults( &conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, suiteb ? MBEDTLS_SSL_PRESET_SUITEB : MBEDTLS_SSL_PRESET_SUITEC)); mbedtls_ssl_conf_authmode(&conf, authmode); mbedtls_ssl_conf_ca_chain(&conf, cachain, 0); mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &drbg); CHECK_EQ(0, mbedtls_ssl_setup(&ssl, &conf)); int status; latencies_c = 1024; latencies = malloc(latencies_c * sizeof(*latencies)); start_run = nowl(); while (!isdone && --connectsremaining >= 0) { start_fetch = nowl(); status = fetch(); end_fetch = nowl(); if (status == 200) { ++connect_count; ++message_count; latencies = realloc(latencies, ++latencies_n * sizeof(*latencies)); latencies[latencies_n - 1] = end_fetch - start_fetch; } else if (status == 900) { ++failure_count; } else { ++error_count; } } end_run = nowl(); double latencies_sum = fsum(latencies, latencies_n); double avg_latency = latencies_sum / message_count; printf("wb%s\n", flags); printf("msgs / second: %,ld qps\n", (int64_t)(message_count / (end_run - start_run))); printf("run time: %,ldµs\n", Micros(end_run - start_run)); printf("latency / msgs: %,ldµs\n", Micros(avg_latency)); printf("message count: %,ld\n", message_count); printf("connect count: %,ld\n", connect_count); printf("error count: %,ld (non-200 responses)\n", error_count); printf("failure count: %,ld (transport error)\n", failure_count); return 0; }
15,827
511
jart/cosmopolitan
false
cosmopolitan/tool/net/.init.lua
-- special script called by main redbean process at startup HidePath('/usr/share/zoneinfo/') HidePath('/usr/share/ssl/')
121
4
jart/cosmopolitan
false
cosmopolitan/tool/net/definitions.lua
---@meta error("Tried to evaluate definition file.") --Documents redbean 2.2, lsqlite3 0.9.5 --[[ SYNOPSIS redbean.com [-?BVabdfghjkmsuvz] [-p PORT] [-D DIR] [-- SCRIPTARGS...] DESCRIPTION redbean - single-file distributable web server OVERVIEW redbean makes it possible to share web applications that run offline as a single-file Actually Portable Executable PKZIP archive which contains your assets. All you need to do is download the redbean.com program below, change the filename to .zip, add your content in a zip editing tool, and then change the extension back to .com. redbean can serve 1 million+ gzip encoded responses per second on a cheap personal computer. That performance is thanks to zip and gzip using the same compression format, which enables kernelspace copies. Another reason redbean goes fast is that it's a tiny static binary, which makes fork memory paging nearly free. redbean is also easy to modify to suit your own needs. The program itself is written as a single .c file. It embeds the Lua programming language and SQLite which let you write dynamic pages. FEATURES - Lua v5.4 - SQLite 3.35.5 - TLS v1.2 / v1.1 / v1.0 - HTTP v1.1 / v1.0 / v0.9 - Chromium-Zlib Compression - Statusz Monitoring Statistics - Self-Modifying PKZIP Object Store - Linux + Windows + Mac + FreeBSD + OpenBSD + NetBSD FLAGS -h or -? help -d daemonize -u uniprocess -z print port -m log messages -i interpreter mode -b log message bodies -a log resource usage -g log handler latency -e eval Lua code in arg -F eval Lua code in file -E show crash reports to public ips -j enable ssl client verify -k disable ssl fetch verify -Z log worker system calls -f log worker function calls -B only use stronger cryptography -X disable ssl server and client support -* permit self-modification of executable -J disable non-ssl server and client support -% hasten startup by not generating an rsa key -s increase silence [repeatable] -v increase verbosity [repeatable] -V increase ssl verbosity [repeatable] -S increase pledge sandboxing [repeatable] -H K:V sets http header globally [repeatable] -D DIR overlay assets in local directory [repeatable] -r /X=/Y redirect X to Y [repeatable] -R /X=/Y rewrites X to Y [repeatable] -K PATH tls private key path [repeatable] -C PATH tls certificate(s) path [repeatable] -A PATH add assets with path (recursive) [repeatable] -M INT tunes max message payload size [def. 65536] -t INT timeout ms or keepalive sec if <0 [def. 60000] -p PORT listen port [def. 8080; repeatable] -l ADDR listen addr [def. 0.0.0.0; repeatable] -c SEC configures static cache-control -W TTY use tty path to monitor memory pages -L PATH log file location -P PATH pid file location -U INT daemon set user id -G INT daemon set group id -w PATH launch browser on startup --strace enables system call tracing (see also -Z) --ftrace enables function call tracing (see also -f) KEYBOARD CTRL-D EXIT CTRL-C CTRL-C EXIT CTRL-E END CTRL-A START CTRL-B BACK CTRL-F FORWARD CTRL-L CLEAR CTRL-H BACKSPACE CTRL-D DELETE CTRL-N NEXT HISTORY CTRL-P PREVIOUS HISTORY CTRL-R SEARCH HISTORY CTRL-G CANCEL SEARCH ALT-< BEGINNING OF HISTORY ALT-> END OF HISTORY ALT-F FORWARD WORD ALT-B BACKWARD WORD CTRL-RIGHT FORWARD WORD CTRL-LEFT BACKWARD WORD CTRL-K KILL LINE FORWARDS CTRL-U KILL LINE BACKWARDS ALT-H KILL WORD BACKWARDS CTRL-W KILL WORD BACKWARDS CTRL-ALT-H KILL WORD BACKWARDS ALT-D KILL WORD FORWARDS CTRL-Y YANK ALT-Y ROTATE KILL RING AND YANK AGAIN CTRL-T TRANSPOSE ALT-T TRANSPOSE WORD ALT-U UPPERCASE WORD ALT-L LOWERCASE WORD ALT-C CAPITALIZE WORD CTRL-\ QUIT PROCESS CTRL-S PAUSE OUTPUT CTRL-Q UNPAUSE OUTPUT (IF PAUSED) CTRL-Q ESCAPED INSERT CTRL-ALT-F FORWARD EXPR CTRL-ALT-B BACKWARD EXPR ALT-RIGHT FORWARD EXPR ALT-LEFT BACKWARD EXPR ALT-SHIFT-B BARF EXPR ALT-SHIFT-S SLURP EXPR CTRL-SPACE SET MARK CTRL-X CTRL-X GOTO MARK CTRL-Z SUSPEND PROCESS ALT-\ SQUEEZE ADJACENT WHITESPACE PROTIP REMAP CAPS LOCK TO CTRL ──────────────────────────────────────────────────────────────────────────────── USAGE This executable is also a ZIP file that contains static assets. You can run redbean interactively in your terminal as follows: ./redbean.com -vvvmbag # starts server verbosely open http://127.0.0.1:8080/ # shows zip listing page CTRL-C # 1x: graceful shutdown CTRL-C # 2x: forceful shutdown You can override the default listing page by adding: zip redbean.com index.lua # lua server pages take priority zip redbean.com index.html # default page for directory The listing page only applies to the root directory. However the default index page applies to subdirectories too. In order for it to work, there needs to be an empty directory entry in the zip. That should already be the default practice of your zip editor. wget \ --mirror \ --convert-links \ --adjust-extension \ --page-requisites \ --no-parent \ --no-if-modified-since \ http://a.example/index.html zip -r redbean.com a.example/ # default page for directory redbean normalizes the trailing slash for you automatically: $ printf 'GET /a.example HTTP/1.0\n\n' | nc 127.0.0.1 8080 HTTP/1.0 307 Temporary Redirect Location: /a.example/ Virtual hosting is accomplished this way too. The Host is simply prepended to the path, and if it doesn't exist, it gets removed. $ printf 'GET / HTTP/1.1\nHost:a.example\n\n' | nc 127.0.0.1 8080 HTTP/1.1 200 OK Link: <http://127.0.0.1/a.example/index.html>; rel="canonical" If you mirror a lot of websites within your redbean then you can actually tell your browser that redbean is your proxy server, in which redbean will act as your private version of the Internet. $ printf 'GET http://a.example HTTP/1.0\n\n' | nc 127.0.0.1 8080 HTTP/1.0 200 OK Link: <http://127.0.0.1/a.example/index.html>; rel="canonical" If you use a reverse proxy, then redbean recognizes the following provided that the proxy forwards requests over the local network: X-Forwarded-For: 203.0.113.42:31337 X-Forwarded-Host: foo.example:80 There's a text/plain statistics page called /statusz that makes it easy to track and monitor the health of your redbean: printf 'GET /statusz\n\n' | nc 127.0.0.1 8080 redbean will display an error page using the /redbean.png logo by default, embedded as a bas64 data uri. You can override the custom page for various errors by adding files to the zip root. zip redbean.com 404.html # custom not found page Audio video content should not be compressed in your ZIP files. Uncompressed assets enable browsers to send Range HTTP request. On the other hand compressed assets are best for gzip encoding. zip redbean.com index.html # adds file zip -0 redbean.com video.mp4 # adds without compression You can have redbean run as a daemon by doing the following: sudo ./redbean.com -vvdp80 -p443 -L redbean.log -P redbean.pid kill -TERM $(cat redbean.pid) # 1x: graceful shutdown kill -TERM $(cat redbean.pid) # 2x: forceful shutdown redbean currently has a 32kb limit on request messages and 64kb including the payload. redbean will grow to whatever the system limits allow. Should fork() or accept() fail redbean will react by going into "meltdown mode" which closes lingering workers. You can trigger this at any time using: kill -USR2 $(cat redbean.pid) Another failure condition is running out of disk space in which case redbean reacts by truncating the log file. Lastly, redbean does the best job possible reporting on resource usage when the logger is in debug mode noting that NetBSD is the best at this. Your redbean is an actually portable executable, that's able to run on six different operating systems. To do that, it needs to extract a 4kb loader program to ${TMPDIR:-${HOME:-.}}/.ape that'll map your redbean into memory. It does however check to see if `ape` is on the system path beforehand. You can also "assimilate" any redbean into the platform-local executable format by running: $ file redbean.com redbean.com: DOS/MBR boot sector $ ./redbean.com --assimilate $ file redbean.com redbean.com: ELF 64-bit LSB executable ──────────────────────────────────────────────────────────────────────────────── SECURITY redbean uses a protocol polyglot for serving HTTP and HTTPS on the same port numbers. For example, both of these are valid: http://127.0.0.1:8080/ https://127.0.0.1:8080/ SSL verbosity is controlled as follows for troubleshooting: -V log ssl errors -VV log ssl state changes too -VVV log ssl informational messages too -VVVV log ssl verbose details too Redbean supports sandboxing flags on Linux and OpenBSD. -S (online policy) This causes unix.pledge("stdio rpath inet dns") to be called on workers after fork() is called. This permits read-only operations and APIs like Fetch() that let workers send and receive data with private and public Internet hosts. Access to the unix module is somewhat restricted, disallowing its more powerful APIs like exec. -SS (offline policy) This causes unix.pledge("stdio rpath") to be called on workers after after fork() is called. This prevents workers from talking to the network (other than the client) and allows read-only file system access (e.g. `-D DIR` flag). -SSS (contained policy) This causes unix.pledge("stdio") to be called on workers after after fork() is called. This prevents workers from communicating with the network (other than the client connection) and prevents file system access (with some exceptions like logging). Redbean should only be able to serve from its own zip file in this mode. Lua script access to the unix module is highly restricted. See http://redbean.dev for further details. ──────────────────────────────────────────────────────────────────────────────── LUA SERVER PAGES Any files with the extension .lua will be dynamically served by redbean. Here's the simplest possible example: Write('<b>Hello World</b>') The Lua Server Page above should be able to perform at 700,000 responses per second on a Core i9, without any sort of caching. If you want a Lua handler that can do 1,000,000 responses per second, then try adding the following global handler to your /.init.lua file: function OnHttpRequest() Write('<b>Hello World</b>') end Here's an example of a more typical workflow for Lua Server Pages using the redbean API: SetStatus(200) SetHeader('Content-Type', 'text/plain; charset=utf-8') Write('<p>Hello ') Write(EscapeHtml(GetParam('name'))) We didn't need the first two lines in the previous example, because they're implied by redbean automatically if you don't set them. Responses are also buffered until the script finishes executing. That enables redbean to make HTTP as easy as possible. In the future, API capabilities will be expanded to make possible things like websockets. redbean embeds the Lua standard library. You can use packages such as io to persist and share state across requests and connections, as well as the StoreAsset function, and the lsqlite3 module. Your Lua interpreter begins its life in the main process at startup in the .init.lua, which is likely where you'll want to perform all your expensive one-time operations like importing modules. Then, as requests roll in, isolated processes are cloned from the blueprint you created. ──────────────────────────────────────────────────────────────────────────────── REPL Your redbean displays a Read-Eval-Print-Loop that lets you modify the state of the main server process while your server is running. Any changes will propagate into forked clients. Your REPL is displayed only when redbean is run as a non-daemon in a Unix terminal or the Windows 10 command prompt or PowerShell. Since the REPL is a Lua REPL it's not included in a redbean-static builds. redbean uses the same keyboard shortcuts as GNU Readline and Emacs. Some of its keyboard commands (listed in a previous section) were inspired by Paredit. A history of your commands is saved to `~/.redbean_history`. If you love the redbean repl and want to use it as your language interpreter then you can pass the `-i` flag to put redbean into interpreter mode. redbean.com -i binarytrees.lua 15 When the `-i` flag is passed (for interpreter mode), redbean won't start a web server and instead functions like the `lua` command. The first command line argument becomes the script you want to run. If you don't supply a script, then the repl without a web server is displayed. This is useful for testing since redbean extensions and modules for the Lua language, are still made available. You can also write redbean scripts with shebang lines: #!/usr/bin/redbean -i print('hello world') However UNIX operating systems usually require that interpreters be encoded in its preferred executable format. You can assimilate your redbean into the local format using the following commands: $ file redbean.com redbean.com: DOS/MBR boot sector $ ./redbean.com --assimilate $ file redbean.com redbean.com: ELF 64-bit LSB executable $ sudo cp redbean.com /usr/bin/redbean By following the above steps, redbean can be installed systemwide for multiple user accounts. It's also possible to chmod the binary to have setuid privileges. Please note that, if you do this, the UNIX section provides further details on APIs like `unix.setuid` that will help you remove root privileges from the process in the appropriate manner. ──────────────────────────────────────────────────────────────────────────────── LUA ENHANCEMENTS We've made some enhancements to the Lua language that should make it more comfortable for C/C++ and Python developers. Some of these - redbean supports a printf modulus operator, like Python. For example, you can say `"hello %s" % {"world"}` instead of `string.format("hello %s", "world")`. -- - redbean supports a string multiply operator, like Python. For example, you can say `"hi" * 2` instead of `string.rep("hi", 2)`. - redbean supports octal (base 8) integer literals. For example `0644 == 420` is the case in redbean, whereas in upstream Lua `0644 == 644` would be the case. - redbean supports binary (base 2) integer literals. For example `0b1010 == 10` is the case in redbean, whereas in upstream Lua `0b1010` would result in an error. - redbean supports the GNU syntax for the ASCII ESC character in string literals. For example, `"\e"` is the same as `"\x1b"`. ]] ---@class string ---@operator mod(any[]): string ---@operator mul(integer): string -- GLOBALS --- Array of command line arguments, excluding those parsed by --- getopt() in the C code, which stops parsing at the first --- non-hyphenated arg. In some cases you can use the magic -- --- argument to delimit C from Lua arguments. --- --- For example, if you launch your redbean as follows: --- --- redbean.com -v arg1 arg2 --- --- Then your `/.init.lua` file will have the `arg` array like: --- --- arg[-1] = '/usr/bin/redbean.com' --- arg[ 0] = '/zip/.init.lua' --- arg[ 1] = 'arg1' --- arg[ 2] = 'arg2' --- --- If you launch redbean in interpreter mode (rather than web --- server) mode, then an invocation like this: --- --- ./redbean.com -i script.lua arg1 arg2 --- --- Would have an `arg` array like this: --- --- arg[-1] = './redbean.com' --- arg[ 0] = 'script.lua' --- arg[ 1] = 'arg1' --- arg[ 2] = 'arg2' ---@type string[] arg = nil ---@deprecated Use `arg` instead. argv = nil --[[ ──────────────────────────────────────────────────────────────────────────────── SPECIAL PATHS / redbean will generate a zip central directory listing for this page, and this page only, but only if there isn't an /index.lua or /index.html file defined. /.init.lua This script is run once in the main process at startup. This lets you modify the state of the Lua interpreter before connection processes are forked off. For example, it's a good idea to do expensive one-time computations here. You can also use this file to call the ProgramFOO() functions below. The init module load happens after redbean's arguments and zip assets have been parsed, but before calling functions like socket() and fork(). Note that this path is a hidden file so that it can't be unintentionally run by the network client. /.reload.lua This script is run from the main process when SIGHUP is received. This only applies to redbean when running in daemon mode. Any changes that are made to the Lua interpreter state will be inherited by future forked connection processes. Note that this path is a hidden file so that it can't be unintentionally run by the network client. /.lua/... Your Lua modules go in this directory. The way it works is redbean sets Lua's package.path to /zip/.lua/?.lua;/zip/.lua/?/init.lua by default. Cosmopolitan Libc lets system calls like open read from the ZIP structure, if the filename is prefixed with /zip/. So this works like magic. /redbean.png If it exists, it'll be used as the / listing page icon, embedded as a base64 URI. /usr/share/zoneinfo This directory contains a subset of the timezone database. Your `TZ` environment variable controls which one of these files is used by functions such as unix.localtime(). /usr/share/ssl/root This directory contains your root certificate authorities. It is needed so the Fetch() HTTPS client API can verify that a remote certificate was signed by a third party. You can add your own certificate files to this directory within the ZIP executable. If you enable HTTPS client verification then redbean will check that HTTPS clients (a) have a certificate and (b) it was signed. /.args Specifies default command-line arguments. There's one argument per line. Trailing newline is ignored. If the special argument `...` is *not* encountered, then the replacement will only happen if *no* CLI args are specified. If the special argument `...` *is* encountered, then it'll be replaced with whatever CLI args were specified by the user. For example, you might want to use redbean.com in interpreter mode, where your script file is inside the zip. Then, if your redbean is run, what you want is to have the default behavior be running your script. In that case, you might: $ cat <<'EOF' >.args -i /zip/hello.lua EOF $ cat <<'EOF' >hello.lua print("hello world") EOF $ zip redbean.com .args hello.lua $ ./redbean.com hello world Please note that if you ran: $ ./redbean.com -vv Then the default mode of redbean will kick back in. To prevent that from happening, simply add the magic arg `...` to the end of your `.args` file. ]] -- HOOKS --- Hooks HTTP message handling. --- --- If this function is defined in the global scope by your `/.init.lua` --- then redbean will call it at the earliest possible moment to --- hand over control for all messages (with the exception of `OPTIONS--*` --- See functions like `Route` which asks redbean to do its default --- thing from the handler. --- function OnHttpRequest() end --- Hooks client connection creation. --- --- If this function is defined it'll be called from the main process --- each time redbean accepts a new client connection. --- ---@param ip uint32 ---@param port uint16 ---@param serverip uint32 ---@param serverport uint16 ---@return boolean # If it returns `true`, redbean will close the connection without calling `fork`. function OnClientConnection(ip, port, serverip, serverport) end --- Hook latency logging. --- --- If this function is defined it'll be called from the main process --- each time redbean completes handling of a request, but before the --- response is sent. The handler received the time (in µs) since the --- request handling and connection handling started. --- ---@param reqtimeus integer ---@param contimeus integer function OnLogLatency(reqtimeus, contimeus) end --- Hooks process creation. --- --- If this function is defined it'll be called from the main process --- each time redbean forks a connection handler worker process. The --- ip/port of the remote client is provided, along with the ip/port --- of the listening interface that accepted the connection. This may --- be used to create a server activity dashboard, in which case the --- data provider handler should set `SetHeader('Connection','Close')`. --- This won't be called in uniprocess mode. --- ---@param pid integer ---@param ip uint32 ---@param port uint16 ---@param serverip uint32 ---@param serverport uint16 function OnProcessCreate(pid, ip, port, serverip, serverport) end --- If this function is defined it'll be called from the main process --- each time redbean reaps a child connection process using `wait4()`. --- This won't be called in uniprocess mode. ---@param pid integer function OnProcessDestroy(pid) end --- If this function is defined it'll be called from the main process --- on each server heartbeat. The heartbeat interval is configurable --- with `ProgramHeartbeatInterval`. function OnServerHeartbeat() end --- If this function is defined it'll be called from the main process --- before redbean starts listening on a port. This hook can be used --- to modify socket configuration to set `SO_REUSEPORT`, for example. ---@param socketdescriptor integer ---@param serverip uint32 ---@param serverport uint16 ---@return boolean ignore If `true`, redbean will not listen to that ip/port. function OnServerListen(socketdescriptor, serverip, serverport) end --- If this function is defined it'll be called from the main process --- right before the main event loop starts. function OnServerStart() end --- If this function is defined it'll be called from the main process --- after all the connection processes have been reaped and `exit()` is --- ready to be called. function OnServerStop() end --- If this function is defined it'll be called from the child worker --- process after it's been forked and before messages are handled. --- This won't be called in uniprocess mode. function OnWorkerStart() end --- If this function is defined it'll be called from the child worker --- process once `_exit()` is ready to be called. This won't be called --- in uniprocess mode. function OnWorkerStop() end -- DATATYPES ---@class Url ---@field scheme string e.g. `"http"` ---@field user string? the username string, or nil if absent ---@field pass string? the password string, or nil if absent ---@field host string? the hostname string, or nil if `url` was a path ---@field port string? the port string, or nil if absent ---@field path string? the path string, or nil if absent ---@field params string[][]? the URL paramaters e.g. `/?a=b&c` would be --- represented as the data structure `{{"a", "b"}, {"c"}, ...}` ---@field fragment string? the stuff after the `#` character ---@alias uint32 integer Unsigned 32-bit integer ---@alias uint16 integer Unsigned 16-bit integer ---@class EncoderOptions ---@field useoutput boolean? defaults to `false`. Encodes the result directly to the output buffer and returns `nil` value. This option is ignored if used outside of request handling code. ---@field sorted boolean? defaults to `true`. Lua uses hash tables so the order of object keys is lost in a Lua table. So, by default, we use strcmp to impose a deterministic output order. If you don't care about ordering then setting sorted=false should yield a performance boost in serialization. ---@field pretty boolean? defaults to `false`. Setting this option to true will cause tables with more than one entry to be formatted across multiple lines for readability. ---@field indent string? defaults to " ". This option controls the indentation of pretty formatting. This field is ignored if pretty isn't true. ---@field maxdepth integer? defaults to 64. This option controls the maximum amount of recursion the serializer is allowed to perform. The max is 32767. You might not be able to set it that high if there isn't enough C stack memory. Your serializer checks for this and will return an error rather than crashing. -- FUNCTIONS --- Appends data to HTTP response payload buffer. --- --- This is buffered independently of headers. --- ---@param data string function Write(data) end --- Starts an HTTP response, specifying the parameters on its first line. --- --- This method will reset the response and is therefore mutually --- exclusive with `ServeAsset` and other `Serve*` functions. If a --- status setting function isn't called, then the default behavior is --- to send `200 OK`. --- ---@param code integer ---@param reason? string is optional since redbean can fill in the appropriate text for well-known magic numbers, e.g. `200`, `404`, etc. function SetStatus(code, reason) end --- Appends HTTP header to response header buffer. --- --- Leading and trailing whitespace is trimmed automatically. Overlong --- characters are canonicalized. C0 and C1 control codes are forbidden, --- with the exception of tab. This function automatically calls --- `SetStatus(200, "OK")` if a status has not yet been set. As --- `SetStatus` and `Serve*` functions reset the response, `SetHeader` --- needs to be called after `SetStatus` and `Serve*` functions are --- called. The header buffer is independent of the payload buffer. --- Neither is written to the wire until the Lua Server Page has --- finished executing. This function disallows the setting of certain --- headers such as and Content-Range which are abstracted by the --- transport layer. In such cases, consider calling `ServeAsset`. --- ---@param name string is case-insensitive and restricted to non-space ASCII ---@param value string is a UTF-8 string that must be encodable as ISO-8859-1. function SetHeader(name, value) end --- Appends Set-Cookie HTTP header to the response header buffer. --- --- Several Set-Cookie headers can be added to the same response. --- `__Host-` and `__Secure-` prefixes are supported and may set or --- overwrite some of the options (for example, specifying `__Host-` --- prefix sets the Secure option to `true`, sets the path to `"/"`, and --- removes the Domain option). The following options can be used (their --- lowercase equivalents are supported as well): --- --- - `Expires` sets the maximum lifetime of the cookie as an HTTP-date timestamp. Can be specified as a Date in the RFC1123 (string) format or as a UNIX timestamp (number of seconds). --- - `MaxAge` sets number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and MaxAge are set, MaxAge has precedence. --- - `Domain` sets the host to which the cookie will be sent. --- - `Path` sets the path that must be present in the request URL, or the client will not send the Cookie header. --- - `Secure` (boolean) requests the cookie to be only send to the server when a request is made with the https: scheme. --- - `HttpOnly` (boolean) forbids JavaScript from accessing the cookie. --- - `SameSite` (Strict, Lax, or None) controls whether a cookie is sent with cross-origin requests, providing some protection against cross-site request forgery attacks. --- ---@param name string ---@param value string ---@param options { Expires: string|integer?, MaxAge: integer?, Domain: string?, Path: string?, Secure: boolean?, HttpOnly: boolean?, SameSite: "Strict"|"Lax"|"None"? }? function SetCookie(name, value, options) end --- Returns first value associated with name. name is handled in a case-sensitive manner. This function checks Request-URL parameters first. Then it checks `application/x-www-form-urlencoded` from the message body, if it exists, which is common for HTML forms sending `POST` requests. If a parameter is supplied matching name that has no value, e.g. `foo` in `?foo&bar=value`, then the returned value will be `nil`, whereas for `?foo=&bar=value` it would be `""`. To differentiate between no-equal and absent, use the `HasParam` function. The returned value is decoded from ISO-8859-1 (only in the case of Request-URL) and we assume that percent-encoded characters were supplied by the client as UTF-8 sequences, which are returned exactly as the client supplied them, and may therefore may contain overlong sequences, control codes, `NUL` characters, and even numbers which have been banned by the IETF. It is the responsibility of the caller to impose further restrictions on validity, if they're desired. ---@param name string ---@return string value ---@nodiscard function GetParam(name) end --- Escapes HTML entities: The set of entities is `&><"'` which become `&amp;&gt;&lt;&quot;&#39;`. This function is charset agnostic and will not canonicalize overlong encodings. It is assumed that a UTF-8 string will be supplied. See `escapehtml.c`. ---@param str string ---@return string ---@nodiscard function EscapeHtml(str) end --- Launches web browser on local machine with URL to this redbean server. This function may be called from your `/.init.lua`. ---@param path string? function LaunchBrowser(path) end ---@param ip uint32 ---@return string # a string describing the IP address. This is currently Class A granular. It can tell you if traffic originated from private networks, ARIN, APNIC, DOD, etc. ---@nodiscard function CategorizeIp(ip) end --- Decodes binary data encoded as base64. --- --- This turns ASCII into binary, in a permissive way that ignores --- characters outside the base64 alphabet, such as whitespace. See --- `decodebase64.c`. --- ---@param ascii string ---@return string binary ---@nodiscard function DecodeBase64(ascii) end --- Turns ISO-8859-1 string into UTF-8. --- ---@param iso_8859_1 string ---@return string UTF8 ---@nodiscard function DecodeLatin1(iso_8859_1) end --- Turns binary into ASCII. This can be used to create HTML data: --- URIs that do things like embed a PNG file in a web page. See --- encodebase64.c. ---@param binary string ---@return string ascii ---@nodiscard function EncodeBase64(binary) end ---@alias JsonEl<T> string|number|boolean|nil|{ [integer]: T }|{ [string]: T } ---@alias JsonValue JsonEl<JsonEl<JsonEl<JsonEl<JsonEl<JsonEl<JsonEl<any>>>>>>> --- Turns JSON string into a Lua data structure. --- --- This is a generally permissive parser, in the sense that like --- v8, it permits scalars as top-level values. Therefore we must --- note that this API can be thought of as special, in the sense --- --- val = assert(DecodeJson(str)) --- --- will usually do the right thing, except in cases where `false` --- or `null` are the top-level value. In those cases, it's needed --- to check the second value too in order to discern from error --- --- val, err = DecodeJson(str) --- if not val then --- if err then --- print('bad json', err) --- elseif val == nil then --- print('val is null') --- elseif val == false then --- print('val is false') --- end --- end --- --- This parser supports 64-bit signed integers. If an overflow --- happens, then the integer is silently coerced to double, as --- consistent with v8. If a double overflows into `Infinity`, we --- coerce it to `null` since that's what v8 does, and the same --- goes for underflows which, like v8, are coerced to `0.0`. --- --- When objects are parsed, your Lua object can't preserve the --- original ordering of fields. As such, they'll be sorted by --- `EncodeJson()` and may not round-trip with original intent. --- --- This parser has perfect conformance with JSONTestSuite. --- --- This parser validates utf-8 and utf-16. ---@param input string ---@return JsonValue ---@nodiscard ---@overload fun(input: string): nil, error: string function DecodeJson(input) end --- Turns Lua data structure into JSON string. --- --- Since Lua uses tables are both hashmaps and arrays, we use a --- simple fast algorithm for telling the two apart. Tables with --- non-zero length (as reported by `#`) are encoded as arrays, --- and any non-array elements are ignored. For example: --- --- >: EncodeJson({2}) --- "[2]" --- >: EncodeJson({[1]=2, ["hi"]=1}) --- "[2]" --- --- If there are holes in your array, then the serialized array --- will exclude everything after the first hole. If the beginning --- of your array is a hole, then an error is returned. --- --- >: EncodeJson({[1]=1, [3]=3}) --- "[1]" --- >: EncodeJson({[2]=1, [3]=3}) --- "[]" --- >: EncodeJson({[2]=1, [3]=3}) --- nil "json objects must only use string keys" --- --- If the raw length of a table is reported as zero, then we --- check for the magic element `[0]=false`. If it's present, then --- your table will be serialized as empty array `[]`. An entry is --- inserted by `DecodeJson()` automatically, only when encountering --- empty arrays, and it's necessary in order to make empty arrays --- round-trip. If raw length is zero and `[0]=false` is absent, --- then your table will be serialized as an iterated object. --- --- >: EncodeJson({}) --- "{}" --- >: EncodeJson({[0]=false}) --- "[]" --- >: EncodeJson({["hi"]=1}) --- "{\"hi\":1}" --- >: EncodeJson({["hi"]=1, [0]=false}) --- "[]" --- >: EncodeJson({["hi"]=1, [7]=false}) --- nil "json objects must only use string keys" --- --- The following options may be used: --- --- - `useoutput`: `(bool=false)` encodes the result directly to the output buffer --- and returns nil value. This option is ignored if used outside of request --- handling code. --- - `sorted`: `(bool=true)` Lua uses hash tables so the order of object keys is --- lost in a Lua table. So, by default, we use strcmp to impose a deterministic --- output order. If you don't care about ordering then setting `sorted=false` --- should yield a performance boost in serialization. --- - `pretty`: `(bool=false)` Setting this option to true will cause tables with --- more than one entry to be formatted across multiple lines for readability. --- - `indent`: `(str=" ")` This option controls the indentation of pretty --- formatting. This field is ignored if pretty isn't `true`. --- - `maxdepth`: `(int=64)` This option controls the maximum amount of recursion --- the serializer is allowed to perform. The max is 32767. You might not be able --- to set it that high if there isn't enough C stack memory. Your serializer --- checks for this and will return an error rather than crashing. --- --- If the raw length of a table is reported as zero, then we --- check for the magic element `[0]=false`. If it's present, then --- your table will be serialized as empty array `[]`. An entry is --- inserted by `DecodeJson()` automatically, only when encountering --- empty arrays, and it's necessary in order to make empty arrays --- round-trip. If raw length is zero and `[0]=false` is absent, --- then your table will be serialized as an iterated object. --- --- This function will return an error if: --- --- - value is cyclic --- - value has depth greater than 64 --- - value contains functions, user data, or threads --- - value is table that blends string / non-string keys --- - Your serializer runs out of C heap memory (setrlimit) --- --- We assume strings in value contain UTF-8. This serializer currently does not --- produce UTF-8 output. The output format is right now ASCII. Your UTF-8 data --- will be safely transcoded to `\uXXXX` sequences which are UTF-16. Overlong --- encodings in your input strings will be canonicalized rather than validated. --- --- NaNs are serialized as `null` and Infinities are `null` which is consistent --- with the v8 behavior. ---@param value JsonValue ---@param options { useoutput: false?, sorted: boolean?, pretty: boolean?, indent: string?, maxdepth: integer? }? ---@return string ---@nodiscard ---@overload fun(value: JsonValue, options: { useoutput: true, sorted: boolean?, pretty: boolean?, indent: string?, maxdepth: integer? }): true ---@overload fun(value: JsonValue, options: { useoutput: boolean?, sorted: boolean?, pretty: boolean?, indent: string?, maxdepth: integer? }? ): nil, error: string function EncodeJson(value, options) end --- Turns Lua data structure into Lua code string. --- --- Since Lua uses tables as both hashmaps and arrays, tables will only be --- serialized as an array with determinate order, if it's an array in the --- strictest possible sense. --- --- 1. for all 𝑘=𝑣 in table, 𝑘 is an integer ≥1 --- 2. no holes exist between MIN(𝑘) and MAX(𝑘) --- 3. if non-empty, MIN(𝑘) is 1 --- --- In all other cases, your table will be serialized as an object which is --- iterated and displayed as a list of (possibly) sorted entries that have --- equal signs. --- --- >: EncodeLua({3, 2}) --- "{3, 2}" --- >: EncodeLua({[1]=3, [2]=3}) --- "{3, 2}" --- >: EncodeLua({[1]=3, [3]=3}) --- "{[1]=3, [3]=3}" --- >: EncodeLua({["hi"]=1, [1]=2}) --- "{[1]=2, hi=1}" --- --- The following options may be used: --- --- - `useoutput`: `(bool=false)` encodes the result directly to the output buffer --- and returns nil value. This option is ignored if used outside of request --- handling code. --- - `sorted`: `(bool=true)` Lua uses hash tables so the order of object keys is --- lost in a Lua table. So, by default, we use strcmp to impose a deterministic --- output order. If you don't care about ordering then setting `sorted=false` --- should yield a performance boost in serialization. --- - `pretty`: `(bool=false)` Setting this option to true will cause tables with --- more than one entry to be formatted across multiple lines for readability. --- - `indent`: `(str=" ")` This option controls the indentation of pretty --- formatting. This field is ignored if pretty isn't `true`. --- - `maxdepth`: `(int=64)` This option controls the maximum amount of recursion --- the serializer is allowed to perform. The max is 32767. You might not be able --- to set it that high if there isn't enough C stack memory. Your serializer --- checks for this and will return an error rather than crashing. --- --- If a user data object has a `__repr` or `__tostring` meta method, then that'll --- be used to encode the Lua code. --- --- This serializer is designed primarily to describe data. For example, it's used --- by the REPL where we need to be able to ignore errors when displaying data --- structures, since showing most things imperfectly is better than crashing. --- Therefore this isn't the kind of serializer you'd want to use to persist data --- in prod. Try using the JSON serializer for that purpose. --- --- Non-encodable value types (e.g. threads, functions) will be represented as a --- string literal with the type name and pointer address. The string description --- is of an unspecified format that could most likely change. This encoder detects --- cyclic tables; however instead of failing, it embeds a string of unspecified --- layout describing the cycle. --- --- Integer literals are encoded as decimal. However if the int64 number is ≥256 --- and has a population count of 1 then we switch to representating the number in --- hexadecimal, for readability. Hex numbers have leading zeroes added in order --- to visualize whether the number fits in a uint16, uint32, or int64. Also some --- numbers can only be encoded expressionally. For example, `NaN`s are serialized --- as `0/0`, and `Infinity` is `math.huge`. --- --- >: 7000 --- 7000 --- >: 0x100 --- 0x0100 --- >: 0x10000 --- 0x00010000 --- >: 0x100000000 --- 0x0000000100000000 --- >: 0/0 --- 0/0 --- >: 1.5e+9999 --- math.huge --- >: -9223372036854775807 - 1 --- -9223372036854775807 - 1 --- --- The only failure return condition currently implemented is when C runs out of heap memory. ---@param options { useoutput: false?, sorted: boolean?, pretty: boolean?, indent: string?, maxdepth: integer? }? ---@return string ---@nodiscard ---@overload fun(value, options: { useoutput: true, sorted: boolean?, pretty: boolean?, indent: string?, maxdepth: integer? }): true ---@overload fun(value, options: EncoderOptions? ): nil, error: string function EncodeLua(value, options) end --- Turns UTF-8 into ISO-8859-1 string. ---@param utf8 string ---@param flags integer ---@return string iso_8859_1 ---@nodiscard function EncodeLatin1(utf8, flags) end --- Escapes URL #fragment. The allowed characters are `-/?.~_@:!$&'()*+,;=0-9A-Za-z` --- and everything else gets `%XX` encoded. Please note that `'&` can still break --- HTML and that `'()` can still break CSS URLs. This function is charset agnostic --- and will not canonicalize overlong encodings. It is assumed that a UTF-8 string --- will be supplied. See `kescapefragment.c`. ---@param str string ---@return string ---@nodiscard function EscapeFragment(str) end --- Escapes URL host. See `kescapeauthority.c`. ---@param str string ---@return string ---@nodiscard function EscapeHost(str) end --- Escapes JavaScript or JSON string literal content. The caller is responsible --- for adding the surrounding quotation marks. This implementation \uxxxx sequences --- for all non-ASCII sequences. HTML entities are also encoded, so the output --- doesn't need `EscapeHtml`. This function assumes UTF-8 input. Overlong --- encodings are canonicalized. Invalid input sequences are assumed to --- be ISO-8859-1. The output is UTF-16 since that's what JavaScript uses. For --- example, some individual codepoints such as emoji characters will encode as --- multiple `\uxxxx` sequences. Ints that are impossible to encode as UTF-16 are --- substituted with the `\xFFFD` replacement character. --- See `escapejsstringliteral.c`. ---@param str string ---@return string ---@nodiscard function EscapeLiteral(str) end --- Escapes URL parameter name or value. The allowed characters are `-.*_0-9A-Za-z` --- and everything else gets `%XX` encoded. This function is charset agnostic and --- will not canonicalize overlong encodings. It is assumed that a UTF-8 string --- will be supplied. See `kescapeparam.c`. ---@param str string ---@return string ---@nodiscard function EscapeParam(str) end --- Escapes URL password. See `kescapeauthority.c`. ---@param str string ---@return string ---@nodiscard function EscapePass(str) end --- Escapes URL path. This is the same as EscapeSegment except slash is allowed. --- The allowed characters are `-.~_@:!$&'()*+,;=0-9A-Za-z/` and everything else --- gets `%XX` encoded. Please note that `'&` can still break HTML, so the output --- may need EscapeHtml too. Also note that `'()` can still break CSS URLs. This --- function is charset agnostic and will not canonicalize overlong encodings. --- It is assumed that a UTF-8 string will be supplied. See `kescapepath.c`. ---@param str string ---@return string ---@nodiscard function EscapePath(str) end --- Escapes URL path segment. This is the same as EscapePath except slash isn't --- allowed. The allowed characters are `-.~_@:!$&'()*+,;=0-9A-Za-z` and everything --- else gets `%XX` encoded. Please note that `'&` can still break HTML, so the --- output may need EscapeHtml too. Also note that `'()` can still break CSS URLs. --- This function is charset agnostic and will not canonicalize overlong encodings. --- It is assumed that a UTF-8 string will be supplied. See `kescapesegment.c`. ---@param str string ---@return string ---@nodiscard function EscapeSegment(str) end --- Escapes URL username. See `kescapeauthority.c`. ---@param str string ---@return string ---@nodiscard function EscapeUser(str) end --- If this option is programmed then redbean will not transmit a Server Name --- Indicator (SNI) when performing `Fetch()` requests. This function is not --- available in unsecure mode. ---@param bool boolean function EvadeDragnetSurveillance(bool) end --- Sends an HTTP/HTTPS request to the specified URL. If only the URL is provided, --- then a GET request is sent. If both URL and body parameters are specified, then --- a POST request is sent. If any other method needs to be specified (for example, --- PUT or DELETE), then passing a table as the second value allows setting method --- and body values as well other options: --- --- - `method` (default: `"GET"`): sets the method to be used for the request. --- The specified method is converted to uppercase. --- - `body` (default: `""`): sets the body value to be sent. --- - `followredirect` (default: `true`): forces temporary and permanent redirects --- to be followed. This behavior can be disabled by passing `false`. --- - `maxredirects` (default: `5`): sets the number of allowed redirects to --- minimize looping due to misconfigured servers. When the number is exceeded, --- the result of the last redirect is returned. --- --- When the redirect is being followed, the same method and body values are being --- sent in all cases except when 303 status is returned. In that case the method --- is set to GET and the body is removed before the redirect is followed. Note --- that if these (method/body) values are provided as table fields, they will be --- modified in place. ---@param url string ---@param body? string|{ headers: table<string,string>, value: string, method: string, body: string, maxredirects: integer? } ---@return integer status, table<string,string> headers, string body/ ---@nodiscard ---@overload fun(url:string, body?: string|{ headers: table<string,string>, value: string, method: string, body: string, maxredirects?: integer }): nil, error: string function Fetch(url, body) end --- Converts UNIX timestamp to an RFC1123 string that looks like this: --- `Mon, 29 Mar 2021 15:37:13 GMT`. See `formathttpdatetime.c`. ---@param seconds integer ---@return string ---@nodiscard rfc1123 function FormatHttpDateTime(seconds) end --- Turns integer like `0x01020304` into a string like `"1.2.3.4"`. See also --- `ParseIp` for the inverse operation. ---@param uint32 integer ---@return string ---@nodiscard function FormatIp(uint32) end --- Returns client ip4 address and port, e.g. `0x01020304`,`31337` would represent --- `1.2.3.4:31337`. This is the same as `GetClientAddr` except it will use the --- ip:port from the `X-Forwarded-For` header, only if `IsPrivateIp` or --- `IsPrivateIp` returns `true`. ---@return integer ip, integer port uint32 and uint16 respectively ---@nodiscard function GetRemoteAddr() end ---@return string ---@nodiscard # the response message body if present or an empty string. Also --- returns an empty string during streaming. function GetResponseBody() end --- Returns client socket ip4 address and port, e.g. `0x01020304,31337` would --- represent `1.2.3.4:31337`. Please consider using `GetRemoteAddr` instead, --- since the latter takes into consideration reverse proxy scenarios. ---@return uint32 ip uint32 ---@return uint16 port uint16 ---@nodiscard function GetClientAddr() end --- Returns address to which listening server socket is bound, e.g. --- `0x01020304,8080` would represent `1.2.3.4:8080`. If `-p 0` was supplied as --- the listening port, then the port in this string will be whatever number the --- operating system assigned. ---@return uint32 ip uint32 ---@return uint16 port uint16 ---@nodiscard function GetServerAddr() end ---@return integer clientfd ---@nodiscard function GetClientFd() end ---@return integer unixts date associated with request that's used to generate the --- Date header, which is now, give or take a second. The returned value is a UNIX --- timestamp. ---@nodiscard function GetDate() end ---@return string? ---@nodiscard function GetFragment() end --- Returns HTTP header. name is case-insensitive. The header value is returned as --- a canonical UTF-8 string, with leading and trailing whitespace trimmed, which --- was decoded from ISO-8859-1, which is guaranteed to not have C0/C1 control --- sequences, with the exception of the tab character. Leading and trailing --- whitespace is automatically removed. In the event that the client suplies raw --- UTF-8 in the HTTP message headers, the original UTF-8 sequence can be --- losslessly restored by counter-intuitively recoding the returned string back --- to Latin1. If the requested header is defined by the RFCs as storing --- comma-separated values (e.g. Allow, Accept-Encoding) and the field name occurs --- multiple times in the message, then this function will fold those multiple --- entries into a single string. ---@param name string ---@return string ---@nodiscard value function GetHeader(name) end --- Returns HTTP headers as dictionary mapping header key strings to their UTF-8 --- decoded values. The ordering of headers from the request message is not --- preserved. Whether or not the same key can repeat depends on whether or not --- it's a standard header, and if so, if it's one of the ones that the RFCs --- define as repeatable. See `khttprepeatable.c`. Those headers will not be --- folded. Standard headers which aren't on that list, will be overwritten with --- the last-occurring one during parsing. Extended headers are always passed --- through exactly as they're received. Please consider using `GetHeader` API if --- possible since it does a better job abstracting these issues. ---@return table<string, string> ---@nodiscard function GetHeaders() end --- Returns logger verbosity level. Likely return values are `kLogDebug` > --- `kLogVerbose` > `kLogInfo` > `kLogWarn` > `kLogError` > `kLogFatal`. ---@return integer ---@nodiscard function GetLogLevel() end ---@return string # host associated with request. This will be the Host header, if it's supplied. Otherwise it's the bind address. ---@nodiscard function GetHost() end ---@return "LINUX"|"METAL"|"WINDOWS"|"XNU"|"NETBSD"|"FREEBSD"|"OPENBSD" osname string that describes the host OS. ---@nodiscard function GetHostOs() end ---@return "X86_64"|"AARCH64"|"POWERPC64"|"S390X" isaname string that describes the host instruction set architecture ---@nodiscard function GetHostIsa() end ---@param str string|integer monospace display width of string. --- This is useful for fixed-width formatting. For example, CJK characters --- typically take up two cells. This function takes into consideration combining --- characters, which are discounted, as well as control codes and ANSI escape --- sequences. ---@return integer ---@nodiscard function GetMonospaceWidth(str) end ---@return string method HTTP method. --- Normally this will be GET, HEAD, or POST in which case redbean normalizes this --- value to its uppercase form. Anything else that the RFC classifies as a "token" --- string is accepted too, which might contain characters like &". ---@nodiscard function GetMethod() end ---@return { [1]: string, [2]: string? }[] # name=value parameters from Request-URL and `application/x-www-form-urlencoded` message body in the order they were received. --- This may contain duplicates. The inner array will have either one or two items, --- depending on whether or not the equals sign was used. ---@nodiscard function GetParams() end ---@return string? pass ---@nodiscard function GetPass() end ---@return string path the Request-URL path. --- This is guaranteed to begin with `"/"` It is further guaranteed that no `"//"` --- or `"/."` exists in the path. The returned value is returned as a UTF-8 string --- which was decoded from ISO-8859-1. We assume that percent-encoded characters --- were supplied by the client as UTF-8 sequences, which are returned exactly as --- the client supplied them, and may therefore may contain overlong sequences, --- control codes, `NUL` characters, and even numbers which have been banned by --- the IETF. redbean takes those things into consideration when performing path --- safety checks. It is the responsibility of the caller to impose further --- restrictions on validity, if they're desired. ---@nodiscard function GetPath() end ---@return string path as it was resolved by the routing algorithms, which might contain the virtual host prepended if used. ---@nodiscard function GetEffectivePath() end ---@return uint16 port ---@nodiscard function GetPort() end ---@return string? scheme from Request-URL, if any. ---@nodiscard function GetScheme() end ---@return integer? current status (as set by an earlier `SetStatus` call) or `nil` if the status hasn't been set yet. ---@nodiscard function GetStatus() end ---@return number seconds current time as a UNIX timestamp with 0.0001s precision. ---@nodiscard function GetTime() end ---@return string url the effective Request-URL as an ASCII string --- Illegal characters or UTF-8 is guaranteed to be percent encoded, and has been --- normalized to include either the Host or `X-Forwarded-Host` headers, if they --- exist, and possibly a scheme too if redbean is being used as an HTTP proxy --- server. --- --- In the future this API might change to return an object instead. ---@nodiscard function GetUrl() end ---@return string? user ---@nodiscard function GetUser() end ---@return integer httpversion the request HTTP protocol version, which can be `9` for `HTTP/0.9`, `10` for `HTTP/1.0`, or `11` for `HTTP/1.1`. ---@nodiscard function GetHttpVersion() end ---@return integer ---@nodiscard ---@deprecated Use `GetHttpVersion` instead. function GetVersion() end ---@param code integer ---@return string reason string describing the HTTP reason phrase. See `gethttpreason.c`. ---@nodiscard function GetHttpReason(code) end ---@param length integer? ---@return string # with the specified number of random bytes (1..256). If no length is specified, then a string of length 16 is returned. ---@nodiscard function GetRandomBytes(length) end ---@return integer redbeanversion the Redbean version in the format 0xMMmmpp, with major (MM), minor (mm), and patch (pp) versions encoded. The version value 1.4 would be represented as 0x010400. ---@nodiscard function GetRedbeanVersion() end ---@param prefix string? paths of all assets in the zip central directory, prefixed by a slash. --- If prefix parameter is provided, then only paths that start with the prefix --- (case sensitive) are returned. ---@return string[] ---@nodiscard function GetZipPaths(prefix) end ---@param name string ---@return boolean # `true` if parameter with name was supplied in either the Request-URL or an application/x-www-form-urlencoded message body. ---@nodiscard function HasParam(name) end --- Programs redbean `/` listing page to not display any paths beginning with prefix. --- This function should only be called from `/.init.lua`. ---@param prefix string function HidePath(prefix) end ---@param path string ---@return boolean # `true` if the prefix of the given path is set with `HidePath`. ---@nodiscard function IsHiddenPath(path) end ---@param uint32 integer ---@return boolean # `true` if IP address is not a private network (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) and is not localhost (`127.0.0.0/8`). --- Note: we intentionally regard TEST-NET IPs as public. ---@nodiscard function IsPublicIp(uint32) end ---@param uint32 integer ---@return boolean # `true` if IP address is part of a private network (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). ---@nodiscard function IsPrivateIp(uint32) end ---@return boolean # `true` if the client IP address (returned by GetRemoteAddr) is part of the localhost network (127.0.0.0/8). ---@nodiscard function IsLoopbackClient() end ---@param uint32 integer ---@return boolean # true if IP address is part of the localhost network (127.0.0.0/8). ---@nodiscard function IsLoopbackIp(uint32) end ---@param path string ---@return boolean # `true` if ZIP artifact at path is stored on disk using DEFLATE compression. ---@nodiscard function IsAssetCompressed(path) end ---@deprecated use IsAssetCompressed instead. ---@param path string ---@return boolean ---@nodiscard function IsCompressed(path) end ---@return boolean ---@nodiscard function IsClientUsingSsl() end --- Adds spaces to beginnings of multiline string. If the int parameter is not --- supplied then 1 space will be added. ---@param str string ---@param int integer? ---@return string ---@nodiscard function IndentLines(str, int) end ---@param path string ---@return string asset contents of file as string. --- The asset may be sourced from either the zip (decompressed) or the local --- filesystem if the `-D` flag was used. If slurping large file into memory is a --- concern, then consider using `ServeAsset` which can serve directly off disk. ---@nodiscard function LoadAsset(path) end --- Stores asset to executable's ZIP central directory. This currently happens in --- an append-only fashion and is still largely in the proof-of-concept stages. --- Currently only supported on Linux, XNU, and FreeBSD. In order to use this --- feature, the `-*` flag must be passed. ---@param path string ---@param data string ---@param mode? integer function StoreAsset(path, data, mode) end --- Emits message string to log, if level is less than or equal to `GetLogLevel`. --- If redbean is running in interactive mode, then this will log to the console. --- If redbean is running as a daemon or the `-L LOGFILE` flag is passed, then this --- will log to the file. Reasonable values for level are `kLogDebug` > --- `kLogVerbose` > `kLogInfo` > `kLogWarn` > `kLogError` > `kLogFatal`. The --- logger emits timestamps in the local timezone with microsecond precision. If --- log entries are emitted more frequently than once per second, then the log --- entry will display a delta timestamp, showing how much time has elapsed since --- the previous log entry. This behavior is useful for quickly measuring how long --- various portions of your code take to execute. ---@param level integer ---@param message string function Log(level, message) end --- Converts RFC1123 string that looks like this: Mon, 29 Mar 2021 15:37:13 GMT to --- a UNIX timestamp. See `parsehttpdatetime.c`. ---@param rfc1123 string ---@return integer seconds ---@nodiscard function ParseHttpDateTime(rfc1123) end --- Parses URL. --- ---@return Url url An object containing the following fields is returned: --- --- - `scheme` is a string, e.g. `"http"` --- - `user` is the username string, or nil if absent --- - `pass` is the password string, or nil if absent --- - `host` is the hostname string, or nil if `url` was a path --- - `port` is the port string, or nil if absent --- - `path` is the path string, or nil if absent --- - `params` is the URL paramaters, e.g. `/?a=b&c` would be --- represented as the data structure `{{"a", "b"}, {"c"}, ...}` --- - `fragment` is the stuff after the `#` character --- ---@param url string ---@param flags integer? may have: --- --- - `kUrlPlus` to turn `+` into space --- - `kUrlLatin1` to transcode ISO-8859-1 input into UTF-8 --- --- This parser is charset agnostic. Percent encoded bytes are --- decoded for all fields. 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 data 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 data:opaque, better in fact than most things which --- claim to be URI parsers. --- ---@nodiscard function ParseUrl(url, flags) end ---@param str string ---@return boolean # `true` if path doesn't contain ".", ".." or "//" segments See `isacceptablepath.c` ---@nodiscard function IsAcceptablePath(str) end ---@param str string ---@return boolean # `true` if path doesn't contain "." or ".." segments See `isreasonablepath.c` ---@nodiscard function IsReasonablePath(str) end --- This function is the inverse of ParseUrl. The output will always be correctly --- formatted. The exception is if illegal characters are supplied in the scheme --- field, since there's no way of escaping those. Opaque parts are escaped as --- though they were paths, since many URI parsers won't understand things like --- an unescaped question mark in path. ---@param url Url ---@return string url ---@nodiscard function EncodeUrl(url) end --- Converts IPv4 address string to integer, e.g. "1.2.3.4" → 0x01020304, or --- returns -1 for invalid inputs. See also `FormatIp` for the inverse operation. ---@param ip string ---@return integer ip ---@nodiscard function ParseIp(ip) end ---@param path string ---@return string? comment comment text associated with asset in the ZIP central directory. ---@nodiscard function GetAssetComment(path) end ---@deprecated Use `GetAssetComment` instead. ---@param path string ---@return string? ---@nodiscard function GetComment(path) end ---@param path string ---@return number seconds UNIX timestamp for modification time of a ZIP asset (or local file if the -D flag is used). If both a file and a ZIP asset are present, then the file is used. ---@nodiscard function GetAssetLastModifiedTime(path) end ---@deprecated Use `GetAssetLastModifiedTime` instead. ---@param path string ---@return number ---@nodiscard function GetLastModifiedTime(path) end ---@param path string ---@return integer mode UNIX-style octal mode for ZIP asset (or local file if the -D flag is used) ---@nodiscard function GetAssetMode(path) end ---@param path string ---@return integer bytesize byte size of uncompressed contents of ZIP asset (or local file if the `-D` flag is used) ---@nodiscard function GetAssetSize(path) end ---@return string body the request message body if present or an empty string. ---@nodiscard function GetBody() end ---@return string ---@nodiscard ---@deprecated Use `GetBody` instead. function GetPayload() end ---@param name string ---@return string cookie ---@nodiscard function GetCookie(name) end --- Computes MD5 checksum, returning 16 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Md5(str) end --- Computes SHA1 checksum, returning 20 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Sha1(str) end --- Computes SHA224 checksum, returning 28 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Sha224(str) end --- Computes SHA256 checksum, returning 32 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Sha256(str) end --- Computes SHA384 checksum, returning 48 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Sha384(str) end --- Computes SHA512 checksum, returning 64 bytes of binary. ---@param str string ---@return string checksum ---@nodiscard function Sha512(str) end ---@param name "MD5"|"SHA1"|"SHA224"|"SHA256"|"SHA384"|"SHA512"|"BLAKE2B256" ---@param payload string ---@param key string? If the key is provided, then HMAC value of the same function is returned. ---@return string # value of the specified cryptographic hash function. ---@nodiscard function GetCryptoHash(name, payload, key) end --- Configures the address on which to listen. This can be called multiple times --- to set more than one address. If an integer is provided then it should be a --- word-encoded IPv4 address, such as the ones returned by `ResolveIp()`. If a --- string is provided, it will first be passed to ParseIp() to see if it's an --- IPv4 address. If it isn't, then a HOSTS.TXT lookup is performed, with fallback --- to the system-configured DNS resolution service. Please note that in MODE=tiny --- the HOSTS.TXT and DNS resolution isn't included, and therefore an IP must be --- provided. ---@param ip integer ---@overload fun(host:string) function ProgramAddr(ip) end --- Changes HTTP Server header, as well as the `<h1>` title on the `/` listing page. --- The brand string needs to be a UTF-8 value that's encodable as ISO-8859-1. --- If the brand is changed to something other than redbean, then the promotional --- links will be removed from the listing page too. This function should only be --- called from `/.init.lua`. ---@param str string function ProgramBrand(str) end --- Configures Cache-Control and Expires header generation for static asset serving. --- A negative value will disable the headers. Zero means don't cache. Greater than --- zero asks public proxies and browsers to cache for a given number of seconds. --- This should only be called from `/.init.lua`. ---@param seconds integer function ProgramCache(seconds) end --- This function is the same as the -C flag if called from `.init.lua`, e.g. --- `ProgramCertificate(LoadAsset("/.sign.crt"))` for zip loading or --- `ProgramCertificate(Slurp("/etc/letsencrypt.lol/fullchain.pem"))` for local --- file system only. This function is not available in unsecure mode. ---@param pem string function ProgramCertificate(pem) end --- Appends HTTP header to the header buffer for all responses (whereas `SetHeader` --- only appends a header to the current response buffer). name is case-insensitive --- and restricted to non-space ASCII. value is a UTF-8 string that must be --- encodable as ISO-8859-1. Leading and trailing whitespace is trimmed --- automatically. Overlong characters are canonicalized. C0 and C1 control codes --- are forbidden, with the exception of tab. The header buffer is independent of --- the payload buffer. This function disallows the setting of certain headers --- such as Content-Range and Date, which are abstracted by the transport layer. ---@param name string ---@param value string function ProgramHeader(name, value) end --- Sets the heartbeat interval (in milliseconds). 5000ms is the default and 100ms is the minimum. ---@param milliseconds integer Negative values `(<0)` sets the interval in seconds. function ProgramHeartbeatInterval(milliseconds) end ---@param milliseconds integer Negative values `(<0)` sets the interval in seconds. --- Default timeout is 60000ms. Minimal value of timeout is 10(ms). --- This should only be called from `/.init.lua`. function ProgramTimeout(milliseconds) end --- Hard-codes the port number on which to listen, which can be any number in the --- range `1..65535`, or alternatively `0` to ask the operating system to choose a --- port, which may be revealed later on by `GetServerAddr` or the `-z` flag to stdout. ---@param uint16 integer function ProgramPort(uint16) end --- Sets the maximum HTTP message payload size in bytes. The --- default is very conservatively set to 65536 so this is --- something many people will want to increase. This limit is --- enforced at the transport layer, before any Lua code is --- called, because right now redbean stores and forwards --- messages. (Use the UNIX API for raw socket streaming.) Setting --- this to a very high value can be useful if you're less --- concerned about rogue clients and would rather have your Lua --- code be granted more control to bounce unreasonable messages. --- If a value less than 1450 is supplied, it'll automatically be --- increased to 1450, since that's the size of ethernet frames. --- This function can only be called from `.init.lua`. ---@param int integer function ProgramMaxPayloadSize(int) end --- This function is the same as the -K flag if called from .init.lua, e.g. --- `ProgramPrivateKey(LoadAsset("/.sign.key"))` for zip loading or --- `ProgramPrivateKey(Slurp("/etc/letsencrypt/privkey.pem"))` for local file --- system only. This function is not available in unsecure mode. ---@param pem string function ProgramPrivateKey(pem) end --- Configures fallback routing for paths which would otherwise return 404 Not --- Found. If code is `0` then the path is rewritten internally as an accelerated --- redirect. If code is `301`, `302`, `307`, or `308` then a redirect response --- will be sent to the client. This should only be called from `/.init.lua`. ---@param code integer ---@param src string ---@param location string function ProgramRedirect(code, src, location) end --- Defaults to `86400` (24 hours). This may be set to `≤0` to disable SSL tickets. --- It's a good idea to use these since it increases handshake performance 10x and --- eliminates a network round trip. This function is not available in unsecure mode. ---@param seconds integer function ProgramSslTicketLifetime(seconds) end --- This function can be used to enable the PSK ciphersuites which simplify SSL --- and enhance its performance in controlled environments. key may contain 1..32 --- bytes of random binary data and identity is usually a short plaintext string. --- The first time this function is called, the preshared key will be added to --- both the client and the server SSL configs. If it's called multiple times, --- then the remaining keys will be added to the server, which is useful if you --- want to assign separate keys to each client, each of which needs a separate --- identity too. If this function is called multiple times with the same identity --- string, then the latter call will overwrite the prior. If a preshared key is --- supplied and no certificates or key-signing-keys are programmed, then redbean --- won't bother auto-generating any serving certificates and will instead use --- only PSK ciphersuites. This function is not available in unsecure mode. ---@param key string ---@param identity string function ProgramSslPresharedKey(key, identity) end --- May be used to disable the verification of certificates --- for remote hosts when using the Fetch() API. This function is --- not available in unsecure mode. ---@param enabled boolean function ProgramSslFetchVerify(enabled) end --- Enables the verification of certificates supplied by the HTTP clients that --- connect to your redbean. This has the same effect as the -j flag. Tuning this --- option alone does not preclude the possibility of unsecured HTTP clients, which --- can be disabled using ProgramSslRequired(). This function can only be called --- from `.init.lua`. This function is not available in unsecure mode. ---@param enabled boolean function ProgramSslClientVerify(enabled) end --- Enables the blocking of HTTP so that all inbound clients and must use the TLS --- transport layer. This has the same effect as the -J flag. `Fetch()` is still --- allowed to make outbound HTTP requests. This function can only be called from --- `.init.lua`. This function is not available in unsecure mode. ---@param mandatory string function ProgramSslRequired(mandatory) end --- This function may be called multiple times to specify the subset of available --- ciphersuites you want to use in both the HTTPS server and the `Fetch()` client. --- The default list, ordered by preference, is as follows: --- --- - ECDHE-ECDSA-AES256-GCM-SHA384 --- - ECDHE-ECDSA-AES128-GCM-SHA256 --- - ECDHE-ECDSA-CHACHA20-POLY1305-SHA256 --- - ECDHE-PSK-AES256-GCM-SHA384 --- - ECDHE-PSK-AES128-GCM-SHA256 --- - ECDHE-PSK-CHACHA20-POLY1305-SHA256 --- - ECDHE-RSA-AES256-GCM-SHA384 --- - ECDHE-RSA-AES128-GCM-SHA256 --- - ECDHE-RSA-CHACHA20-POLY1305-SHA256 --- - DHE-RSA-AES256-GCM-SHA384 --- - DHE-RSA-AES128-GCM-SHA256 --- - DHE-RSA-CHACHA20-POLY1305-SHA256 --- - ECDHE-ECDSA-AES128-CBC-SHA256 --- - ECDHE-RSA-AES256-CBC-SHA384 --- - ECDHE-RSA-AES128-CBC-SHA256 --- - DHE-RSA-AES256-CBC-SHA256 --- - DHE-RSA-AES128-CBC-SHA256 --- - ECDHE-PSK-AES256-CBC-SHA384 --- - ECDHE-PSK-AES128-CBC-SHA256 --- - ECDHE-ECDSA-AES256-CBC-SHA --- - ECDHE-ECDSA-AES128-CBC-SHA --- - ECDHE-RSA-AES256-CBC-SHA --- - ECDHE-RSA-AES128-CBC-SHA --- - DHE-RSA-AES256-CBC-SHA --- - DHE-RSA-AES128-CBC-SHA --- - ECDHE-PSK-AES256-CBC-SHA --- - ECDHE-PSK-AES128-CBC-SHA --- - RSA-AES256-GCM-SHA384 --- - RSA-AES128-GCM-SHA256 --- - RSA-AES256-CBC-SHA256 --- - RSA-AES128-CBC-SHA256 --- - RSA-AES256-CBC-SHA --- - RSA-AES128-CBC-SHA --- - PSK-AES256-GCM-SHA384 --- - PSK-AES128-GCM-SHA256 --- - PSK-CHACHA20-POLY1305-SHA256 --- - PSK-AES256-CBC-SHA384 --- - PSK-AES128-CBC-SHA256 --- - PSK-AES256-CBC-SHA --- - PSK-AES128-CBC-SHA --- - ECDHE-RSA-3DES-EDE-CBC-SHA --- - DHE-RSA-3DES-EDE-CBC-SHA --- - ECDHE-PSK-3DES-EDE-CBC-SHA --- - RSA-3DES-EDE-CBC-SHA --- - PSK-3DES-EDE-CBC-SHA --- --- When redbean is run on an old (or low-power) CPU that doesn't have the AES-NI --- instruction set (Westmere c. 2010) then the default ciphersuite is tuned --- automatically to favor the ChaCha20 Poly1305 suites. --- --- The names above are canonical to redbean. They were programmatically simplified --- from the official IANA names. This function will accept the IANA names too. In --- most cases it will accept the OpenSSL and GnuTLS naming convention as well. --- --- This function is not available in unsecure mode. ---@param name string function ProgramSslCiphersuite(name) end --- Returns `true` if `-d` flag was passed to redbean. ---@return boolean ---@nodiscard function IsDaemon() end --- Same as the `-U` flag if called from `.init.lua` for `setuid()` function ProgramUid(int) end --- Same as the `-G` flag if called from `.init.lua` for `setgid()` ---@param int integer function ProgramGid(int) end --- Same as the `-D` flag if called from `.init.lua` for overlaying local file --- system directories. This may be called multiple times. The first directory --- programmed is preferred. These currently do not show up in the index page listing. ---@param str string function ProgramDirectory(str) end --- Same as the `-m` flag if called from `.init.lua` for logging message headers only. ---@param bool boolean function ProgramLogMessages(bool) end --- Same as the `-b` flag if called from `.init.lua` for logging message bodies as --- part of `POST` / `PUT` / etc. requests. ---@param bool boolean function ProgramLogBodies(bool) end --- Same as the `-L` flag if called from `.init.lua` for setting the log file path --- on the local file system. It's created if it doesn't exist. This is called --- before de-escalating the user / group id. The file is opened in append only --- mode. If the disk runs out of space then redbean will truncate the log file if --- has access to change the log file after daemonizing. ---@param bool boolean function ProgramLogPath(bool) end --- Same as the `-P` flag if called from `.init.lua` for setting the pid file path --- on the local file system. It's useful for reloading daemonized redbean using --- `kill -HUP $(cat /var/run/redbean.pid)` or terminating redbean with --- `kill $(cat /var/run/redbean.pid)` which will gracefully terminate all clients. --- Sending the `TERM` signal twice will cause a forceful shutdown, which might --- make someone with a slow internet connection who's downloading big files unhappy. ---@param str string function ProgramPidPath(str) end --- Same as the `-u` flag if called from `.init.lua`. Can be used to configure the --- uniprocess mode. The current value is returned. ---@param bool boolean? ---@return boolean function ProgramUniprocess(bool) end --- Reads all data from file the easy way. --- --- This function reads file data from local file system. Zip file assets can be --- accessed using the `/zip/...` prefix. --- --- `i` and `j` may be used to slice a substring in filename. These parameters are --- 1-indexed and behave consistently with Lua's `string.sub()` API. For example: --- --- assert(Barf('x.txt', 'abc123')) --- assert(assert(Slurp('x.txt', 2, 3)) == 'bc') --- --- This function is uninterruptible so `unix.EINTR` errors will be ignored. This --- should only be a concern if you've installed signal handlers. Use the UNIX API --- if you need to react to it. --- ---@param filename string ---@param i integer ---@param j integer ---@return string data ---@nodiscard ---@overload fun(filename: string, i: integer, j: integer): nil, unix.Errno function Slurp(filename, i, j) end --- Writes all data to file the easy way. --- --- This function writes to the local file system. --- ---@param filename string ---@param data string ---@param mode integer? defaults to 0644. This parameter is ignored when flags doesn't have `unix.O_CREAT`. --- ---@param flags integer? defaults to `unix.O_TRUNC | unix.O_CREAT`. --- ---@param offset integer? is 1-indexed and may be used to overwrite arbitrary slices within a file when used in conjunction with `flags=0`. --- For example: --- --- assert(Barf('x.txt', 'abc123')) --- assert(Barf('x.txt', 'XX', 0, 0, 3)) --- assert(assert(Slurp('x.txt', 1, 6)) == 'abXX23') --- ---@return true ---@overload fun(filename: string, data: string, mode?: integer, flags?: integer, offset?: integer): nil, error: unix.Errno function Barf(filename, data, mode, flags, offset) end --- Sleeps the specified number of seconds (can be fractional). --- The smallest interval is a microsecond. ---@param seconds number function Sleep(seconds) end --- Instructs redbean to follow the normal HTTP serving path. This function is --- useful when writing an OnHttpRequest handler, since that overrides the --- serving path entirely. So if the handler decides it doesn't want to do --- anything, it can simply call this function, to hand over control back to the --- redbean core. By default, the host and path arguments are supplied from the --- resolved `GetUrl` value. This handler always resolves, since it will generate --- a 404 Not Found response if redbean couldn't find an appropriate endpoint. ---@param host string? ---@param path string? function Route(host, path) end --- This is the same as `Route`, except it only implements the subset of request --- routing needed for serving virtual-hosted assets, where redbean tries to prefix --- the path with the hostname when looking up a file. This function returns `true` --- if the request was resolved. If it was resolved, then your `OnHttpRequest` --- request handler can still set additional headers. ---@param host string? ---@param path string? ---@return boolean function RouteHost(host, path) end --- This is the same as `Route`, except it only implements the subset of request --- routing needed for serving assets. This function returns `true` if the --- request was resolved. If it was resolved, then your `OnHttpRequest` request --- handler can still set additional headers. ---@param path string? ---@return boolean function RoutePath(path) end --- Instructs redbean to serve static asset at path. This function causes what --- would normally happen outside a dynamic handler to happen. The asset can be --- sourced from either the zip or local filesystem if `-D` is used. This function --- is mutually exclusive with `SetStatus` and `ServeError`. ---@param path string function ServeAsset(path) end --- Instructs redbean to serve a boilerplate error page. This takes care of logging --- the error, setting the reason phrase, and adding a payload. This function is --- mutually exclusive with `SetStatus` and `ServeAsset`. ---@param code integer ---@param reason string? function ServeError(code, reason) end --- Instructs redbean to return the specified redirect code along with --- the Location header set. This function is mutually exclusive with --- `SetStatus` and other `Serve*` functions. --- ---@param code integer ---@param location string function ServeRedirect(code, location) end --- Sets logger verbosity. Reasonable values for level are `kLogDebug` > --- `kLogVerbose` > `kLogInfo` > `kLogWarn` > `kLogError` > `kLogFatal`. ---@param level integer function SetLogLevel(level) end --- Replaces C0 control codes and trojan source characters with descriptive --- UNICODE pictorial representation. This function also canonicalizes overlong --- encodings. C1 control codes are replaced with a JavaScript-like escape sequence. ---@param str string ---@return string ---@nodiscard function VisualizeControlCodes(str) end --- Canonicalizes overlong encodings. ---@param str string ---@return string ---@nodiscard function Underlong(str) end ---@param x integer ---@return integer # position of first bit set. --- Passing `0` will raise an error. Same as the Intel x86 instruction BSF. ---@nodiscard function Bsf(x) end ---@param x integer ---@return integer # binary logarithm of `x` --- Passing `0` will raise an error. Same as the Intel x86 instruction BSR. ---@nodiscard function Bsr(x) end --- Computes Phil Katz CRC-32 used by zip/zlib/gzip/etc. ---@param initial integer ---@param data string ---@return integer ---@nodiscard function Crc32(initial, data) end --- Computes 32-bit Castagnoli Cyclic Redundancy Check. ---@param initial integer ---@param data string ---@return integer ---@nodiscard function Crc32c(initial, data) end --- Returns number of bits set in integer. ---@param x integer ---@return integer ---@nodiscard function Popcnt(x) end --- Returns CPU timestamp counter. ---@return integer ---@nodiscard function Rdtsc() end ---@return integer # fastest pseudorandom non-cryptographic random number. --- This linear congruential generator passes practrand and bigcrush. ---@nodiscard function Lemur64() end ---@return integer # nondeterministic pseudorandom non-cryptographic number. --- This linear congruential generator passes practrand and bigcrush. This --- generator is safe across `fork()`, threads, and signal handlers. ---@nodiscard function Rand64() end ---@return integer # 64-bit hardware random integer from RDRND instruction, with automatic fallback to `getrandom()` if not available. ---@nodiscard function Rdrand() end ---@return integer # 64-bit hardware random integer from `RDSEED` instruction, with automatic fallback to `RDRND` and `getrandom()` if not available. ---@nodiscard function Rdseed() end ---@return integer cpucount CPU core count or `0` if it couldn't be determined. ---@nodiscard function GetCpuCount() end ---@return integer # 0-indexed CPU core on which process is currently scheduled. ---@nodiscard function GetCpuCore() end ---@return integer # 0-indexed NUMA node on which process is currently scheduled. ---@nodiscard function GetCpuNode() end --- Shrinks byte buffer in half using John Costella's magic kernel. This downscales --- data 2x using an eight-tap convolution, e.g. --- --- >: Decimate('\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00') --- "\xff\x00\xff\x00\xff\x00" --- --- This is very fast if SSSE3 is available (Intel 2004+ / AMD 2011+). ---@param data string ---@return string ---@nodiscard function Decimate(data) end ---@param data string ---@return number # Shannon entropy of `data`. --- This gives you an idea of the density of information. Cryptographic random --- should be in the ballpark of `7.9` whereas plaintext will be more like `4.5`. ---@nodiscard function MeasureEntropy(data) end --- Compresses data. --- --- >: Deflate("hello") --- "\xcbH\xcd\xc9\xc9\x07\x00" --- >: Inflate("\xcbH\xcd\xc9\xc9\x07\x00", 5) --- "hello" --- --- The output format is raw DEFLATE that's suitable for embedding into formats --- like a ZIP file. It's recommended that, like ZIP, you also store separately a --- `Crc32()` checksum in addition to the original uncompressed size. --- ---@param uncompressed string ---@param level integer? the compression level, which defaults to `7`. The max is `9`. --- Lower numbers go faster (4 for instance is a sweet spot) and higher numbers go --- slower but have better compression. ---@return string compressed ---@nodiscard ---@overload fun(uncompressed: string, level?: integer): nil, error: string function Deflate(uncompressed, level) end --- Decompresses data. --- --- This function performs the inverse of Deflate(). It's recommended that you --- perform a `Crc32()` check on the output string after this function succeeds. --- ---@param compressed string ---@param maxoutsize integer the uncompressed size, which should be known. --- However, it is permissable (although not advised) to specify some large number --- in which case (on success) the byte length of the output string may be less --- than `maxoutsize`. ---@return string uncompressed ---@nodiscard ---@overload fun(compressed: string, maxoutsize: integer): nil, error: string function Inflate(compressed, maxoutsize) end --- Performs microbenchmark. Nanoseconds are computed from RDTSC tick counts, --- using an approximation that's measured beforehand with the --- unix.`clock_gettime()` function. The `ticks` result is the canonical average --- number of clock ticks. This subroutine will subtract whatever the overhead --- happens to be for benchmarking a function that does nothing. This overhead --- value will be reported in the result. `tries` indicates if your microbenchmark --- needed to be repeated, possibly because your system is under load and the --- benchmark was preempted by the operating system, or moved to a different core. ---@param func function ---@param count integer? ---@param maxattempts integer? ---@return number nanoseconds the average number of nanoseconds that `func` needed to execute ---@return integer ticks ---@return integer overhead_ticks ---@return integer tries ---@nodiscard function Benchmark(func, count, maxattempts) end --- Formats string as octal integer literal string. If the provided value is zero, --- the result will be `"0"`. Otherwise the resulting value will be the --- zero-prefixed octal string. The result is currently modulo 2^64. Negative --- numbers are converted to unsigned. ---@param int integer ---@return string ---@nodiscard function oct(int) end --- Formats string as hexadecimal integer literal string. If the provided value is --- zero, the result will be `"0"`. Otherwise the resulting value will be the --- "0x"-prefixed hex string. The result is currently modulo 2^64. Negative numbers --- are converted to unsigned. ---@param int integer ---@return string ---@nodiscard function hex(int) end --- Formats string as binary integer literal string. If the provided value is zero, --- the result will be `"0"`. Otherwise the resulting value will be the --- "0b"-prefixed binary str. The result is currently modulo 2^64. Negative numbers --- are converted to unsigned. ---@param int integer ---@return string ---@nodiscard function bin(int) end --- Gets IP address associated with hostname. --- --- This function first checks if hostname is already an IP address, in which case --- it returns the result of `ParseIp`. Otherwise, it checks HOSTS.TXT on the local --- system and returns the first IPv4 address associated with hostname. If no such --- entry is found, a DNS lookup is performed using the system configured (e.g. --- `/etc/resolv.conf`) DNS resolution service. If the service returns multiple IN --- A records then only the first one is returned. --- --- The returned address is word-encoded in host endian order. For example, --- 1.2.3.4 is encoded as 0x01020304. The `FormatIp` function may be used to turn --- this value back into a string. --- --- If no IP address could be found, then `nil` is returned alongside a string of --- unspecified format describing the error. Calls to this function may be wrapped --- in `assert()` if an exception is desired. ---@param hostname string ---@return uint32 ip uint32 ---@nodiscard ---@overload fun(hostname: string): nil, error: string function ResolveIp(hostname) end -- MODULES ---Please refer to the LuaSQLite3 Documentation. --- --- For example, you could put the following in your `/.init.lua` file: --- --- lsqlite3 = require "lsqlite3" --- db = lsqlite3.open_memory() --- db:exec[[ --- CREATE TABLE test ( --- id INTEGER PRIMARY KEY, --- content TEXT --- ); --- INSERT INTO test (content) VALUES ('Hello World'); --- INSERT INTO test (content) VALUES ('Hello Lua'); --- INSERT INTO test (content) VALUES ('Hello Sqlite3'); --- ]] --- --- Then, your Lua server pages or OnHttpRequest handler may perform SQL --- queries by accessing the db global. The performance is good too, at about --- 400k qps. --- --- for row in db:nrows("SELECT * FROM test") do --- Write(row.id.." "..row.content.."<br>") --- end --- --- redbean supports a subset of what's defined in the upstream LuaSQLite3 --- project. Most of the unsupported APIs relate to pointers and database --- notification hooks. lsqlite3 = { -- Error Codes --- The `lsqlite3.OK` result code means that the operation was successful --- and that there were no errors. Most other result codes indicate an --- error. OK = 0, --- The `lsqlite3.ERROR` result code is a generic error code that is used --- when no other more specific error code is available. ERROR = 1, --- The `lsqlite3.INTERNAL` result code indicates an internal malfunction. --- In a working version of SQLite, an application should never see this --- result code. If application does encounter this result code, it shows --- that there is a bug in the database engine. --- --- SQLite does not currently generate this result code. However, --- application-defined SQL functions or virtual tables, or VFSes, or other --- extensions might cause this result code to be returned. INTERNAL = 2, --- The `lsqlite3.PERM` result code indicates that the requested access mode --- for a newly created database could not be provided. PERM = 3, --- The `lsqlite3.ABORT` result code indicates that an operation was aborted --- prior to completion, usually be application request. See also: --- `lsqlite3.INTERRUPT`. --- --- If the callback function to `exec()` returns non-zero, then `exec()` --- will return `lsqlite3.ABORT`. --- --- If a ROLLBACK operation occurs on the same database connection as a --- pending read or write, then the pending read or write may fail with an --- `lsqlite3.ABORT` error. ABORT = 4, --- The lsqlite3.BUSY result code indicates that the database file could not --- be written (or in some cases read) because of concurrent activity by --- some other database connection, usually a database connection in a --- separate process. --- --- For example, if process A is in the middle of a large write transaction --- and at the same time process B attempts to start a new write --- transaction, process B will get back an `lsqlite3.BUSY` result because --- SQLite only supports one writer at a time. Process B will need to wait --- for process A to finish its transaction before starting a new --- transaction. The `db:busy_timeout()` and `db:busy_handler()` interfaces --- are available to process B to help it deal with `lsqlite3.BUSY` errors. --- --- An `lsqlite3.BUSY` error can occur at any point in a transaction: when --- the transaction is first started, during any write or update operations, --- or when the transaction commits. To avoid encountering `lsqlite3.BUSY` --- errors in the middle of a transaction, the application can use --- `BEGIN IMMEDIATE` instead of just `BEGIN` to start a transaction. The --- `BEGIN IMMEDIATE` command might itself return `lsqlite3.BUSY`, but if it --- succeeds, then SQLite guarantees that no subsequent operations on the same database through the next COMMIT will return `lsqlite3.BUSY`. --- --- The `lsqlite3.BUSY` result code differs from `lsqlite3.LOCKED` in that --- `lsqlite3.BUSY` indicates a conflict with a separate database --- connection, probably in a separate process, whereas `lsqlite3.LOCKED` --- indicates a conflict within the same database connection (or sometimes --- a database connection with a shared cache). BUSY = 5, --- The `lsqlite3.LOCKED` result code indicates that a write operation could --- not continue because of a conflict within the same database connection --- or a conflict with a different database connection that uses a shared --- cache. --- --- For example, a DROP TABLE statement cannot be run while another thread --- is reading from that table on the same database connection because --- dropping the table would delete the table out from under the concurrent --- reader. --- --- The `lsqlite3.LOCKED` result code differs from `lsqlite3.BUSY` in that --- `lsqlite3.LOCKED` indicates a conflict on the same database connection --- (or on a connection with a shared cache) whereas `lsqlite3.BUSY` --- indicates a conflict with a different database connection, probably in --- a different process. LOCKED = 6, --- The `lsqlite3.NOMEM` result code indicates that SQLite was unable to --- allocate all the memory it needed to complete the operation. In other --- words, an internal call to `sqlite3_malloc()` or `sqlite3_realloc()` has --- failed in a case where the memory being allocated was required in order --- to continue the operation. NOMEM = 7, --- The `lsqlite3.READONLY` result code is returned when an attempt is made --- to alter some data for which the current database connection does not --- have write permission. READONLY = 8, --- The `lsqlite3.INTERRUPT` result code indicates that an operation was --- interrupted by the `sqlite3_interrupt()` interface. See also: --- `lsqlite3.ABORT` INTERRUPT = 9, --- The `lsqlite3.IOERR` result code says that the operation could not --- finish because the operating system reported an I/O error. --- --- A full disk drive will normally give an `lsqlite3.FULL` error rather --- than an `lsqlite3.IOERR` error. --- --- There are many different extended result codes for I/O errors that --- identify the specific I/O operation that failed. IOERR = 10, --- The `lsqlite3.CORRUPT` result code indicates that the database file has --- been corrupted. See [How To Corrupt Your Database Files](https://www.sqlite.org/lockingv3.html#how_to_corrupt) --- for further discussion on how corruption can occur. CORRUPT = 11, --- The `lsqlite3.NOTFOUND` result code is exposed in three ways: --- --- `lsqlite3.NOTFOUND` can be returned by the `sqlite3_file_control()` --- interface to indicate that the file control opcode passed as the third --- argument was not recognized by the underlying VFS. --- --- `lsqlite3.NOTFOUND` can also be returned by the xSetSystemCall() method --- of an sqlite3_vfs object. --- --- `lsqlite3.NOTFOUND` an be returned by sqlite3_vtab_rhs_value() to --- indicate that the right-hand operand of a constraint is not available --- to the xBestIndex method that made the call. --- --- The `lsqlite3.NOTFOUND` result code is also used internally by the --- SQLite implementation, but those internal uses are not exposed to the --- application. NOTFOUND = 12, --- The `lsqlite3.FULL` result code indicates that a write could not --- complete because the disk is full. Note that this error can occur when --- trying to write information into the main database file, or it can also --- occur when writing into temporary disk files. --- --- Sometimes applications encounter this error even though there is an --- abundance of primary disk space because the error occurs when writing --- into temporary disk files on a system where temporary files are stored --- on a separate partition with much less space that the primary disk. FULL = 13, --- The `lsqlite3.CANTOPEN` result code indicates that SQLite was unable to --- open a file. The file in question might be a primary database file or --- one of several temporary disk files. CANTOPEN = 14, --- The `lsqlite3.PROTOCOL` result code indicates a problem with the file --- locking protocol used by SQLite. The `lsqlite3.PROTOCOL` error is --- currently only returned when using WAL mode and attempting to start a --- new transaction. There is a race condition that can occur when two --- separate database connections both try to start a transaction at the --- same time in WAL mode. The loser of the race backs off and tries again, --- after a brief delay. If the same connection loses the locking race --- dozens of times over a span of multiple seconds, it will eventually give --- up and return `lsqlite3.PROTOCOL`. The `lsqlite3.PROTOCOL` error should --- appear in practice very, very rarely, and only when there are many --- separate processes all competing intensely to write to the same --- database. PROTOCOL = 15, --- The `lsqlite3.EMPTY` result code is not currently used. EMPTY = 16, --- The `lsqlite3.SCHEMA` result code indicates that the database schema has --- changed. This result code can be returned from `Statement:step()`. If --- the database schema was changed by some other process in between the --- time that the statement was prepared and the time the statement was run, --- this error can result. --- --- The statement is automatically re-prepared if the schema changes, up to --- `SQLITE_MAX_SCHEMA_RETRY` times (default: 50). The `step()` interface --- will only return `lsqlite3.SCHEMA` back to the application if the --- failure persists after these many retries. SCHEMA = 17, --- The `lsqlite3.TOOBIG` error code indicates that a string or BLOB was too --- large. The default maximum length of a string or BLOB in SQLite is --- 1,000,000,000 bytes. This maximum length can be changed at compile-time --- using the `SQLITE_MAX_LENGTH` compile-time option. The `lsqlite3.TOOBIG` --- error results when SQLite encounters a string or BLOB that exceeds the --- compile-time limit. --- --- The `lsqlite3.TOOBIG` error code can also result when an oversized SQL --- statement is passed into one of the `db:prepare()` interface. The --- maximum length of an SQL statement defaults to a much smaller value of --- 1,000,000,000 bytes. TOOBIG = 18, --- The `lsqlite3.CONSTRAINT` error code means that an SQL constraint --- violation occurred while trying to process an SQL statement. Additional --- information about the failed constraint can be found by consulting the --- accompanying error message (returned via `errmsg()`) or by looking at --- the extended error code. --- --- The `lsqlite3.CONSTRAINT` code can also be used as the return value from --- the `xBestIndex()` method of a virtual table implementation. When --- `xBestIndex()` returns `lsqlite3.CONSTRAINT`, that indicates that the --- particular combination of inputs submitted to `xBestIndex()` cannot --- result in a usable query plan and should not be given further --- consideration. CONSTRAINT = 19, --- SQLite is normally very forgiving about mismatches between the type of a --- value and the declared type of the container in which that value is to --- be stored. For example, SQLite allows the application to store a large --- BLOB in a column with a declared type of BOOLEAN. But in a few cases, --- SQLite is strict about types. The `lsqlite3.MISMATCH` error is returned --- in those few cases when the types do not match. --- --- The rowid of a table must be an integer. Attempt to set the rowid to --- anything other than an integer (or a NULL which will be automatically --- converted into the next available integer rowid) results in an --- `lsqlite3.MISMATCH` error. MISMATCH = 20, --- The `lsqlite3.MISUSE` return code might be returned if the application --- uses any SQLite interface in a way that is undefined or unsupported. For --- example, using a prepared statement after that prepared statement has --- been finalized might result in an `lsqlite3.MISUSE` error. --- --- SQLite tries to detect misuse and report the misuse using this result --- code. However, there is no guarantee that the detection of misuse will --- be successful. Misuse detection is probabilistic. Applications should --- never depend on an `lsqlite3.MISUSE` return value. --- --- If SQLite ever returns `lsqlite3.MISUSE` from any interface, that means --- that the application is incorrectly coded and needs to be fixed. Do not --- ship an application that sometimes returns `lsqlite3.MISUSE` from a --- standard SQLite interface because that application contains potentially --- serious bugs. MISUSE = 21, --- The `lsqlite3.NOLFS` error can be returned on systems that do not --- support large files when the database grows to be larger than what the --- filesystem can handle. "NOLFS" stands for "NO Large File Support". NOLFS = 22, --- The `lsqlite3.FORMAT` error code is not currently used by SQLite. FORMAT = 24, --- The `lsqlite3.RANGE` error indices that the parameter number argument to --- one of the `bind` routines or the column number in one of the `column` --- routines is out of range. RANGE = 25, --- When attempting to open a file, the `lsqlite3.NOTADB` error indicates --- that the file being opened does not appear to be an SQLite database --- file. NOTADB = 26, --- The `lsqlite3.ROW` result code returned by sqlite3_step() indicates that --- another row of output is available. ROW = 100, --- The `lsqlite3.DONE` result code indicates that an operation has --- completed. The `lsqlite3.DONE` result code is most commonly seen as a --- return value from `step()` indicating that the SQL statement has run to --- completion, but `lsqlite3.DONE` can also be returned by other multi-step --- interfaces. DONE = 101, -- Authorizer Action Codes CREATE_INDEX = 1, CREATE_TABLE = 2, CREATE_TEMP_INDEX = 3, CREATE_TEMP_TABLE = 4, CREATE_TEMP_TRIGGER = 5, CREATE_TEMP_VIEW = 6, CREATE_TRIGGER = 7, CREATE_VIEW = 8, DELETE = 9, DROP_INDEX = 10, DROP_TABLE = 11, DROP_TEMP_INDEX = 12, DROP_TEMP_TABLE = 13, DROP_TEMP_TRIGGER = 14, DROP_TEMP_VIEW = 15, DROP_TRIGGER = 16, DROP_VIEW = 17, INSERT = 18, PRAGMA = 19, READ = 20, SELECT = 21, TRANSACTION = 22, UPDATE = 23, ATTACH = 24, DETACH = 25, ALTER_TABLE = 26, REINDEX = 27, ANALYZE = 28, CREATE_VTABLE = 29, DROP_VTABLE = 30, FUNCTION = 31, SAVEPOINT = 32, -- Open Flags ---@type integer --- The database is created if it does not already exist. OPEN_CREATE = nil, ---@type integer --- The database is opened with shared cache disabled, overriding the --- default shared cache setting provided by sqlite3_enable_shared_cache(). OPEN_PRIVATECACHE = nil, ---@type integer --- The new database connection will use the "serialized" threading mode. --- This means the multiple threads can safely attempt to use the same --- database connection at the same time. (Mutexes will block any actual --- concurrency, but in this mode there is no harm in trying.) OPEN_FULLMUTEX = nil, ---@type integer --- The new database connection will use the "multi-thread" threading mode. --- This means that separate threads are allowed to use SQLite at the same --- time, as long as each thread is using a different database connection. OPEN_NOMUTEX = nil, ---@type integer --- The database will be opened as an in-memory database. The database is --- named by the "filename" argument for the purposes of cache-sharing, if --- shared cache mode is enabled, but the "filename" is otherwise ignored. OPEN_MEMORY = nil, ---@type integer --- The filename can be interpreted as a URI if this flag is set. See --- https://www.sqlite.org/c3ref/open.html OPEN_URI = nil, ---@type integer --- The database is opened for reading and writing if possible, or reading --- only if the file is write protected by the operating system. In either --- case the database must already exist, otherwise an error is returned. OPEN_READWRITE = nil, ---@type integer --- The database is opened in read-only mode. If the database does not --- already exist, an error is returned. OPEN_READONLY = nil, ---@type integer --- The database is opened shared cache enabled, overriding the default --- shared cache setting provided by sqlite3_enable_shared_cache(). The use --- of shared cache mode is discouraged and hence shared cache capabilities --- may be omitted from many builds of SQLite. In such cases, this option is --- a no-op. OPEN_SHAREDCACHE = nil, ---@type integer TEXT = nil, ---@type integer BLOB = nil, ---@type integer NULL = nil, ---@type integer FLOAT = nil, } --- Opens (or creates if it does not exist) an SQLite database with name filename --- and returns its handle as userdata (the returned object should be used for all --- further method calls in connection with this specific database, see Database --- methods). Example: --- --- myDB = lsqlite3.open('MyDatabase.sqlite3') -- open --- -- do some database calls... --- myDB:close() -- close --- --- In case of an error, the function returns `nil`, an error code and an error message. --- --- Since `0.9.4`, there is a second optional `flags` argument to `lsqlite3.open`. --- See https://www.sqlite.org/c3ref/open.html for an explanation of these flags and options. --- --- local db = lsqlite3.open('foo.db', lsqlite3.OPEN_READWRITE + lsqlite3.OPEN_CREATE + lsqlite3.OPEN_SHAREDCACHE) --- ---@param filename string ---@param flags? integer defaults to `lsqlite3.OPEN_READWRITE + lsqlite3.OPEN_CREATE` ---@return lsqlite3.Database db ---@nodiscard ---@overload fun(filename: string, flags?: integer): nil, errorcode: integer, errormsg: string function lsqlite3.open(filename, flags) end --- Opens an SQLite database in memory and returns its handle as userdata. In case --- of an error, the function returns `nil`, an error code and an error message. --- (In-memory databases are volatile as they are never stored on disk.) ---@return lsqlite3.Database db ---@nodiscard ---@overload fun(): nil, errorcode: integer, errormsg: string function lsqlite3.open_memory() end ---@return string version lsqlite3 library version information, in the form 'x.y[.z]'. ---@nodiscard function lsqlite3.lversion() end ---@return string version SQLite version information, in the form 'x.y[.z[.p]]'. ---@nodiscard function lsqlite3.version() end ---@class lsqlite3.Context: userdata --- A callback context is available as a parameter inside the callback functions --- `db:create_aggregate()` and `db:create_function()`. It can be used to get --- further information about the state of a query. local Context = nil ---@return any udata the user-definable data field for callback funtions. ---@nodiscard function Context:get_aggregate_data() end --- Set the user-definable data field for callback funtions to `udata`. function Context:set_aggregate_data(udata) end --- Sets the result of a callback function to `res`. The type of the result --- depends on the type of `res` and is either a number or a string or `nil`. --- All other values will raise an error message. ---@param res string|number? function Context:result(res) end --- Sets the result of a callback function to the binary string in blob. ---@param blob string function Context:result_blob(blob) end --- Sets the result of a callback function to the value number. ---@param double number function Context:result_double(double) end Context.result_number = Context.result_double --- Sets the result of a callback function to the error value in `err`. function Context:result_error(err) end --- Sets the result of a callback function to the integer `number` ---@param number integer function Context:result_int(number) end --- Sets the result of a callback function to `nil`. function Context:result_null() end --- Sets the result of a callback function to the string in `str`. ---@param str string function Context:result_text(str) end --- Returns the userdata parameter given in the call to install the callback --- function (see db:create_aggregate() and db:create_function() for details). ---@return any function Context:user_data() end ---@class lsqlite3.Database: userdata --- After opening a database with `lsqlite3.open()` or `lsqlite3.open_memory()` --- the returned database object should be used for all further method calls in --- connection with that database. local Database = {} ---@param changeset string ---@param filter_cb function ---@param conflict_cb function ---@param udata? any ---@param rebaser? lsqlite3.Rebaser ---@param flags? integer ---@return true ---@overload fun(db: lsqlite3.Database, changeset: string, filter_cb: function, conflict_cb: function, udata?, rebaser?: lsqlite3.Rebaser, flags?: integer): nil, errno: integer ---@overload fun(db: lsqlite3.Database, changeset: string, conflict_cb?: function, udata?, rebaser?: lsqlite3.Rebaser, flags?: integer): true ---@overload fun(db: lsqlite3.Database, changeset: string, conflict_cb?: function, udata?, rebaser?: lsqlite3.Rebaser, flags?: integer): nil, errno: integer ---@overload fun(db: lsqlite3.Database, changeset: string, filter_cb: function, conflict_cb: function, udata?): true ---@overload fun(db: lsqlite3.Database, changeset: string, filter_cb: function, conflict_cb: function, udata?): nil, errno: integer ---@overload fun(db: lsqlite3.Database, changeset: string, conflict_cb?: function, udata?): true ---@overload fun(db: lsqlite3.Database, changeset: string, conflict_cb?: function, udata?): nil, errno: integer function Database:apply_changeset(changeset, conflict_cb, filter_cb, udata, rebaser, flags) end --- Sets or removes a busy handler for a database. ---@generic Udata ---@param func fun(udata: Udata, tries: integer)? is either a Lua function that implements the busy handler or `nil` to remove a previously set handler. This function returns nothing. ---@param udata? Udata --- The handler function is called with two parameters: `udata` and the number --- of (re-)tries for a pending transaction. It should return `nil`, `false` or --- `0` if the transaction is to be aborted. All other values will result in --- another attempt to perform the transaction. (See the SQLite documentation --- for important hints about writing busy handlers.) function Database:busy_handler(func, udata) end --- Sets a busy handler that waits for `milliseconds` if a transaction cannot proceed. --- Calling this function will remove any busy handler set by `db:busy_handler()`; --- calling it with an argument less than or equal to `0` will turn off all busy handlers. ---@param milliseconds integer function Database:busy_timeout(milliseconds) end ---@return integer # the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. ---@nodiscard --- Only changes that are directly specified by INSERT, UPDATE, or DELETE --- statements are counted. Auxiliary changes caused by triggers are not --- counted. Use `db:total_changes()` to find the total number of changes. function Database:changes() end --- Closes a database. All SQL statements prepared using `db:prepare()` should --- have been finalized before this function is called. The function returns --- `lsqlite3.OK` on success or else a numerical error code. ---@return integer function Database:close() end --- Finalizes all statements that have not been explicitly finalized. If --- `temponly` is `true`, only internal, temporary statements are finalized. ---@param temponly? boolean function Database:close_vm(temponly) end --- This function installs a `commit_hook` callback handler. ---@generic Udata ---@param func fun(udata: Udata) a Lua function that is invoked by SQLite3 whenever a transaction is committed. This callback receives one argument: ---@param udata Udata argument used when the callback was installed. --- --- If `func` returns `false` or `nil` the COMMIT is allowed to proceed, --- otherwise the COMMIT is converted to a ROLLBACK. --- --- See: `db:rollback_hook` and `db:update_hook` function Database:commit_hook(func, udata) end --- Concatenate a list of changesets. ---@param changesets string[] ---@return string changeset function Database:concat_changeset(changesets) end --- This function creates an aggregate callback function. Aggregates perform an --- operation over all rows in a query. ---@param name string the name of the aggregate function as given in an SQL statement. ---@param nargs integer the number of arguments this call will provide ---@param step fun(ctx: lsqlite3.Context, ...: string|number|nil) the actual Lua function that gets called once for every row. --- It should accept a function context (see Methods for callback contexts) plus --- the same number of parameters as given in `nargs`. ---@param final fun(ctx: lsqlite3.Context) a function that is called once after all rows have been processed. --- It receives one argument, the function context. ---@param userdata? any If provided, userdata can be any Lua value and would be returned by the `context:user_data()` method. --- --- The function context can be used inside the two callback functions to --- communicate with SQLite3. Here is a simple example: --- --- db:exec[=[ --- CREATE TABLE numbers(num1,num2); --- INSERT INTO numbers VALUES(1,11); --- INSERT INTO numbers VALUES(2,22); --- INSERT INTO numbers VALUES(3,33); --- ]=] --- local num_sum=0 --- local function oneRow(context, num) -- add one column in all rows --- num_sum = num_sum + num --- end --- local function afterLast(context) -- return sum after last row has been processed --- context:result_number(num_sum) --- num_sum = 0 --- end --- db:create_aggregate("do_the_sums", 1, oneRow, afterLast) --- for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end --- for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end --- --- This prints: --- --- Sum of col 1: 6 --- Sum of col 2: 66 --- ---@return boolean success function Database:create_aggregate(name, nargs, step, final, userdata) end --- This creates a collation callback. A collation callback is used to establish --- a collation order, mostly for string comparisons and sorting purposes. ---@param name string the name of the collation to be created ---@param func fun(s1: string, s2: string): -1|0|1 a function that accepts two string arguments, compares them and returns `0` if both strings are identical, `-1` if the first argument is lower in the collation order than the second and `1` if the first argument is higher in the collation order than the second. --- A simple example: --- --- local function collate(s1,s2) --- s1=s1:lower() --- s2=s2:lower() --- if s1==s2 then return 0 --- elseif s1<s2 then return -1 --- else return 1 end --- end --- db:exec[=[ --- CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS); --- INSERT INTO test VALUES(NULL,'hello world'); --- INSERT INTO test VALUES(NULL,'Buenos dias'); --- INSERT INTO test VALUES(NULL,'HELLO WORLD'); --- ]=] --- db:create_collation('CINSENS',collate) --- for row in db:nrows('SELECT * FROM test') do --- print(row.id, row.content) --- end --- function Database:create_collation(name, func) end --- This function creates a callback function. Callback function are called by --- SQLite3 once for every row in a query. ---@param name string the name of the aggregate function as given in an SQL statement. ---@param nargs integer the number of arguments this call will provide ---@param func fun(ctx: lsqlite3.Context, ...) the actual Lua function that gets called once for every row. --- It should accept a function context (see Methods for callback contexts) plus --- the same number of parameters as given in `nargs`. ---@param userdata? any If provided, userdata can be any Lua value and would be returned by the `context:user_data()` method. --- Here is an example: --- --- db:exec'CREATE TABLE test(col1,col2,col3)' --- db:exec'INSERT INTO test VALUES(1,2,4)' --- db:exec'INSERT INTO test VALUES(2,4,9)' --- db:exec'INSERT INTO test VALUES(3,6,16)' --- db:create_function('sum_cols',3,function(ctx,a,b,c) --- ctx:result_number(a+b+c) --- end)) --- for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do --- util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum) --- end --- ---@return boolean success function Database:create_function(name, nargs, func, userdata) end ---@return lsqlite3.Rebaser ---@overload fun(self: lsqlite3.Database): nil, errno: integer ---@nodiscard function Database:create_rebaser() end ---@param name string? defaults to `"main"` ---@return lsqlite3.Session ---@overload fun(self: lsqlite3.Database, name?: string): nil, errno: integer ---@nodiscard function Database:create_session(name) end ---@return string? filename associated with database `name` of connection `db`. ---@nodiscard ---@param name string may be `"main"` for the main database file, or the name specified after the AS keyword in an ATTACH statement for an attached database. --- If there is no attached database name on the database connection, then no value is --- returned; if database name is a temporary or in-memory database, then an --- empty string is returned. function Database:db_filename(name) end --- Deserializes data from a string which was created by `db:serialize`. ---@param s string function Database:deserialize(s) end ---@return integer error the numerical result code (or extended result code) for the most recent failed call associated with database db. --- See http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki#numerical_error_and_result_codes for details. ---@nodiscard function Database:error_code() end Database.errcode = Database.error_code ---@return string message an error message for the most recent failed call associated with database `db`. ---@nodiscard function Database:error_message() end Database.errmsg = Database.error_message --- Compiles and executes the SQL statement(s) given in string sql. The statements --- are simply executed one after the other and not stored. The function returns --- `lsqlite3.OK` on success or else a numerical error code. --- --- If one or more of the SQL statements are queries, then the callback function --- specified in func is invoked once for each row of the query result (if func is --- `nil`, no callback is invoked). --- --- The callback receives four arguments: --- - `udata (the third parameter of the db:exec() call), --- - the number of columns in the row --- - a table with the column values --- - another table with the column names. --- --- The callback function should return `0`. If the callback returns a non-zero --- value then the query is aborted, all subsequent SQL statements are skipped --- and `db:exec()` returns `lsqlite3.ABORT`. Here is a simple example: --- --- sql=[=[ --- CREATE TABLE numbers(num1,num2,str); --- INSERT INTO numbers VALUES(1,11,"ABC"); --- INSERT INTO numbers VALUES(2,22,"DEF"); --- INSERT INTO numbers VALUES(3,33,"UVW"); --- INSERT INTO numbers VALUES(4,44,"XYZ"); --- SELECT * FROM numbers; --- ]=] --- function showrow(udata,cols,values,names) --- assert(udata=='test_udata') --- print('exec:') --- for i=1,cols do print('',names[i],values[i]) end --- return 0 --- end --- db:exec(sql,showrow,'test_udata') --- ---@generic Udata ---@param sql string ---@param func? fun(udata: Udata, cols: integer, values: string[], names: string[]): integer ---@param udata? Udata function Database:execute(sql, func, udata) end Database.exec = Database.execute --- This function causes any pending database operation to abort and return at --- the next opportunity. function Database:interrupt() end ---@param changeset string ---@return string ---@nodiscard function Database:invert_changeset(changeset) end ---@return boolean ---@nodiscard function Database:isopen() end ---@param name string ---@param flags integer? defaults to `0` ---@return lsqlite3.Iterator ---@overload fun(self: lsqlite3.Database, name?: string, flags?: integer): nil, errno: integer ---@nodiscard function Database:iterate_changeset(name, flags) end ---@return integer rowid the most recent INSERT into the database. If no inserts have ever occurred, `0` is returned. --- Each row in an SQLite table has a unique 64-bit signed integer key called --- the rowid. This id is always available as an undeclared column named ROWID, --- OID, or _ROWID_. If the table has a column of type INTEGER PRIMARY KEY then --- that column is another alias for the rowid. ---@nodiscard --- --- If an INSERT occurs within a trigger, then the rowid of the inserted row is --- returned as long as the trigger is running. Once the trigger terminates, the --- value returned reverts to the last value inserted before the trigger fired. function Database:last_insert_rowid() end --- Creates an iterator that returns the successive rows selected by the --- SQL statement given in string `sql`. Each call to the iterator --- returns a table in which the named fields correspond to the columns --- in the database. Here is an example: --- --- db:exec[=[ --- CREATE TABLE numbers(num1,num2); --- INSERT INTO numbers VALUES(1,11); --- INSERT INTO numbers VALUES(2,22); --- INSERT INTO numbers VALUES(3,33); --- ]=] --- for a in db:nrows('SELECT * FROM numbers') do table.print(a) end --- --- This script prints: --- --- num2: 11 --- num1: 1 --- num2: 22 --- num1: 2 --- num2: 33 --- num1: 3 --- ---@param sql string ---@return fun(vm: lsqlite3.VM) iterator, lsqlite3.VM vm ---@nodiscard function Database:nrows(sql) end --- This function compiles the SQL statement in string sql into an internal --- representation and returns this as userdata. The returned object should be --- used for all further method calls in connection with this specific SQL --- statement. --- See http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki#methods_for_prepared_statements. ---@param sql string ---@return lsqlite3.Statement ---@nodiscard function Database:prepare(sql) end --- This function installs a rollback_hook callback handler. --- See: `db:commit_hook` and `db:update_hook` ---@generic Udata ---@param func fun(udata: Udata) a Lua function that is invoked by SQLite3 whenever a transaction is rolled back. This callback receives one argument: the `udata` argument used when the callback was installed. ---@param udata Udata function Database:rollback_hook(func, udata) end --- Creates an iterator that returns the successive rows selected by the SQL --- statement given in string `sql`. Each call to the iterator returns a table in --- which the numerical indices 1 to n correspond to the selected columns 1 to n in --- the database. Here is an example: --- --- db:exec[=[ --- CREATE TABLE numbers(num1,num2); --- INSERT INTO numbers VALUES(1,11); --- INSERT INTO numbers VALUES(2,22); --- INSERT INTO numbers VALUES(3,33); --- ]=] --- for a in db:rows('SELECT * FROM numbers') do table.print(a) end --- --- This script prints: --- --- 1: 1 --- 2: 11 --- 1: 2 --- 2: 22 --- 1: 3 --- 2: 33 --- ---@param sql string ---@return fun(vm: lsqlite3.VM): (string|number|nil)[]? iterator, lsqlite3.VM vm ---@nodiscard function Database:rows(sql) end --- Serialize a database to be restored later with `Database:deserialize`. ---@return string? -- `nil` if the database has no tables ---@nodiscard function Database:serialize() end ---@return integer # the number of database rows that have been modified by INSERT, UPDATE or DELETE statements since the database was opened. --- This includes UPDATE, INSERT and DELETE statements executed as part of trigger --- programs. All changes are counted as soon as the statement that produces them --- is completed by calling either `stmt:reset()` or `stmt:finalize()`. ---@nodiscard function Database:total_changes() end --- This function installs an update_hook Data Change Notification --- Callback handler. See: `db:commit_hook` and `db:rollback_hook` --- ---@generic Udata ---@param func fun(udata: Udata, op: integer, db: lsqlite3.Database, name: string, rowid: integer) a Lua function that is invoked by SQLite3 --- whenever a row is updated, inserted or deleted. This callback --- receives five arguments: the first is the `udata` argument used --- when the callback was installed; the second is an integer --- indicating the operation that caused the callback to be invoked --- (one of `lsqlite3.UPDATE`, `lsqlite3.INSERT`, or --- `lsqlite3.DELETE`). The third and fourth arguments are the --- database and table name containing the affected row. The final --- callback parameter is the rowid of the row. In the case of an --- update, this is the rowid after the update takes place. ---@param udata Udata function Database:update_hook(func, udata) end --- Creates an iterator that returns the successive rows selected by the SQL --- statement given in string sql. Each call to the iterator returns the values --- that correspond to the columns in the currently selected row. --- Here is an example: --- --- db:exec[=[ --- CREATE TABLE numbers(num1,num2); --- INSERT INTO numbers VALUES(1,11); --- INSERT INTO numbers VALUES(2,22); --- INSERT INTO numbers VALUES(3,33); --- ]=] --- for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end --- --- This script prints: --- --- 1 11 --- 2 22 --- 3 33 --- ---@param sql string ---@return fun(vm: lsqlite3.VM): ...: string|number|nil iterator, lsqlite3.VM vm ---@nodiscard function Database:urows(sql) end ---@param mode integer? ---@param name string? ---@return integer nlog, integer nckpt ---@overload fun(self, mode?: integer, name?: integer): nil, errno: integer function Database:wal_checkpoint(mode, name) end ---@generic Udata ---@param func (fun(udata: Udata, db: lsqlite3.Database, name: string, page_count: integer): integer)? ---@param udata Udata? function Database:wal_hook(func, udata) end ---@class lsqlite3.Iterator: userdata --- Returned by `db:iterate_changeset` local Iterator = nil ---@return (string|number|false|nil)[] ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:conflict() end ---@return integer nout ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:fk_conflicts() end ---@return true ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:finalize() end ---@return integer ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:next() end ---@return (string|number|false?)[] ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:new() end ---@return (string|number|false?)[] ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:old() end ---@return string, integer, boolean indirect ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:op() end ---@return boolean[] ---@overload fun(self: lsqlite3.Iterator): nil, errno: integer function Iterator:pk() end ---@class lsqlite3.Rebaser: userdata --- Returned by `db:create_rebaser`. local Rebaser = nil function Rebaser:delete() end ---@param changeset string ---@return string ---@overload fun(self: lsqlite3.Rebaser, changeset: string): nil, errno: integer function Rebaser:rebase(changeset) end ---@class lsqlite3.Session: userdata --- Returned by `db:create_session`. local Session = nil ---@generic Udata ---@param filter_cb fun(udata: Udata)? ---@param udata Udata ---@overload fun(self: lsqlite3.Session, filter_cb?: fun(udata), udata?): nil, errno: integer ---@overload fun(self: lsqlite3.Session, s: string): true ---@overload fun(self: lsqlite3.Session, s: string): nil, errno: integer ---@return true function Session:attach(filter_cb, udata) end ---@return string changeset ---@nodiscard function Session:changeset() end --- Closes the session. Further method calls on the session will throw errors. function Session:delete() end ---@param s1 string ---@param s2 string ---@return boolean ---@nodiscard function Session:diff(s1, s2) end ---@return boolean function Session:enable() end ---@return boolean function Session:indirect() end ---@return boolean ---@nodiscard function Session:isempty() end ---@return string ---@nodiscard function Session:patchset() end ---@class lsqlite3.Statement: userdata --- After creating a prepared statement with `db:prepare()` the returned statement --- object should be used for all further calls in connection with that statement. local Statement = nil --- Binds `value` to statement parameter `n`. If the type of `value` is --- string it is bound as text. If the type of value is number, it is --- bound as an integer or double depending on its subtype using --- `lua_isinteger`. If `value` is a boolean then it is bound as `0` for --- `false` or `1` for `true`. If `value` is `nil` or missing, any --- previous binding is removed. --- ---@return integer `lsqlite3.OK` on success or else a numerical error code, ---@param n integer ---@param value string|number|boolean|nil function Statement:bind(n, value) end --- Binds string `blob` (which can be a binary string) as a blob to --- statement parameter `n`. --- ---@param n integer ---@param blob string ---@return integer `lsqlite3.OK` on success or else a numerical error code, function Statement:bind_blob(n, blob) end --- Binds the values in `nametable` to statement parameters. If the --- statement parameters are named (i.e., of the form `":AAA"` or --- `"$AAA"`) then this function looks for appropriately named fields in --- nametable; if the statement parameters are not named, it looks for --- numerical fields 1 to the number of statement parameters. --- ---@return integer `lsqlite3.OK` on success or else a numerical error code, ---@param nametable table ---@return integer function Statement:bind_names(nametable) end ---@return any # the largest statement parameter index in prepared the statement. ---@nodiscard --- When the statement parameters are of the forms `":AAA"` or `"?"`, then they are --- assigned sequentially increasing numbers beginning with one, so the value --- returned is the number of parameters. However if the same statement parameter --- name is used multiple times, each occurrence is given the same number, so the --- value returned is the number of unique statement parameter names. --- --- If statement parameters of the form `"?NNN"` are used (where `NNN` is an --- integer) then there might be gaps in the numbering and the value returned by --- this interface is the index of the statement parameter with the largest index --- value. function Statement:bind_parameter_count() end ---@param n integer ---@return string? -- the name of the n-th parameter in prepared statement. --- Statement parameters of the form `":AAA"` or `"@AAA"` or `"$VVV"` have a name --- which is the string `":AAA"` or `"@AAA"` or `"$VVV"`. In other words, the --- initial `":"` or `"$"` or `"@"` is included as part of the name. Parameters of --- the form `"?"` or `"?NNN"` have no name. The first bound parameter has an index --- of `1`. If the value `n` is out of range or if the `n`-th parameter is nameless, --- then `nil` is returned. function Statement:bind_parameter_name(n) end --- Binds the given values to statement parameters. ---@param ... string|number|nil ---@return integer `lsqlite3.OK` on success or else a numerical error code, function Statement:bind_values(...) end ---@return integer cols the number of columns in the result set returned by the statement or `0` if the statement does not return data (for example an `UPDATE`). ---@nodiscard function Statement:columns() end --- This function frees the prepared statement. ---@return integer # If the statement was executed successfully, or not executed at all, then `lsqlite3.OK` is returned. If execution of the statement failed then an error code is returned. function Statement:finalize() end ---@return any # the name of column n in the result set of statement. (The left-most column is number 0.) ---@nodiscard function Statement:get_name(n) end ---@return table # the names and types of all columns in the result set of the statement. ---@nodiscard function Statement:get_named_types() end ---@return table # the names and values of all columns in the current result row of a query. ---@nodiscard function Statement:get_named_values() end ---@return string[] # the names of all columns in the result set returned by the statement. ---@nodiscard function Statement:get_names() end ---@return any # the type of column n in the result set of statement. (The left-most column is number 0.) ---@nodiscard ---@nodiscard function Statement:get_type(n) end ---@return any[] # the types of all columns in the result set returned by the statement. ---@nodiscard function Statement:get_types() end ---@return any[] unames the names of all columns in the result set returned by the statement. ---@nodiscard function Statement:get_unames() end ---@return any[] utypes the types of all columns in the result set returned by the statement. ---@nodiscard function Statement:get_utypes() end ---@return any[] uvalues the values of all columns in the current result row of a query. ---@nodiscard function Statement:get_uvalues() end ---@param n any ---@return any value the value of column n in the result set of the statement. (The left-most column is number 0.) ---@nodiscard function Statement:get_value(n) end ---@return any[] values the values of all columns in the result set returned by the statement. ---@nodiscard function Statement:get_values() end ---@return boolean isopen `true` if `stmt` has not yet been finalized, `false` otherwise. ---@nodiscard function Statement:isopen() end ---@return function iterator iterates over the names and values of the result set of the statement. Each iteration returns a table with the names and values for the current row. This is the prepared statement equivalent of `db:nrows()`. ---@nodiscard function Statement:nrows() end --- This function resets the SQL statement, so that it is ready to be re-executed. Any statement variables that had values bound to them using the `stmt:bind*()` functions retain their values. function Statement:reset() end ---@return function iterator iterates over the values of the result set of statement `stmt`. Each iteration returns an array with the values for the current row. This is the prepared statement equivalent of `db:rows()`. ---@nodiscard function Statement:rows() end --- This function must be called to evaluate the (next iteration of the) prepared statement. ---@return integer # one of the following values: --- - `lsqlite3.BUSY`: the engine was unable to acquire the locks needed. --- If the statement is a COMMIT or occurs outside of an explicit transaction, --- then you can retry the statement. If the statement is not a COMMIT and occurs --- within a explicit transaction then you should rollback the transaction before --- continuing. --- - `lsqlite3.DONE`: the statement has finished executing successfully. --- `stmt:step()` should not be called again on this statement without first --- calling `stmt:reset()` to reset the virtual machine back to the initial state. --- - `lsqlite3.ROW`: this is returned each time a new row of data is ready for --- processing by the caller. The values may be accessed using the column access --- functions. `stmt:step()` can be called again to retrieve the next --- row of data. --- - `lsqlite3.ERROR`: a run-time error (such as a constraint violation) has --- occurred. `stmt:step()` should not be called again. More --- information may be found by calling `db:errmsg()`. A more specific error --- code (can be obtained by calling `stmt:reset()`. --- - `lsqlite3.MISUSE`: the function was called inappropriately, perhaps because --- the statement has already been finalized or a previous call to `stmt:step()` --- has returned `lsqlite3.ERROR` or `lsqlite3.DONE`. ---@nodiscard function Statement:step() end ---@return function iterator iterates over the values of the result set of the statement. --- Each iteration returns the values for the current row. This is the prepared --- statement equivalent of `db:urows()`. ---@nodiscard function Statement:urows() end ---@return any row_id the rowid of the most recent `INSERT` into the database corresponding to this statement. See `db:last_insert_rowid()`. ---@nodiscard function Statement:last_insert_rowid() end ---@class lsqlite3.VM: userdata local VM = nil ---@param index integer ---@param value string|number|boolean|nil ---@return integer errno function VM:bind(index, value) end ---@param index integer ---@param value string ---@return integer errno function VM:bind_blob(index, value) end ---@param names string[] ---@return integer errno function VM:bind_names(names) end ---@return integer parameter_count ---@nodiscard function VM:bind_parameter_count() end ---@param index number ---@return string parameter_name ---@nodiscard function VM:bind_parameter_name(index) end ---@param ... string|number|nil ---@return integer errno function VM:bind_values(...) end ---@return integer columns the column count ---@nodiscard function VM:columns() end ---@return integer errno function VM:finalize() end ---@param index integer ---@return string name ---@nodiscard function VM:get_name(index) end ---@return string[] ---@nodiscard function VM:get_named_types() end VM.type = VM.get_named_types ---@return (string|number?)[] ---@nodiscard function VM:get_named_values() end VM.data = VM.get_named_values ---@return string[] ---@nodiscard function VM:get_names() end VM.inames = VM.get_names ---@param index integer ---@return string ---@nodiscard function VM:get_type(index) end ---@return string[] ---@nodiscard function VM:get_types() end VM.itypes = VM.get_types ---@return string ... ---@nodiscard function VM:get_unames() end ---@return string ... ---@nodiscard function VM:get_utypes() end ---@return string|number? ... ---@nodiscard function VM:get_uvalues() end ---@param index integer ---@return string|number? ---@nodiscard function VM:get_value(index) end ---@return (string|number?)[] ---@nodiscard function VM:get_values() end VM.idata = VM.get_values ---@return boolean ---@nodiscard function VM:isopen() end ---@return integer rowid ---@nodiscard function VM:last_insert_rowid() end ---@param sql string ---@return fun(self: lsqlite3.VM): { [string]: string|number } iterator, self ---@nodiscard function VM:nrows(sql) end ---@return integer errno function VM:reset() end ---@param sql string ---@return fun(self: lsqlite3.VM): (string|number|nil)[] iterator, self ---@nodiscard function VM:rows(sql) end ---@return integer function VM:step() end ---@param sql string ---@return fun(self: lsqlite3.VM): ...: string|number|nil iterator, self ---@nodiscard function VM:urows(sql) end --- This module exposes an API for POSIX regular expressions which enable you to --- validate input, search for substrings, extract pieces of strings, etc. --- Here's a usage example: --- --- -- Example IPv4 Address Regular Expression (see also ParseIP) --- p = assert(re.compile([[^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})--- $]])) --- m,a,b,c,d = assert(p:search(𝑠)) --- if m then --- print("ok", tonumber(a), tonumber(b), tonumber(c), tonumber(d)) --- else --- print("not ok") --- end re = { --- No match NOMATCH = 1, --- Invalid regex BADPAT = 2, --- Unknown collating element ECOLLATE = 3, --- Unknown character class name ECTYPE = 4, --- Trailing backslash EESCAPE = 5, --- Invalid back reference ESUBREG = 6, --- Missing ] EBRACK = 7, --- Missing ) EPAREN = 8, --- Missing } EBRACE = 9, --- Invalid contents of {} BADBR = 10, --- Invalid character range. ERANGE = 11, --- Out of memory ESPACE = 12, --- Repetition not preceded by valid expression BADRPT = 13, --- Use this flag if you prefer the default POSIX regex syntax. --- We use extended regex notation by default. For example, an extended regular --- expression for matching an IP address might look like --- `([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)` whereas with basic syntax it would --- look like `\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)`. --- This flag may only be used with `re.compile` and `re.search`. BASIC = 1, --- Use this flag if you prefer the default POSIX regex syntax. We use extended --- regex notation by default. For example, an extended regular expression for --- matching an IP address might look like `([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)` --- whereas with basic syntax it would look like `\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)`. --- This flag may only be used with `re.compile` and `re.search`. ICASE = 2, --- Use this flag to change the handling of NEWLINE (\x0a) characters. When this --- flag is set, (1) a NEWLINE shall not be matched by a "." or any form of a --- non-matching list, (2) a "^" shall match the zero-length string immediately --- after a NEWLINE (regardless of `re.NOTBOL`), and (3) a "$" shall match the --- zero-length string immediately before a NEWLINE (regardless of `re.NOTEOL`). NEWLINE = 4, --- Causes `re.search` to only report success and failure. This is reported via --- the API by returning empty string for success. This flag may only be used ---` with `re.compile` and `re.search`. NOSUB = 8, --- The first character of the string pointed to by string is not the beginning --- of the line. This flag may only be used with `re.search` and `regex_t*:search`. NOTBOL = 0x0100, --- The last character of the string pointed to by string is not the end of the --- line. This flag may only be used with `re.search` and `regex_t*:search`. NOTEOL = 0x0200, } ---@class re.Errno: userdata re.Errno = nil ---@return integer # one of the following ---@nodiscard --- - `unix.NOMATCH` No match --- - `unix.BADPAT` Invalid regex --- - `unix.ECOLLATE` Unknown collating element --- - `unix.ECTYPE` Unknown character class name --- - `unix.EESCAPE` Trailing backslash --- - `unix.ESUBREG` Invalid back reference --- - `unix.EBRACK` Missing `]` --- - `unix.EPAREN` Missing `)` --- - `unix.EBRACE` Missing `}` --- - `unix.BADBR` Invalid contents of `{}` --- - `unix.ERANGE` Invalid character range. --- - `unix.ESPACE` Out of memory --- - `unix.BADRPT` Repetition not preceded by valid expression function re.Errno:errno() end ---@return string description the English string describing the error code. ---@nodiscard function re.Errno:doc() end ---Delegates to `re.Errno:doc()`. ---@return string ---@nodiscard function re.Errno:__tostring() end ---@class re.Regex: userdata re.Regex = {} --- Executes precompiled regular expression. --- --- Returns nothing (`nil`) if the pattern doesn't match anything. Otherwise it --- pushes the matched substring and any parenthesis-captured values too. Flags may --- contain `re.NOTBOL` or `re.NOTEOL` to indicate whether or not text should be --- considered at the start and/or end of a line. --- ---@param str string ---@param flags? integer defaults to zero and may have any of: --- --- - `re.NOTBOL` --- - `re.NOTEOL` --- --- This has an O(𝑛) cost. ---@return string match, string ... the match, followed by any captured groups ---@nodiscard ---@overload fun(self: re.Regex, text: string, flags?: integer): nil, error: re.Errno function re.Regex:search(str, flags) end --- Searches for regular expression match in text. --- --- This is a shorthand notation roughly equivalent to: --- --- preg = re.compile(regex) --- patt = preg:search(re, text) --- ---@param regex string ---@param text string ---@param flags integer? defaults to zero and may have any of: --- --- - `re.BASIC` --- - `re.ICASE` --- - `re.NEWLINE` --- - `re.NOSUB` --- - `re.NOTBOL` --- - `re.NOTEOL` --- --- This has exponential complexity. Please use `re.compile()` to compile your regular expressions once from `/.init.lua`. This API exists for convenience. This isn't recommended for prod. --- --- This uses POSIX extended syntax by default. ---@return string match, string ... the match, followed by any captured groups ---@nodiscard ---@overload fun(regex: string, text: string, flags?: integer): nil, error: re.Errno function re.search(regex, text, flags) end --- Compiles regular expression. --- ---@param regex string ---@param flags integer? defaults to zero and may have any of: --- --- - `re.BASIC` --- - `re.ICASE` --- - `re.NEWLINE` --- - `re.NOSUB` --- --- This has an O(2^𝑛) cost. Consider compiling regular expressions once --- from your `/.init.lua` file. --- --- If regex is an untrusted user value, then `unix.setrlimit` should be --- used to impose cpu and memory quotas for security. --- --- This uses POSIX extended syntax by default. ---@return re.Regex ---@nodiscard ---@overload fun(regex: string, flags?: integer): nil, error: re.Errno function re.compile(regex, flags) end --- The path module may be used to manipulate unix paths. --- --- Note that we use unix paths on Windows. For example, if you have a --- path like `C:\foo\bar` then it should be `/c/foo/bar` with redbean. --- It should also be noted the unix module is more permissive when --- using Windows paths, where translation to win32 is very light. path = {} --- Strips final component of path, e.g. --- --- path │ dirname --- ─────────────────── --- . │ . --- .. │ . --- / │ / --- usr │ . --- /usr/ │ / --- /usr/lib │ /usr --- /usr/lib/ │ /usr ---@param str string ---@return string ---@nodiscard function path.dirname(str) end --- Returns final component of path, e.g. --- --- path │ basename --- ───────────────────── --- . │ . --- .. │ .. --- / │ / --- usr │ usr --- /usr/ │ usr --- /usr/lib │ lib --- /usr/lib/ │ lib ---@param str string ---@return string ---@nodiscard function path.basename(str) end ---Concatenates path components, e.g. --- --- x │ y │ joined --- ───────────────────────────────── --- / │ / │ / --- /usr │ lib │ /usr/lib --- /usr/ │ lib │ /usr/lib --- /usr/lib │ /lib │ /lib --- --- You may specify 1+ arguments. --- --- Specifying no arguments will raise an error. If `nil` arguments are specified, --- then they're skipped over. If exclusively `nil` arguments are passed, then `nil` --- is returned. Empty strings behave similarly to `nil`, but unlike `nil` may --- coerce a trailing slash. ---@param str string? ---@param ... string? ---@return string? ---@nodiscard function path.join(str, ...) end ---Returns `true` if path exists. ---This function is inclusive of regular files, directories, and special files. --- Symbolic links are followed are resolved. On error, `false` is returned. ---@param path string ---@return boolean ---@nodiscard function path.exists(path) end ---Returns `true` if path exists and is regular file. ---Symbolic links are not followed. On error, `false` is returned. ---@param path string ---@return boolean ---@nodiscard function path.isfile(path) end ---Returns `true` if path exists and is directory. ---Symbolic links are not followed. On error, `false` is returned. ---@param path string ---@return boolean ---@nodiscard function path.isdir(path) end ---Returns `true` if path exists and is symbolic link. ---Symbolic links are not followed. On error, `false` is returned. ---@param path string ---@return boolean ---@nodiscard function path.islink(path) end --- ### MaxMind --- --- This module may be used to get city/country/asn/etc from IPs, e.g. --- --- -- .init.lua --- maxmind = require 'maxmind' --- asndb = maxmind.open('/usr/local/share/maxmind/GeoLite2-ASN.mmdb') --- --- -- request handler --- as = asndb:lookup(GetRemoteAddr()) --- if as then --- asnum = as:get('autonomous_system_number') --- asorg = as:get('autonomous_system_organization') --- Write(EscapeHtml(asnum)) --- Write(' ') --- Write(EscapeHtml(asorg)) --- end --- --- The database file is distributed by MaxMind. You need to sign up on their --- website to get a free copy. The database has a generalized structure. For a --- concrete example of how this module may be used, please see `maxmind.lua` --- in `redbean-demo.com`. maxmind = {} ---@param filepath string the location of the MaxMind database ---@return maxmind.Db db ---@nodiscard function maxmind.open(filepath) end ---@class maxmind.Db maxmind.Db = {} ---@param ip uint32 IPv4 address as uint32 ---@return maxmind.Result? result ---@nodiscard function maxmind.Db:lookup(ip) end ---@class maxmind.Result maxmind.Result = {} ---@return any ---@nodiscard function maxmind.Result:get() end ---@return integer ---@nodiscard function maxmind.Result:netmask() end --- This is an experimental module that, like the maxmind module, gives you insight --- into what kind of device is connecting to your redbean. This module can help --- you protect your redbean because it provides tools for identifying clients that --- misrepresent themselves. For example the User-Agent header might report itself --- as a Windows computer when the SYN packet says it's a Linux computer. --- --- function OnServerListen(fd, ip, port) --- unix.setsockopt(fd, unix.SOL_TCP, unix.TCP_SAVE_SYN, true) --- return false --- end --- --- function OnClientConnection(ip, port, serverip, serverport) --- fd = GetClientFd() --- syn = unix.getsockopt(fd, unix.SOL_TCP, unix.TCP_SAVED_SYN) --- end --- --- function OnHttpRequest() --- Log(kLogInfo, "client is running %s and reports %s" % { --- finger.GetSynFingerOs(finger.FingerSyn(syn)), --- GetHeader('User-Agent')}) --- Route() --- end --- finger = {} --- Fingerprints 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. We make no guarantees this --- hashing algorithm won't change as we learn more about the optimal way to ---- fingerprint, so be sure to save your syn packets too if you're using this --- feature, in case they need to be rehashed in the future. --- --- This function is nil/error propagating. ---@param syn_packet_bytes string ---@return integer synfinger uint32 ---@nodiscard ---@overload fun(syn_packet_bytes: string): nil, error: string ---@overload fun(nil: nil, error?: string): nil, error: string? function finger.FingerSyn(syn_packet_bytes) end --- Fingerprints IP+TCP SYN packet. --- --- If synfinger is a known hard-coded magic number, then one of the following --- strings may be returned: --- --- - `"LINUX"` --- - `"WINDOWS"` --- - `"XNU"` --- - `"NETBSD"` --- - `"FREEBSD"` --- - `"OPENBSD"` --- --- If this function returns `nil`, then one thing you can do to help is file an --- issue and share with us your SYN packet specimens. The way we prefer to receive --- them is in `EncodeLua(syn_packet_bytes)` format along with details on the --- operating system which you must know. ---@param synfinger integer ---@return "LINUX"|"WINDOWS"|"XNU"|"NETBSD"|"FREEBSD"|"OPENBSD" osname ---@nodiscard ---@overload fun(synfinger: integer): nil, error: string function finger.GetSynFingerOs(synfinger) end --- Describes IP+TCP SYN packet. --- --- The layout looks as follows: --- --- - `TTL:OPTIONS:WSIZE:MSS` --- --- The `TTL`, `WSIZE`, and `MSS` fields are unsigned decimal fields. --- --- The `OPTIONS` field communicates the ordering of the commonly used subset of --- tcp options. The following character mappings are defined. TCP options not on --- this list will be ignored. --- --- - `E`: End of Option list --- - `N`: No-Operation --- - `M`: Maximum Segment Size --- - `K`: Window Scale --- - `O`: SACK Permitted --- - `A`: SACK --- - `e`: Echo (obsolete) --- - `r`: Echo reply (obsolete) --- - `T`: Timestamps --- --- This function is nil/error propagating. ---@param syn_packet_bytes string ---@return string description ---@nodiscard ---@overload fun(syn_packet_bytes: string): nil, error: string ---@overload fun(nil: nil, error?: string): nil, error: string? function finger.DescribeSyn(syn_packet_bytes) end --- This module implements a password hashing algorithm based on blake2b that won --- the Password Hashing Competition. --- --- It can be used to securely store user passwords in your SQLite database, in a --- way that destroys the password, but can be verified by regenerating the hash --- again the next time the user logs in. Destroying the password is important, --- since if your database is compromised, the bad guys won't be able to use --- rainbow tables to recover the plain text of the passwords. --- --- Argon2 achieves this security by being expensive to compute. Care should be --- taken in choosing parameters, since an HTTP endpoint that uses Argon2 can just --- as easily become a denial of service vector. For example, you may want to --- consider throttling your login endpoint. argon2 = { variants = { ---@type integer blend of other two methods [default] argon2_id = nil, ---@type integer maximize resistance to side-channel attacks argon2_i = nil, ---@type integer maximize resistance to gpu cracking attacks argon2_d = nil } } ---@class argon2.Config argon2.Config = { --- The memory hardness in kibibytes, which defaults --- to 4096 (4 mibibytes). It's recommended that this be tuned upwards. m_cost = nil, --- The number of iterations, which defaults to `3`. t_cost = nil, --- The parallelism factor, which defaults to `1`. parallelism = nil, --- the number of desired bytes in hash output, --- which defaults to 32. hash_len = nil, ---@type integer `config.variant` may be: --- --- - `argon2.variants.argon2_id` blend of other two methods [default] --- - `argon2.variants.argon2_i` maximize resistance to side-channel attacks --- - `argon2.variants.argon2_d` maximize resistance to gpu cracking attacks variant = nil } --- Hashes password. --- --- This is consistent with the README of the reference implementation: --- --- >: assert(argon2.hash_encoded("password", "somesalt", { --- variant = argon2.variants.argon2_i, --- hash_len = 24, --- t_cost = 2, --- })) --- --- --- `salt` is a nonce value used to hash the string. --- --- `config.m_cost` is the memory hardness in kibibytes, which defaults --- to 4096 (4 mibibytes). It's recommended that this be tuned upwards. --- --- `config.t_cost` is the number of iterations, which defaults to 3. --- --- `config.parallelism` is the parallelism factor, which defaults to 1. --- --- `config.hash_len` is the number of desired bytes in hash output, --- which defaults to 32. --- --- `config.variant` may be: --- --- - `argon2.variants.argon2_id` blend of other two methods [default] --- - `argon2.variants.argon2_i` maximize resistance to side-channel attacks --- - `argon2.variants.argon2_d` maximize resistance to gpu cracking attacks --- ---@param pass string ---@param salt string ---@param config argon2.Config ---@return string ascii ---@nodiscard ---@overload fun(pass: string, salt: string, config?: argon2.Config): nil, error: string function argon2.hash_encoded(pass, salt, config) end --- Verifies password, e.g. --- --- >: argon2.verify( --- "p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG", --- true --- ---@param encoded string ---@param pass string ---@return boolean ok ---@nodiscard ---@overload fun(encoded: string, pass: string): nil, error: string function argon2.verify(encoded, pass) end --- This module exposes the low-level System Five system call interface. --- This module works on all supported platforms, including Windows NT. unix = { --- @type integer AF_INET = nil, --- @type integer AF_UNIX = nil, --- @type integer AF_UNSPEC = nil, --- @type integer Returns maximum length of arguments for new processes. --- --- This is the character limit when calling `execve()`. It's the sum of --- the lengths of `argv` and `envp` including any nul terminators and --- pointer arrays. For example to see how much your shell `envp` uses --- --- $ echo $(($(env | wc -c) + 1 + ($(env | wc -l) + 1) * 8)) --- 758 --- --- POSIX mandates this be 4096 or higher. On Linux this it's 128*1024. --- On Windows NT it's 32767*2 because CreateProcess lpCommandLine and --- environment block are separately constrained to 32,767 characters. --- Most other systems define this limit much higher. ARG_MAX = nil, --- @type integer AT_EACCES = nil, --- @type integer AT_FDCWD = nil, --- @type integer AT_SYMLINK_NOFOLLOW = nil, --- @type integer Returns default buffer size. --- --- The UNIX module does not perform any buffering between calls. --- --- Each time a read or write is performed via the UNIX API your redbean --- will allocate a buffer of this size by default. This current default --- would be 4096 across platforms. BUFSIZ = nil, --- @type integer Returns the scheduler frequency. --- --- This is granularity at which the kernel does work. For example, the --- Linux kernel normally operates at 100hz so its CLK_TCK will be 100. --- --- This value is useful for making sense out of unix.Rusage data. CLK_TCK = nil, --- @type integer CLOCK_BOOTTIME = nil, --- @type integer CLOCK_BOOTTIME_ALARM = nil, --- @type integer CLOCK_MONOTONIC = nil, --- @type integer CLOCK_MONOTONIC_COARSE = nil, --- @type integer CLOCK_MONOTONIC_PRECISE = nil, --- @type integer CLOCK_MONOTONIC_FAST = nil, --- @type integer CLOCK_MONOTONIC_RAW = nil, --- @type integer CLOCK_PROCESS_CPUTIME_ID = nil, --- @type integer CLOCK_PROF = nil, --- @type integer CLOCK_REALTIME = nil, --- @type integer CLOCK_REALTIME_PRECISE = nil, --- @type integer CLOCK_REALTIME_ALARM = nil, --- @type integer CLOCK_REALTIME_COARSE = nil, --- @type integer CLOCK_REALTIME_FAST = nil, --- @type integer CLOCK_TAI = nil, --- @type integer DT_BLK = nil, --- @type integer DT_CHR = nil, --- @type integer DT_DIR = nil, --- @type integer DT_FIFO = nil, --- @type integer DT_LNK = nil, --- @type integer DT_REG = nil, --- @type integer DT_SOCK = nil, --- @type integer DT_UNKNOWN = nil, --- @type integer Argument list too long. --- --- Raised by `execve`, `sched_setattr`. E2BIG = nil, --- @type integer Permission denied. --- --- Raised by `access`, `bind`, `chdir`, `chmod`, `chown`, `chroot`, --- `clock_getres`, `connect`, `execve`, `fcntl`, `getpriority`, --- `link`, `mkdir`, `mknod`, `mmap`, `mprotect`, `msgctl`, `open`, --- `prctl`, `ptrace`, `readlink`, `rename`, `rmdir`, `semget`, --- `send`, `setpgid`, `socket`, `stat`, `symlink`, `truncate`, --- `unlink`, `uselib`, `utime`, `utimensat`. EACCES = nil, --- @type integer Address already in use. Raised by `bind`, `connect`, `listen`. EADDRINUSE = nil, --- @type integer Address not available. Raised by `bind`, `connect`. EADDRNOTAVAIL = nil, --- @type integer Address family not supported. Raised by `connect`, `socket`, `socketpair`. EAFNOSUPPORT = nil, --- @type integer --- Resource temporarily unavailable (e.g. SO_RCVTIMEO expired, too many --- processes, too much memory locked, read or write with O_NONBLOCK --- needs polling, etc.). --- --- Raised by `accept`, `connect`, `fcntl`, `fork`, `getrandom`, --- `mincore`, `mlock`, `mmap`, `mremap`, `poll`, `read`, `select`, --- `send`, `setresuid`, `setreuid`, `setuid`, `sigwaitinfo`, --- `splice`, `tee`, `timer_create`, `timerfd_create`, `tkill`, --- `write`, EAGAIN = nil, --- @type integer Connection already in progress. Raised by `connect`, `send`. EALREADY = nil, --- @type integer Bad file descriptor; cf. EBADFD. --- --- Raised by `accept`, `access`, `bind`, `chdir`, `chmod`, `chown`, --- `close`, `connect`, `copy_file_range`, `dup`, `fcntl`, `flock`, --- `fsync`, `futimesat`, `opendir`, `getpeername`, `getsockname`, --- `getsockopt`, `ioctl`, `link`, `listen`, `lseek`, `mkdir`, --- `mknod`, `mmap`, `open`, `prctl`, `read`, `readahead`, --- `readlink`, `recv`, `rename`, `select`, `send`, `shutdown`, --- `splice`, `stat`, `symlink`, `sync`, `sync_file_range`, --- `timerfd_create`, `truncate`, `unlink`, `utimensat`, `write`. EBADF = nil, --- @type integer EBADFD = nil, --- @type integer EBADMSG = nil, --- @type integer Device or resource busy. --- --- Raised by dup, fcntl, msync, prctl, ptrace, rename, --- rmdir. EBUSY = nil, --- @type integer ECANCELED = nil, --- @type integer No child process. --- --- Raised by `wait`, `waitpid`, `waitid`, `wait3`, `wait4`. ECHILD = nil, --- @type integer Connection reset before accept. Raised by `accept`. ECONNABORTED = nil, --- @type integer System-imposed limit on the number of threads was encountered. --- --- Raised by connect, listen, recv. ECONNREFUSED = nil, --- @type integer Connection reset by client. Raised by `send`. ECONNRESET = nil, --- @type integer Resource deadlock avoided. --- --- Raised by `fcntl`. EDEADLK = nil, --- @type integer Destination address required. Raised by `send`, `write`. EDESTADDRREQ = nil, --- @type integer EDOM = nil, --- @type integer Disk quota exceeded. --- --- Raised by link, mkdir, mknod, open, rename, symlink, --- write. EDQUOT = nil, --- @type integer File exists. --- --- Raised by `link`, `mkdir`, `mknod`, `mmap`, `open`, `rename`, --- `rmdir`, `symlink`. EEXIST = nil, --- @type integer EFAULT = nil, --- @type integer File too large. --- --- Raised by `copy_file_range`, `open`, `truncate`, `write`. EFBIG = nil, --- @type integer Host is down. Raised by `accept`. EHOSTDOWN = nil, --- @type integer Host is unreachable. Raised by `accept`. EHOSTUNREACH = nil, --- @type integer Identifier removed. Raised by `msgctl`. EIDRM = nil, --- @type integer EILSEQ = nil, --- @type integer EINPROGRESS = nil, --- @type integer The greatest of all errnos; crucial for building real time reliable software. --- --- Raised by `accept`, `clock_nanosleep`, `close`, `connect`, `dup`, `fcntl`, --- `flock`, `getrandom`, `nanosleep`, `open`, `pause`, `poll`, `ptrace`, `read`, `recv`, --- `select`, `send`, `sigsuspend`, `sigwaitinfo`, `truncate`, `wait`, `write`. EINTR = nil, --- @type integer Invalid argument. --- Raised by [pretty much everything]. EINVAL = nil, --- @type integer --- Raised by `access`, `acct`, `chdir`, `chmod`, `chown`, `chroot`, `close`, --- `copy_file_range`, `execve`, `fallocate`, `fsync`, `ioperm`, `link`, `madvise`, --- `mbind`, `pciconfig_read`, `ptrace`, `read`, `readlink`, `sendfile`, `statfs`, --- `symlink`, `sync_file_range`, `truncate`, `unlink`, `write`. EIO = nil, --- @type integer Socket is connected. Raised by `connect`, `send`. EISCONN = nil, --- @type integer Is a directory. --- --- Raised by `copy_file_range`, `execve`, `open`, `read`, `rename`, `truncate`, --- `unlink`. EISDIR = nil, --- @type integer Too many levels of symbolic links. --- --- Raised by access, bind, chdir, chmod, chown, chroot, execve, link, --- mkdir, mknod, open, readlink, rename, rmdir, stat, symlink, --- truncate, unlink, utimensat. ELOOP = nil, --- @type integer Too many open files. --- --- Raised by `accept`, `dup`, `execve`, `fanotify_init`, `fcntl`, --- `open`, `pipe`, `socket`, `socketpair`, `timerfd_create`. EMFILE = nil, --- @type integer Too many links; --- --- Raised by `link`, `mkdir`, `rename`. EMLINK = nil, --- @type integer Message too long. Raised by `send`. EMSGSIZE = nil, --- @type integer Filename too long. Cosmopolitan Libc currently defines `PATH_MAX` as --- 1024 characters. On UNIX that limit should only apply to system call --- wrappers like realpath. On Windows NT it's observed by all system --- calls that accept a pathname. --- --- Raised by `access`, `bind`, `chdir`, `chmod`, `chown`, `chroot`, --- `execve`, `gethostname`, `link`, `mkdir`, `mknod`, `open`, --- `readlink`, `rename`, `rmdir`, `stat`, `symlink`, `truncate`, --- `unlink`, `utimensat`. ENAMETOOLONG = nil, --- @type integer Network is down. Raised by `accept`. ENETDOWN = nil, --- @type integer Connection reset by network. ENETRESET = nil, --- @type integer Host is unreachable. Raised by `accept`, `connect`. ENETUNREACH = nil, --- @type integer Too many open files in system. --- --- Raised by `accept`, `execve`, `mmap`, `open`, `pipe`, `socket`, --- `socketpair`, `swapon`, `timerfd_create`, `uselib`, --- `userfaultfd`. ENFILE = nil, --- @type integer No buffer space available; --- --- Raised by `getpeername`, `getsockname`, `send`. ENOBUFS = nil, --- @type integer No message is available in xsi stream or named pipe is being closed; --- no data available; barely in posix; returned by ioctl; very close in --- spirit to EPIPE? ENODATA = nil, --- @type integer No such device. --- --- Raised by `arch_prctl`, `mmap`, `open`, `prctl`, `timerfd_create`. ENODEV = nil, --- @type integer No such file or directory. --- --- Raised by `access`, `bind`, `chdir`, `chmod`, `chown`, `chroot`, --- `clock_getres`, `execve`, `opendir`, `link`, `mkdir`, `mknod`, --- `open`, `readlink`, `rename`, `rmdir`, `stat`, `swapon`, --- `symlink`, `truncate`, `unlink`, `utime`, `utimensat`. ENOENT = nil, --- @type integer Exec format error. Raised by `execve`, `uselib`. ENOEXEC = nil, --- @type integer No locks available. Raised by `fcntl`, `flock`. ENOLCK = nil, --- @type integer ENOMEM = nil, --- @type integer Raised by `msgop`. ENOMSG = nil, --- @type integer ENONET = nil, --- @type integer Protocol not available. Raised by `getsockopt`, `accept`. ENOPROTOOPT = nil, --- @type integer No space left on device. --- --- Raised by `copy_file_range`, `fsync`, `link`, `mkdir`, `mknod`, --- `open`, `rename`, `symlink`, `sync_file_range`, `write`. ENOSPC = nil, --- @type integer System call not available on this platform. On --- Windows this is raised by `chroot`, `setuid`, `setgid`, --- `getsid`, `setsid`, and others we're doing our best to --- document. ENOSYS = nil, --- @type integer Block device required. Raised by `umount`. ENOTBLK = nil, --- @type integer Socket is not connected. --- --- Raised by `getpeername`, `recv`, `send`, `shutdown`. ENOTCONN = nil, --- @type integer Not a directory. This means that a directory --- component in a supplied path *existed* but wasn't a --- directory. For example, if you try to `open("foo/bar")` and --- `foo` is a regular file, then `ENOTDIR` will be returned. --- --- Raised by `open`, `access`, `chdir`, `chroot`, `execve`, `link`, --- `mkdir`, `mknod`, `opendir`, `readlink`, `rename`, `rmdir`, --- `stat`, `symlink`, `truncate`, `unlink`, `utimensat`, `bind`, --- `chmod`, `chown`, `fcntl`, `futimesat`. ENOTDIR = nil, --- @type integer Directory not empty. Raised by `rmdir`. ENOTEMPTY = nil, --- @type integer ENOTRECOVERABLE = nil, --- @type integer Not a socket. --- --- Raised by `accept`, `bind`, `connect`, `getpeername`, --- `getsockname`, `getsockopt`, `listen`, `recv`, `send`, --- `shutdown`. ENOTSOCK = nil, --- @type integer Operation not supported. --- --- Raised by `chmod`, `clock_getres`, `clock_nanosleep`, --- `timer_create`. ENOTSUP = nil, --- @type integer Inappropriate i/o control operation. Raised by `ioctl`. ENOTTY = nil, --- @type integer No such device or address. Raised by `lseek`, `open`, `prctl`. ENXIO = nil, --- @type integer Socket operation not supported. --- --- Raised by accept, listen, mmap, prctl, readv, send, --- socketpair. EOPNOTSUPP = nil, --- @type integer Raised by `copy_file_range`, `fanotify_init`, `lseek`, `mmap`, --- `open`, `stat`, `statfs` EOVERFLOW = nil, --- @type integer EOWNERDEAD = nil, --- @type integer Operation not permitted. --- --- Raised by `accept`, `chmod`, `chown`, `chroot`, --- `copy_file_range`, `execve`, `fallocate`, `fanotify_init`, --- `fcntl`, `futex`, `get_robust_list`, `getdomainname`, --- `getgroups`, `gethostname`, `getpriority`, `getrlimit`, --- `getsid`, `gettimeofday`, `idle`, `init_module`, `io_submit`, --- `ioctl_console`, `ioctl_ficlonerange`, `ioctl_fideduperange`, --- `ioperm`, `iopl`, `ioprio_set`, `keyctl`, `kill`, `link`, --- `lookup_dcookie`, `madvise`, `mbind`, `membarrier`, --- `migrate_pages`, `mkdir`, `mknod`, `mlock`, `mmap`, `mount`, --- `move_pages`, `msgctl`, `nice`, `open`, `open_by_handle_at`, --- `pciconfig_read`, `perf_event_open`, `pidfd_getfd`, --- `pidfd_send_signal`, `pivot_root`, `prctl`, `process_vm_readv`, --- `ptrace`, `quotactl`, `reboot`, `rename`, `request_key`, --- `rmdir`, `rt_sigqueueinfo`, `sched_setaffinity`, --- `sched_setattr`, `sched_setparam`, `sched_setscheduler`, --- `seteuid`, `setfsgid`, `setfsuid`, `setgid`, `setns`, `setpgid`, --- `setresuid`, `setreuid`, `setsid`, `setuid`, `setup`, --- `setxattr`, `sigaltstack`, `spu_create`, `stime`, `swapon`, --- `symlink`, `syslog`, `truncate`, `unlink`, `utime`, `utimensat`, --- `write`. EPERM = nil, --- @type integer Protocol family not supported. EPFNOSUPPORT = nil, --- @type integer Broken pipe. --- Returned by `write`, `send`. This happens when you try --- to write data to a subprocess via a pipe but the reader end has --- already closed, possibly because the process died. Normally i/o --- routines only return this if `SIGPIPE` doesn't kill the process. --- Unlike default UNIX programs, redbean currently ignores `SIGPIPE` by --- default, so this error code is a distinct possibility when pipes or --- sockets are being used. EPIPE = nil, --- @type integer Raised by `accept`, `connect`, `socket`, `socketpair`. EPROTO = nil, --- @type integer Protocol not supported. Raised by `socket`, `socketpair`. EPROTONOSUPPORT = nil, --- @type integer Protocol wrong type for socket. Raised by `connect`. EPROTOTYPE = nil, --- @type integer Result too large. --- --- Raised by `prctl`. ERANGE = nil, --- @type integer EREMOTE = nil, --- @type integer ERESTART = nil, --- @type integer Read-only filesystem. --- --- Raised by access, bind, chmod, chown, link, mkdir, mknod, open, --- rename, rmdir, symlink, truncate, unlink, utime, utimensat. EROFS = nil, --- @type integer Cannot send after transport endpoint shutdown; note that shutdown write is an `EPIPE`. ESHUTDOWN = nil, --- @type integer Socket type not supported. ESOCKTNOSUPPORT = nil, --- @type integer Invalid seek. --- --- Raised by `lseek`, `splice`, `sync_file_range`. ESPIPE = nil, --- @type integer No such process. --- --- Raised by `getpriority`, `getrlimit`, `getsid`, `ioprio_set`, `kill`, `setpgid`, `tkill`, `utimensat`. ESRCH = nil, --- @type integer ESTALE = nil, --- @type integer Timer expired. Raised by `connect`. ETIME = nil, --- @type integer Connection timed out. Raised by `connect`. ETIMEDOUT = nil, --- @type integer Too many references: cannot splice. Raised by `sendmsg`. ETOOMANYREFS = nil, --- @type integer Won't open executable that's executing in write mode. --- --- Raised by access, copy_file_range, execve, mmap, open, truncate. ETXTBSY = nil, --- @type integer EUSERS = nil, --- @type integer Improper link. --- --- Raised by copy_file_range, link, rename. EXDEV = nil, --- @type integer FD_CLOEXEC = nil, --- @type integer F_GETFD = nil, --- @type integer F_GETFL = nil, --- @type integer F_OK = nil, --- @type integer F_RDLCK = nil, --- @type integer F_SETFD = nil, --- @type integer F_SETFL = nil, --- @type integer F_SETLK = nil, --- @type integer F_SETLKW = nil, --- @type integer F_UNLCK = nil, --- @type integer F_WRLCK = nil, --- @type integer IPPROTO_ICMP = nil, --- @type integer IPPROTO_IP = nil, --- @type integer IPPROTO_RAW = nil, --- @type integer IPPROTO_TCP = nil, --- @type integer IPPROTO_UDP = nil, --- @type integer IP_HDRINCL = nil, --- @type integer IP_MTU = nil, --- @type integer IP_TOS = nil, --- @type integer IP_TTL = nil, --- @type integer ITIMER_PROF = nil, --- @type integer ITIMER_REAL = nil, --- @type integer ITIMER_VIRTUAL = nil, --- @type integer LOG_ALERT = nil, --- @type integer LOG_CRIT = nil, --- @type integer LOG_DEBUG = nil, --- @type integer LOG_EMERG = nil, --- @type integer LOG_ERR = nil, --- @type integer LOG_INFO = nil, --- @type integer LOG_NOTICE = nil, --- @type integer LOG_WARNING = nil, --- @type integer MSG_DONTROUTE = nil, --- @type integer MSG_MORE = nil, --- @type integer MSG_NOSIGNAL = nil, --- @type integer MSG_OOB = nil, --- @type integer MSG_PEEK = nil, --- @type integer MSG_WAITALL = nil, --- @type integer Returns maximum length of file path component. --- --- POSIX requires this be at least 14. Most operating systems define it --- as 255. It's a good idea to not exceed 253 since that's the limit on --- DNS labels. NAME_MAX = nil, --- @type integer Returns maximum number of signals supported by underlying system. --- --- The limit for unix.Sigset is 128 to support FreeBSD, but most --- operating systems define this much lower, like 32. This constant --- reflects the value chosen by the underlying operating system. NSIG = nil, --- @type integer open for reading (default) O_RDONLY = nil, --- @type integer open for writing O_WRONLY = nil, --- @type integer open for reading and writing O_RDWR = nil, --- @type integer create file if it doesn't exist O_CREAT = nil, --- @type integer automatic `ftruncate(fd, 0)` if exists O_TRUNC = nil, --- @type integer automatic `close()` upon `execve()` O_CLOEXEC = nil, --- @type integer exclusive access (see below) O_EXCL = nil, --- @type integer open file for append only O_APPEND = nil, --- @type integer asks read/write to fail with EAGAIN rather than block O_NONBLOCK = nil, --- @type integer it's complicated (not supported on Apple and OpenBSD) O_DIRECT = nil, --- @type integer useful for stat'ing (hint on UNIX but required on NT) O_DIRECTORY = nil, --- @type integer try to make temp more secure (Linux and Windows only) O_TMPFILE = nil, --- @type integer fail if it's a symlink (zero on Windows) O_NOFOLLOW = nil, --- @type integer it's complicated (zero on non-Linux/Apple) O_DSYNC = nil, --- @type integer it's complicated (zero on non-Linux/Apple) O_RSYNC = nil, --- @type integer it's complicated (zero on non-Linux) O_PATH = nil, --- @type integer it's complicated (zero on non-FreeBSD) O_VERIFY = nil, --- @type integer it's complicated (zero on non-BSD) O_SHLOCK = nil, --- @type integer it's complicated (zero on non-BSD) O_EXLOCK = nil, --- @type integer don't record access time (zero on non-Linux) O_NOATIME = nil, --- @type integer hint random access intent (zero on non-Windows) O_RANDOM = nil, --- @type integer hint sequential access intent (zero on non-Windows) O_SEQUENTIAL = nil, --- @type integer ask fs to abstract compression (zero on non-Windows) O_COMPRESSED = nil, --- @type integer turns on that slow performance (zero on non-Windows) O_INDEXED = nil, --- @type integer O_ACCMODE = nil, --- @type integer O_ASYNC = nil, --- @type integer O_EXEC = nil, --- @type integer O_NOCTTY = nil, --- @type integer O_SEARCH = nil, --- @type integer O_SYNC = nil, --- @type integer Returns maximum length of file path. --- --- This applies to a complete path being passed to system calls. --- --- POSIX.1 XSI requires this be at least 1024 so that's what most --- platforms support. On Windows NT, the limit is technically 260 --- characters. Your redbean works around that by prefixing `//?/` --- to your paths as needed. On Linux this limit will be 4096, but --- that won't be the case for functions such as realpath that are --- implemented at the C library level; however such functions are --- the exception rather than the norm, and report `enametoolong()`, --- when exceeding the libc limit. PATH_MAX = nil, --- @type integer Returns maximum size at which pipe i/o is guaranteed atomic. --- --- POSIX requires this be at least 512. Linux is more generous and --- allows 4096. On Windows NT this is currently 4096, and it's the --- parameter redbean passes to `CreateNamedPipe()`. PIPE_BUF = nil, --- @type integer POLLERR = nil, --- @type integer POLLHUP = nil, --- @type integer POLLIN = nil, --- @type integer POLLNVAL = nil, --- @type integer POLLOUT = nil, --- @type integer POLLPRI = nil, --- @type integer POLLRDBAND = nil, --- @type integer POLLRDHUP = nil, --- @type integer POLLRDNORM = nil, --- @type integer POLLWRBAND = nil, --- @type integer POLLWRNORM = nil, --- @type integer RLIMIT_AS = nil, --- @type integer RLIMIT_CPU = nil, --- @type integer RLIMIT_FSIZE = nil, --- @type integer RLIMIT_NOFILE = nil, --- @type integer RLIMIT_NPROC = nil, --- @type integer RLIMIT_RSS = nil, --- @type integer RUSAGE_BOTH = nil, --- @type integer RUSAGE_CHILDREN = nil, --- @type integer RUSAGE_SELF = nil, --- @type integer RUSAGE_THREAD = nil, --- @type integer R_OK = nil, --- @type integer SA_NOCLDSTOP = nil, --- @type integer SA_NOCLDWAIT = nil, --- @type integer SA_NODEFER = nil, --- @type integer SA_RESETHAND = nil, --- @type integer SA_RESTART = nil, --- @type integer SEEK_CUR = nil, --- @type integer SEEK_END = nil, --- @type integer SEEK_SET = nil, ---@type integer sends a tcp half close for reading SHUT_RD = nil, ---@type integer sends a tcp half close for writing SHUT_WR = nil, ---@type integer SHUT_RDWR = nil, --- @type integer Process aborted. SIGABRT = nil, --- @type integer Sent by setitimer(). SIGALRM = nil, --- @type integer Valid memory access that went beyond underlying end of file. SIGBUS = nil, --- @type integer Child process exited or terminated and is now a zombie (unless this --- is `SIG_IGN` or `SA_NOCLDWAIT`) or child process stopped due to terminal --- i/o or profiling/debugging (unless you used `SA_NOCLDSTOP`) SIGCHLD = nil, --- @type integer Child process resumed from profiling/debugging. SIGCONT = nil, --- @type integer SIGEMT = nil, --- @type integer Illegal math. SIGFPE = nil, --- @type integer Terminal hangup or daemon reload; auto-broadcasted to process group. SIGHUP = nil, --- @type integer Illegal instruction. SIGILL = nil, --- @type integer SIGINFO = nil, --- @type integer Terminal CTRL-C keystroke. SIGINT = nil, --- @type integer SIGIO = nil, --- @type integer Terminate with extreme prejudice. SIGKILL = nil, --- @type integer Write to closed file descriptor. SIGPIPE = nil, --- @type integer Profiling timer expired. SIGPROF = nil, --- @type integer Not implemented in most community editions of system five. SIGPWR = nil, --- @type integer Terminal CTRL-\ keystroke. SIGQUIT = nil, --- @type integer SIGRTMAX = nil, --- @type integer SIGRTMIN = nil, --- @type integer Invalid memory access. SIGSEGV = nil, --- @type integer SIGSTKFLT = nil, --- @type integer Child process stopped due to profiling/debugging. SIGSTOP = nil, --- @type integer SIGSYS = nil, --- @type integer Terminate. SIGTERM = nil, --- @type integer INT3 instruction. SIGTRAP = nil, --- @type integer Terminal CTRL-Z keystroke. SIGTSTP = nil, --- @type integer Terminal input for background process. SIGTTIN = nil, --- @type integer Terminal input for background process. SIGTTOU = nil, --- @type integer SIGURG = nil, --- @type integer Do whatever you want. SIGUSR1 = nil, --- @type integer Do whatever you want. SIGUSR2 = nil, --- @type integer Virtual alarm clock. SIGVTALRM = nil, --- @type integer Terminal resized. SIGWINCH = nil, --- @type integer CPU time limit exceeded. SIGXCPU = nil, --- @type integer File size limit exceeded. SIGXFSZ = nil, --- @type integer SIG_BLOCK = nil, --- @type integer SIG_DFL = nil, --- @type integer SIG_IGN = nil, --- @type integer SIG_SETMASK = nil, --- @type integer SIG_UNBLOCK = nil, --- @type integer SOCK_CLOEXEC = nil, --- @type integer SOCK_DGRAM = nil, --- @type integer SOCK_NONBLOCK = nil, --- @type integer SOCK_RAW = nil, --- @type integer SOCK_RDM = nil, --- @type integer SOCK_SEQPACKET = nil, --- @type integer SOCK_STREAM = nil, --- @type integer SOL_IP = nil, --- @type integer SOL_SOCKET = nil, --- @type integer SOL_TCP = nil, --- @type integer SOL_UDP = nil, --- @type integer SO_ACCEPTCONN = nil, --- @type integer SO_BROADCAST = nil, --- @type integer SO_DEBUG = nil, --- @type integer SO_DONTROUTE = nil, --- @type integer SO_ERROR = nil, --- @type integer SO_KEEPALIVE = nil, --- @type integer SO_LINGER = nil, --- @type integer SO_RCVBUF = nil, --- @type integer SO_RCVLOWAT = nil, --- @type integer SO_RCVTIMEO = nil, --- @type integer SO_REUSEADDR = nil, --- @type integer SO_REUSEPORT = nil, --- @type integer SO_SNDBUF = nil, --- @type integer SO_SNDLOWAT = nil, --- @type integer SO_SNDTIMEO = nil, --- @type integer SO_TYPE = nil, --- @type integer TCP_CORK = nil, --- @type integer TCP_DEFER_ACCEPT = nil, --- @type integer TCP_FASTOPEN = nil, --- @type integer TCP_FASTOPEN_CONNECT = nil, --- @type integer TCP_KEEPCNT = nil, --- @type integer TCP_KEEPIDLE = nil, --- @type integer TCP_KEEPINTVL = nil, --- @type integer TCP_MAXSEG = nil, --- @type integer TCP_NODELAY = nil, --- @type integer TCP_NOTSENT_LOWAT = nil, --- @type integer TCP_QUICKACK = nil, --- @type integer TCP_SAVED_SYN = nil, --- @type integer TCP_SAVE_SYN = nil, --- @type integer TCP_SYNCNT = nil, --- @type integer TCP_WINDOW_CLAMP = nil, --- @type integer UTIME_NOW = nil, --- @type integer UTIME_OMIT = nil, --- @type integer WNOHANG = nil, --- @type integer W_OK = nil, --- @type integer X_OK = nil } --- Opens file. --- --- Returns a file descriptor integer that needs to be closed, e.g. --- --- fd = assert(unix.open("/etc/passwd", unix.O_RDONLY)) --- print(unix.read(fd)) --- unix.close(fd) --- --- `flags` should have one of: --- --- - `O_RDONLY`: open for reading (default) --- - `O_WRONLY`: open for writing --- - `O_RDWR`: open for reading and writing --- --- The following values may also be OR'd into `flags`: --- --- - `O_CREAT` create file if it doesn't exist --- - `O_TRUNC` automatic ftruncate(fd,0) if exists --- - `O_CLOEXEC` automatic close() upon execve() --- - `O_EXCL` exclusive access (see below) --- - `O_APPEND` open file for append only --- - `O_NONBLOCK` asks read/write to fail with EAGAIN rather than block --- - `O_DIRECT` it's complicated (not supported on Apple and OpenBSD) --- - `O_DIRECTORY` useful for stat'ing (hint on UNIX but required on NT) --- - `O_TMPFILE` try to make temp more secure (Linux and Windows only) --- - `O_NOFOLLOW` fail if it's a symlink (zero on Windows) --- - `O_DSYNC` it's complicated (zero on non-Linux/Apple) --- - `O_RSYNC` it's complicated (zero on non-Linux/Apple) --- - `O_PATH` it's complicated (zero on non-Linux) --- - `O_VERIFY` it's complicated (zero on non-FreeBSD) --- - `O_SHLOCK` it's complicated (zero on non-BSD) --- - `O_EXLOCK` it's complicated (zero on non-BSD) --- - `O_NOATIME` don't record access time (zero on non-Linux) --- - `O_RANDOM` hint random access intent (zero on non-Windows) --- - `O_SEQUENTIAL` hint sequential access intent (zero on non-Windows) --- - `O_COMPRESSED` ask fs to abstract compression (zero on non-Windows) --- - `O_INDEXED` turns on that slow performance (zero on non-Windows) --- --- There are three regular combinations for the above flags: --- --- - `O_RDONLY`: Opens existing file for reading. If it doesn't exist --- then nil is returned and errno will be `ENOENT` (or in some other --- cases `ENOTDIR`). --- --- - `O_WRONLY|O_CREAT|O_TRUNC`: Creates file. If it already exists, --- then the existing copy is destroyed and the opened file will --- start off with a length of zero. This is the behavior of the --- traditional creat() system call. --- --- - `O_WRONLY|O_CREAT|O_EXCL`: Create file only if doesn't exist --- already. If it does exist then `nil` is returned along with --- `errno` set to `EEXIST`. --- --- `dirfd` defaults to to `unix.AT_FDCWD` and may optionally be set to --- a directory file descriptor to which `path` is relative. --- --- Returns `ENOENT` if `path` doesn't exist. --- --- Returns `ENOTDIR` if `path` contained a directory component that --- wasn't a directory ---. ---@param path string ---@param flags integer ---@param mode integer? ---@param dirfd integer? ---@return integer fd ---@nodiscard ---@overload fun(path: string, flags: integer, mode?: integer, dirfd?: integer): nil, error: unix.Errno function unix.open(path, flags, mode, dirfd) end --- Closes file descriptor. --- --- This function should never be called twice for the same file --- descriptor, regardless of whether or not an error happened. The file --- descriptor is always gone after close is called. So it technically --- always succeeds, but that doesn't mean an error should be ignored. --- For example, on NFS a close failure could indicate data loss. --- --- Closing does not mean that scheduled i/o operations have been --- completed. You'd need to use fsync() or fdatasync() beforehand to --- ensure that. You shouldn't need to do that normally, because our --- close implementation guarantees a consistent view, since on systems --- where it isn't guaranteed (like Windows) close will implicitly sync. --- --- File descriptors are automatically closed on exit(). --- --- Returns `EBADF` if `fd` wasn't valid. --- --- Returns `EINTR` possibly maybe. --- --- Returns `EIO` if an i/o error occurred. ---@param fd integer ---@return true ---@overload fun(fd: integer): nil, error: unix.Errno function unix.close(fd) end --- Reads from file descriptor. --- --- This function returns empty string on end of file. The exception is --- if `bufsiz` is zero, in which case an empty returned string means --- the file descriptor works. ---@param fd integer ---@param bufsiz string? ---@param offset integer? ---@return string data ---@overload fun(fd: integer, bufsiz?: string, offset?: integer): nil, error: unix.Errno function unix.read(fd, bufsiz, offset) end --- Writes to file descriptor. ---@param fd integer ---@param data string ---@param offset integer? ---@return integer wrotebytes ---@overload fun(fd: integer, data: string, offset?: integer): nil, error: unix.Errno function unix.write(fd, data, offset) end --- Invokes `_Exit(exitcode)` on the process. This will immediately --- halt the current process. Memory will be freed. File descriptors --- will be closed. Any open connections it owns will be reset. This --- function never returns. ---@param exitcode integer? function unix.exit(exitcode) end --- Returns raw environment variables. --- --- This allocates and constructs the C/C++ `environ` variable as a Lua --- table consisting of string keys and string values. --- --- This data structure preserves casing. On Windows NT, by convention, --- environment variable keys are treated in a case-insensitive way. It --- is the responsibility of the caller to consider this. --- --- This data structure preserves valueless variables. It's possible on --- both UNIX and Windows to have an environment variable without an --- equals, even though it's unusual. --- --- This data structure preserves duplicates. For example, on Windows, --- there's some irregular uses of environment variables such as how the --- command prompt inserts multiple environment variables with empty --- string as keys, for its internal bookkeeping. --- ---@return table<string, string?> ---@nodiscard function unix.environ() end --- Creates a new process mitosis style. --- --- This system call returns twice. The parent process gets the nonzero --- pid. The child gets zero. --- --- Here's a simple usage example of creating subprocesses, where we --- fork off a child worker from a main process hook callback to do some --- independent chores, such as sending an HTTP request back to redbean. --- --- -- as soon as server starts, make a fetch to the server --- -- then signal redbean to shutdown when fetch is complete --- local onServerStart = function() --- if assert(unix.fork()) == 0 then --- local ok, headers, body = Fetch('http://127.0.0.1:8080/test') --- unix.kill(unix.getppid(), unix.SIGTERM) --- unix.exit(0) --- end --- end --- OnServerStart = onServerStart --- --- We didn't need to use `wait()` here, because (a) we want redbean to go --- back to what it was doing before as the `Fetch()` completes, and (b) --- redbean's main process already has a zombie collector. However it's --- a moot point, since once the fetch is done, the child process then --- asks redbean to gracefully shutdown by sending SIGTERM its parent. --- --- This is actually a situation where we *must* use fork, because the --- purpose of the main redbean process is to call accept() and create --- workers. So if we programmed redbean to use the main process to send --- a blocking request to itself instead, then redbean would deadlock --- and never be able to accept() the client. --- --- While deadlocking is an extreme example, the truth is that latency --- issues can crop up for the same reason that just cause jitter --- instead, and as such, can easily go unnoticed. For example, if you --- do soemething that takes longer than a few milliseconds from inside --- your redbean heartbeat, then that's a few milliseconds in which --- redbean is no longer concurrent, and tail latency is being added to --- its ability to accept new connections. fork() does a great job at --- solving this. --- --- If you're not sure how long something will take, then when in doubt, --- fork off a process. You can then report its completion to something --- like SQLite. Redbean makes having lots of processes cheap. On Linux --- they're about as lightweight as what heavyweight environments call --- greenlets. You can easily have 10,000 Redbean workers on one PC. --- --- Here's some benchmarks for fork() performance across platforms: --- --- Linux 5.4 fork l: 97,200𝑐 31,395𝑛𝑠 [metal] --- FreeBSD 12 fork l: 236,089𝑐 78,841𝑛𝑠 [vmware] --- Darwin 20.6 fork l: 295,325𝑐 81,738𝑛𝑠 [metal] --- NetBSD 9 fork l: 5,832,027𝑐 1,947,899𝑛𝑠 [vmware] --- OpenBSD 6.8 fork l: 13,241,940𝑐 4,422,103𝑛𝑠 [vmware] --- Windows10 fork l: 18,802,239𝑐 6,360,271𝑛𝑠 [metal] --- --- One of the benefits of using `fork()` is it creates an isolation --- barrier between the different parts of your app. This can lead to --- enhanced reliability and security. For example, redbean uses fork so --- it can wipe your ssl keys from memory before handing over control to --- request handlers that process untrusted input. It also ensures that --- if your Lua app crashes, it won't take down the server as a whole. --- Hence it should come as no surprise that `fork()` would go slower on --- operating systems that have more security features. So depending on --- your use case, you can choose the operating system that suits you. --- ---@return integer|0 childpid ---@overload fun(): nil, error: unix.Errno function unix.fork() end --- Performs `$PATH` lookup of executable. --- --- unix = require 'unix' --- prog = assert(unix.commandv('ls')) --- unix.execve(prog, {prog, '-hal', '.'}, {'PATH=/bin'}) --- unix.exit(127) --- --- We automatically suffix `.com` and `.exe` for all platforms when --- path searching. By default, the current directory is not on the --- path. If `prog` is an absolute path, then it's returned as-is. If --- `prog` contains slashes then it's not path searched either and will --- be returned if it exists. ---@param prog string ---@return string path ---@overload fun(prog: string): nil, error: unix.Errno function unix.commandv(prog) end --- Exits current process, replacing it with a new instance of the --- specified program. `prog` needs to be an absolute path, see --- commandv(). `env` defaults to to the current `environ`. Here's --- a basic usage example: --- --- unix.execve("/bin/ls", {"/bin/ls", "-hal"}, {"PATH=/bin"}) --- unix.exit(127) --- --- `prog` needs to be the resolved pathname of your executable. You --- can use commandv() to search your `PATH`. --- --- `args` is a string list table. The first element in `args` --- should be `prog`. Values are coerced to strings. This parameter --- defaults to `{prog}`. --- --- `env` is a string list table. Values are coerced to strings. No --- ordering requirement is imposed. By convention, each string has its --- key and value divided by an equals sign without spaces. If this --- parameter is not specified, it'll default to the C/C++ `environ` --- variable which is inherited from the shell that launched redbean. --- It's the responsibility of the user to supply a sanitized environ --- when spawning untrusted processes. --- --- `execve()` is normally called after `fork()` returns `0`. If that isn't --- the case, then your redbean worker will be destroyed. --- --- This function never returns on success. --- --- `EAGAIN` is returned if you've enforced a max number of --- processes using `setrlimit(RLIMIT_NPROC)`. --- ---@param prog string ---@param args string[] ---@param env string[] ---@return nil, unix.Errno error ---@overload fun(prog: string): nil, error: unix.Errno function unix.execve(prog, args, env) end --- Duplicates file descriptor. --- --- `newfd` may be specified to choose a specific number for the new --- file descriptor. If it's already open, then the preexisting one will --- be silently closed. `EINVAL` is returned if `newfd` equals `oldfd`. --- --- `flags` can have `O_CLOEXEC` which means the returned file --- descriptors will be automatically closed upon execve(). --- --- `lowest` defaults to zero and defines the lowest numbered file --- descriptor that's acceptable to use. If `newfd` is specified then --- `lowest` is ignored. For example, if you wanted to duplicate --- standard input, then: --- --- stdin2 = assert(unix.dup(0, nil, unix.O_CLOEXEC, 3)) --- --- Will ensure that, in the rare event standard output or standard --- error are closed, you won't accidentally duplicate standard input to --- those numbers. --- ---@param oldfd integer ---@param newfd integer? ---@param flags integer? ---@param lowest integer? ---@return integer newfd ---@overload fun(oldfd: integer, newfd?: integer, flags?: integer, lowest?: integer): nil, error: unix.Errno function unix.dup(oldfd, newfd, flags, lowest) end --- Creates fifo which enables communication between processes. --- ---@param flags integer? may have any combination (using bitwise OR) of: --- --- - `O_CLOEXEC`: Automatically close file descriptor upon execve() --- --- - `O_NONBLOCK`: Request `EAGAIN` be raised rather than blocking --- --- - `O_DIRECT`: Enable packet mode w/ atomic reads and writes, so long --- as they're no larger than `PIPE_BUF` (guaranteed to be 512+ bytes) --- with support limited to Linux, Windows NT, FreeBSD, and NetBSD. --- --- Returns two file descriptors: one for reading and one for writing. --- --- Here's an example of how pipe(), fork(), dup(), etc. may be used --- to serve an HTTP response containing the output of a subprocess. --- --- local unix = require "unix" --- ls = assert(unix.commandv("ls")) --- reader, writer = assert(unix.pipe()) --- if assert(unix.fork()) == 0 then --- unix.close(1) --- unix.dup(writer) --- unix.close(writer) --- unix.close(reader) --- unix.execve(ls, {ls, "-Shal"}) --- unix.exit(127) --- else --- unix.close(writer) --- SetHeader('Content-Type', 'text/plain') --- while true do --- data, err = unix.read(reader) --- if data then --- if data ~= "" then --- Write(data) --- else --- break --- end --- elseif err:errno() ~= EINTR then --- Log(kLogWarn, tostring(err)) --- break --- end --- end --- assert(unix.close(reader)) --- assert(unix.wait()) --- end --- ---@return integer reader, integer writer ---@nodiscard ---@overload fun(flags?: integer): nil, error: unix.Errno function unix.pipe(flags) end --- Waits for subprocess to terminate. --- --- `pid` defaults to `-1` which means any child process. Setting --- `pid` to `0` is equivalent to `-getpid()`. If `pid < -1` then --- that means wait for any pid in the process group `-pid`. Then --- lastly if `pid > 0` then this waits for a specific process id --- --- Options may have `WNOHANG` which means don't block, check for --- the existence of processes that are already dead (technically --- speaking zombies) and if so harvest them immediately. --- --- Returns the process id of the child that terminated. In other --- cases, the returned `pid` is nil and `errno` is non-nil. --- --- The returned `wstatus` contains information about the process --- exit status. It's a complicated integer and there's functions --- that can help interpret it. For example: --- --- -- wait for zombies --- -- traditional technique for SIGCHLD handlers --- while true do --- pid, status = unix.wait(-1, unix.WNOHANG) --- if pid then --- if unix.WIFEXITED(status) then --- print('child', pid, 'exited with', --- unix.WEXITSTATUS(status)) --- elseif unix.WIFSIGNALED(status) then --- print('child', pid, 'crashed with', --- unix.strsignal(unix.WTERMSIG(status))) --- end --- elseif status:errno() == unix.ECHILD then --- Log(kLogDebug, 'no more zombies') --- break --- else --- Log(kLogWarn, tostring(err)) --- break --- end --- end --- ---@param pid? integer ---@param options? integer ---@return integer pid, integer wstatus, unix.Rusage rusage ---@overload fun(pid?: integer, options?: integer): nil, error: unix.Errno function unix.wait(pid, options) end --- Returns `true` if process exited cleanly. ---@param wstatus integer ---@return boolean ---@nodiscard function unix.WIFEXITED(wstatus) end --- Returns code passed to exit() assuming `WIFEXITED(wstatus)` is true. ---@param wstatus integer ---@return integer exitcode uint8 ---@nodiscard function unix.WEXITSTATUS(wstatus) end --- Returns `true` if process terminated due to a signal. ---@param wstatus integer ---@return boolean ---@nodiscard function unix.WIFSIGNALED(wstatus) end --- Returns signal that caused process to terminate assuming --- `WIFSIGNALED(wstatus)` is `true`. ---@param wstatus integer ---@return integer sig uint8 ---@nodiscard function unix.WTERMSIG(wstatus) end --- Returns process id of current process. --- --- This function does not fail. ---@return integer pid ---@nodiscard function unix.getpid() end --- Returns process id of parent process. --- --- This function does not fail. ---@return integer pid ---@nodiscard function unix.getppid() end --- Sends signal to process(es). --- --- The impact of this action can be terminating the process, or --- interrupting it to request something happen. --- --- `pid` can be: --- --- - `pid > 0` signals one process by id --- - `== 0` signals all processes in current process group --- - `-1` signals all processes possible (except init) --- - `< -1` signals all processes in -pid process group --- --- `sig` can be: --- --- - `0` checks both if pid exists and we can signal it --- - `SIGINT` sends ctrl-c keyboard interrupt --- - `SIGQUIT` sends backtrace and exit signal --- - `SIGTERM` sends shutdown signal --- - etc. --- --- Windows NT only supports the kill() signals required by the ANSI C89 --- standard, which are `SIGINT` and `SIGQUIT`. All other signals on the --- Windows platform that are sent to another process via kill() will be --- treated like `SIGKILL`. ---@param pid integer ---@param sig integer ---@return true ---@overload fun(pid: integer, sid: integer): nil, error: unix.Errno function unix.kill(pid, sig) end --- Triggers signal in current process. --- --- This is pretty much the same as `kill(getpid(), sig)`. ---@param sig integer ---@return integer rc ---@overload fun(sig: integer): nil, error: unix.Errno function unix.raise(sig) end --- Checks if effective user of current process has permission to access file. ---@param path string ---@param how integer can be `R_OK`, `W_OK`, `X_OK`, or `F_OK` to check for read, write, execute, and existence respectively. ---@param flags? integer may have any of: --- - `AT_SYMLINK_NOFOLLOW`: do not follow symbolic links. ---@param dirfd? integer ---@return true ---@overload fun(path: string, how: integer, flags?: integer, dirfd?: integer): nil, error: unix.Errno function unix.access(path, how, flags, dirfd) end --- Makes directory. --- --- `path` is the path of the directory you wish to create. --- --- `mode` is octal permission bits, e.g. `0755`. --- --- Fails with `EEXIST` if `path` already exists, whether it be a --- directory or a file. --- --- Fails with `ENOENT` if the parent directory of the directory you --- want to create doesn't exist. For making `a/really/long/path/` --- consider using makedirs() instead. --- --- Fails with `ENOTDIR` if a parent directory component existed that --- wasn't a directory. --- --- Fails with `EACCES` if the parent directory doesn't grant write --- permission to the current user. --- --- Fails with `ENAMETOOLONG` if the path is too long. --- ---@param path string ---@param mode? integer ---@param dirfd? integer ---@return true ---@overload fun(path: string, mode?: integer, dirfd?: integer): nil, error: unix.Errno function unix.mkdir(path, mode, dirfd) end --- Unlike mkdir() this convenience wrapper will automatically create --- parent parent directories as needed. If the directory already exists --- then, unlike mkdir() which returns EEXIST, the makedirs() function --- will return success. --- --- `path` is the path of the directory you wish to create. --- --- `mode` is octal permission bits, e.g. `0755`. --- ---@param path string ---@param mode? integer ---@return true ---@overload fun(path: string, mode?: integer): nil, error: unix.Errno function unix.makedirs(path, mode) end --- Changes current directory to `path`. ---@param path string ---@return true ---@overload fun(path: string): nil, error: unix.Errno function unix.chdir(path) end --- Removes file at `path`. --- --- If `path` refers to a symbolic link, the link is removed. --- --- Returns `EISDIR` if `path` refers to a directory. See `rmdir()`. --- ---@param path string ---@param dirfd? integer ---@return true ---@overload fun(path: string, dirfd?: integer): nil, error: unix.Errno function unix.unlink(path, dirfd) end --- Removes empty directory at `path`. --- --- Returns `ENOTDIR` if `path` isn't a directory, or a path component --- in `path` exists yet wasn't a directory. --- ---@param path string ---@param dirfd? integer ---@return true ---@overload fun(path: string, dirfd?: integer): nil, error: unix.Errno function unix.rmdir(path, dirfd) end --- Renames file or directory. ---@param oldpath string ---@param newpath string ---@param olddirfd integer ---@param newdirfd integer ---@return true ---@overload fun(oldpath: string, newpath: string): true ---@overload fun(oldpath: string, newpath: string, olddirfd: integer, newdirfd: integer): nil, error: unix.Errno ---@overload fun(oldpath: string, newpath: string): nil, error: unix.Errno function unix.rename(oldpath, newpath, olddirfd, newdirfd) end ---Creates hard link, so your underlying inode has two names. ---@param existingpath string ---@param newpath string ---@param flags integer ---@param olddirfd integer ---@param newdirfd integer ---@return true ---@overload fun(existingpath: string, newpath: string, flags?: integer): true ---@overload fun(existingpath: string, newpath: string, flags?: integer): nil, error: unix.Errno ---@overload fun(existingpath: string, newpath: string, flags: integer, olddirfd: integer, newdirfd: integer): true ---@overload fun(existingpath: string, newpath: string, flags: integer, olddirfd: integer, newdirfd: integer): nil, error: unix.Errno function unix.link(existingpath, newpath, flags, olddirfd, newdirfd) end --- Creates symbolic link. --- --- On Windows NT a symbolic link is called a "reparse point" and can --- only be created from an administrator account. Your redbean will --- automatically request the appropriate permissions. ---@param target string ---@param linkpath string ---@param newdirfd? integer ---@return true ---@overload fun(target: string, linkpath: string, newdirfd?: integer): nil, error: unix.Errno function unix.symlink(target, linkpath, newdirfd) end --- Reads contents of symbolic link. --- --- Note that broken links are supported on all platforms. A symbolic --- link can contain just about anything. It's important to not assume --- that `content` will be a valid filename. --- --- On Windows NT, this function transliterates `\` to `/` and --- furthermore prefixes `//?/` to WIN32 DOS-style absolute paths, --- thereby assisting with simple absolute filename checks in addition --- to enabling one to exceed the traditional 260 character limit. ---@param path string ---@param dirfd? integer ---@return string content ---@nodiscard ---@overload fun(path: string, dirfd?: integer): nil, error: unix.Errno function unix.readlink(path, dirfd) end --- Returns absolute path of filename, with `.` and `..` components --- removed, and symlinks will be resolved. ---@param path string ---@return string path ---@nodiscard ---@overload fun(path: string): nil, error: unix.Errno function unix.realpath(path) end --- Changes access and/or modified timestamps on file. --- --- `path` is a string with the name of the file. --- --- The `asecs` and `ananos` parameters set the access time. If they're --- none or nil, the current time will be used. --- --- The `msecs` and `mnanos` parameters set the modified time. If --- they're none or nil, the current time will be used. --- --- The nanosecond parameters (`ananos` and `mnanos`) must be on the --- interval [0,1000000000) or `unix.EINVAL` is raised. On XNU this is --- truncated to microsecond precision. On Windows NT, it's truncated to --- hectonanosecond precision. These nanosecond parameters may also be --- set to one of the following special values: --- --- - `unix.UTIME_NOW`: Fill this timestamp with current time. This --- feature is not available on old versions of Linux, e.g. RHEL5. --- --- - `unix.UTIME_OMIT`: Do not alter this timestamp. This feature is --- not available on old versions of Linux, e.g. RHEL5. --- --- `dirfd` is a file descriptor integer opened with `O_DIRECTORY` --- that's used for relative path names. It defaults to `unix.AT_FDCWD`. --- --- `flags` may have have any of the following flags bitwise or'd --- --- - `AT_SYMLINK_NOFOLLOW`: Do not follow symbolic links. This makes it --- possible to edit the timestamps on the symbolic link itself, --- rather than the file it points to. --- ---@param path string ---@param asecs integer ---@param ananos integer ---@param msecs integer ---@param mnanos integer ---@param dirfd? integer ---@param flags? integer ---@return 0 ---@overload fun(path: string): 0 ---@overload fun(path: string, asecs: integer, ananos: integer, msecs: integer, mnanos: integer, dirfd?: integer, flags?: integer): nil, error: unix.Errno ---@overload fun(path: string): nil, error: unix.Errno function unix.utimensat(path, asecs, ananos, msecs, mnanos, dirfd, flags) end --- Changes access and/or modified timestamps on file descriptor. --- --- `fd` is the file descriptor of a file opened with `unix.open`. --- --- The `asecs` and `ananos` parameters set the access time. If they're --- none or nil, the current time will be used. --- --- The `msecs` and `mnanos` parameters set the modified time. If --- they're none or nil, the current time will be used. --- --- The nanosecond parameters (`ananos` and `mnanos`) must be on the --- interval [0,1000000000) or `unix.EINVAL` is raised. On XNU this is --- truncated to microsecond precision. On Windows NT, it's truncated to --- hectonanosecond precision. These nanosecond parameters may also be --- set to one of the following special values: --- --- - `unix.UTIME_NOW`: Fill this timestamp with current time. --- --- - `unix.UTIME_OMIT`: Do not alter this timestamp. --- --- This system call is currently not available on very old versions of --- Linux, e.g. RHEL5. --- ---@param fd integer ---@param asecs integer ---@param ananos integer ---@param msecs integer ---@param mnanos integer ---@return 0 ---@overload fun(fd: integer): 0 ---@overload fun(fd: integer, asecs: integer, ananos: integer, msecs: integer, mnanos: integer): nil, error: unix.Errno ---@overload fun(fd: integer): nil, error: unix.Errno function unix.futimens(fd, asecs, ananos, msecs, mnanos) end --- Changes user and group on file. --- --- Returns `ENOSYS` on Windows NT. ---@param path string ---@param uid integer ---@param gid integer ---@param flags? integer ---@param dirfd? integer ---@return true ---@overload fun(path: string, uid: integer, gid: integer, flags?: integer, dirfd?: integer): nil, error: unix.Errno function unix.chown(path, uid, gid, flags, dirfd) end --- Changes mode bits on file. --- --- On Windows NT the chmod system call only changes the read-only --- status of a file. ---@param path string ---@param mode integer ---@param flags? integer ---@param dirfd? integer ---@return true ---@overload fun(path: string, mode: integer, flags?: integer, dirfd?: integer): nil, error: unix.Errno function unix.chmod(path, mode, flags, dirfd) end --- Returns current working directory. --- --- On Windows NT, this function transliterates `\` to `/` and --- furthermore prefixes `//?/` to WIN32 DOS-style absolute paths, --- thereby assisting with simple absolute filename checks in addition --- to enabling one to exceed the traditional 260 character limit. ---@return string path ---@nodiscard ---@overload fun(): nil, error: unix.Errno function unix.getcwd() end --- Recursively removes filesystem path. --- --- Like `unix.makedirs()` this function isn't actually a system call but --- rather is a Libc convenience wrapper. It's intended to be equivalent --- to using the UNIX shell's `rm -rf path` command. --- ---@param path string the file or directory path you wish to destroy. ---@return true ---@overload fun(path: string): nil, error: unix.Errno function unix.rmrf(path) end --- Manipulates file descriptor. --- --- `cmd` may be one of: --- --- - `unix.F_GETFD` Returns file descriptor flags. --- - `unix.F_SETFD` Sets file descriptor flags. --- - `unix.F_GETFL` Returns file descriptor status flags. --- - `unix.F_SETFL` Sets file descriptor status flags. --- - `unix.F_SETLK` Acquires lock on file interval. --- - `unix.F_SETLKW` Waits for lock on file interval. --- - `unix.F_GETLK` Acquires information about lock. --- --- unix.fcntl(fd:int, unix.F_GETFD) --- ├─→ flags:int --- └─→ nil, unix.Errno --- --- Returns file descriptor flags. --- --- The returned `flags` may include any of: --- --- - `unix.FD_CLOEXEC` if `fd` was opened with `unix.O_CLOEXEC`. --- --- Returns `EBADF` if `fd` isn't open. --- --- unix.fcntl(fd:int, unix.F_SETFD, flags:int) --- ├─→ true --- └─→ nil, unix.Errno --- --- Sets file descriptor flags. --- --- `flags` may include any of: --- --- - `unix.FD_CLOEXEC` to re-open `fd` with `unix.O_CLOEXEC`. --- --- Returns `EBADF` if `fd` isn't open. --- --- unix.fcntl(fd:int, unix.F_GETFL) --- ├─→ flags:int --- └─→ nil, unix.Errno --- --- Returns file descriptor status flags. --- --- `flags & unix.O_ACCMODE` includes one of: --- --- - `O_RDONLY` --- - `O_WRONLY` --- - `O_RDWR` --- --- Examples of values `flags & ~unix.O_ACCMODE` may include: --- --- - `O_NONBLOCK` --- - `O_APPEND` --- - `O_SYNC` --- - `O_ASYNC` --- - `O_NOATIME` on Linux --- - `O_RANDOM` on Windows --- - `O_SEQUENTIAL` on Windows --- - `O_DIRECT` on Linux/FreeBSD/NetBSD/Windows --- --- Examples of values `flags & ~unix.O_ACCMODE` won't include: --- --- - `O_CREAT` --- - `O_TRUNC` --- - `O_EXCL` --- - `O_NOCTTY` --- --- Returns `EBADF` if `fd` isn't open. --- --- unix.fcntl(fd:int, unix.F_SETFL, flags:int) --- ├─→ true --- └─→ nil, unix.Errno --- --- Changes file descriptor status flags. --- --- Examples of values `flags` may include: --- --- - `O_NONBLOCK` --- - `O_APPEND` --- - `O_SYNC` --- - `O_ASYNC` --- - `O_NOATIME` on Linux --- - `O_RANDOM` on Windows --- - `O_SEQUENTIAL` on Windows --- - `O_DIRECT` on Linux/FreeBSD/NetBSD/Windows --- --- These values should be ignored: --- --- - `O_RDONLY`, `O_WRONLY`, `O_RDWR` --- - `O_CREAT`, `O_TRUNC`, `O_EXCL` --- - `O_NOCTTY` --- --- Returns `EBADF` if `fd` isn't open. --- --- unix.fcntl(fd:int, unix.F_SETLK[, type[, start[, len[, whence]]]]) --- unix.fcntl(fd:int, unix.F_SETLKW[, type[, start[, len[, whence]]]]) --- ├─→ true --- └─→ nil, unix.Errno --- --- Acquires lock on file interval. --- --- POSIX Advisory Locks allow multiple processes to leave voluntary --- hints to each other about which portions of a file they're using. --- --- The command may be: --- --- - `F_SETLK` to acquire lock if possible --- - `F_SETLKW` to wait for lock if necessary --- --- `fd` is file descriptor of open() file. --- --- `type` may be one of: --- --- - `F_RDLCK` for read lock (default) --- - `F_WRLCK` for read/write lock --- - `F_UNLCK` to unlock --- --- `start` is 0-indexed byte offset into file. The default is zero. --- --- `len` is byte length of interval. Zero is the default and it means --- until the end of the file. --- --- `whence` may be one of: --- --- - `SEEK_SET` start from beginning (default) --- - `SEEK_CUR` start from current position --- - `SEEK_END` start from end --- --- Returns `EAGAIN` if lock couldn't be acquired. POSIX says this --- theoretically could also be `EACCES` but we haven't seen this --- behavior on any of our supported platforms. --- --- Returns `EBADF` if `fd` wasn't open. --- --- unix.fcntl(fd:int, unix.F_GETLK[, type[, start[, len[, whence]]]]) --- ├─→ unix.F_UNLCK --- ├─→ type, start, len, whence, pid --- └─→ nil, unix.Errno --- --- Acquires information about POSIX advisory lock on file. --- --- This function accepts the same parameters as fcntl(F_SETLK) and --- tells you if the lock acquisition would be successful for a given --- range of bytes. If locking would have succeeded, then F_UNLCK is --- returned. If the lock would not have succeeded, then information --- about a conflicting lock is returned. --- --- Returned `type` may be `F_RDLCK` or `F_WRLCK`. --- --- Returned `pid` is the process id of the current lock owner. --- --- This function is currently not supported on Windows. --- --- Returns `EBADF` if `fd` wasn't open. --- ---@param fd integer ---@param cmd integer ---@param ... any ---@return any ... ---@overload fun(fd: integer, unix.F_GETFD: integer): flags: integer ---@overload fun(fd: integer, unix.F_GETFD: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_SETFD: integer, flags: integer): true ---@overload fun(fd: integer, unix.F_SETFD: integer, flags: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_GETFL: integer): flags: integer ---@overload fun(fd: integer, unix.F_GETFL: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_SETFL: integer, flags: integer): true ---@overload fun(fd: integer, unix.F_SETFL: integer, flags: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_SETLK: integer, type?: integer, start?: integer, len?: integer, whence?: integer): true ---@overload fun(fd: integer, unix.F_SETLK: integer, type?: integer, start?: integer, len?: integer, whence?: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_SETLKW: integer, type?: integer, start?: integer, len?: integer, whence?: integer): true ---@overload fun(fd: integer, unix.F_SETLKW: integer, type?: integer, start?: integer, len?: integer, whence?: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unix.F_GETLK: integer, type?: integer, start?: integer, len?: integer, whence?: integer): unix.F_UNLCK: integer ---@overload fun(fd: integer, unix.F_GETLK: integer, type?: integer, start?: integer, len?: integer, whence?: integer): type: integer, start: integer, len: integer, whence: integer, pid: integer ---@overload fun(fd: integer, unix.F_GETLK: integer, type?: integer, start?: integer, len?: integer, whence?: integer): nil, error: unix.Errno function unix.fcntl(fd, cmd, ...) end ---Gets session id. ---@param pid integer ---@return integer sid ---@nodiscard ---@overload fun(pid: integer): nil, error: unix.Errno function unix.getsid(pid) end --- Gets process group id. ---@return integer pgid ---@nodiscard ---@overload fun(): nil, error: unix.Errno function unix.getpgrp() end --- Sets process group id. This is the same as `setpgid(0,0)`. ---@return integer pgid ---@overload fun(): nil, error: unix.Errno function unix.setpgrp() end --- Sets process group id the modern way. ---@param pid integer ---@param pgid integer ---@return true ---@overload fun(pid: integer, pgid: integer): nil, error: unix.Errno function unix.setpgid(pid, pgid) end --- Gets process group id the modern way. ---@param pid integer ---@overload fun(pid: integer): nil, error: unix.Errno function unix.getpgid(pid) end --- Sets session id. --- --- This function can be used to create daemons. --- --- Fails with `ENOSYS` on Windows NT. ---@return integer sid ---@overload fun(): nil, error: unix.Errno function unix.setsid() end --- Gets real user id. --- --- On Windows this system call is polyfilled by running `GetUserNameW()` --- through Knuth's multiplicative hash. --- --- This function does not fail. ---@return integer uid ---@nodiscard function unix.getuid() end --- Sets real group id. --- --- On Windows this system call is polyfilled as getuid(). --- --- This function does not fail. ---@return integer gid ---@nodiscard function unix.getgid() end --- Gets effective user id. --- --- For example, if your redbean is a setuid binary, then getuid() will --- return the uid of the user running the program, and geteuid() shall --- return zero which means root, assuming that's the file owning user. --- --- On Windows this system call is polyfilled as getuid(). --- --- This function does not fail. ---@return integer uid ---@nodiscard function unix.geteuid() end --- Gets effective group id. --- --- On Windows this system call is polyfilled as getuid(). --- --- This function does not fail. ---@return integer gid ---@nodiscard function unix.getegid() end --- Changes root directory. --- --- Returns `ENOSYS` on Windows NT. ---@param path string ---@return true ---@overload fun(path: string): nil, error: unix.Errno function unix.chroot(path) end --- Sets user id. --- --- One use case for this function is dropping root privileges. Should --- you ever choose to run redbean as root and decide not to use the --- `-G` and `-U` flags, you can replicate that behavior in the Lua --- processes you spawn as follows: --- --- ok, err = unix.setgid(1000) -- check your /etc/groups --- if not ok then Log(kLogFatal, tostring(err)) end --- ok, err = unix.setuid(1000) -- check your /etc/passwd --- if not ok then Log(kLogFatal, tostring(err)) end --- --- If your goal is to relinquish privileges because redbean is a setuid --- binary, then things are more straightforward: --- --- ok, err = unix.setgid(unix.getgid()) --- if not ok then Log(kLogFatal, tostring(err)) end --- ok, err = unix.setuid(unix.getuid()) --- if not ok then Log(kLogFatal, tostring(err)) end --- --- See also the setresuid() function and be sure to refer to your local --- system manual about the subtleties of changing user id in a way that --- isn't restorable. --- --- Returns `ENOSYS` on Windows NT if `uid` isn't `getuid()`. ---@param uid integer ---@return true ---@overload fun(uid: integer): nil, error: unix.Errno function unix.setuid(uid) end ---Sets user id for file system ops. ---@param uid integer ---@return true ---@overload fun(uid: integer): nil, error: unix.Errno function unix.setfsuid(uid) end ---Sets group id. --- ---Returns `ENOSYS` on Windows NT if `gid` isn't `getgid()`. ---@param gid integer ---@return true ---@overload fun(gid: integer): nil, error: unix.Errno function unix.setgid(gid) end ---Sets real, effective, and saved user ids. --- ---If any of the above parameters are -1, then it's a no-op. --- ---Returns `ENOSYS` on Windows NT. ---Returns `ENOSYS` on Macintosh and NetBSD if `saved` isn't -1. ---@param real integer ---@param effective integer ---@param saved integer ---@return true ---@overload fun(real: integer, effective: integer, saved: integer): nil, error: unix.Errno function unix.setresuid(real, effective, saved) end --- Sets real, effective, and saved group ids. --- --- If any of the above parameters are -1, then it's a no-op. --- --- Returns `ENOSYS` on Windows NT. --- Returns `ENOSYS` on Macintosh and NetBSD if `saved` isn't -1. ---@param real integer ---@param effective integer ---@param saved integer ---@return true ---@overload fun(real: integer, effective: integer, saved: integer): nil, error: unix.Errno function unix.setresgid(real, effective, saved) end --- Sets file permission mask and returns the old one. --- --- This is used to remove bits from the `mode` parameter of functions --- like open() and mkdir(). The masks typically used are 027 and 022. --- Those masks ensure that, even if a file is created with 0666 bits, --- it'll be turned into 0640 or 0644 so that users other than the owner --- can't modify it. --- --- To read the mask without changing it, try doing this: --- --- mask = unix.umask(027) --- unix.umask(mask) --- --- On Windows NT this is a no-op and `mask` is returned. --- --- This function does not fail. ---@param newmask integer ---@return integer oldmask function unix.umask(newmask) end --- Generates a log message, which will be distributed by syslogd. --- --- `priority` is a bitmask containing the facility value and the level --- value. If no facility value is ORed into priority, then the default --- value set by openlog() is used. If set to NULL, the program name is --- used. Level is one of `LOG_EMERG`, `LOG_ALERT`, `LOG_CRIT`, --- `LOG_ERR`, `LOG_WARNING`, `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`. --- --- This function currently works on Linux, Windows, and NetBSD. On --- WIN32 it uses the ReportEvent() facility. ---@param priority integer ---@param msg string function unix.syslog(priority, msg) end --- Returns nanosecond precision timestamp from system, e.g. --- --- >: unix.clock_gettime() --- 1651137352 774458779 --- >: Benchmark(unix.clock_gettime) --- 126 393 571 1 --- --- `clock` can be any one of of: --- --- - `CLOCK_REALTIME`: universally supported --- - `CLOCK_REALTIME_FAST`: ditto but faster on freebsd --- - `CLOCK_REALTIME_PRECISE`: ditto but better on freebsd --- - `CLOCK_REALTIME_COARSE`: : like `CLOCK_REALTIME_FAST` but needs Linux 2.6.32+ --- - `CLOCK_MONOTONIC`: universally supported --- - `CLOCK_MONOTONIC_FAST`: ditto but faster on freebsd --- - `CLOCK_MONOTONIC_PRECISE`: ditto but better on freebsd --- - `CLOCK_MONOTONIC_COARSE`: : like `CLOCK_MONOTONIC_FAST` but needs Linux 2.6.32+ --- - `CLOCK_MONOTONIC_RAW`: is actually monotonic but needs Linux 2.6.28+ --- - `CLOCK_PROCESS_CPUTIME_ID`: linux and bsd --- - `CLOCK_THREAD_CPUTIME_ID`: linux and bsd --- - `CLOCK_MONOTONIC_COARSE`: linux, freebsd --- - `CLOCK_PROF`: linux and netbsd --- - `CLOCK_BOOTTIME`: linux and openbsd --- - `CLOCK_REALTIME_ALARM`: linux-only --- - `CLOCK_BOOTTIME_ALARM`: linux-only --- - `CLOCK_TAI`: linux-only --- --- Returns `EINVAL` if clock isn't supported on platform. --- --- This function only fails if `clock` is invalid. --- --- This function goes fastest on Linux and Windows. ---@param clock? integer ---@return integer seconds, integer nanos ---@nodiscard ---@overload fun(clock?: integer): nil, error: unix.Errno function unix.clock_gettime(clock) end --- Sleeps with nanosecond precision. --- --- Returns `EINTR` if a signal was received while waiting. ---@param seconds integer ---@param nanos integer? ---@return integer remseconds, integer remnanos ---@overload fun(seconds: integer, nanos?: integer): nil, error: unix.Errno function unix.nanosleep(seconds, nanos) end --- These functions are used to make programs slower by asking the --- operating system to flush data to the physical medium. function unix.sync() end --- These functions are used to make programs slower by asking the --- operating system to flush data to the physical medium. ---@param fd integer ---@return true ---@overload fun(fd: integer): nil, error: unix.Errno function unix.fsync(fd) end --- These functions are used to make programs slower by asking the --- operating system to flush data to the physical medium. ---@param fd integer ---@return true ---@overload fun(fd: integer): nil, error: unix.Errno function unix.fdatasync(fd) end --- Seeks to file position. --- --- `whence` can be one of: --- --- - `SEEK_SET`: Sets the file position to `offset` [default] --- - `SEEK_CUR`: Sets the file position to `position + offset` --- - `SEEK_END`: Sets the file position to `filesize + offset` --- --- Returns the new position relative to the start of the file. ---@param fd integer ---@param offset integer ---@param whence? integer ---@return integer newposbytes ---@overload fun(fd: integer, offset: integer, whence?: integer): nil, error: unix.Errno function unix.lseek(fd, offset, whence) end --- Reduces or extends underlying physical medium of file. --- If file was originally larger, content >length is lost. ---@param path string ---@param length? integer defaults to zero (`0`) ---@return true ---@overload fun(path: string, length?: integer): nil, error: unix.Errno function unix.truncate(path, length) end --- Reduces or extends underlying physical medium of open file. --- If file was originally larger, content >length is lost. ---@param fd integer ---@param length? integer defaults to zero (`0`) ---@return true ---@overload fun(fd: integer, length?: integer): nil, error: unix.Errno function unix.ftruncate(fd, length) end ---@param family? integer defaults to `AF_INET` and can be: --- --- - `AF_INET`: Creates Internet Protocol Version 4 (IPv4) socket. --- --- - `AF_UNIX`: Creates local UNIX domain socket. On the New Technology --- this requires Windows 10 and only works with `SOCK_STREAM`. --- ---@param type? integer defaults to `SOCK_STREAM` and can be: --- --- - `SOCK_STREAM` --- - `SOCK_DGRAM` --- - `SOCK_RAW` --- - `SOCK_RDM` --- - `SOCK_SEQPACKET` --- --- You may bitwise OR any of the following into `type`: --- --- - `SOCK_CLOEXEC` --- - `SOCK_NONBLOCK` --- ---@param protocol? integer may be any of: --- --- - `0` to let kernel choose [default] --- - `IPPROTO_TCP` --- - `IPPROTO_UDP` --- - `IPPROTO_RAW` --- - `IPPROTO_IP` --- - `IPPROTO_ICMP` --- ---@return integer fd ---@nodiscard ---@overload fun(family?: integer, type?: integer, protocol?: integer): nil, error: unix.Errno function unix.socket(family, type, protocol) end --- Creates bidirectional pipe. --- ---@param family? integer defaults to `AF_UNIX`. ---@param type? integer defaults to `SOCK_STREAM` and can be: --- --- - `SOCK_STREAM` --- - `SOCK_DGRAM` --- - `SOCK_SEQPACKET` --- --- You may bitwise OR any of the following into `type`: --- --- - `SOCK_CLOEXEC` --- - `SOCK_NONBLOCK` --- ---@param protocol? integer defaults to `0`. ---@return integer fd1, integer fd2 ---@overload fun(family?: integer, type?: integer, protocol?: integer): nil, error: unix.Errno function unix.socketpair(family, type, protocol) end --- Binds socket. --- --- `ip` and `port` are in host endian order. For example, if you --- wanted to listen on `1.2.3.4:31337` you could do any of these --- --- unix.bind(sock, 0x01020304, 31337) --- unix.bind(sock, ParseIp('1.2.3.4'), 31337) --- unix.bind(sock, 1 << 24 | 0 << 16 | 0 << 8 | 1, 31337) --- --- `ip` and `port` both default to zero. The meaning of bind(0, 0) --- is to listen on all interfaces with a kernel-assigned ephemeral --- port number, that can be retrieved and used as follows: --- --- sock = assert(unix.socket()) -- create ipv4 tcp socket --- assert(unix.bind(sock)) -- all interfaces ephemeral port --- ip, port = assert(unix.getsockname(sock)) --- print("listening on ip", FormatIp(ip), "port", port) --- assert(unix.listen(sock)) --- while true do --- client, clientip, clientport = assert(unix.accept(sock)) --- print("got client ip", FormatIp(clientip), "port", clientport) --- unix.close(client) --- end --- --- Further note that calling `unix.bind(sock)` is equivalent to not --- calling bind() at all, since the above behavior is the default. ---@param fd integer ---@param ip? uint32 ---@param port? uint16 ---@return true ---@overload fun(fd: integer, unixpath: string): true ---@overload fun(fd: integer, ip?: integer, port?: integer): nil, error: unix.Errno ---@overload fun(fd: integer, unixpath: string): nil, error: unix.Errno function unix.bind(fd, ip, port) end ---Returns list of network adapter addresses. ---@return { name: string, ip: integer, netmask: integer }[] addresses ---@nodiscard ---@overload fun(): nil, error: unix.Errno function unix.siocgifconf() end --- Tunes networking parameters. --- --- `level` and `optname` may be one of the following pairs. The ellipses --- type signature above changes depending on which options are used. --- --- `optname` is the option feature magic number. The constants for --- these will be set to `0` if the option isn't supported on the host --- platform. --- --- Raises `ENOPROTOOPT` if your `level` / `optname` combination isn't --- valid, recognized, or supported on the host platform. --- --- Raises `ENOTSOCK` if `fd` is valid but isn't a socket. --- --- Raises `EBADF` if `fd` isn't valid. --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ value:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, value:bool) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_TYPE` --- - `SOL_SOCKET`, `SO_DEBUG` --- - `SOL_SOCKET`, `SO_ACCEPTCONN` --- - `SOL_SOCKET`, `SO_BROADCAST` --- - `SOL_SOCKET`, `SO_REUSEADDR` --- - `SOL_SOCKET`, `SO_REUSEPORT` --- - `SOL_SOCKET`, `SO_KEEPALIVE` --- - `SOL_SOCKET`, `SO_DONTROUTE` --- - `SOL_TCP`, `TCP_NODELAY` --- - `SOL_TCP`, `TCP_CORK` --- - `SOL_TCP`, `TCP_QUICKACK` --- - `SOL_TCP`, `TCP_FASTOPEN_CONNECT` --- - `SOL_TCP`, `TCP_DEFER_ACCEPT` --- - `SOL_IP`, `IP_HDRINCL` --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ value:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, value:int) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_SNDBUF` --- - `SOL_SOCKET`, `SO_RCVBUF` --- - `SOL_SOCKET`, `SO_RCVLOWAT` --- - `SOL_SOCKET`, `SO_SNDLOWAT` --- - `SOL_TCP`, `TCP_KEEPIDLE` --- - `SOL_TCP`, `TCP_KEEPINTVL` --- - `SOL_TCP`, `TCP_FASTOPEN` --- - `SOL_TCP`, `TCP_KEEPCNT` --- - `SOL_TCP`, `TCP_MAXSEG` --- - `SOL_TCP`, `TCP_SYNCNT` --- - `SOL_TCP`, `TCP_NOTSENT_LOWAT` --- - `SOL_TCP`, `TCP_WINDOW_CLAMP` --- - `SOL_IP`, `IP_TOS` --- - `SOL_IP`, `IP_MTU` --- - `SOL_IP`, `IP_TTL` --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ secs:int, nsecs:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, secs:int[, nanos:int]) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_RCVTIMEO`: If this option is specified then --- your stream socket will have a read() / recv() timeout. If the --- specified interval elapses without receiving data, then EAGAIN --- shall be returned by read. If this option is used on listening --- sockets, it'll be inherited by accepted sockets. Your redbean --- already does this for GetClientFd() based on the `-t` flag. --- --- - `SOL_SOCKET`, `SO_SNDTIMEO`: This is the same as `SO_RCVTIMEO` --- but it applies to the write() / send() functions. --- --- unix.getsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER) --- ├─→ seconds:int, enabled:bool --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER, secs:int, enabled:bool) --- ├─→ true --- └─→ nil, unix.Errno --- --- This `SO_LINGER` parameter can be used to make close() a blocking --- call. Normally when the kernel returns immediately when it receives --- close(). Sometimes it's desirable to have extra assurance on errors --- happened, even if it comes at the cost of performance. --- --- unix.setsockopt(serverfd:int, unix.SOL_TCP, unix.TCP_SAVE_SYN, enabled:int) --- ├─→ true --- └─→ nil, unix.Errno --- unix.getsockopt(clientfd:int, unix.SOL_TCP, unix.TCP_SAVED_SYN) --- ├─→ syn_packet_bytes:str --- └─→ nil, unix.Errno --- --- This `TCP_SAVED_SYN` option may be used to retrieve the bytes of the --- TCP SYN packet that the client sent when the connection for `fd` was --- opened. In order for this to work, `TCP_SAVE_SYN` must have been set --- earlier on the listening socket. This is Linux-only. You can use the --- `OnServerListen` hook to enable SYN saving in your Redbean. When the --- `TCP_SAVE_SYN` option isn't used, this may return empty string. ---@param fd integer ---@param level integer ---@param optname integer ---@return integer value ---@nodiscard ---@overload fun(fd: integer, level: integer, optname: integer): nil, error: unix.Errno ---@overload fun(fd:integer, unix.SOL_SOCKET: integer, unix.SO_LINGER: integer): seconds: integer, enabled: boolean ---@overload fun(fd:integer, unix.SOL_SOCKET: integer, unix.SO_LINGER: integer): nil, error: unix.Errno ---@overload fun(serverfd:integer, unix.SOL_TCP: integer, unix.TCP_SAVE_SYN: integer): syn_packet_bytes: string ---@overload fun(serverfd:integer, unix.SOL_TCP: integer, unix.TCP_SAVE_SYN: integer): nil, error: unix.Errno function unix.getsockopt(fd, level, optname) end --- Tunes networking parameters. --- --- `level` and `optname` may be one of the following pairs. The ellipses --- type signature above changes depending on which options are used. --- --- `optname` is the option feature magic number. The constants for --- these will be set to `0` if the option isn't supported on the host --- platform. --- --- Raises `ENOPROTOOPT` if your `level` / `optname` combination isn't --- valid, recognized, or supported on the host platform. --- --- Raises `ENOTSOCK` if `fd` is valid but isn't a socket. --- --- Raises `EBADF` if `fd` isn't valid. --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ value:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, value:bool) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_TYPE` --- - `SOL_SOCKET`, `SO_DEBUG` --- - `SOL_SOCKET`, `SO_ACCEPTCONN` --- - `SOL_SOCKET`, `SO_BROADCAST` --- - `SOL_SOCKET`, `SO_REUSEADDR` --- - `SOL_SOCKET`, `SO_REUSEPORT` --- - `SOL_SOCKET`, `SO_KEEPALIVE` --- - `SOL_SOCKET`, `SO_DONTROUTE` --- - `SOL_TCP`, `TCP_NODELAY` --- - `SOL_TCP`, `TCP_CORK` --- - `SOL_TCP`, `TCP_QUICKACK` --- - `SOL_TCP`, `TCP_FASTOPEN_CONNECT` --- - `SOL_TCP`, `TCP_DEFER_ACCEPT` --- - `SOL_IP`, `IP_HDRINCL` --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ value:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, value:int) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_SNDBUF` --- - `SOL_SOCKET`, `SO_RCVBUF` --- - `SOL_SOCKET`, `SO_RCVLOWAT` --- - `SOL_SOCKET`, `SO_SNDLOWAT` --- - `SOL_TCP`, `TCP_KEEPIDLE` --- - `SOL_TCP`, `TCP_KEEPINTVL` --- - `SOL_TCP`, `TCP_FASTOPEN` --- - `SOL_TCP`, `TCP_KEEPCNT` --- - `SOL_TCP`, `TCP_MAXSEG` --- - `SOL_TCP`, `TCP_SYNCNT` --- - `SOL_TCP`, `TCP_NOTSENT_LOWAT` --- - `SOL_TCP`, `TCP_WINDOW_CLAMP` --- - `SOL_IP`, `IP_TOS` --- - `SOL_IP`, `IP_MTU` --- - `SOL_IP`, `IP_TTL` --- --- unix.getsockopt(fd:int, level:int, optname:int) --- ├─→ secs:int, nsecs:int --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, level:int, optname:int, secs:int[, nanos:int]) --- ├─→ true --- └─→ nil, unix.Errno --- --- - `SOL_SOCKET`, `SO_RCVTIMEO`: If this option is specified then --- your stream socket will have a read() / recv() timeout. If the --- specified interval elapses without receiving data, then EAGAIN --- shall be returned by read. If this option is used on listening --- sockets, it'll be inherited by accepted sockets. Your redbean --- already does this for GetClientFd() based on the `-t` flag. --- --- - `SOL_SOCKET`, `SO_SNDTIMEO`: This is the same as `SO_RCVTIMEO` --- but it applies to the write() / send() functions. --- --- unix.getsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER) --- ├─→ seconds:int, enabled:bool --- └─→ nil, unix.Errno --- unix.setsockopt(fd:int, unix.SOL_SOCKET, unix.SO_LINGER, secs:int, enabled:bool) --- ├─→ true --- └─→ nil, unix.Errno --- --- This `SO_LINGER` parameter can be used to make close() a blocking --- call. Normally when the kernel returns immediately when it receives --- close(). Sometimes it's desirable to have extra assurance on errors --- happened, even if it comes at the cost of performance. --- --- unix.setsockopt(serverfd:int, unix.SOL_TCP, unix.TCP_SAVE_SYN, enabled:int) --- ├─→ true --- └─→ nil, unix.Errno --- unix.getsockopt(clientfd:int, unix.SOL_TCP, unix.TCP_SAVED_SYN) --- ├─→ syn_packet_bytes:str --- └─→ nil, unix.Errno --- --- This `TCP_SAVED_SYN` option may be used to retrieve the bytes of the --- TCP SYN packet that the client sent when the connection for `fd` was --- opened. In order for this to work, `TCP_SAVE_SYN` must have been set --- earlier on the listening socket. This is Linux-only. You can use the --- `OnServerListen` hook to enable SYN saving in your Redbean. When the --- `TCP_SAVE_SYN` option isn't used, this may return empty string. ---@param fd integer ---@param level integer ---@param optname integer ---@param value boolean|integer ---@return true ---@overload fun(fd: integer, level: integer, optname: integer, value: boolean|integer): nil, error: unix.Errno ---@overload fun(fd:integer, unix.SOL_SOCKET: integer, unix.SO_LINGER: integer, secs:integer, enabled:boolean): true ---@overload fun(fd:integer, unix.SOL_SOCKET: integer, unix.SO_LINGER: integer, secs:integer, enabled:boolean): nil, error: unix.Errno ---@overload fun(serverfd:integer, unix.SOL_TCP: integer, unix.TCP_SAVE_SYN: integer, enabled:integer): true ---@overload fun(serverfd:integer, unix.SOL_TCP: integer, unix.TCP_SAVE_SYN: integer, enabled:integer): nil, error: unix.Errno function unix.setsockopt(fd, level, optname, value) end --- Checks for events on a set of file descriptors. --- --- The table of file descriptors to poll uses sparse integer keys. Any --- pairs with non-integer keys will be ignored. Pairs with negative --- keys are ignored by poll(). The returned table will be a subset of --- the supplied file descriptors. --- --- `events` and `revents` may be any combination (using bitwise OR) of: --- --- - `POLLIN` (events, revents): There is data to read. --- - `POLLOUT` (events, revents): Writing is now possible, although may --- still block if available space in a socket or pipe is exceeded --- (unless `O_NONBLOCK` is set). --- - `POLLPRI` (events, revents): There is some exceptional condition --- (for example, out-of-band data on a TCP socket). --- - `POLLRDHUP` (events, revents): Stream socket peer closed --- connection, or shut down writing half of connection. --- - `POLLERR` (revents): Some error condition. --- - `POLLHUP` (revents): Hang up. When reading from a channel such as --- a pipe or a stream socket, this event merely indicates that the --- peer closed its end of the channel. --- - `POLLNVAL` (revents): Invalid request. --- ---@param fds table<integer,integer> `{[fd:int]=events:int, ...}` ---@param timeoutms integer? the number of milliseconds to block. --- If this is set to -1 then that means block as long as it takes until there's an --- event or an interrupt. If the timeout expires, an empty table is returned. ---@return table<integer,integer> `{[fd:int]=revents:int, ...}` ---@nodiscard ---@overload fun(fds: table<integer,integer>, timeoutms:integer): nil, unix.Errno function unix.poll(fds, timeoutms) end --- Returns hostname of system. ---@return string host ---@nodiscard ---@overload fun(): nil, unix.Errno function unix.gethostname() end --- Begins listening for incoming connections on a socket. ---@param fd integer ---@param backlog integer? ---@return true ---@overload fun(fd:integer, backlog:integer?): nil, unix.Errno function unix.listen(fd, backlog) end --- Accepts new client socket descriptor for a listening tcp socket. --- --- `flags` may have any combination (using bitwise OR) of: --- --- - `SOCK_CLOEXEC` --- - `SOCK_NONBLOCK` --- ---@param serverfd integer ---@param flags integer? ---@return integer clientfd, uint32 ip, uint16 port ---@nodiscard ---@overload fun(serverfd:integer, flags:integer?):clientfd:integer, unixpath:string ---@overload fun(serverfd:integer, flags:integer?):nil, unix.Errno function unix.accept(serverfd, flags) end --- Connects a TCP socket to a remote host. --- --- With TCP this is a blocking operation. For a UDP socket it simply --- remembers the intended address so that `send()` or `write()` may be used --- rather than `sendto()`. ---@param fd integer ---@param ip uint32 ---@param port uint16 ---@return true ---@overload fun(fd:integer, ip:integer, port:integer): nil, unix.Errno ---@overload fun(fd:integer, unixpath:string): true ---@overload fun(fd:integer, unixpath:string): nil, unix.Errno function unix.connect(fd, ip, port) end --- Retrieves the local address of a socket. ---@param fd integer ---@return uint32 ip, uint16 port ---@nodiscard ---@overload fun(fd: integer): unixpath:string ---@overload fun(fd: integer): nil, unix.Errno function unix.getsockname(fd) end --- Retrieves the remote address of a socket. --- --- This operation will either fail on `AF_UNIX` sockets or return an --- empty string. --- ---@param fd integer ---@return uint32 ip, uint16 port ---@nodiscard ---@overload fun(fd: integer): unixpath:string ---@overload fun(fd: integer): nil, unix.Errno function unix.getpeername(fd) end ---@param fd integer ---@param bufsiz integer? ---@param flags integer? may have any combination (using bitwise OR) of: --- - `MSG_WAITALL` --- - `MSG_DONTROUTE` --- - `MSG_PEEK` --- - `MSG_OOB` ---@return string data ---@nodiscard ---@overload fun(fd: integer, bufsiz?: integer, flags?: integer): nil, unix.Errno function unix.recv(fd, bufsiz, flags) end ---@param fd integer ---@param bufsiz integer? ---@param flags integer? may have any combination (using bitwise OR) of: --- - `MSG_WAITALL` --- - `MSG_DONTROUTE` --- - `MSG_PEEK` --- - `MSG_OOB` ---@return string data, integer ip, integer port ---@nodiscard ---@overload fun(fd: integer, bufsiz?: integer, flags?: integer): data: string, unixpath: string ---@overload fun(fd: integer, bufsiz?: integer, flags?: integer): nil, unix.Errno function unix.recvfrom(fd, bufsiz, flags) end --- This is the same as `write` except it has a `flags` argument --- that's intended for sockets. ---@param fd integer ---@param data string ---@param flags integer? may have any combination (using bitwise OR) of: --- - `MSG_NOSIGNAL`: Don't SIGPIPE on EOF --- - `MSG_OOB`: Send stream data through out of bound channel --- - `MSG_DONTROUTE`: Don't go through gateway (for diagnostics) --- - `MSG_MORE`: Manual corking to belay nodelay (0 on non-Linux) ---@return integer sent ---@overload fun(fd: integer, data: string, flags?: integer): nil, unix.Errno function unix.send(fd, data, flags) end --- This is useful for sending messages over UDP sockets to specific --- addresses. --- ---@param fd integer ---@param data string ---@param ip uint32 ---@param port uint16 ---@param flags? integer may have any combination (using bitwise OR) of: --- - `MSG_OOB` --- - `MSG_DONTROUTE` --- - `MSG_NOSIGNAL` ---@return integer sent ---@overload fun(fd:integer, data:string, ip:integer, port:integer, flags?:integer): nil, unix.Errno ---@overload fun(fd:integer, data:string, unixpath:string, flags?:integer): sent: integer ---@overload fun(fd:integer, data:string, unixpath:string, flags?:integer): nil, unix.Errno function unix.sendto(fd, data, ip, port, flags) end --- Partially closes socket. --- ---@param fd integer ---@param how integer is set to one of: --- --- - `SHUT_RD`: sends a tcp half close for reading --- - `SHUT_WR`: sends a tcp half close for writing --- - `SHUT_RDWR` --- --- This system call currently has issues on Macintosh, so portable code --- should log rather than assert failures reported by `shutdown()`. --- ---@return true ---@overload fun(fd: integer, how: integer): nil, error: unix.Errno function unix.shutdown(fd, how) end --- Manipulates bitset of signals blocked by process. --- ---@param how integer can be one of: --- --- - `SIG_BLOCK`: applies `mask` to set of blocked signals using bitwise OR --- - `SIG_UNBLOCK`: removes bits in `mask` from set of blocked signals --- - `SIG_SETMASK`: replaces process signal mask with `mask` --- --- `mask` is a unix.Sigset() object (see section below). --- --- For example, to temporarily block `SIGTERM` and `SIGINT` so critical --- work won't be interrupted, sigprocmask() can be used as follows: --- --- newmask = unix.Sigset(unix.SIGTERM) --- oldmask = assert(unix.sigprocmask(unix.SIG_BLOCK, newmask)) --- -- do something... --- assert(unix.sigprocmask(unix.SIG_SETMASK, oldmask)) --- ---@param newmask unix.Sigset ---@return unix.Sigset oldmask ---@overload fun(how: integer, newmask: unix.Sigset): nil, error: unix.Errno function unix.sigprocmask(how, newmask) end ---@param sig integer can be one of: --- --- - `unix.SIGINT` --- - `unix.SIGQUIT` --- - `unix.SIGTERM` --- - etc. --- ---@param handler? function|integer can be: --- --- - Lua function --- - `unix.SIG_IGN` --- - `unix.SIG_DFL` --- ---@param flags? integer can have: --- --- - `unix.SA_RESTART`: Enables BSD signal handling semantics. Normally --- i/o entrypoints check for pending signals to deliver. If one gets --- delivered during an i/o call, the normal behavior is to cancel the --- i/o operation and return -1 with `EINTR` in errno. If you use the --- `SA_RESTART` flag then that behavior changes, so that any function --- that's been annotated with @restartable will not return `EINTR` --- and will instead resume the i/o operation. This makes coding --- easier but it can be an anti-pattern if not used carefully, since --- poor usage can easily result in latency issues. It also requires --- one to do more work in signal handlers, so special care needs to --- be given to which C library functions are @asyncsignalsafe. --- --- - `unix.SA_RESETHAND`: Causes signal handler to be single-shot. This --- means that, upon entry of delivery to a signal handler, it's reset --- to the `SIG_DFL` handler automatically. You may use the alias --- `SA_ONESHOT` for this flag, which means the same thing. --- --- - `unix.SA_NODEFER`: Disables the reentrancy safety check on your signal --- handler. Normally that's a good thing, since for instance if your --- `SIGSEGV` signal handler happens to segfault, you're going to want --- your process to just crash rather than looping endlessly. But in --- some cases it's desirable to use `SA_NODEFER` instead, such as at --- times when you wish to `longjmp()` out of your signal handler and --- back into your program. This is only safe to do across platforms --- for non-crashing signals such as `SIGCHLD` and `SIGINT`. Crash --- handlers should use Xed instead to recover execution, because on --- Windows a `SIGSEGV` or `SIGTRAP` crash handler might happen on a --- separate stack and/or a separate thread. You may use the alias --- `SA_NOMASK` for this flag, which means the same thing. --- --- - `unix.SA_NOCLDWAIT`: Changes `SIGCHLD` so the zombie is gone and --- you can't call wait() anymore; similar but may still deliver the --- SIGCHLD. --- --- - `unix.SA_NOCLDSTOP`: Lets you set `SIGCHLD` handler that's only --- notified on exit/termination and not notified on `SIGSTOP`, --- `SIGTSTP`, `SIGTTIN`, `SIGTTOU`, or `SIGCONT`. --- --- Example: --- --- function OnSigUsr1(sig) --- gotsigusr1 = true --- end --- gotsigusr1 = false --- oldmask = assert(unix.sigprocmask(unix.SIG_BLOCK, unix.Sigset(unix.SIGUSR1))) --- assert(unix.sigaction(unix.SIGUSR1, OnSigUsr1)) --- assert(unix.raise(unix.SIGUSR1)) --- assert(not gotsigusr1) --- ok, err = unix.sigsuspend(oldmask) --- assert(not ok) --- assert(err:errno() == unix.EINTR) --- assert(gotsigusr1) --- assert(unix.sigprocmask(unix.SIG_SETMASK, oldmask)) --- --- It's a good idea to not do too much work in a signal handler. --- ---@param mask? unix.Sigset ---@return function|integer oldhandler, integer flags, unix.Sigset mask ---@overload fun(sig: integer, handler?: function|integer, flags?: integer, mask?: unix.Sigset): nil, error: unix.Errno function unix.sigaction(sig, handler, flags, mask) end --- Waits for signal to be delivered. --- --- The signal mask is temporarily replaced with `mask` during this system call. ---@param mask? unix.Sigset specifies which signals should be blocked. ---@return nil, unix.Errno error function unix.sigsuspend(mask) end --- Causes `SIGALRM` signals to be generated at some point(s) in the --- future. The `which` parameter should be `ITIMER_REAL`. --- --- Here's an example of how to create a 400 ms interval timer: --- --- ticks = 0 --- assert(unix.sigaction(unix.SIGALRM, function(sig) --- print('tick no. %d' % {ticks}) --- ticks = ticks + 1 --- end)) --- assert(unix.setitimer(unix.ITIMER_REAL, 0, 400e6, 0, 400e6)) --- while true do --- unix.sigsuspend() --- end --- --- Here's how you'd do a single-shot timeout in 1 second: --- --- unix.sigaction(unix.SIGALRM, MyOnSigAlrm, unix.SA_RESETHAND) --- unix.setitimer(unix.ITIMER_REAL, 0, 0, 1, 0) --- ---@param which integer ---@param intervalsec integer ---@param intervalns integer needs to be on the interval `[0,1000000000)` ---@param valuesec integer ---@param valuens integer needs to be on the interval `[0,1000000000)` ---@return integer intervalsec, integer intervalns, integer valuesec, integer valuens ---@overload fun(which: integer): intervalsec: integer, intervalns: integer, valuesec: integer, valuens: integer ---@overload fun(which: integer, intervalsec: integer, intervalns: integer, valuesec: integer, valuens: integer): nil, error: unix.Errno ---@overload fun(which: integer): nil, error: unix.Errno function unix.setitimer(which, intervalsec, intervalns, valuesec, valuens) end --- Turns platform-specific `sig` code into its symbolic name. --- --- For example: --- --- >: unix.strsignal(9) --- "SIGKILL" --- >: unix.strsignal(unix.SIGKILL) --- "SIGKILL" --- --- Please note that signal numbers are normally different across --- supported platforms, and the constants should be preferred. --- ---@param sig integer ---@return string signalname ---@nodiscard function unix.strsignal(sig) end --- Changes resource limit. --- ---@param resource integer may be one of: --- --- - `RLIMIT_AS` limits the size of the virtual address space. This --- will work on all platforms. It's emulated on XNU and Windows which --- means it won't propagate across execve() currently. --- --- - `RLIMIT_CPU` causes `SIGXCPU` to be sent to the process when the --- soft limit on CPU time is exceeded, and the process is destroyed --- when the hard limit is exceeded. It works everywhere but Windows --- where it should be possible to poll getrusage() with setitimer(). --- --- - `RLIMIT_FSIZE` causes `SIGXFSZ` to sent to the process when the --- soft limit on file size is exceeded and the process is destroyed --- when the hard limit is exceeded. It works everywhere but Windows. --- --- - `RLIMIT_NPROC` limits the number of simultaneous processes and it --- should work on all platforms except Windows. Please be advised it --- limits the process, with respect to the activities of the user id --- as a whole. --- --- - `RLIMIT_NOFILE` limits the number of open file descriptors and it --- should work on all platforms except Windows (TODO). --- --- If a limit isn't supported by the host platform, it'll be set to --- 127. On most platforms these limits are enforced by the kernel and --- as such are inherited by subprocesses. --- ---@param soft integer ---@param hard? integer defaults to whatever was specified in `soft`. ---@return true ---@overload fun(resource: integer, soft: integer, hard?: integer): nil, error: unix.Errno function unix.setrlimit(resource, soft, hard) end --- Returns information about resource limits for current process. ---@param resource integer ---@return integer soft, integer hard ---@nodiscard ---@overload fun(resource: integer): nil, error: unix.Errno function unix.getrlimit(resource) end --- Returns information about resource usage for current process, e.g. --- --- >: unix.getrusage() --- {utime={0, 53644000}, maxrss=44896, minflt=545, oublock=24, nvcsw=9} --- ---@param who? integer defaults to `RUSAGE_SELF` and can be any of: --- --- - `RUSAGE_SELF`: current process --- - `RUSAGE_THREAD`: current thread --- - `RUSAGE_CHILDREN`: not supported on Windows NT --- - `RUSAGE_BOTH`: not supported on non-Linux --- ---@return unix.Rusage # See `unix.Rusage` for details on returned fields. ---@nodiscard ---@overload fun(who?: integer): nil, error: unix.Errno function unix.getrusage(who) end --- Restrict system operations. --- --- This can be used to sandbox your redbean workers. It allows finer --- customization compared to the `-S` flag. --- --- Pledging causes most system calls to become unavailable. On Linux the --- disabled calls will return EPERM whereas OpenBSD kills the process. --- --- Using pledge is irreversible. On Linux it causes PR_SET_NO_NEW_PRIVS --- to be set on your process. --- --- By default exit and exit_group are always allowed. This is useful --- for processes that perform pure computation and interface with the --- parent via shared memory. --- --- Once pledge is in effect, the chmod functions (if allowed) will not --- permit the sticky/setuid/setgid bits to change. Linux will EPERM here --- and OpenBSD should ignore those three bits rather than crashing. --- --- User and group IDs also can't be changed once pledge is in effect. --- OpenBSD should ignore the chown functions without crashing. Linux --- will just EPERM. --- --- Memory functions won't permit creating executable code after pledge. --- Restrictions on origin of SYSCALL instructions will become enforced --- on Linux (cf. msyscall) after pledge too, which means the process --- gets killed if SYSCALL is used outside the .privileged section. One --- exception is if the "exec" group is specified, in which case these --- restrictions need to be loosened. --- ---@param promises? string may include any of the following groups delimited by spaces. --- This list has been curated to focus on the --- system calls for which this module provides wrappers. See the --- Cosmopolitan Libc pledge() documentation for a comprehensive and --- authoritative list of raw system calls. Having the raw system call --- list may be useful if you're executing foreign programs. --- --- ### stdio --- --- Allows read, write, send, recv, recvfrom, close, clock_getres, --- clock_gettime, dup, fchdir, fstat, fsync, fdatasync, ftruncate, --- getdents, getegid, getrandom, geteuid, getgid, getgroups, --- getitimer, getpgid, getpgrp, getpid, hgetppid, getresgid, --- getresuid, getrlimit, getsid, gettimeofday, getuid, lseek, --- madvise, brk, mmap/mprotect (PROT_EXEC isn't allowed), msync, --- munmap, gethostname, nanosleep, pipe, pipe2, poll, setitimer, --- shutdown, sigaction, sigsuspend, sigprocmask, socketpair, umask, --- wait4, getrusage, ioctl(FIONREAD), ioctl(FIONBIO), ioctl(FIOCLEX), --- ioctl(FIONCLEX), fcntl(F_GETFD), fcntl(F_SETFD), fcntl(F_GETFL), --- fcntl(F_SETFL). --- --- ### rpath --- --- Allows chdir, getcwd, open, stat, fstat, access, readlink, chmod, --- chmod, fchmod. --- --- ### wpath --- --- Allows getcwd, open, stat, fstat, access, readlink, chmod, fchmod. --- --- ### cpath --- --- Allows rename, link, symlink, unlink, mkdir, rmdir. --- --- ### fattr --- --- Allows chmod, fchmod, utimensat, futimens. --- --- ### flock --- --- Allows flock, fcntl(F_GETLK), fcntl(F_SETLK), fcntl(F_SETLKW). --- --- ### tty --- --- Allows isatty, tiocgwinsz, tcgets, tcsets, tcsetsw, tcsetsf. --- --- ### inet --- --- Allows socket (AF_INET), listen, bind, connect, accept, --- getpeername, getsockname, setsockopt, getsockopt. --- --- ### unix --- --- Allows socket (AF_UNIX), listen, bind, connect, accept, --- getpeername, getsockname, setsockopt, getsockopt. --- --- ### dns --- --- Allows sendto, recvfrom, socket(AF_INET), connect. --- --- ### recvfd --- --- Allows recvmsg, recvmmsg. --- --- ### sendfd --- --- Allows sendmsg, sendmmsg. --- --- ### proc --- --- Allows fork, vfork, clone, kill, tgkill, getpriority, setpriority, --- setrlimit, setpgid, setsid. --- --- ### id --- --- Allows setuid, setreuid, setresuid, setgid, setregid, setresgid, --- setgroups, setrlimit, getpriority, setpriority. --- --- ### settime --- --- Allows settimeofday and clock_adjtime. --- --- ### unveil --- --- Allows unveil(). --- --- ### exec --- --- Allows execve. --- --- If the executable in question needs a loader, then you will need --- "rpath prot_exec" too. With APE, security is strongest when you --- assimilate your binaries beforehand, using the --assimilate flag, --- or the o//tool/build/assimilate.com program. On OpenBSD this is --- mandatory. --- --- ### prot_exec --- --- Allows mmap(PROT_EXEC) and mprotect(PROT_EXEC). --- --- This may be needed to launch non-static non-native executables, --- such as non-assimilated APE binaries, or programs that link --- dynamic shared objects, i.e. most Linux distro binaries. --- ---@param execpromises? string only matters if "exec" is specified in `promises`. --- In that case, this specifies the promises that'll apply once `execve()` --- happens. If this is `NULL` then the default is used, which is --- unrestricted. OpenBSD allows child processes to escape the sandbox --- (so a pledged OpenSSH server process can do things like spawn a root --- shell). Linux however requires monotonically decreasing privileges. --- This function will will perform some validation on Linux to make --- sure that `execpromises` is a subset of `promises`. Your libc --- wrapper for `execve()` will then apply its SECCOMP BPF filter later. --- Since Linux has to do this before calling `sys_execve()`, the executed --- process will be weakened to have execute permissions too. --- ---@return true ---@overload fun(promises?: string, execpromises?: string): nil, error: unix.Errno function unix.pledge(promises, execpromises) end --- Restricts filesystem operations, e.g. --- --- unix.unveil(".", "r"); -- current dir + children visible --- unix.unveil("/etc", "r"); -- make /etc readable too --- unix.unveil(nil, nil); -- commit and lock policy --- --- Unveiling restricts a thread's view of the filesystem to a set of --- allowed paths with specific privileges. --- --- Once you start using unveil(), the entire file system is considered --- hidden. You then specify, by repeatedly calling unveil(), which paths --- should become unhidden. When you're finished, you call `unveil(nil,nil)` --- which commits your policy, after which further use is forbidden, in --- the current thread, as well as any threads or processes it spawns. --- --- There are some differences between unveil() on Linux versus OpenBSD. --- --- 1. Build your policy and lock it in one go. On OpenBSD, policies take --- effect immediately and may evolve as you continue to call unveil() --- but only in a more restrictive direction. On Linux, nothing will --- happen until you call `unveil(nil,nil)` which commits and locks. --- --- 2. Try not to overlap directory trees. On OpenBSD, if directory trees --- overlap, then the most restrictive policy will be used for a given --- file. On Linux overlapping may result in a less restrictive policy --- and possibly even undefined behavior. --- --- 3. OpenBSD and Linux disagree on error codes. On OpenBSD, accessing --- paths outside of the allowed set raises ENOENT, and accessing ones --- with incorrect permissions raises EACCES. On Linux, both these --- cases raise EACCES. --- --- 4. Unlike OpenBSD, Linux does nothing to conceal the existence of --- paths. Even with an unveil() policy in place, it's still possible --- to access the metadata of all files using functions like stat() --- and open(O_PATH), provided you know the path. A sandboxed process --- can always, for example, determine how many bytes of data are in --- /etc/passwd, even if the file isn't readable. But it's still not --- possible to use opendir() and go fishing for paths which weren't --- previously known. --- --- This system call is supported natively on OpenBSD and polyfilled on --- Linux using the Landlock LSM[1]. --- ---@param path string is the file or directory to unveil --- ---@param permissions string is a string consisting of zero or more of the following characters: --- --- - `r` makes `path` available for read-only path operations, --- corresponding to the pledge promise "rpath". --- --- - `w` makes `path` available for write operations, corresponding --- to the pledge promise "wpath". --- --- - `x` makes `path` available for execute operations, --- corresponding to the pledge promises "exec" and "execnative". --- --- - `c` allows `path` to be created and removed, corresponding to --- the pledge promise "cpath". --- ---@return true ---@overload fun(path: string, permissions: string): nil, error: unix.Errno function unix.unveil(path, permissions) end --- Breaks down UNIX timestamp into Zulu Time numbers. ---@param unixts integer ---@return integer year ---@return integer mon 1 ≤ mon ≤ 12 ---@return integer mday 1 ≤ mday ≤ 31 ---@return integer hour 0 ≤ hour ≤ 23 ---@return integer min 0 ≤ min ≤ 59 ---@return integer sec 0 ≤ sec ≤ 60 ---@return integer gmtoffsec ±93600 seconds ---@return integer wday 0 ≤ wday ≤ 6 ---@return integer yday 0 ≤ yday ≤ 365 ---@return integer dst 1 if daylight savings, 0 if not, -1 if unknown ---@return string zone ---@nodiscard ---@overload fun(unixts: integer): nil, error: unix.Errno function unix.gmtime(unixts) end --- Breaks down UNIX timestamp into local time numbers, e.g. --- --- >: unix.localtime(unix.clock_gettime()) --- 2022 4 28 2 14 22 -25200 4 117 1 "PDT" --- --- This follows the same API as `gmtime()` which has further details. --- --- Your redbean ships with a subset of the time zone database. --- --- - `/zip/usr/share/zoneinfo/Honolulu` Z-10 --- - `/zip/usr/share/zoneinfo/Anchorage` Z -9 --- - `/zip/usr/share/zoneinfo/GST` Z -8 --- - `/zip/usr/share/zoneinfo/Boulder` Z -6 --- - `/zip/usr/share/zoneinfo/Chicago` Z -5 --- - `/zip/usr/share/zoneinfo/New_York` Z -4 --- - `/zip/usr/share/zoneinfo/UTC` Z +0 --- - `/zip/usr/share/zoneinfo/GMT` Z +0 --- - `/zip/usr/share/zoneinfo/London` Z +1 --- - `/zip/usr/share/zoneinfo/Berlin` Z +2 --- - `/zip/usr/share/zoneinfo/Israel` Z +3 --- - `/zip/usr/share/zoneinfo/India` Z +5 --- - `/zip/usr/share/zoneinfo/Beijing` Z +8 --- - `/zip/usr/share/zoneinfo/Japan` Z +9 --- - `/zip/usr/share/zoneinfo/Sydney` Z+10 --- --- You can control which timezone is used using the `TZ` environment --- variable. If your time zone isn't included in the above list, you --- can simply copy it inside your redbean. The same is also the case --- for future updates to the database, which can be swapped out when --- needed, without having to recompile. --- ---@param unixts integer ---@return integer year ---@return integer mon 1 ≤ mon ≤ 12 ---@return integer mday 1 ≤ mday ≤ 31 ---@return integer hour 0 ≤ hour ≤ 23 ---@return integer min 0 ≤ min ≤ 59 ---@return integer sec 0 ≤ sec ≤ 60 ---@return integer gmtoffsec ±93600 seconds ---@return integer wday 0 ≤ wday ≤ 6 ---@return integer yday 0 ≤ yday ≤ 365 ---@return integer dst 1 if daylight savings, 0 if not, -1 if unknown ---@return string zone ---@overload fun(unixts: integer): nil, error: unix.Errno function unix.localtime(unixts) end --- Gets information about file or directory. ---@param flags? integer may have any of: --- - `AT_SYMLINK_NOFOLLOW`: do not follow symbolic links. ---@param dirfd? integer defaults to `unix.AT_FDCWD` and may optionally be set to a directory file descriptor to which `path` is relative. ---@return unix.Stat ---@nodiscard ---@overload fun(path: string, flags?: integer, dirfd?: integer): nil, unix.Errno function unix.stat(path, flags, dirfd) end --- Gets information about opened file descriptor. --- ---@param fd integer should be a file descriptor that was opened using `unix.open(path, O_RDONLY|O_DIRECTORY)`. --- --- `flags` may have any of: --- --- - `AT_SYMLINK_NOFOLLOW`: do not follow symbolic links. --- --- `dirfd` defaults to to `unix.AT_FDCWD` and may optionally be set to --- a directory file descriptor to which `path` is relative. --- --- A common use for `fstat()` is getting the size of a file. For example: --- --- fd = assert(unix.open("hello.txt", unix.O_RDONLY)) --- st = assert(unix.fstat(fd)) --- Log(kLogInfo, 'hello.txt is %d bytes in size' % {st:size()}) --- unix.close(fd) --- ---@return unix.Stat ---@nodiscard ---@overload fun(fd: integer): nil, unix.Errno function unix.fstat(fd) end --- Opens directory for listing its contents. --- --- For example, to print a simple directory listing: --- --- Write('<ul>\r\n') --- for name, kind, ino, off in assert(unix.opendir(dir)) do --- if name ~= '.' and name ~= '..' then --- Write('<li>%s\r\n' % {EscapeHtml(name)}) --- end --- end --- Write('</ul>\r\n') --- ---@param path string ---@return unix.Dir state ---@nodiscard ---@overload fun(path: string): nil, error: unix.Errno function unix.opendir(path) end --- Opens directory for listing its contents, via an fd. --- --- @param fd integer should be created by `open(path, O_RDONLY|O_DIRECTORY)`. --- The returned `unix.Dir` takes ownership of the file descriptor --- and will close it automatically when garbage collected. --- ---@return function next, unix.Dir state ---@nodiscard ---@overload fun(fd: integer): nil, error: unix.Errno function unix.fdopendir(fd) end --- Returns true if file descriptor is a teletypewriter. Otherwise nil --- with an Errno object holding one of the following values: --- --- - `ENOTTY` if `fd` is valid but not a teletypewriter --- - `EBADF` if `fd` isn't a valid file descriptor. --- - `EPERM` if pledge() is used without `tty` in lenient mode --- --- No other error numbers are possible. --- ---@param fd integer ---@return true ---@nodiscard ---@overload fun(fd: integer): nil, error: unix.Errno function unix.isatty(fd) end ---@param fd integer ---@return integer rows, integer cols cellular dimensions of pseudoteletypewriter display. ---@nodiscard ---@overload fun(fd: integer): nil, error: unix.Errno function unix.tiocgwinsz(fd) end --- Returns file descriptor of open anonymous file. --- --- This creates a secure temporary file inside `$TMPDIR`. If it isn't --- defined, then `/tmp` is used on UNIX and GetTempPath() is used on --- the New Technology. This resolution of `$TMPDIR` happens once in a --- ctor, which is copied to the `kTmpDir` global. --- --- Once close() is called, the returned file is guaranteed to be --- deleted automatically. On UNIX the file is unlink()'d before this --- function returns. On the New Technology it happens upon close(). --- --- On the New Technology, temporary files created by this function --- should have better performance, because `kNtFileAttributeTemporary` --- asks the kernel to more aggressively cache and reduce i/o ops. ---@return integer fd ---@overload fun(): nil, error: unix.Errno function unix.tmpfd() end --- Relinquishes scheduled quantum. function unix.sched_yield() end --- Creates interprocess shared memory mapping. --- --- This function allocates special memory that'll be inherited across --- fork in a shared way. By default all memory in Redbean is "private" --- memory that's only viewable and editable to the process that owns --- it. When unix.fork() happens, memory is copied appropriately so --- that changes to memory made in the child process, don't clobber --- the memory at those same addresses in the parent process. If you --- don't want that to happen, and you want the memory to be shared --- similar to how it would be shared if you were using threads, then --- you can use this function to achieve just that. --- --- The memory object this function returns may be accessed using its --- methods, which support atomics and futexes. It's very low-level. --- For example, you can use it to implement scalable mutexes: --- --- mem = unix.mapshared(8000 * 8) --- --- LOCK = 0 -- pick an arbitrary word index for lock --- --- -- From Futexes Are Tricky Version 1.1 § Mutex, Take 3; --- -- Ulrich Drepper, Red Hat Incorporated, June 27, 2004. --- function Lock() --- local ok, old = mem:cmpxchg(LOCK, 0, 1) --- if not ok then --- if old == 1 then --- old = mem:xchg(LOCK, 2) --- end --- while old > 0 do --- mem:wait(LOCK, 2) --- old = mem:xchg(LOCK, 2) --- end --- end --- end --- function Unlock() --- old = mem:add(LOCK, -1) --- if old == 2 then --- mem:store(LOCK, 0) --- mem:wake(LOCK, 1) --- end --- end --- --- It's possible to accomplish the same thing as unix.mapshared() --- using files and unix.fcntl() advisory locks. However this goes --- significantly faster. For example, that's what SQLite does and --- we recommend using SQLite for IPC in redbean. But, if your app --- has thousands of forked processes fighting for a file lock you --- might need something lower level than file locks, to implement --- things like throttling. Shared memory is a good way to do that --- since there's nothing that's faster. --- ---@param size integer --- The `size` parameter needs to be a multiple of 8. The returned --- memory is zero initialized. When allocating shared memory, you --- should try to get as much use out of it as possible, since the --- overhead of allocating a single shared mapping is 500 words of --- resident memory and 8000 words of virtual memory. It's because --- the Cosmopolitan Libc mmap() granularity is 2**16. --- --- This system call does not fail. An exception is instead thrown --- if sufficient memory isn't available. --- ---@return unix.Memory function unix.mapshared(size) end ---@class unix.Memory: userdata --- unix.Memory encapsulates memory that's shared across fork() and --- this module provides the fundamental synchronization primitives --- --- Redbean memory maps may be used in two ways: --- --- 1. as an array of bytes a.k.a. a string --- 2. as an array of words a.k.a. integers --- --- They're aliased, union, or overlapped views of the same memory. --- For example if you write a string to your memory region, you'll --- be able to read it back as an integer. --- --- Reads, writes, and word operations will throw an exception if a --- memory boundary error or overflow occurs. unix.Memory = {} ---@param offset integer? --- The starting byte index from which memory is copied, which defaults to zero. --- ---@param bytes integer? --- If `bytes` is none or nil, then the nul-terminated string at --- `offset` is returned. You may specify `bytes` to safely read --- binary data. --- --- This operation happens atomically. Each shared mapping has a --- single lock which is used to synchronize reads and writes to --- that specific map. To make it scale, create additional maps. ---@return string ---@nodiscard function unix.Memory:read(offset, bytes) end --- Writes bytes to memory region. --- ---@param data string ---@param offset integer? --- `offset` is the starting byte index to which memory is copied, --- which defaults to zero. --- ---@param bytes integer? --- If `bytes` is none or nil, then an implicit nil-terminator --- will be included after your `data` so things like json can --- be easily serialized to shared memory. --- --- This operation happens atomically. Each shared mapping has a --- single lock which is used to synchronize reads and writes to --- that specific map. To make it scale, create additional maps. function unix.Memory:write(data, offset, bytes) end --- Loads word from memory region. --- --- This operation is atomic and has relaxed barrier semantics. ---@param word_index integer ---@return integer ---@nodiscard function unix.Memory:load(word_index) end --- Stores word from memory region. --- --- This operation is atomic and has relaxed barrier semantics. ---@param word_index integer ---@param value integer function unix.Memory:store(word_index, value) end --- Exchanges value. --- --- This sets word at `word_index` to `value` and returns the value --- previously held in by the word. --- --- This operation is atomic and provides the same memory barrier --- semantics as the aligned x86 LOCK XCHG instruction. ---@param word_index integer ---@param value integer ---@return integer function unix.Memory:xchg(word_index, value) end --- Compares and exchanges value. --- --- This inspects the word at `word_index` and if its value is the same --- as `old` then it'll be replaced by the value `new`, in which case --- `true, old` shall be returned. If a different value was held at --- word, then `false` shall be returned along with the word. --- --- This operation happens atomically and provides the same memory --- barrier semantics as the aligned x86 LOCK CMPXCHG instruction. ---@param word_index integer ---@param old integer ---@param new integer ---@return boolean success, integer old function unix.Memory:cmpxchg(word_index, old, new) end --- Fetches then adds value. --- --- This method modifies the word at `word_index` to contain the sum of --- value and the `value` paremeter. This method then returns the value --- as it existed before the addition was performed. --- --- This operation is atomic and provides the same memory barrier --- semantics as the aligned x86 LOCK XADD instruction. ---@param word_index integer ---@param value integer ---@return integer old function unix.Memory:fetch_add(word_index, value) end --- Fetches and bitwise ands value. --- --- This operation happens atomically and provides the same memory --- barrier ordering semantics as its x86 implementation. ---@param word_index integer ---@param value integer ---@return integer function unix.Memory:fetch_and(word_index, value) end --- Fetches and bitwise ors value. --- --- This operation happens atomically and provides the same memory --- barrier ordering semantics as its x86 implementation. ---@param word_index integer ---@param value integer ---@return integer function unix.Memory:fetch_or(word_index, value) end --- Fetches and bitwise xors value. --- --- This operation happens atomically and provides the same memory --- barrier ordering semantics as its x86 implementation. ---@param word_index integer ---@param value integer ---@return integer function unix.Memory:fetch_xor(word_index, value) end --- Waits for word to have a different value. --- --- This method asks the kernel to suspend the process until either the --- absolute deadline expires or we're woken up by another process that --- calls `unix.Memory:wake()`. --- --- The `expect` parameter is used only upon entry to synchronize the --- transition to kernelspace. The kernel doesn't actually poll the --- memory location. It uses `expect` to make sure the process doesn't --- get added to the wait list unless it's sure that it needs to wait, --- since the kernel can only control the ordering of wait / wake calls --- across processes. --- --- The default behavior is to wait until the heat death of the universe --- if necessary. You may alternatively specify an absolute deadline. If --- it's less than or equal to the value returned by clock_gettime, then --- this routine is non-blocking. Otherwise we'll block at most until --- the current time reaches the absolute deadline. --- --- Futexes are currently supported on Linux, FreeBSD, OpenBSD. On other --- platforms this method calls sched_yield() and will either (1) return --- unix.EINTR if a deadline is specified, otherwise (2) 0 is returned. --- This means futexes will *work* on Windows, Mac, and NetBSD but they --- won't be scalable in terms of CPU usage when many processes wait on --- one process that holds a lock for a long time. In the future we may --- polyfill futexes in userspace for these platforms to improve things --- for folks who've adopted this api. If lock scalability is something --- you need on Windows and MacOS today, then consider fcntl() which is --- well-supported on all supported platforms but requires using files. --- Please test your use case though, because it's kind of an edge case --- to have the scenario above, and chances are this op will work fine. --- ---@return 0 ---@overload fun(self, word_index: integer, expect: integer, abs_deadline?: integer, nanos?: integer): nil, error: unix.Errno --- --- `EINTR` if a signal is delivered while waiting on deadline. Callers --- should use futexes inside a loop that is able to cope with spurious --- wakeups. We don't actually guarantee the value at word has in fact --- changed when this returns. --- --- `EAGAIN` is raised if, upon entry, the word at `word_index` had a --- different value than what's specified at `expect`. --- --- `ETIMEDOUT` is raised when the absolute deadline expires. --- ---@param word_index integer ---@param expect integer ---@param abs_deadline integer? ---@param nanos integer? function unix.Memory:wait(word_index, expect, abs_deadline, nanos) end --- Wakes other processes waiting on word. --- --- This method may be used to signal or broadcast to waiters. The --- `count` specifies the number of processes that should be woken, --- which defaults to `INT_MAX`. --- --- The return value is the number of processes that were actually woken --- as a result of the system call. No failure conditions are defined. ---@param index integer ---@param count integer? ---@return integer woken function unix.Memory:wake(index, count) end ---@class unix.Dir: userdata --- `unix.Dir` objects are created by `opendir()` or `fdopendir()`. unix.Dir = {} --- Closes directory stream object and associated its file descriptor. --- --- This is called automatically by the garbage collector. --- --- This may be called multiple times. ---@return true ---@overload fun(self: unix.Dir): nil, error: unix.Errno function unix.Dir:close() end --- Reads entry from directory stream. --- --- Returns `nil` if there are no more entries. --- On error, `nil` will be returned and `errno` will be non-nil. --- --- `kind` can be any of: --- --- - `DT_REG`: file is a regular file --- - `DT_DIR`: file is a directory --- - `DT_BLK`: file is a block device --- - `DT_LNK`: file is a symbolic link --- - `DT_CHR`: file is a character device --- - `DT_FIFO`: file is a named pipe --- - `DT_SOCK`: file is a named socket --- - `DT_UNKNOWN` --- --- Note: This function also serves as the `__call` metamethod, so that --- `unix.Dir` objects may be used as a for loop iterator. --- ---@return string name, integer kind, integer ino, integer off ---@nodiscard ---@overload fun(): nil function unix.Dir:read() end ---@return integer fd file descriptor of open directory object. ---@nodiscard ---@overload fun(): nil, error: unix.Errno --- Returns `EOPNOTSUPP` if using a `/zip/...` path or if using Windows NT. function unix.Dir:fd() end ---@return integer off current arbitrary offset into stream. ---@nodiscard ---@overload fun(): nil, error: unix.Errno function unix.Dir:tell() end ---Resets stream back to beginning. function unix.Dir:rewind() end ---@class unix.Rusage: userdata ---`unix.Rusage` objects are created by `wait()` or `getrusage()`. unix.Rusage = {} ---@return integer seconds, integer nanos amount of CPU consumed in userspace. ---@nodiscard --- --- It's always the case that `0 ≤ nanos < 1e9`. --- --- On Windows NT this is collected from GetProcessTimes(). function unix.Rusage:utime() end ---@return integer seconds, integer nanos amount of CPU consumed in kernelspace. ---@nodiscard --- --- It's always the case that `0 ≤ nanos < 1e9`. --- --- On Windows NT this is collected from GetProcessTimes(). function unix.Rusage:stime() end ---@return integer kilobytes amount of physical memory used at peak consumption. ---@nodiscard --- --- On Windows NT this is collected from --- `NtProcessMemoryCountersEx::PeakWorkingSetSize / 1024`. function unix.Rusage:maxrss() end ---@return integer integralkilobytes integral private memory consumption w.r.t. scheduled ticks. ---@nodiscard --- --- If you chart memory usage over the lifetime of your process, then --- this would be the space filled in beneath the chart. The frequency --- of kernel scheduling is defined as `unix.CLK_TCK`. Each time a tick --- happens, the kernel samples your process's memory usage, by adding --- it to this value. You can derive the average consumption from this --- value by computing how many ticks are in `utime + stime`. --- --- Currently only available on FreeBSD and NetBSD. function unix.Rusage:idrss() end ---@return integer integralkilobytes integral shared memory consumption w.r.t. scheduled ticks. ---@nodiscard --- --- If you chart memory usage over the lifetime of your process, then --- this would be the space filled in beneath the chart. The frequency --- of kernel scheduling is defined as unix.CLK_TCK. Each time a tick --- happens, the kernel samples your process's memory usage, by adding --- it to this value. You can derive the average consumption from this --- value by computing how many ticks are in `utime + stime`. --- --- Currently only available on FreeBSD and NetBSD. function unix.Rusage:ixrss() end ---@return integer integralkilobytes integral stack memory consumption w.r.t. scheduled ticks. ---@nodiscard --- --- If you chart memory usage over the lifetime of your process, then --- this would be the space filled in beneath the chart. The frequency --- of kernel scheduling is defined as `unix.CLK_TCK`. Each time a tick --- happens, the kernel samples your process's memory usage, by adding --- it to this value. You can derive the average consumption from this --- value by computing how many ticks are in `utime + stime`. --- --- This is only applicable to redbean if its built with MODE=tiny, --- because redbean likes to allocate its own deterministic stack. --- --- Currently only available on FreeBSD and NetBSD. function unix.Rusage:isrss() end ---@return integer count number of minor page faults. ---@nodiscard --- --- This number indicates how many times redbean was preempted by the --- kernel to `memcpy()` a 4096-byte page. This is one of the tradeoffs --- `fork()` entails. This number is usually tinier, when your binaries --- are tinier. --- --- Not available on Windows NT. function unix.Rusage:minflt() end ---Returns number of major page faults. --- ---This number indicates how many times redbean was preempted by the ---kernel to perform i/o. For example, you might have used `mmap()` to ---load a large file into memory lazily. --- ---On Windows NT this is `NtProcessMemoryCountersEx::PageFaultCount`. ---@return integer count ---@nodiscard function unix.Rusage:majflt() end ---@return integer count number of swap operations. ---@nodiscard --- --- Operating systems like to reserve hard disk space to back their RAM --- guarantees, like using a gold standard for fiat currency. When your --- system is under heavy memory load, swap operations may happen while --- redbean is working. This number keeps track of them. --- --- Not available on Linux, Windows NT. function unix.Rusage:nswap() end ---@return integer count number of times filesystem had to perform input. ---@nodiscard ---On Windows NT this is `NtIoCounters::ReadOperationCount`. function unix.Rusage:inblock() end ---@return integer count number of times filesystem had to perform output. ---@nodiscard --- On Windows NT this is `NtIoCounters::WriteOperationCount`. function unix.Rusage:oublock() end ---@return integer count count of ipc messages sent. ---@nodiscard --- Not available on Linux, Windows NT. function unix.Rusage:msgsnd() end ---@return integer count count of ipc messages received. ---@nodiscard --- Not available on Linux, Windows NT. function unix.Rusage:msgrcv() end ---@return integer count number of signals received. ---@nodiscard --- Not available on Linux. function unix.Rusage:nsignals() end ---@return integer count number of voluntary context switches. ---@nodiscard --- --- This number is a good thing. It means your redbean finished its work --- quickly enough within a time slice that it was able to give back the --- remaining time to the system. function unix.Rusage:nvcsw() end --- @return integer count number of non-consensual context switches. --- --- This number is a bad thing. It means your redbean was preempted by a --- higher priority process after failing to finish its work, within the --- allotted time slice. function unix.Rusage:nivcsw() end ---@class unix.Stat: userdata ---`unix.Stat` objects are created by `stat()` or `fstat()`. unix.Stat = {} ---@return integer bytes Size of file in bytes. ---@nodiscard function unix.Stat:size() end --- Contains file type and permissions. --- --- For example, `0010644` is what you might see for a file and --- `0040755` is what you might see for a directory. --- --- To determine the file type: --- --- - `unix.S_ISREG(st:mode())` means regular file --- - `unix.S_ISDIR(st:mode())` means directory --- - `unix.S_ISLNK(st:mode())` means symbolic link --- - `unix.S_ISCHR(st:mode())` means character device --- - `unix.S_ISBLK(st:mode())` means block device --- - `unix.S_ISFIFO(st:mode())` means fifo or pipe --- - `unix.S_ISSOCK(st:mode())` means socket --- ---@return integer mode ---@nodiscard function unix.Stat:mode() end ---@return integer uid User ID of file owner. ---@nodiscard function unix.Stat:uid() end ---@return integer gid Group ID of file owner. ---@nodiscard function unix.Stat:gid() end --- File birth time. --- --- This field should be accurate on Apple, Windows, and BSDs. On Linux --- this is the minimum of atim/mtim/ctim. On Windows NT nanos is only --- accurate to hectonanoseconds. --- --- Here's an example of how you might print a file timestamp: --- --- st = assert(unix.stat('/etc/passwd')) --- unixts, nanos = st:birthtim() --- year,mon,mday,hour,min,sec,gmtoffsec = unix.localtime(unixts) --- Write('%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.9d%+.2d%.2d % { --- year, mon, mday, hour, min, sec, nanos, --- gmtoffsec / (60 * 60), math.abs(gmtoffsec) % 60}) ---@return integer unixts, integer nanos ---@nodiscard function unix.Stat:birthtim() end ---@return integer unixts, integer nanos Last modified time. ---@nodiscard function unix.Stat:mtim() end ---@return integer unixts, integer nanos Last access time. ---@nodiscard --- --- Please note that file systems are sometimes mounted with `noatime` --- out of concern for i/o performance. Linux also provides `O_NOATIME` --- as an option for open(). --- --- On Windows NT this is the same as birth time. function unix.Stat:atim() end ---@return integer unixts, integer nanos Complicated time. ---@nodiscard --- --- Means time file status was last changed on UNIX. --- --- On Windows NT this is the same as birth time. function unix.Stat:ctim() end ---@return integer count512 Number of 512-byte blocks used by storage medium. ---@nodiscard --- This provides some indication of how much physical storage a file --- actually consumes. For example, for small file systems, your system --- might report this number as being 8, which means 4096 bytes. --- --- On Windows NT, if `O_COMPRESSED` is used for a file, then this --- number will reflect the size *after* compression. you can use: --- --- st = assert(unix.stat("moby.txt")) --- print('file size is %d bytes' % {st:size()}) --- print('file takes up %d bytes of space' % {st:blocks() * 512}) --- if GetHostOs() == 'WINDOWS' and st:flags() & 0x800 then --- print('thanks to file system compression') --- end --- --- To tell whether or not compression is being used on a file, function unix.Stat:blocks() end ---@return integer bytes Block size that underlying device uses. ---@nodiscard --- --- This field might be of assistance in computing optimal i/o sizes. --- --- Please note this field has no relationship to blocks, as the latter --- is fixed at a 512 byte size. function unix.Stat:blksize() end ---@return integer inode Inode number. ---@nodiscard --- --- This can be used to detect some other process used `rename()` to swap --- out a file underneath you, so you can do a refresh. redbean does it --- during each main process heartbeat for its own use cases. --- --- On Windows NT this is set to `NtByHandleFileInformation::FileIndex`. function unix.Stat:ino() end ---@return integer dev ID of device containing file. ---@nodiscard --- On Windows NT this is set to `NtByHandleFileInformation::VolumeSerialNumber`. function unix.Stat:dev() end ---@return integer rdev Information about device type. ---@nodiscard --- This value may be set to `0` or `-1` for files that aren't devices, --- depending on the operating system. `unix.major()` and `unix.minor()` --- may be used to extract the device numbers. function unix.Stat:rdev() end ---@return any ---@nodiscard function unix.Stat:nlink() end ---@return any ---@nodiscard function unix.Stat:gen() end ---@return any ---@nodiscard function unix.Stat:flags() end ---@class unix.Sigset: userdata --- The unix.Sigset class defines a mutable bitset that may currently --- contain 128 entries. See `unix.NSIG` to find out how many signals --- your operating system actually supports. --- Constructs new signal bitset object. ---@param sig integer ---@param ... integer ---@return unix.Sigset ---@nodiscard function unix.Sigset(sig, ...) end --- Adds signal to bitset. ---@param sig integer function unix.Sigset:add(sig) end --- Removes signal from bitset. ---@param sig integer function unix.Sigset:remove(sig) end --- Sets all bits in signal bitset to `true`. function unix.Sigset:fill() end --- Sets all bits in signal bitset to `false`. function unix.Sigset:clear() end ---@param sig integer ---@return boolean # `true` if `sig` is member of signal bitset. ---@nodiscard function unix.Sigset:contains(sig) end ---@return string # Lua code string that recreates object. ---@nodiscard function unix.Sigset:__repr() end ---@return string # Lua code string that recreates object. ---@nodiscard function unix.Sigset:__tostring() end --- This object is returned by system calls that fail. We prefer returning --- an object because for many system calls, an error is part their normal --- operation. For example, it's often desirable to use the `errno()` method --- when performing a `read()` to check for EINTR. ---@class unix.Errno: userdata unix.Errno = {} ---@return integer error error magic number. ---@nodiscard --- --- The error number is always different for different platforms. On --- UNIX systems, error numbers occupy the range [1,127] in practice. --- The System V ABI reserves numbers as high as 4095. On Windows NT, --- error numbers can go up to 65535. function unix.Errno:errno() end ---@return integer error Windows error number. ---@nodiscard --- --- On UNIX systems this is always 0. On Windows NT this will normally --- be the same as `errno(). Because Windows defines so many error codes, --- there's oftentimes a multimapping between its error codes and System --- Five. In those cases, this value reflects the `GetLastError()` result --- at the time the error occurred. function unix.Errno:winerr() end ---@return string symbol string of symbolic name of System Five error code. ---@nodiscard --- For example, this might return `"EINTR"`. function unix.Errno:name() end ---@return string symbol name of system call that failed. ---@nodiscard --- For example, this might return `"read"` if `read()` was what failed. function unix.Errno:call() end ---@return string # English string describing System Five error code. ---@nodiscard --- For example, this might return `"Interrupted system call"`. function unix.Errno:doc() end ---@return string # verbose string describing error. ---@nodiscard --- --- Different information components are delimited by slash. --- --- For example, this might return `"EINTR/4/Interrupted system call"`. --- --- On Windows NT this will include additional information about the --- Windows error (including FormatMessage() output) if the WIN32 error --- differs from the System Five error code. function unix.Errno:__tostring() end -- CONSTANTS ---@type integer for debug logging level. See `Log`. kLogDebug = nil ---@type integer for verbose logging level, which is less than `kLogDebug`. See `Log`. kLogVerbose = nil ---@type integer for info logging level, which is less than `kLogVerbose`. See `Log`. kLogInfo = nil ---@type integer for warn logging level, which is less than `kLogVerbose`. See `Log`. kLogWarn = nil ---@type integer for error logging level, which is less than `kLogWarn`. See `Log`. kLogError = nil ---@type integer for fatal logging level, which is less than `kLogError`. See `Log`. ---Logging anything at this level will result in a backtrace and process exit. kLogFatal = nil ---@type integer turn `+` into space. See `ParseUrl`. kUrlPlus = nil ---@type integer to transcode ISO-8859-1 input into UTF-8. See `ParseUrl`. kUrlLatin1 = nil --[[ ──────────────────────────────────────────────────────────────────────────────── LEGAL redbean contains software licensed ISC, MIT, BSD-2, BSD-3, zlib which makes it a permissively licensed gift to anyone who might find it useful. The transitive closure of legalese can be found inside the binary structure, because notice licenses require we distribute the license along with any software that uses it. By putting them in the binary, compliance in automated and no need for further action on the part of the user who is distributing. ──────────────────────────────────────────────────────────────────────────────── SEE ALSO https://redbean.dev/ https://news.ycombinator.com/item?id=26271117 ]]
303,303
7,732
jart/cosmopolitan
false
cosmopolitan/tool/net/lmaxmind.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/x/x.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/lua.h" #include "third_party/lua/luaconf.h" #include "third_party/maxmind/maxminddb.h" struct MaxmindDb { int refs; MMDB_s mmdb; }; struct MaxmindResult { uint32_t ip; struct MaxmindDb *db; MMDB_lookup_result_s mmlr; }; static const char *GetMmdbError(int err) { switch (err) { case MMDB_FILE_OPEN_ERROR: return "FILE_OPEN_ERROR"; case MMDB_CORRUPT_SEARCH_TREE_ERROR: return "CORRUPT_SEARCH_TREE_ERROR"; case MMDB_INVALID_METADATA_ERROR: return "INVALID_METADATA_ERROR"; case MMDB_IO_ERROR: return "IO_ERROR"; case MMDB_OUT_OF_MEMORY_ERROR: return "OUT_OF_MEMORY_ERROR"; case MMDB_UNKNOWN_DATABASE_FORMAT_ERROR: return "UNKNOWN_DATABASE_FORMAT_ERROR"; case MMDB_INVALID_DATA_ERROR: return "INVALID_DATA_ERROR"; case MMDB_INVALID_LOOKUP_PATH_ERROR: return "INVALID_LOOKUP_PATH_ERROR"; case MMDB_LOOKUP_PATH_DOES_NOT_MATCH_DATA_ERROR: return "LOOKUP_PATH_DOES_NOT_MATCH_DATA_ERROR"; case MMDB_INVALID_NODE_NUMBER_ERROR: return "INVALID_NODE_NUMBER_ERROR"; case MMDB_IPV6_LOOKUP_IN_IPV4_DATABASE_ERROR: return "IPV6_LOOKUP_IN_IPV4_DATABASE_ERROR"; default: return "UNKNOWN"; } }; static int LuaMaxmindOpen(lua_State *L) { int err; const char *p; struct MaxmindDb **udb, *db; p = luaL_checklstring(L, 1, 0); db = xmalloc(sizeof(struct MaxmindDb)); if ((err = MMDB_open(p, 0, &db->mmdb)) != MMDB_SUCCESS) { free(db); luaL_error(L, "MMDB_open(%s) → MMDB_%s", p, GetMmdbError(err)); unreachable; } db->refs = 1; udb = lua_newuserdatauv(L, sizeof(db), 1); luaL_setmetatable(L, "MaxmindDb*"); *udb = db; return 1; } static wontreturn void LuaThrowMaxmindIpError(lua_State *L, const char *function_name, uint32_t ip, int err) { luaL_error(L, "%s(%d.%d.%d.%d) → MMDB_%s", function_name, (ip & 0xff000000) >> 030, (ip & 0x00ff0000) >> 020, (ip & 0x0000ff00) >> 010, (ip & 0x000000ff) >> 000, GetMmdbError(err)); unreachable; } static int LuaMaxmindDbLookup(lua_State *L) { int err; lua_Integer ip; struct MaxmindDb **udb, *db; struct MaxmindResult **ur, *r; udb = luaL_checkudata(L, 1, "MaxmindDb*"); ip = luaL_checkinteger(L, 2); if (ip < 0 || ip > 0xffffffff) { lua_pushnil(L); return 1; } db = *udb; r = xmalloc(sizeof(struct MaxmindResult)); r->mmlr = MMDB_lookup(&db->mmdb, ip, &err); if (err) { free(r); LuaThrowMaxmindIpError(L, "MMDB_lookup", ip, err); } if (!r->mmlr.found_entry) { free(r); lua_pushnil(L); return 1; } r->ip = ip; r->db = db; r->db->refs++; ur = lua_newuserdatauv(L, sizeof(r), 1); luaL_setmetatable(L, "MaxmindResult*"); *ur = r; return 1; } static int LuaMaxmindResultNetmask(lua_State *L) { struct MaxmindResult **ur; ur = luaL_checkudata(L, 1, "MaxmindResult*"); lua_pushinteger(L, (*ur)->mmlr.netmask - (128 - 32)); return 1; } static MMDB_entry_data_list_s *LuaMaxmindDump(lua_State *L, MMDB_entry_data_list_s *dl) { size_t i, n; char ibuf[64]; switch (dl->entry_data.type) { case MMDB_DATA_TYPE_UTF8_STRING: lua_pushlstring(L, dl->entry_data.utf8_string, dl->entry_data.data_size); return dl->next; case MMDB_DATA_TYPE_BYTES: lua_pushlstring(L, (void *)dl->entry_data.bytes, dl->entry_data.data_size); return dl->next; case MMDB_DATA_TYPE_INT32: lua_pushinteger(L, dl->entry_data.int32); return dl->next; case MMDB_DATA_TYPE_UINT16: lua_pushinteger(L, dl->entry_data.uint16); return dl->next; case MMDB_DATA_TYPE_UINT32: lua_pushinteger(L, dl->entry_data.uint32); return dl->next; case MMDB_DATA_TYPE_BOOLEAN: lua_pushboolean(L, dl->entry_data.boolean); return dl->next; case MMDB_DATA_TYPE_UINT64: lua_pushinteger(L, dl->entry_data.uint64); return dl->next; case MMDB_DATA_TYPE_UINT128: sprintf(ibuf, "%#jjx", dl->entry_data.uint128); lua_pushstring(L, ibuf); return dl->next; case MMDB_DATA_TYPE_DOUBLE: lua_pushnumber(L, dl->entry_data.double_value); return dl->next; case MMDB_DATA_TYPE_FLOAT: lua_pushnumber(L, dl->entry_data.float_value); return dl->next; case MMDB_DATA_TYPE_ARRAY: lua_newtable(L); n = dl->entry_data.data_size; for (dl = dl->next, i = 0; dl && i < n; ++i) { dl = LuaMaxmindDump(L, dl); lua_seti(L, -2, i + 1); } return dl; case MMDB_DATA_TYPE_MAP: lua_newtable(L); n = dl->entry_data.data_size; for (dl = dl->next; dl && n; n--) { dl = LuaMaxmindDump(L, dl); dl = LuaMaxmindDump(L, dl); lua_settable(L, -3); } return dl; default: lua_pushnil(L); return dl->next; } } static int LuaMaxmindResultGet(lua_State *L) { int i, n, err; const char **path; MMDB_entry_s entry, *ep; MMDB_entry_data_s edata; struct MaxmindResult **ur; MMDB_entry_data_list_s *dl; n = lua_gettop(L) - 1; ur = luaL_checkudata(L, 1, "MaxmindResult*"); if (n <= 0) { ep = &(*ur)->mmlr.entry; } else { path = xcalloc(n + 1, sizeof(const char *)); for (i = 0; i < n; ++i) path[i] = lua_tostring(L, 2 + i); err = MMDB_aget_value(&(*ur)->mmlr.entry, &edata, path); free(path); if (err) { if (err == MMDB_LOOKUP_PATH_DOES_NOT_MATCH_DATA_ERROR) { lua_pushnil(L); return 1; } else { LuaThrowMaxmindIpError(L, "getpath", (*ur)->ip, err); } } if (!edata.offset) { lua_pushnil(L); return 1; } entry.mmdb = (*ur)->mmlr.entry.mmdb; entry.offset = edata.offset; ep = &entry; } err = MMDB_get_entry_data_list(ep, &dl); if (err) LuaThrowMaxmindIpError(L, "getlist", (*ur)->ip, err); LuaMaxmindDump(L, dl); MMDB_free_entry_data_list(dl); return 1; } static void FreeMaxmindDb(struct MaxmindDb *db) { if (!--db->refs) { MMDB_close(&db->mmdb); free(db); } } static int LuaMaxmindDbGc(lua_State *L) { struct MaxmindDb **udb; udb = luaL_checkudata(L, 1, "MaxmindDb*"); if (*udb) { FreeMaxmindDb(*udb); *udb = 0; } return 0; } static int LuaMaxmindResultGc(lua_State *L) { struct MaxmindResult **ur; ur = luaL_checkudata(L, 1, "MaxmindResult*"); if (*ur) { FreeMaxmindDb((*ur)->db); free(*ur); *ur = 0; } return 0; } static const luaL_Reg kLuaMaxmind[] = { {"open", LuaMaxmindOpen}, // {0}, // }; static const luaL_Reg kLuaMaxmindDbMeth[] = { {"lookup", LuaMaxmindDbLookup}, // {0}, // }; static const luaL_Reg kLuaMaxmindDbMeta[] = { {"__gc", LuaMaxmindDbGc}, // {0}, // }; static const luaL_Reg kLuaMaxmindResultMeth[] = { {"get", LuaMaxmindResultGet}, // {"netmask", LuaMaxmindResultNetmask}, // {0}, // }; static const luaL_Reg kLuaMaxmindResultMeta[] = { {"__gc", LuaMaxmindResultGc}, // {0}, // }; static void LuaMaxmindDb(lua_State *L) { luaL_newmetatable(L, "MaxmindDb*"); luaL_setfuncs(L, kLuaMaxmindDbMeta, 0); luaL_newlibtable(L, kLuaMaxmindDbMeth); luaL_setfuncs(L, kLuaMaxmindDbMeth, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } static void LuaMaxmindResult(lua_State *L) { luaL_newmetatable(L, "MaxmindResult*"); luaL_setfuncs(L, kLuaMaxmindResultMeta, 0); luaL_newlibtable(L, kLuaMaxmindResultMeth); luaL_setfuncs(L, kLuaMaxmindResultMeth, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } int LuaMaxmind(lua_State *L) { luaL_newlib(L, kLuaMaxmind); LuaMaxmindResult(L); LuaMaxmindDb(L); return 1; }
9,850
310
jart/cosmopolitan
false
cosmopolitan/tool/net/lfinger.h
#ifndef COSMOPOLITAN_TOOL_NET_LFINGER_H_ #define COSMOPOLITAN_TOOL_NET_LFINGER_H_ #include "third_party/lua/lauxlib.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int LuaFinger(lua_State *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_NET_LFINGER_H_ */
322
12
jart/cosmopolitan
false
cosmopolitan/tool/net/lsqlite3.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ lsqlite3 │ │ Copyright (C) 2002-2016 Tiago Dionizio, Doug Currie │ │ All rights reserved. │ │ Author : Tiago Dionizio <[email protected]> │ │ Author : Doug Currie <[email protected]> │ │ Library : lsqlite3 - an SQLite 3 database binding for Lua 5 │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/weirdtypes.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/lua.h" #include "third_party/lua/luaconf.h" #include "third_party/sqlite3/extensions.h" #include "third_party/sqlite3/sqlite3.h" // clang-format off asm(".ident\t\"\\n\\n\ lsqlite3 (MIT License)\\n\ Copyright 2002-2016 Tiago Dionizio, Doug Currie\""); asm(".include \"libc/disclaimer.inc\""); // LOCAL CHANGES // // - Remove online backup code // - Remove trace callback code // - Remove progress callback code // - Removed extension loading code // - Relocate static .data to .rodata // - Changed lua_strlen() to lua_rawlen() // #define LSQLITE_VERSION "0.9.5" /* luaL_typerror always used with arg at ndx == NULL */ #define luaL_typerror(L,ndx,str) luaL_error(L,"bad argument %d (%s expected, got nil)",ndx,str) /* luaL_register used once, so below expansion is OK for this case */ #define luaL_register(L,name,reg) lua_newtable(L);luaL_setfuncs(L,reg,0) /* luaL_openlib always used with name == NULL */ #define luaL_openlib(L,name,reg,nup) luaL_setfuncs(L,reg,nup) #define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) #define PUSH_INT64(L,i64in,fallback) \ do { \ sqlite_int64 i64 = i64in; \ lua_Integer i = (lua_Integer )i64; \ if (i == i64) lua_pushinteger(L, i);\ else { \ lua_Number n = (lua_Number)i64; \ if (n == i64) lua_pushnumber(L, n); \ else fallback; \ } \ } while (0) typedef struct sdb sdb; typedef struct sdb_vm sdb_vm; typedef struct sdb_bu sdb_bu; typedef struct sdb_func sdb_func; /* to use as C user data so i know what function sqlite is calling */ struct sdb_func { /* references to associated lua values */ int fn_step; int fn_finalize; int udata; sdb *db; char aggregate; sdb_func *next; }; /* information about database */ struct sdb { /* associated lua state */ lua_State *L; /* sqlite database handle */ sqlite3 *db; /* sql functions stack usage */ sdb_func *func; /* top SQL function being called */ /* references */ int busy_cb; /* busy callback */ int busy_udata; int wal_hook_cb; /* wal_hook callback */ int wal_hook_udata; int update_hook_cb; /* update_hook callback */ int update_hook_udata; int commit_hook_cb; /* commit_hook callback */ int commit_hook_udata; int rollback_hook_cb; /* rollback_hook callback */ int rollback_hook_udata; }; static const char *const sqlite_meta = ":sqlite3"; static const char *const sqlite_vm_meta = ":sqlite3:vm"; static const char *const sqlite_bu_meta = ":sqlite3:bu"; static const char *const sqlite_ctx_meta = ":sqlite3:ctx"; static int sqlite_ctx_meta_ref; #ifdef SQLITE_ENABLE_SESSION static const char *const sqlite_ses_meta = ":sqlite3:ses"; static const char *const sqlite_reb_meta = ":sqlite3:reb"; static const char *const sqlite_itr_meta = ":sqlite3:itr"; static int sqlite_ses_meta_ref; static int sqlite_reb_meta_ref; static int sqlite_itr_meta_ref; #endif /* global config configuration */ static int log_cb = LUA_NOREF; /* log callback */ static int log_udata; /* ** ======================================================= ** Database Virtual Machine Operations ** ======================================================= */ static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) { switch (sqlite3_column_type(vm, idx)) { case SQLITE_INTEGER: PUSH_INT64(L, sqlite3_column_int64(vm, idx) , lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx) , sqlite3_column_bytes(vm, idx))); break; case SQLITE_FLOAT: lua_pushnumber(L, sqlite3_column_double(vm, idx)); break; case SQLITE_TEXT: lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx)); break; case SQLITE_BLOB: lua_pushlstring(L, sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx)); break; case SQLITE_NULL: lua_pushnil(L); break; default: lua_pushnil(L); break; } } /* virtual machine information */ struct sdb_vm { sdb *db; /* associated database handle */ sqlite3_stmt *vm; /* virtual machine */ /* sqlite3_step info */ int columns; /* number of columns in result */ char has_values; /* true when step succeeds */ char temp; /* temporary vm used in db:rows */ }; /* called with db,sql text on the lua stack */ static sdb_vm *newvm(lua_State *L, sdb *db) { sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm)); /* db sql svm_ud -- */ luaL_getmetatable(L, sqlite_vm_meta); lua_setmetatable(L, -2); /* set metatable */ svm->db = db; svm->columns = 0; svm->has_values = 0; svm->vm = NULL; svm->temp = 0; /* add an entry on the database table: svm -> db to keep db live while svm is live */ lua_pushlightuserdata(L, db); /* db sql svm_ud db_lud -- */ lua_rawget(L, LUA_REGISTRYINDEX); /* db sql svm_ud reg[db_lud] -- */ lua_pushvalue(L, -2); /* db sql svm_ud reg[db_lud] svm_ud -- */ lua_pushvalue(L, -5); /* db sql svm_ud reg[db_lud] svm_ud db -- */ lua_rawset(L, -3); /* (reg[db_lud])[svm_ud] = db ; set the db for this vm */ lua_pop(L, 1); /* db sql svm_ud -- */ return svm; } static int cleanupvm(lua_State *L, sdb_vm *svm) { svm->columns = 0; svm->has_values = 0; if (!svm->vm) return 0; lua_pushinteger(L, sqlite3_finalize(svm->vm)); svm->vm = NULL; return 1; } static int stepvm(lua_State *L, sdb_vm *svm) { return sqlite3_step(svm->vm); } static sdb_vm *lsqlite_getvm(lua_State *L, int index) { sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta); if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine"); return svm; } static sdb_vm *lsqlite_checkvm(lua_State *L, int index) { sdb_vm *svm = lsqlite_getvm(L, index); if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine"); return svm; } static int dbvm_isopen(lua_State *L) { sdb_vm *svm = lsqlite_getvm(L, 1); lua_pushboolean(L, svm->vm != NULL ? 1 : 0); return 1; } static int dbvm_tostring(lua_State *L) { char buff[40]; sdb_vm *svm = lsqlite_getvm(L, 1); if (svm->vm == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", svm); lua_pushfstring(L, "sqlite virtual machine (%s)", buff); return 1; } static int dbvm_gc(lua_State *L) { cleanupvm(L, lsqlite_getvm(L, 1)); return 0; } static int dbvm_step(lua_State *L) { int result; sdb_vm *svm = lsqlite_checkvm(L, 1); result = stepvm(L, svm); svm->has_values = result == SQLITE_ROW ? 1 : 0; svm->columns = sqlite3_data_count(svm->vm); lua_pushinteger(L, result); return 1; } static int dbvm_finalize(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); return cleanupvm(L, svm); } static int dbvm_reset(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_reset(svm->vm); lua_pushinteger(L, sqlite3_errcode(svm->db->db)); return 1; } static void dbvm_check_contents(lua_State *L, sdb_vm *svm) { if (!svm->has_values) { luaL_error(L, "misuse of function"); } } static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) { if (index < 0 || index >= svm->columns) { luaL_error(L, "index out of range [0..%d]", svm->columns - 1); } } static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) { if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) { luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm)); } } static int dbvm_last_insert_rowid(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); /* conversion warning: int64 -> luaNumber */ sqlite_int64 rowid = sqlite3_last_insert_rowid(svm->db->db); PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid)); return 1; } /* ** ======================================================= ** Virtual Machine - generic info ** ======================================================= */ static int dbvm_columns(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); lua_pushinteger(L, sqlite3_column_count(svm->vm)); return 1; } /* ** ======================================================= ** Virtual Machine - getters ** ======================================================= */ static int dbvm_get_value(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); int index = luaL_checkint(L, 2); dbvm_check_contents(L, svm); dbvm_check_index(L, svm, index); vm_push_column(L, svm->vm, index); return 1; } static int dbvm_get_name(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); int index = luaL_checknumber(L, 2); dbvm_check_index(L, svm, index); lua_pushstring(L, sqlite3_column_name(svm->vm, index)); return 1; } static int dbvm_get_type(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); int index = luaL_checknumber(L, 2); dbvm_check_index(L, svm, index); lua_pushstring(L, sqlite3_column_decltype(svm->vm, index)); return 1; } static int dbvm_get_values(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = svm->columns; int n; dbvm_check_contents(L, svm); lua_createtable(L, columns, 0); for (n = 0; n < columns;) { vm_push_column(L, vm, n++); lua_rawseti(L, -2, n); } return 1; } static int dbvm_get_names(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ int n; lua_createtable(L, columns, 0); for (n = 0; n < columns;) { lua_pushstring(L, sqlite3_column_name(vm, n++)); lua_rawseti(L, -2, n); } return 1; } static int dbvm_get_types(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ int n; lua_createtable(L, columns, 0); for (n = 0; n < columns;) { lua_pushstring(L, sqlite3_column_decltype(vm, n++)); lua_rawseti(L, -2, n); } return 1; } static int dbvm_get_uvalues(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = svm->columns; int n; dbvm_check_contents(L, svm); lua_checkstack(L, columns); for (n = 0; n < columns; ++n) vm_push_column(L, vm, n); return columns; } static int dbvm_get_unames(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ int n; lua_checkstack(L, columns); for (n = 0; n < columns; ++n) lua_pushstring(L, sqlite3_column_name(vm, n)); return columns; } static int dbvm_get_utypes(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ int n; lua_checkstack(L, columns); for (n = 0; n < columns; ++n) lua_pushstring(L, sqlite3_column_decltype(vm, n)); return columns; } static int dbvm_get_named_values(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = svm->columns; int n; dbvm_check_contents(L, svm); lua_createtable(L, 0, columns); for (n = 0; n < columns; ++n) { lua_pushstring(L, sqlite3_column_name(vm, n)); vm_push_column(L, vm, n); lua_rawset(L, -3); } return 1; } static int dbvm_get_named_types(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int columns = sqlite3_column_count(vm); int n; lua_createtable(L, 0, columns); for (n = 0; n < columns; ++n) { lua_pushstring(L, sqlite3_column_name(vm, n)); lua_pushstring(L, sqlite3_column_decltype(vm, n)); lua_rawset(L, -3); } return 1; } /* ** ======================================================= ** Virtual Machine - Bind ** ======================================================= */ static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) { switch (lua_type(L, lindex)) { case LUA_TSTRING: return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_rawlen(L, lindex), SQLITE_TRANSIENT); case LUA_TNUMBER: #if LUA_VERSION_NUM > 502 if (lua_isinteger(L, lindex)) return sqlite3_bind_int64(vm, index, lua_tointeger(L, lindex)); #endif return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex)); case LUA_TBOOLEAN: return sqlite3_bind_int(vm, index, lua_toboolean(L, lindex) ? 1 : 0); case LUA_TNONE: case LUA_TNIL: return sqlite3_bind_null(vm, index); default: luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lua_type(L, lindex))); return SQLITE_MISUSE; /*!*/ } } static int dbvm_bind_parameter_count(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); lua_pushinteger(L, sqlite3_bind_parameter_count(svm->vm)); return 1; } static int dbvm_bind_parameter_name(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); int index = luaL_checknumber(L, 2); dbvm_check_bind_index(L, svm, index); lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index)); return 1; } static int dbvm_bind(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int index = luaL_checkint(L, 2); int result; dbvm_check_bind_index(L, svm, index); result = dbvm_bind_index(L, vm, index, 3); lua_pushinteger(L, result); return 1; } static int dbvm_bind_blob(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); int index = luaL_checkint(L, 2); const char *value = luaL_checkstring(L, 3); int len = lua_rawlen(L, 3); lua_pushinteger(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT)); return 1; } static int dbvm_bind_values(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int top = lua_gettop(L); int result, n; if (top - 1 != sqlite3_bind_parameter_count(vm)) luaL_error(L, "incorrect number of parameters to bind (%d given, %d to bind)", top - 1, sqlite3_bind_parameter_count(vm) ); for (n = 2; n <= top; ++n) { if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) { lua_pushinteger(L, result); return 1; } } lua_pushinteger(L, SQLITE_OK); return 1; } static int dbvm_bind_names(lua_State *L) { sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm = svm->vm; int count = sqlite3_bind_parameter_count(vm); const char *name; int result, n; luaL_checktype(L, 2, LUA_TTABLE); for (n = 1; n <= count; ++n) { name = sqlite3_bind_parameter_name(vm, n); if (name && (name[0] == ':' || name[0] == '$')) { lua_pushstring(L, ++name); lua_gettable(L, 2); result = dbvm_bind_index(L, vm, n, -1); lua_pop(L, 1); } else { lua_pushinteger(L, n); lua_gettable(L, 2); result = dbvm_bind_index(L, vm, n, -1); lua_pop(L, 1); } if (result != SQLITE_OK) { lua_pushinteger(L, result); return 1; } } lua_pushinteger(L, SQLITE_OK); return 1; } /* ** ======================================================= ** Database (internal management) ** ======================================================= */ /* ** When creating database handles, always creates a `closed' database handle ** before opening the actual database; so, if there is a memory error, the ** database is not left opened. ** ** Creates a new 'table' and leaves it in the stack */ static sdb *newdb (lua_State *L) { sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb)); db->L = L; db->db = NULL; /* database handle is currently `closed' */ db->func = NULL; db->busy_cb = db->busy_udata = db->wal_hook_cb = db->wal_hook_udata = db->update_hook_cb = db->update_hook_udata = db->commit_hook_cb = db->commit_hook_udata = db->rollback_hook_cb = db->rollback_hook_udata = LUA_NOREF; luaL_getmetatable(L, sqlite_meta); lua_setmetatable(L, -2); /* set metatable */ /* to keep track of 'open' virtual machines; make keys week */ lua_pushlightuserdata(L, db); lua_newtable(L); // t lua_newtable(L); // t mt lua_pushstring(L, "k"); // t mt v lua_setfield(L, -2, "__mode"); // t mt lua_setmetatable(L, -2); // t lua_rawset(L, LUA_REGISTRYINDEX); return db; } /* cleanup all vms or just temporary ones */ static void closevms(lua_State *L, sdb *db, int temp) { /* free associated virtual machines */ lua_pushlightuserdata(L, db); lua_rawget(L, LUA_REGISTRYINDEX); /* close all used handles */ lua_pushnil(L); while (lua_next(L, -2)) { sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */ if ((!temp || svm->temp)) lua_pop(L, cleanupvm(L, svm)); lua_pop(L, 1); /* pop value; leave key in the stack */ } } static int cleanupdb(lua_State *L, sdb *db) { sdb_func *func; sdb_func *func_next; int top = lua_gettop(L); int result; if (!db->db) return SQLITE_MISUSE; closevms(L, db, 0); /* remove entry in lua registry table */ lua_pushlightuserdata(L, db); lua_pushnil(L); lua_rawset(L, LUA_REGISTRYINDEX); /* 'free' all references */ luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_udata); luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata); luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata); luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); /* close database; _v2 is intended for use with garbage collected languages and where the order in which destructors are called is arbitrary. */ result = sqlite3_close_v2(db->db); db->db = NULL; /* free associated memory with created functions */ func = db->func; while (func) { func_next = func->next; luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step); luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize); luaL_unref(L, LUA_REGISTRYINDEX, func->udata); free(func); func = func_next; } db->func = NULL; lua_settop(L, top); return result; } static sdb *lsqlite_getdb(lua_State *L, int index) { sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta); if (db == NULL) luaL_typerror(L, index, "sqlite database"); return db; } static sdb *lsqlite_checkdb(lua_State *L, int index) { sdb *db = lsqlite_getdb(L, index); if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database"); return db; } /* ** ======================================================= ** User Defined Functions - Context Methods ** ======================================================= */ typedef struct { sqlite3_context *ctx; int ud; } lcontext; static lcontext *lsqlite_make_context(lua_State *L) { lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext)); lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref); lua_setmetatable(L, -2); ctx->ctx = NULL; ctx->ud = LUA_NOREF; return ctx; } static lcontext *lsqlite_getcontext(lua_State *L, int index) { lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta); if (ctx == NULL) luaL_typerror(L, index, "sqlite context"); return ctx; } static lcontext *lsqlite_checkcontext(lua_State *L, int index) { lcontext *ctx = lsqlite_getcontext(L, index); if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context"); return ctx; } static int lcontext_tostring(lua_State *L) { char buff[41]; lcontext *ctx = lsqlite_getcontext(L, 1); if (ctx->ctx == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", ctx->ctx); lua_pushfstring(L, "sqlite function context (%s)", buff); return 1; } static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) { sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); if (!func->aggregate) { luaL_error(L, "attempt to call aggregate method from scalar function"); } } static int lcontext_user_data(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata); return 1; } static int lcontext_get_aggregate_context(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); lcontext_check_aggregate(L, ctx); lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud); return 1; } static int lcontext_set_aggregate_context(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); lcontext_check_aggregate(L, ctx); lua_settop(L, 2); luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX); return 0; } #if 0 void *sqlite3_get_auxdata(sqlite3_context*, int); void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); #endif static int lcontext_result(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); switch (lua_type(L, 2)) { case LUA_TNUMBER: #if LUA_VERSION_NUM > 502 if (lua_isinteger(L, 2)) sqlite3_result_int64(ctx->ctx, luaL_checkinteger(L, 2)); else #endif sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2)); break; case LUA_TSTRING: sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_rawlen(L, 2), SQLITE_TRANSIENT); break; case LUA_TNIL: case LUA_TNONE: sqlite3_result_null(ctx->ctx); break; default: luaL_error(L, "invalid result type %s", lua_typename(L, 2)); break; } return 0; } static int lcontext_result_blob(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); const char *blob = luaL_checkstring(L, 2); int size = lua_rawlen(L, 2); sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT); return 0; } static int lcontext_result_double(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); double d = luaL_checknumber(L, 2); sqlite3_result_double(ctx->ctx, d); return 0; } static int lcontext_result_error(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); const char *err = luaL_checkstring(L, 2); int size = lua_rawlen(L, 2); sqlite3_result_error(ctx->ctx, err, size); return 0; } static int lcontext_result_int(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); int i = luaL_checkint(L, 2); sqlite3_result_int(ctx->ctx, i); return 0; } static int lcontext_result_null(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); sqlite3_result_null(ctx->ctx); return 0; } static int lcontext_result_text(lua_State *L) { lcontext *ctx = lsqlite_checkcontext(L, 1); const char *text = luaL_checkstring(L, 2); int size = lua_rawlen(L, 2); sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT); return 0; } /* ** ======================================================= ** Database Methods ** ======================================================= */ static int db_isopen(lua_State *L) { sdb *db = lsqlite_getdb(L, 1); lua_pushboolean(L, db->db != NULL ? 1 : 0); return 1; } static int db_last_insert_rowid(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); /* conversion warning: int64 -> luaNumber */ sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db); PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid)); return 1; } static int db_changes(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); lua_pushinteger(L, sqlite3_changes(db->db)); return 1; } static int db_total_changes(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); lua_pushinteger(L, sqlite3_total_changes(db->db)); return 1; } static int db_errcode(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); lua_pushinteger(L, sqlite3_errcode(db->db)); return 1; } static int db_errmsg(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); lua_pushstring(L, sqlite3_errmsg(db->db)); return 1; } static int db_interrupt(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); sqlite3_interrupt(db->db); return 0; } static int db_db_filename(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *db_name = luaL_checkstring(L, 2); // sqlite3_db_filename may return NULL, in that case Lua pushes nil... lua_pushstring(L, sqlite3_db_filename(db->db, db_name)); return 1; } static int pusherr(lua_State *L, int rc) { lua_pushnil(L); lua_pushinteger(L, rc); return 2; } static int db_wal_checkpoint(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); int eMode = luaL_optinteger(L, 2, SQLITE_CHECKPOINT_PASSIVE); const char *db_name = luaL_optstring(L, 3, NULL); int nLog, nCkpt; if (sqlite3_wal_checkpoint_v2(db->db, db_name, eMode, &nLog, &nCkpt) != SQLITE_OK) { return pusherr(L, sqlite3_errcode(db->db)); } lua_pushinteger(L, nLog); lua_pushinteger(L, nCkpt); return 2; } /* ** Registering SQL functions: */ static void db_push_value(lua_State *L, sqlite3_value *value) { switch (sqlite3_value_type(value)) { case SQLITE_TEXT: lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value)); break; case SQLITE_INTEGER: PUSH_INT64(L, sqlite3_value_int64(value) , lua_pushlstring(L, (const char*)sqlite3_value_text(value) , sqlite3_value_bytes(value))); break; case SQLITE_FLOAT: lua_pushnumber(L, sqlite3_value_double(value)); break; case SQLITE_BLOB: lua_pushlstring(L, sqlite3_value_blob(value), sqlite3_value_bytes(value)); break; case SQLITE_NULL: lua_pushnil(L); break; default: /* things done properly (SQLite + Lua SQLite) ** this should never happen */ lua_pushnil(L); break; } } /* ** callback functions used when calling registered sql functions */ /* scalar function to be called ** callback params: context, values... */ static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) { sdb_func *func = (sdb_func*)sqlite3_user_data(context); lua_State *L = func->db->L; int n; lcontext *ctx; int top = lua_gettop(L); /* ensure there is enough space in the stack */ lua_checkstack(L, argc + 3); lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step); /* function to call */ if (!func->aggregate) { ctx = lsqlite_make_context(L); /* push context - used to set results */ } else { /* reuse context userdata value */ void *p = sqlite3_aggregate_context(context, 1); /* i think it is OK to use assume that using a light user data ** as an entry on LUA REGISTRY table will be unique */ lua_pushlightuserdata(L, p); lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ if (lua_isnil(L, -1)) { /* not yet created? */ lua_pop(L, 1); ctx = lsqlite_make_context(L); lua_pushlightuserdata(L, p); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } else ctx = lsqlite_getcontext(L, -1); } /* push params */ for (n = 0; n < argc; ++n) { db_push_value(L, argv[n]); } /* set context */ ctx->ctx = context; if (lua_pcall(L, argc + 1, 0, 0)) { const char *errmsg = lua_tostring(L, -1); int size = lua_rawlen(L, -1); sqlite3_result_error(context, errmsg, size); } /* invalidate context */ ctx->ctx = NULL; if (!func->aggregate) { luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); } lua_settop(L, top); } static void db_sql_finalize_function(sqlite3_context *context) { sdb_func *func = (sdb_func*)sqlite3_user_data(context); lua_State *L = func->db->L; void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */ lcontext *ctx; int top = lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize); /* function to call */ /* i think it is OK to use assume that using a light user data ** as an entry on LUA REGISTRY table will be unique */ lua_pushlightuserdata(L, p); lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */ lua_pop(L, 1); ctx = lsqlite_make_context(L); lua_pushlightuserdata(L, p); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } else ctx = lsqlite_getcontext(L, -1); /* set context */ ctx->ctx = context; if (lua_pcall(L, 1, 0, 0)) { sqlite3_result_error(context, lua_tostring(L, -1), -1); } /* invalidate context */ ctx->ctx = NULL; /* cleanup context */ luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); /* remove it from registry */ lua_pushlightuserdata(L, p); lua_pushnil(L); lua_rawset(L, LUA_REGISTRYINDEX); lua_settop(L, top); } /* ** Register a normal function ** Params: db, function name, number arguments, [ callback | step, finalize], user data ** Returns: true on success ** ** Normal function: ** Params: context, params ** ** Aggregate function: ** Params of step: context, params ** Params of finalize: context */ static int db_register_function(lua_State *L, int aggregate) { sdb *db = lsqlite_checkdb(L, 1); const char *name; int args; int result; sdb_func *func; /* safety measure */ if (aggregate) aggregate = 1; name = luaL_checkstring(L, 2); args = luaL_checkint(L, 3); luaL_checktype(L, 4, LUA_TFUNCTION); if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION); /* maybe an alternative way to allocate memory should be used/avoided */ func = (sdb_func*)malloc(sizeof(sdb_func)); if (func == NULL) { luaL_error(L, "out of memory"); } result = sqlite3_create_function( db->db, name, args, SQLITE_UTF8, func, aggregate ? NULL : db_sql_normal_function, aggregate ? db_sql_normal_function : NULL, aggregate ? db_sql_finalize_function : NULL ); if (result == SQLITE_OK) { /* safety measures for userdata field to be present in the stack */ lua_settop(L, 5 + aggregate); /* save registered function in db function list */ func->db = db; func->aggregate = aggregate; func->next = db->func; db->func = func; /* save the setp/normal function callback */ lua_pushvalue(L, 4); func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX); /* save user data */ lua_pushvalue(L, 5+aggregate); func->udata = luaL_ref(L, LUA_REGISTRYINDEX); if (aggregate) { lua_pushvalue(L, 5); func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX); } else func->fn_finalize = LUA_NOREF; } else { /* free allocated memory */ free(func); } lua_pushboolean(L, result == SQLITE_OK ? 1 : 0); return 1; } static int db_create_function(lua_State *L) { return db_register_function(L, 0); } static int db_create_aggregate(lua_State *L) { return db_register_function(L, 1); } /* create_collation; contributed by Thomas Lauer */ typedef struct { lua_State *L; int ref; } scc; static int collwrapper(scc *co,int l1,const void *p1, int l2,const void *p2) { int res=0; lua_State *L=co->L; lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref); lua_pushlstring(L,p1,l1); lua_pushlstring(L,p2,l2); if (lua_pcall(L,2,1,0)==0) res=(int)lua_tonumber(L,-1); lua_pop(L,1); return res; } static void collfree(scc *co) { if (co) { luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref); free(co); } } static int db_create_collation(lua_State *L) { sdb *db=lsqlite_checkdb(L,1); const char *collname=luaL_checkstring(L,2); scc *co=NULL; int (*collfunc)(scc *,int,const void *,int,const void *)=NULL; lua_settop(L,3); /* default args to nil, and exclude extras */ if (lua_isfunction(L,3)) collfunc=collwrapper; else if (!lua_isnil(L,3)) luaL_error(L,"create_collation: function or nil expected"); if (collfunc != NULL) { co=(scc *)malloc(sizeof(scc)); /* userdata is a no-no as it will be garbage-collected */ if (co) { co->L=L; /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */ co->ref=luaL_ref(L,LUA_REGISTRYINDEX); } else luaL_error(L,"create_collation: could not allocate callback"); } sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8, (void *)co, (int(*)(void*,int,const void*,int,const void*))collfunc, (void(*)(void*))collfree); return 0; } /* ** wal_hook callback: ** Params: database, callback function, userdata ** ** callback function: ** Params: userdata, db handle, database name, number of wal file pages */ static int db_wal_hook_callback(void *user, sqlite3 *dbh, char const *dbname, int pnum) { sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); /* setup lua callback call */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->wal_hook_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->wal_hook_udata); /* get callback user data */ lua_pushstring(L, dbname); /* hook database name */ lua_pushinteger(L, pnum); if (lua_pcall(L, 3, 0, 0) != LUA_OK) return lua_error(L); lua_settop(L, top); return SQLITE_OK; } static int db_wal_hook(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_udata); if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { db->wal_hook_cb = db->wal_hook_udata = LUA_NOREF; /* clear hook handler */ sqlite3_wal_hook(db->db, NULL, NULL); } else { luaL_checktype(L, 2, LUA_TFUNCTION); /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); db->wal_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); db->wal_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); /* set hook handler */ sqlite3_wal_hook(db->db, db_wal_hook_callback, db); } return 0; } /* ** update_hook callback: ** Params: database, callback function, userdata ** ** callback function: ** Params: userdata, {one of SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE}, ** database name, table name (containing the affected row), rowid of the row */ static void db_update_hook_callback(void *user, int op, char const *dbname, char const *tblname, sqlite3_int64 rowid) { sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); lua_Number n; /* setup lua callback call */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_udata); /* get callback user data */ lua_pushinteger(L, op); lua_pushstring(L, dbname); /* update_hook database name */ lua_pushstring(L, tblname); /* update_hook database name */ PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid)); /* call lua function */ lua_pcall(L, 5, 0, 0); /* ignore any error generated by this function */ lua_settop(L, top); } static int db_update_hook(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata); if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { db->update_hook_cb = db->update_hook_udata = LUA_NOREF; /* clear update_hook handler */ sqlite3_update_hook(db->db, NULL, NULL); } else { luaL_checktype(L, 2, LUA_TFUNCTION); /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); /* set update_hook handler */ sqlite3_update_hook(db->db, db_update_hook_callback, db); } return 0; } /* ** commit_hook callback: ** Params: database, callback function, userdata ** ** callback function: ** Params: userdata ** Returned value: Return false or nil to continue the COMMIT operation normally. ** return true (non false, non nil), then the COMMIT is converted into a ROLLBACK. */ static int db_commit_hook_callback(void *user) { sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); int rollback = 0; /* setup lua callback call */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_udata); /* get callback user data */ /* call lua function */ if (!lua_pcall(L, 1, 1, 0)) rollback = lua_toboolean(L, -1); /* use result if there was no error */ lua_settop(L, top); return rollback; } static int db_commit_hook(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata); if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { db->commit_hook_cb = db->commit_hook_udata = LUA_NOREF; /* clear commit_hook handler */ sqlite3_commit_hook(db->db, NULL, NULL); } else { luaL_checktype(L, 2, LUA_TFUNCTION); /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); /* set commit_hook handler */ sqlite3_commit_hook(db->db, db_commit_hook_callback, db); } return 0; } /* ** rollback hook callback: ** Params: database, callback function, userdata ** ** callback function: ** Params: userdata */ static void db_rollback_hook_callback(void *user) { sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); /* setup lua callback call */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); /* get callback user data */ /* call lua function */ lua_pcall(L, 1, 0, 0); /* ignore any error generated by this function */ lua_settop(L, top); } static int db_rollback_hook(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { db->rollback_hook_cb = db->rollback_hook_udata = LUA_NOREF; /* clear rollback_hook handler */ sqlite3_rollback_hook(db->db, NULL, NULL); } else { luaL_checktype(L, 2, LUA_TFUNCTION); /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); /* set rollback_hook handler */ sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db); } return 0; } /* ** busy handler: ** Params: database, callback function, userdata ** ** callback function: ** Params: userdata, number of tries ** returns: 0 to return immediately and return SQLITE_BUSY, non-zero to try again */ static int db_busy_callback(void *user, int tries) { int retry = 0; /* abort by default */ sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb); lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata); lua_pushinteger(L, tries); /* call lua function */ if (!lua_pcall(L, 2, 1, 0)) retry = lua_toboolean(L, -1); lua_settop(L, top); return retry; } static int db_busy_handler(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { db->busy_cb = db->busy_udata = LUA_NOREF; /* clear busy handler */ sqlite3_busy_handler(db->db, NULL, NULL); } else { luaL_checktype(L, 2, LUA_TFUNCTION); /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX); db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX); /* set busy handler */ sqlite3_busy_handler(db->db, db_busy_callback, db); } return 0; } static int db_busy_timeout(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); int timeout = luaL_checkint(L, 2); sqlite3_busy_timeout(db->db, timeout); /* if there was a timeout callback registered, it is now ** invalid/useless. free any references we may have */ luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); db->busy_cb = db->busy_udata = LUA_NOREF; return 0; } /* ** Params: db, sql, callback, user ** returns: code [, errmsg] ** ** Callback: ** Params: user, number of columns, values, names ** Returns: 0 to continue, other value will cause abort */ static int db_exec_callback(void* user, int columns, char **data, char **names) { int result = SQLITE_ABORT; /* abort by default */ lua_State *L = (lua_State*)user; int n; int top = lua_gettop(L); lua_pushvalue(L, 3); /* function to call */ lua_pushvalue(L, 4); /* user data */ lua_pushinteger(L, columns); /* total number of rows in result */ /* column values */ lua_pushvalue(L, 6); for (n = 0; n < columns;) { lua_pushstring(L, data[n++]); lua_rawseti(L, -2, n); } /* columns names */ lua_pushvalue(L, 5); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_createtable(L, columns, 0); lua_pushvalue(L, -1); lua_replace(L, 5); for (n = 0; n < columns;) { lua_pushstring(L, names[n++]); lua_rawseti(L, -2, n); } } /* call lua function */ if (!lua_pcall(L, 4, 1, 0)) { #if LUA_VERSION_NUM > 502 if (lua_isinteger(L, -1)) result = lua_tointeger(L, -1); else #endif if (lua_isnumber(L, -1)) result = lua_tonumber(L, -1); } lua_settop(L, top); return result; } static int db_exec(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *sql = luaL_checkstring(L, 2); int result; if (!lua_isnoneornil(L, 3)) { /* stack: ** 3: callback function ** 4: userdata ** 5: column names ** 6: reusable column values */ luaL_checktype(L, 3, LUA_TFUNCTION); lua_settop(L, 4); /* 'trap' userdata - nil extra parameters */ lua_pushnil(L); /* column names not known at this point */ lua_newtable(L); /* column values table */ result = sqlite3_exec(db->db, sql, db_exec_callback, L, NULL); } else { /* no callbacks */ result = sqlite3_exec(db->db, sql, NULL, NULL, NULL); } lua_pushinteger(L, result); return 1; } /* ** Params: db, sql ** returns: code, compiled length or error message */ static int db_prepare(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *sql = luaL_checkstring(L, 2); int sql_len = lua_rawlen(L, 2); const char *sqltail; sdb_vm *svm; lua_settop(L,2); /* db,sql is on top of stack for call to newvm */ svm = newvm(L, db); if (sqlite3_prepare_v2(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) { lua_pushnil(L); lua_pushinteger(L, sqlite3_errcode(db->db)); if (cleanupvm(L, svm) == 1) lua_pop(L, 1); /* this should not happen since sqlite3_prepare_v2 will not set ->vm on error */ return 2; } /* vm already in the stack */ lua_pushstring(L, sqltail); return 2; } static int db_do_next_row(lua_State *L, int packed) { int result; sdb_vm *svm = lsqlite_checkvm(L, 1); sqlite3_stmt *vm; int columns; int i; result = stepvm(L, svm); vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */ svm->has_values = result == SQLITE_ROW ? 1 : 0; svm->columns = columns = sqlite3_data_count(vm); if (result == SQLITE_ROW) { if (packed) { if (packed == 1) { lua_createtable(L, columns, 0); for (i = 0; i < columns;) { vm_push_column(L, vm, i); lua_rawseti(L, -2, ++i); } } else { lua_createtable(L, 0, columns); for (i = 0; i < columns; ++i) { lua_pushstring(L, sqlite3_column_name(vm, i)); vm_push_column(L, vm, i); lua_rawset(L, -3); } } return 1; } else { lua_checkstack(L, columns); for (i = 0; i < columns; ++i) vm_push_column(L, vm, i); return svm->columns; } } if (svm->temp) { /* finalize and check for errors */ result = sqlite3_finalize(vm); svm->vm = NULL; cleanupvm(L, svm); } else if (result == SQLITE_DONE) { result = sqlite3_reset(vm); } if (result != SQLITE_OK) { lua_pushstring(L, sqlite3_errmsg(svm->db->db)); lua_error(L); } return 0; } static int db_next_row(lua_State *L) { return db_do_next_row(L, 0); } static int db_next_packed_row(lua_State *L) { return db_do_next_row(L, 1); } static int db_next_named_row(lua_State *L) { return db_do_next_row(L, 2); } static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) { /* sdb_vm *svm = */ lsqlite_checkvm(L, 1); lua_pushvalue(L,1); lua_pushcfunction(L, f); lua_insert(L, -2); return 2; } static int dbvm_rows(lua_State *L) { return dbvm_do_rows(L, db_next_packed_row); } static int dbvm_nrows(lua_State *L) { return dbvm_do_rows(L, db_next_named_row); } static int dbvm_urows(lua_State *L) { return dbvm_do_rows(L, db_next_row); } static int db_do_rows(lua_State *L, int(*f)(lua_State *)) { sdb *db = lsqlite_checkdb(L, 1); const char *sql = luaL_checkstring(L, 2); sdb_vm *svm; lua_settop(L,2); /* db,sql is on top of stack for call to newvm */ svm = newvm(L, db); svm->temp = 1; if (sqlite3_prepare_v2(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) { lua_pushstring(L, sqlite3_errmsg(svm->db->db)); if (cleanupvm(L, svm) == 1) lua_pop(L, 1); /* this should not happen since sqlite3_prepare_v2 will not set ->vm on error */ lua_error(L); } lua_pushcfunction(L, f); lua_insert(L, -2); return 2; } static int db_rows(lua_State *L) { return db_do_rows(L, db_next_packed_row); } static int db_nrows(lua_State *L) { return db_do_rows(L, db_next_named_row); } /* unpacked version of db:rows */ static int db_urows(lua_State *L) { return db_do_rows(L, db_next_row); } static int db_tostring(lua_State *L) { char buff[33]; sdb *db = lsqlite_getdb(L, 1); if (db->db == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", lua_touserdata(L, 1)); lua_pushfstring(L, "sqlite database (%s)", buff); return 1; } static int db_close(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); lua_pushinteger(L, cleanupdb(L, db)); return 1; } static int db_close_vm(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); closevms(L, db, lua_toboolean(L, 2)); return 0; } static int db_gc(lua_State *L) { sdb *db = lsqlite_getdb(L, 1); if (db->db != NULL) /* ignore closed databases */ cleanupdb(L, db); return 0; } static int db_serialize(lua_State *L) { sdb *db = lsqlite_getdb(L, 1); sqlite_int64 size = 0; if (db->db == NULL) /* ignore closed databases */ return 0; char *buffer = (char *)sqlite3_serialize(db->db, "main", &size, 0); if (buffer == NULL) /* ignore failed database serialization */ return 0; lua_pushlstring(L, buffer, size); free(buffer); return 1; } static int db_deserialize(lua_State *L) { sdb *db = lsqlite_getdb(L, 1); size_t size = 0; if (db->db == NULL) /* ignore closed databases */ return 0; const char *buffer = luaL_checklstring(L, 2, &size); if (buffer == NULL || size == 0) /* ignore empty database content */ return 0; const char *sqlbuf = memcpy(sqlite3_malloc(size), buffer, size); sqlite3_deserialize(db->db, "main", sqlbuf, size, size, SQLITE_DESERIALIZE_FREEONCLOSE + SQLITE_DESERIALIZE_RESIZEABLE); return 0; } #ifdef SQLITE_ENABLE_SESSION /* ** ======================================================= ** Iterator functions (for session support) ** ======================================================= */ typedef struct { sqlite3_changeset_iter *itr; bool collectable; } liter; static liter *lsqlite_makeiter(lua_State *L, sqlite3_changeset_iter *piter, bool collectable) { liter *litr = (liter*)lua_newuserdata(L, sizeof(liter)); lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_itr_meta_ref); lua_setmetatable(L, -2); litr->itr = piter; litr->collectable = collectable; return litr; } static liter *lsqlite_getiter(lua_State *L, int index) { return (liter *)luaL_checkudata(L, index, sqlite_itr_meta); } static liter *lsqlite_checkiter(lua_State *L, int index) { liter *litr = lsqlite_getiter(L, index); if (litr->itr == NULL) luaL_argerror(L, index, "invalid sqlite iterator"); return litr; } static int liter_finalize(lua_State *L) { liter *litr = lsqlite_getiter(L, 1); int rc; if (litr->itr) { if (!litr->collectable) { return pusherr(L, SQLITE_CORRUPT); } if ((rc = sqlite3changeset_finalize(litr->itr)) != SQLITE_OK) { return pusherr(L, rc); } litr->itr = NULL; } lua_pushboolean(L, 1); return 1; } static int liter_gc(lua_State *L) { return liter_finalize(L); } static int liter_tostring(lua_State *L) { char buff[33]; liter *litr = lsqlite_getiter(L, 1); if (litr->itr == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", litr->itr); lua_pushfstring(L, "sqlite iterator (%s)", buff); return 1; } static int liter_table( lua_State *L, int (*iter_func)(sqlite3_changeset_iter *pIter, int val, sqlite3_value **ppValue) ) { const char *zTab; int n, rc, nCol, Op, bIndirect; sqlite3_value *pVal; liter *litr = lsqlite_checkiter(L, 1); sqlite3changeset_op(litr->itr, &zTab, &nCol, &Op, &bIndirect); lua_createtable(L, nCol, 0); for (n = 0; n < nCol; n++) { if ((rc = (*iter_func)(litr->itr, n, &pVal)) != LUA_OK) { return pusherr(L, rc); } if (pVal) { db_push_value(L, pVal); } else { // push `false` to indicate that the value wasn't changed // and not included in the record and to keep table valid lua_pushboolean(L, 0); } lua_rawseti(L, -2, n+1); } return 1; } static int liter_new(lua_State *L) { return liter_table(L, sqlite3changeset_new); } static int liter_old(lua_State *L) { return liter_table(L, sqlite3changeset_old); } static int liter_conflict(lua_State *L) { return liter_table(L, sqlite3changeset_conflict); } static int liter_op(lua_State *L) { const char *zTab; int rc, nCol, Op, bIndirect; liter *litr = lsqlite_checkiter(L, 1); if ((rc = sqlite3changeset_op(litr->itr, &zTab, &nCol, &Op, &bIndirect)) != LUA_OK) { return pusherr(L, rc); } lua_pushstring(L, zTab); lua_pushinteger(L, Op); lua_pushboolean(L, bIndirect); return 3; } static int liter_fk_conflicts(lua_State *L) { int rc, nOut; liter *litr = lsqlite_checkiter(L, 1); if ((rc = sqlite3changeset_fk_conflicts(litr->itr, &nOut)) != LUA_OK) { return pusherr(L, rc); } lua_pushinteger(L, nOut); return 1; } static int liter_next(lua_State *L) { liter *litr = lsqlite_checkiter(L, 1); if (!litr->collectable) { return pusherr(L, SQLITE_CORRUPT); } lua_pushinteger(L, sqlite3changeset_next(litr->itr)); return 1; } static int liter_pk(lua_State *L) { const char *zTab; int n, rc, nCol; unsigned char *abPK; liter *litr = lsqlite_checkiter(L, 1); if ((rc = sqlite3changeset_pk(litr->itr, &abPK, &nCol)) != LUA_OK) { return pusherr(L, rc); } lua_createtable(L, nCol, 0); for (n = 0; n < nCol; n++) { lua_pushboolean(L, abPK[n]); lua_rawseti(L, -2, n+1); } return 1; } /* ** ======================================================= ** Rebaser functions (for session support) ** ======================================================= */ typedef struct { sqlite3_rebaser *reb; } lrebaser; static lrebaser *lsqlite_makerebaser(lua_State *L, sqlite3_rebaser *reb) { lrebaser *lreb = (lrebaser*)lua_newuserdata(L, sizeof(lrebaser)); lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_reb_meta_ref); lua_setmetatable(L, -2); lreb->reb = reb; return lreb; } static lrebaser *lsqlite_getrebaser(lua_State *L, int index) { return (lrebaser *)luaL_checkudata(L, index, sqlite_reb_meta); } static lrebaser *lsqlite_checkrebaser(lua_State *L, int index) { lrebaser *lreb = lsqlite_getrebaser(L, index); if (lreb->reb == NULL) luaL_argerror(L, index, "invalid sqlite rebaser"); return lreb; } static int lrebaser_delete(lua_State *L) { lrebaser *lreb = lsqlite_getrebaser(L, 1); if (lreb->reb != NULL) { sqlite3rebaser_delete(lreb->reb); lreb->reb = NULL; } return 0; } static int lrebaser_gc(lua_State *L) { return lrebaser_delete(L); } static int lrebaser_tostring(lua_State *L) { char buff[32]; lrebaser *lreb = lsqlite_getrebaser(L, 1); if (lreb->reb == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", lreb->reb); lua_pushfstring(L, "sqlite rebaser (%s)", buff); return 1; } static int lrebaser_rebase(lua_State *L) { lrebaser *lreb = lsqlite_checkrebaser(L, 1); const char *cset = luaL_checkstring(L, 2); int nset = lua_rawlen(L, 2); int rc; int size; void *buf; if ((rc = sqlite3rebaser_rebase(lreb->reb, nset, cset, &size, &buf)) != SQLITE_OK) { return pusherr(L, rc); } lua_pushlstring(L, buf, size); sqlite3_free(buf); return 1; } static int db_create_rebaser(lua_State *L) { sqlite3_rebaser *reb; int rc; if ((rc = sqlite3rebaser_create(&reb)) != SQLITE_OK) { return pusherr(L, rc); } (void)lsqlite_makerebaser(L, reb); return 1; } /* session/changeset callbacks */ static int changeset_conflict_cb = LUA_NOREF; static int changeset_filter_cb = LUA_NOREF; static int changeset_cb_udata = LUA_NOREF; static int session_filter_cb = LUA_NOREF; static int session_cb_udata = LUA_NOREF; static int db_changeset_conflict_callback( void *user, /* Copy of sixth arg to _apply_v2() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ sqlite3_changeset_iter *p /* Handle describing change and conflict */ ) { // return default code if no callback is provided if (changeset_conflict_cb == LUA_NOREF) return SQLITE_CHANGESET_OMIT; sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); int result, isint; const char *zTab; int nCol, Op, bIndirect; if (sqlite3changeset_op(p, &zTab, &nCol, &Op, &bIndirect) != LUA_OK) { lua_pushliteral(L, "invalid return from changeset iterator"); return lua_error(L); } lua_rawgeti(L, LUA_REGISTRYINDEX, changeset_conflict_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, changeset_cb_udata); /* get callback user data */ lua_pushinteger(L, eConflict); (void)lsqlite_makeiter(L, p, 0); lua_pushstring(L, zTab); lua_pushinteger(L, Op); lua_pushboolean(L, bIndirect); if (lua_pcall(L, 6, 1, 0) != LUA_OK) return lua_error(L); result = lua_tointegerx(L, -1, &isint); /* use result if there was no error */ if (!isint) { lua_pushliteral(L, "non-integer returned from conflict callback"); return lua_error(L); } lua_settop(L, top); return result; } static int db_filter_callback( void *user, /* Context */ const char *zTab, /* Table name */ int filter_cb, int filter_udata ) { // allow the table if no filter callback is provided if (filter_cb == LUA_NOREF || filter_cb == LUA_REFNIL) return 1; sdb *db = (sdb*)user; lua_State *L = db->L; int top = lua_gettop(L); int result, isint; lua_rawgeti(L, LUA_REGISTRYINDEX, filter_cb); /* get callback */ lua_pushstring(L, zTab); lua_rawgeti(L, LUA_REGISTRYINDEX, filter_udata); /* get callback user data */ if (lua_pcall(L, 2, 1, 0) != LUA_OK) return lua_error(L); // allow 0/1 and false/true to be returned // returning 0/false skips the table result = lua_tointegerx(L, -1, &isint); /* use result if there was no error */ if (!isint && !lua_isboolean(L, -1)) { lua_pushliteral(L, "non-integer and non-boolean returned from filter callback"); return lua_error(L); } if (!isint) result = lua_toboolean(L, -1); lua_settop(L, top); return result; } static int db_changeset_filter_callback( void *user, /* Copy of sixth arg to _apply_v2() */ const char *zTab /* Table name */ ) { return db_filter_callback(user, zTab, changeset_filter_cb, changeset_cb_udata); } static int db_session_filter_callback( void *user, /* Copy of third arg to session_attach() */ const char *zTab /* Table name */ ) { return db_filter_callback(user, zTab, session_filter_cb, session_cb_udata); } /* ** ======================================================= ** Session functions ** ======================================================= */ typedef struct { sqlite3_session *ses; sdb *db; // keep track of the DB this session is for } lsession; static lsession *lsqlite_makesession(lua_State *L, sqlite3_session *ses, sdb *db) { lsession *lses = (lsession*)lua_newuserdata(L, sizeof(lsession)); lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ses_meta_ref); lua_setmetatable(L, -2); lses->ses = ses; lses->db = db; return lses; } static lsession *lsqlite_getsession(lua_State *L, int index) { return (lsession *)luaL_checkudata(L, index, sqlite_ses_meta); } static lsession *lsqlite_checksession(lua_State *L, int index) { lsession *lses = lsqlite_getsession(L, index); if (lses->ses == NULL) luaL_argerror(L, index, "invalid sqlite session"); return lses; } static int lsession_attach(lua_State *L) { lsession *lses = lsqlite_checksession(L, 1); int rc; // allow either a table or a callback function to filter tables const char *zTab = lua_type(L, 2) == LUA_TFUNCTION ? NULL : luaL_optstring(L, 2, NULL); if ((rc = sqlite3session_attach(lses->ses, zTab)) != SQLITE_OK) { return pusherr(L, rc); } // allow to pass a filter callback, // but only one shared for all sessions where this callback is used if (lua_type(L, 2) == LUA_TFUNCTION) { // TBD: does this *also* need to be done in cleanupvm? luaL_unref(L, LUA_REGISTRYINDEX, session_filter_cb); luaL_unref(L, LUA_REGISTRYINDEX, session_cb_udata); lua_settop(L, 3); // add udata even if it's not provided session_cb_udata = luaL_ref(L, LUA_REGISTRYINDEX); session_filter_cb = luaL_ref(L, LUA_REGISTRYINDEX); sqlite3session_table_filter(lses->ses, db_session_filter_callback, lses->db); } lua_pushboolean(L, 1); return 1; } static int lsession_isempty(lua_State *L) { lsession *lses = lsqlite_checksession(L, 1); lua_pushboolean(L, sqlite3session_isempty(lses->ses)); return 1; } static int lsession_diff(lua_State *L) { lsession *lses = lsqlite_checksession(L, 1); const char *zFromDb = luaL_checkstring(L, 2); const char *zTbl = luaL_checkstring(L, 3); int rc = sqlite3session_diff(lses->ses, zFromDb, zTbl, NULL); if (rc != SQLITE_OK) return pusherr(L, rc); lua_pushboolean(L, 1); return 1; } static int lsession_bool( lua_State *L, int (*session_func)(sqlite3_session *ses, int val) ) { lsession *lses = lsqlite_checksession(L, 1); int val = lua_isboolean(L, 2) ? lua_toboolean(L, 2) : luaL_optinteger(L, 2, -1); lua_pushboolean(L, (*session_func)(lses->ses, val)); return 1; } static int lsession_indirect(lua_State *L) { return lsession_bool(L, sqlite3session_indirect); } static int lsession_enable(lua_State *L) { return lsession_bool(L, sqlite3session_enable); } static int lsession_getset( lua_State *L, int (*session_setfunc)(sqlite3_session *ses, int *size, void **buf) ) { lsession *lses = lsqlite_checksession(L, 1); int rc; int size; void *buf; if ((rc = (*session_setfunc)(lses->ses, &size, &buf)) != SQLITE_OK) { return pusherr(L, rc); } lua_pushlstring(L, buf, size); sqlite3_free(buf); return 1; } static int lsession_changeset(lua_State *L) { return lsession_getset(L, sqlite3session_changeset); } static int lsession_patchset(lua_State *L) { return lsession_getset(L, sqlite3session_patchset); } static int lsession_delete(lua_State *L) { lsession *lses = lsqlite_getsession(L, 1); if (lses->ses != NULL) { sqlite3session_delete(lses->ses); lses->ses = NULL; } return 0; } static int lsession_tostring(lua_State *L) { char buff[32]; lsession *lses = lsqlite_getsession(L, 1); if (lses->ses == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", lses->ses); lua_pushfstring(L, "sqlite session (%s)", buff); return 1; } static int db_create_session(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *zDb = luaL_optstring(L, 2, "main"); sqlite3_session *ses; if (sqlite3session_create(db->db, zDb, &ses) != SQLITE_OK) { return pusherr(L, sqlite3_errcode(db->db)); } (void)lsqlite_makesession(L, ses, db); return 1; } static int db_iterate_changeset(lua_State *L) { sqlite3_changeset_iter *p; sdb *db = lsqlite_checkdb(L, 1); const char *cset = luaL_checkstring(L, 2); int nset = lua_rawlen(L, 2); int flags = luaL_optinteger(L, 3, 0); int rc; if ((rc = sqlite3changeset_start_v2(&p, nset, cset, flags)) != SQLITE_OK) { return pusherr(L, rc); } (void)lsqlite_makeiter(L, p, 1); return 1; } static int db_invert_changeset(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *cset = luaL_checkstring(L, 2); int nset = lua_rawlen(L, 2); int rc; int size; void *buf; if ((rc = sqlite3changeset_invert(nset, cset, &size, &buf)) != SQLITE_OK) { return pusherr(L, rc); } lua_pushlstring(L, buf, size); sqlite3_free(buf); return 1; } static int db_concat_changeset(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); int size, nset; void *buf, *cset; sqlite3_changegroup *pGrp; luaL_checktype(L, 2, LUA_TTABLE); int n = luaL_len(L, 2); int rc = sqlite3changegroup_new(&pGrp); for (int i = 1; rc == SQLITE_OK && i <= n; i++) { lua_rawgeti(L, 2, i); cset = lua_tostring(L, -1); nset = lua_rawlen(L, -1); rc = sqlite3changegroup_add(pGrp, nset, cset); lua_pop(L, 1); // pop the string } if (rc == SQLITE_OK) rc = sqlite3changegroup_output(pGrp, &size, &buf); sqlite3changegroup_delete(pGrp); if (rc != SQLITE_OK) return pusherr(L, rc); lua_pushlstring(L, buf, size); sqlite3_free(buf); return 1; } static int db_apply_changeset(lua_State *L) { sdb *db = lsqlite_checkdb(L, 1); const char *cset = luaL_checkstring(L, 2); int nset = lua_rawlen(L, 2); int top = lua_gettop(L); int rc; int flags = 0; void *pRebase; int nRebase; lrebaser *lreb = NULL; // parameters: db, changeset[[, filter cb], conflict cb[, udata[, rebaser[, flags]]]] // TBD: does this *also* need to be done in cleanupvm? if (changeset_cb_udata != LUA_NOREF) { luaL_unref(L, LUA_REGISTRYINDEX, changeset_conflict_cb); luaL_unref(L, LUA_REGISTRYINDEX, changeset_filter_cb); luaL_unref(L, LUA_REGISTRYINDEX, changeset_cb_udata); changeset_conflict_cb = changeset_filter_cb = changeset_cb_udata = LUA_NOREF; } // check for conflict/filter callback type if provided if (top >= 3) { luaL_checktype(L, 3, LUA_TFUNCTION); // if no filter callback, insert a dummy one to simplify stack handling if (lua_type(L, 4) != LUA_TFUNCTION) { lua_pushnil(L); lua_insert(L, 3); top = lua_gettop(L); } } if (top >= 6) lreb = lsqlite_checkrebaser(L, 6); if (top >= 7) flags = luaL_checkinteger(L, 7); if (top >= 4) { // two callback are guaranteed to be on the stack in this case // shorten stack or extend to set udata to `nil` if not provided lua_settop(L, 5); changeset_cb_udata = luaL_ref(L, LUA_REGISTRYINDEX); changeset_conflict_cb = luaL_ref(L, LUA_REGISTRYINDEX); changeset_filter_cb = luaL_ref(L, LUA_REGISTRYINDEX); } rc = sqlite3changeset_apply_v2(db->db, nset, cset, db_changeset_filter_callback, db_changeset_conflict_callback, db, // context lreb ? &pRebase : 0, lreb ? &nRebase : 0, flags); if (rc != SQLITE_OK) return pusherr(L, sqlite3_errcode(db->db)); if (lreb) { // if rebaser is present rc = sqlite3rebaser_configure(lreb->reb, nRebase, pRebase); if (rc == SQLITE_OK) lua_pushstring(L, pRebase); sqlite3_free(pRebase); if (rc == SQLITE_OK) return 1; return pusherr(L, rc); } lua_pushboolean(L, 1); return 1; } #endif /* ** ======================================================= ** General library functions ** ======================================================= */ static int lsqlite_version(lua_State *L) { lua_pushstring(L, sqlite3_libversion()); return 1; } static int lsqlite_do_open(lua_State *L, const char *filename, int flags) { sqlite3_initialize(); /* initialize the engine if hasn't been done yet */ sdb *db = newdb(L); /* create and leave in stack */ if (sqlite3_open_v2(filename, &db->db, flags, 0) == SQLITE_OK) { /* database handle already in the stack - return it */ sqlite3_zipfile_init(db->db, 0, 0); return 1; } /* failed to open database */ lua_pushnil(L); /* push nil */ lua_pushinteger(L, sqlite3_errcode(db->db)); lua_pushstring(L, sqlite3_errmsg(db->db)); /* push error message */ /* clean things up */ cleanupdb(L, db); /* return */ return 3; } static int lsqlite_open(lua_State *L) { const char *filename = luaL_checkstring(L, 1); int flags = luaL_optinteger(L, 2, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); return lsqlite_do_open(L, filename, flags); } static int lsqlite_open_memory(lua_State *L) { return lsqlite_do_open(L, ":memory:", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); } /* ** Log callback: ** Params: user, result code, log message ** Returns: none */ static void log_callback(void* user, int rc, const char *msg) { if (log_cb != LUA_NOREF) { lua_State *L = (lua_State*)user; /* setup lua callback call */ int top = lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, log_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, log_udata); /* get callback user data */ lua_pushinteger(L, rc); lua_pushstring(L, msg); if (lua_pcall(L, 3, 0, 0) != LUA_OK) lua_error(L); lua_settop(L, top); } } static int lsqlite_config(lua_State *L) { int rc = SQLITE_MISUSE; int option = luaL_checkint(L, 1); switch (option) { case SQLITE_CONFIG_SINGLETHREAD: case SQLITE_CONFIG_MULTITHREAD: case SQLITE_CONFIG_SERIALIZED: if ((rc = sqlite3_config(option)) == SQLITE_OK) { lua_pushinteger(L, rc); return 1; } break; case SQLITE_CONFIG_LOG: /* make sure we have an userdata field (even if nil) */ lua_settop(L, 3); // prepate to return current (possibly nil) values lua_pushinteger(L, SQLITE_OK); lua_rawgeti(L, LUA_REGISTRYINDEX, log_cb); /* get callback */ lua_rawgeti(L, LUA_REGISTRYINDEX, log_udata); /* get callback user data */ luaL_unref(L, LUA_REGISTRYINDEX, log_cb); luaL_unref(L, LUA_REGISTRYINDEX, log_udata); if (lua_isnil(L, 2)) { log_cb = log_udata = LUA_NOREF; } else { luaL_checktype(L, 2, LUA_TFUNCTION); lua_pushvalue(L, 2); lua_pushvalue(L, 3); log_udata = luaL_ref(L, LUA_REGISTRYINDEX); log_cb = luaL_ref(L, LUA_REGISTRYINDEX); } return 3; // return OK and previous callback and userdata } return pusherr(L, rc); } static int lsqlite_newindex(lua_State *L) { lua_pushliteral(L, "attempt to change readonly table"); lua_error(L); return 0; } /* Version number of this library */ static int lsqlite_lversion(lua_State *L) { lua_pushstring(L, LSQLITE_VERSION); return 1; } /* ** ======================================================= ** Register functions ** ======================================================= */ #define SC(s) { #s, SQLITE_ ## s }, #define LSC(s) { #s, LSQLITE_ ## s }, static const struct { const char* name; int value; } sqlite_constants[] = { /* error codes */ SC(OK) SC(ERROR) SC(INTERNAL) SC(PERM) SC(ABORT) SC(BUSY) SC(LOCKED) SC(NOMEM) SC(READONLY) SC(INTERRUPT) SC(IOERR) SC(CORRUPT) SC(NOTFOUND) SC(FULL) SC(CANTOPEN) SC(PROTOCOL) SC(EMPTY) SC(SCHEMA) SC(TOOBIG) SC(CONSTRAINT) SC(MISMATCH) SC(MISUSE) SC(NOLFS) SC(FORMAT) SC(NOTADB) /* sqlite_step specific return values */ SC(RANGE) SC(ROW) SC(DONE) /* column types */ SC(INTEGER) SC(FLOAT) SC(TEXT) SC(BLOB) SC(NULL) /* Authorizer Action Codes */ SC(CREATE_INDEX ) SC(CREATE_TABLE ) SC(CREATE_TEMP_INDEX ) SC(CREATE_TEMP_TABLE ) SC(CREATE_TEMP_TRIGGER) SC(CREATE_TEMP_VIEW ) SC(CREATE_TRIGGER ) SC(CREATE_VIEW ) SC(DELETE ) SC(DROP_INDEX ) SC(DROP_TABLE ) SC(DROP_TEMP_INDEX ) SC(DROP_TEMP_TABLE ) SC(DROP_TEMP_TRIGGER ) SC(DROP_TEMP_VIEW ) SC(DROP_TRIGGER ) SC(DROP_VIEW ) SC(INSERT ) SC(PRAGMA ) SC(READ ) SC(SELECT ) SC(TRANSACTION ) SC(UPDATE ) SC(ATTACH ) SC(DETACH ) SC(ALTER_TABLE ) SC(REINDEX ) SC(ANALYZE ) SC(CREATE_VTABLE ) SC(DROP_VTABLE ) SC(FUNCTION ) SC(SAVEPOINT ) /* file open flags */ SC(OPEN_READONLY) SC(OPEN_READWRITE) SC(OPEN_CREATE) SC(OPEN_URI) SC(OPEN_MEMORY) SC(OPEN_NOMUTEX) SC(OPEN_FULLMUTEX) SC(OPEN_SHAREDCACHE) SC(OPEN_PRIVATECACHE) /* config flags */ SC(CONFIG_SINGLETHREAD) SC(CONFIG_MULTITHREAD) SC(CONFIG_SERIALIZED) SC(CONFIG_LOG) /* checkpoint flags */ SC(CHECKPOINT_PASSIVE) SC(CHECKPOINT_FULL) SC(CHECKPOINT_RESTART) SC(CHECKPOINT_TRUNCATE) #ifdef SQLITE_ENABLE_SESSION /* session constants */ SC(CHANGESETSTART_INVERT) SC(CHANGESETAPPLY_NOSAVEPOINT) SC(CHANGESETAPPLY_INVERT) SC(CHANGESET_DATA) SC(CHANGESET_NOTFOUND) SC(CHANGESET_CONFLICT) SC(CHANGESET_CONSTRAINT) SC(CHANGESET_FOREIGN_KEY) SC(CHANGESET_OMIT) SC(CHANGESET_REPLACE) SC(CHANGESET_ABORT) #endif /* terminator */ { NULL, 0 } }; /* ======================================================= */ static const luaL_Reg dblib[] = { {"isopen", db_isopen }, {"last_insert_rowid", db_last_insert_rowid }, {"changes", db_changes }, {"total_changes", db_total_changes }, {"errcode", db_errcode }, {"error_code", db_errcode }, {"errmsg", db_errmsg }, {"error_message", db_errmsg }, {"interrupt", db_interrupt }, {"db_filename", db_db_filename }, {"wal_checkpoint", db_wal_checkpoint }, {"create_function", db_create_function }, {"create_aggregate", db_create_aggregate }, {"create_collation", db_create_collation }, {"busy_timeout", db_busy_timeout }, {"busy_handler", db_busy_handler }, {"wal_hook", db_wal_hook }, {"update_hook", db_update_hook }, {"commit_hook", db_commit_hook }, {"rollback_hook", db_rollback_hook }, {"prepare", db_prepare }, {"rows", db_rows }, {"urows", db_urows }, {"nrows", db_nrows }, {"exec", db_exec }, {"execute", db_exec }, {"close", db_close }, {"close_vm", db_close_vm }, {"serialize", db_serialize }, {"deserialize", db_deserialize }, #ifdef SQLITE_ENABLE_SESSION {"create_session", db_create_session }, {"create_rebaser", db_create_rebaser }, {"apply_changeset", db_apply_changeset }, {"invert_changeset", db_invert_changeset }, {"concat_changeset", db_concat_changeset }, {"iterate_changeset", db_iterate_changeset }, #endif {"__tostring", db_tostring }, {"__gc", db_gc }, {NULL, NULL} }; static const luaL_Reg vmlib[] = { {"isopen", dbvm_isopen }, {"step", dbvm_step }, {"reset", dbvm_reset }, {"finalize", dbvm_finalize }, {"columns", dbvm_columns }, {"bind", dbvm_bind }, {"bind_values", dbvm_bind_values }, {"bind_names", dbvm_bind_names }, {"bind_blob", dbvm_bind_blob }, {"bind_parameter_count",dbvm_bind_parameter_count}, {"bind_parameter_name", dbvm_bind_parameter_name}, {"get_value", dbvm_get_value }, {"get_values", dbvm_get_values }, {"get_name", dbvm_get_name }, {"get_names", dbvm_get_names }, {"get_type", dbvm_get_type }, {"get_types", dbvm_get_types }, {"get_uvalues", dbvm_get_uvalues }, {"get_unames", dbvm_get_unames }, {"get_utypes", dbvm_get_utypes }, {"get_named_values", dbvm_get_named_values }, {"get_named_types", dbvm_get_named_types }, {"rows", dbvm_rows }, {"urows", dbvm_urows }, {"nrows", dbvm_nrows }, {"last_insert_rowid", dbvm_last_insert_rowid }, /* compatibility names (added by request) */ {"idata", dbvm_get_values }, {"inames", dbvm_get_names }, {"itypes", dbvm_get_types }, {"data", dbvm_get_named_values }, {"type", dbvm_get_named_types }, {"__tostring", dbvm_tostring }, {"__gc", dbvm_gc }, { NULL, NULL } }; static const luaL_Reg ctxlib[] = { {"user_data", lcontext_user_data }, {"get_aggregate_data", lcontext_get_aggregate_context }, {"set_aggregate_data", lcontext_set_aggregate_context }, {"result", lcontext_result }, {"result_null", lcontext_result_null }, {"result_number", lcontext_result_double }, {"result_double", lcontext_result_double }, {"result_int", lcontext_result_int }, {"result_text", lcontext_result_text }, {"result_blob", lcontext_result_blob }, {"result_error", lcontext_result_error }, {"__tostring", lcontext_tostring }, {NULL, NULL} }; #ifdef SQLITE_ENABLE_SESSION static const luaL_Reg seslib[] = { {"attach", lsession_attach }, {"changeset", lsession_changeset }, {"patchset", lsession_patchset }, {"isempty", lsession_isempty }, {"indirect", lsession_indirect }, {"enable", lsession_enable }, {"diff", lsession_diff }, {"delete", lsession_delete }, {"__tostring", lsession_tostring }, {NULL, NULL} }; static const luaL_Reg reblib[] = { {"rebase", lrebaser_rebase }, {"delete", lrebaser_delete }, {"__tostring", lrebaser_tostring }, {"__gc", lrebaser_gc }, {NULL, NULL} }; static const luaL_Reg itrlib[] = { {"op", liter_op }, {"pk", liter_pk }, {"new", liter_new }, {"old", liter_old }, {"next", liter_next }, {"conflict", liter_conflict }, {"finalize", liter_finalize }, {"fk_conflicts", liter_fk_conflicts }, {"__tostring", liter_tostring }, {"__gc", liter_gc }, {NULL, NULL} }; #endif static const luaL_Reg sqlitelib[] = { {"lversion", lsqlite_lversion }, {"version", lsqlite_version }, {"open", lsqlite_open }, {"open_memory", lsqlite_open_memory }, {"config", lsqlite_config }, {"__newindex", lsqlite_newindex }, {NULL, NULL} }; static void create_meta(lua_State *L, const char *name, const luaL_Reg *lib) { luaL_newmetatable(L, name); lua_pushliteral(L, "__index"); lua_pushvalue(L, -2); /* push metatable */ lua_rawset(L, -3); /* metatable.__index = metatable */ /* register metatable functions */ luaL_openlib(L, NULL, lib, 0); /* remove metatable from stack */ lua_pop(L, 1); } LUALIB_API int luaopen_lsqlite3(lua_State *L) { /* call config before calling initialize */ sqlite3_config(SQLITE_CONFIG_LOG, log_callback, L); create_meta(L, sqlite_meta, dblib); create_meta(L, sqlite_vm_meta, vmlib); create_meta(L, sqlite_ctx_meta, ctxlib); luaL_getmetatable(L, sqlite_ctx_meta); sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); #ifdef SQLITE_ENABLE_SESSION create_meta(L, sqlite_ses_meta, seslib); create_meta(L, sqlite_reb_meta, reblib); create_meta(L, sqlite_itr_meta, itrlib); luaL_getmetatable(L, sqlite_ses_meta); sqlite_ses_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); luaL_getmetatable(L, sqlite_reb_meta); sqlite_reb_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); luaL_getmetatable(L, sqlite_itr_meta); sqlite_itr_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); #endif /* register (local) sqlite metatable */ luaL_register(L, "sqlite3", sqlitelib); { int i = 0; /* add constants to global table */ while (sqlite_constants[i].name) { lua_pushstring(L, sqlite_constants[i].name); lua_pushinteger(L, sqlite_constants[i].value); lua_rawset(L, -3); ++i; } } /* set sqlite's metatable to itself - set as readonly (__newindex) */ lua_pushvalue(L, -1); lua_setmetatable(L, -2); return 1; }
86,344
2,836
jart/cosmopolitan
false
cosmopolitan/tool/net/largon2.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ largon2 │ │ Copyright © 2016 Thibault Charbonnier │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/isystem/stdio.h" #include "libc/isystem/string.h" #include "third_party/argon2/argon2.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/lua.h" #include "third_party/lua/lualib.h" asm(".ident\t\"\\n\\n\ largon2 (MIT License)\\n\ Copyright 2016 Thibault Charbonnier\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /*** Lua C binding for the Argon2 password hashing function. Compatible with Lua 5.x and LuaJIT. See the [Argon2 documentation](https://github.com/P-H-C/phc-winner-argon2) for in-depth instructions and details about Argon2. This module's version is compatible with Argon2 [20161029](https://github.com/P-H-C/phc-winner-argon2/releases/tag/20161029) and later. Note: this document is also valid for the [lua-argon2-ffi](https://github.com/thibaultcha/lua-argon2-ffi) module: an FFI implementation of this binding for LuaJIT which uses the same API as this original implementation. @module argon2 @author Thibault Charbonnier @license MIT @release 3.0.1 */ /*** Argon2 hashing variants. Those fields are `userdatums`, read-only values that can be fed to the module's configuration or the `hash_encoded` function. See the [Argon2 documentation](https://github.com/P-H-C/phc-winner-argon2) for a description of those variants. @field argon2_i @field argon2_d @field argon2_id @table variants */ /*** Argon2 hashing options. Those options can be given to `hash_encoded` as a table. If values are omitted, the default values of this module will be used. Default values of this module can be overridden with `m_cost()`, `t_cost()`, `parallelism()`, `hash_len()`, and `variant()`. @field t_cost Number of iterations (`number`, default: `3`). argon2.hash_encoded("password", "salt", { t_cost = 4 }) Can be set to a new default in lua-argon2 (C binding only) by calling: argon2.t_cost(4) @field m_cost Sets memory usage as KiB (`number`, default: `4096`). argon2.hash_encoded("password", "salt", { m_cost = math.pow(2, 16) -- 2^16 aka 65536 KiB }) Can be set to a new default in lua-argon2 (C binding only) by calling: argon2.m_cost(16) @field parallelism Number of threads and compute lanes (`number`, default: `1`). argon2.hash_encoded("password", "salt", { parallelism = 2 }) Can be set to a new default in lua-argon2 (C binding only) by calling: argon2.parallelism(2) @field hash_len Length of the hash output length (`number`, default: `32`). argon2.hash_encoded("password", "salt", { hash_len = 64 }) Can be set to a new default in lua-argon2 (C binding only) by calling: argon2.hash_len(64) @field variant Choose the Argon2 variant to use (Argon2i, Argon2d, Argon2id) from the `variants` table. (`userdata`, default: `argon2.variants.argon2_i`). argon2.hash_encoded("password", "salt", { variant = argon2.variants.argon2_d }) Can be set to a new default in lua-argon2 (C binding only) by calling: argon2.variant(argon2.variants.argon2_i) argon2.variant(argon2.variants.argon2_d) argon2.variant(argon2.variants.argon2_id) @table options */ #define LUA_ARGON2_DEFAULT_T_COST 3 #define LUA_ARGON2_DEFAULT_M_COST 4096 #define LUA_ARGON2_DEFAULT_PARALLELISM 1 #define LUA_ARGON2_DEFAULT_HASH_LEN 32 typedef struct largon2_config_s largon2_config_t; struct largon2_config_s { uint32_t m_cost; uint32_t t_cost; uint32_t parallelism; uint32_t hash_len; argon2_type variant; }; /* CONFIGURATION */ static void largon2_create_config(lua_State *L) { largon2_config_t *cfg; cfg = lua_newuserdata(L, sizeof(*cfg)); cfg->t_cost = LUA_ARGON2_DEFAULT_T_COST; cfg->m_cost = LUA_ARGON2_DEFAULT_M_COST; cfg->parallelism = LUA_ARGON2_DEFAULT_PARALLELISM; cfg->hash_len = LUA_ARGON2_DEFAULT_HASH_LEN; cfg->variant = Argon2_id; } static largon2_config_t * largon2_fetch_config(lua_State *L) { largon2_config_t *cfg; cfg = lua_touserdata(L, lua_upvalueindex(1)); if (!cfg) luaL_error(L, "could not retrieve argon2 config"); return cfg; } static largon2_config_t * largon2_arg_init(lua_State *L, int nargs) { if (lua_gettop(L) > nargs) { luaL_error(L, "expecting no more than %d arguments, but got %d", nargs, lua_gettop(L)); } lua_settop(L, nargs); return largon2_fetch_config(L); } static void largon2_integer_opt(lua_State *L, uint32_t optidx, uint32_t argidx, uint32_t *property, const char *key) { uint32_t value; char errmsg[64]; if (!lua_isnil(L, optidx)) { if (lua_isnumber(L, optidx)) { value = lua_tonumber(L, optidx); *property = value; } else { sprintf(errmsg, "expected %s to be a number, got %s", key, luaL_typename(L, optidx)); luaL_argerror(L, argidx, errmsg); } } } static int largon2_cfg_t_cost(lua_State *L) { largon2_config_t *cfg = largon2_arg_init(L, 1); largon2_integer_opt(L, 1, 1, &cfg->t_cost, "t_cost"); lua_pushinteger(L, cfg->t_cost); return 1; } static int largon2_cfg_m_cost(lua_State *L) { largon2_config_t *cfg = largon2_arg_init(L, 1); largon2_integer_opt(L, 1, 1, &cfg->m_cost, "m_cost"); lua_pushinteger(L, cfg->m_cost); return 1; } static int largon2_cfg_parallelism(lua_State *L) { largon2_config_t *cfg = largon2_arg_init(L, 1); largon2_integer_opt(L, 1, 1, &cfg->parallelism, "parallelism"); lua_pushinteger(L, cfg->parallelism); return 1; } static int largon2_cfg_hash_len(lua_State *L) { largon2_config_t *cfg = largon2_arg_init(L, 1); largon2_integer_opt(L, 1, 1, &cfg->hash_len, "hash_len"); lua_pushinteger(L, cfg->hash_len); return 1; } static int largon2_cfg_variant(lua_State *L) { largon2_config_t *cfg = largon2_arg_init(L, 1); luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); cfg->variant = (argon2_type) lua_touserdata(L, 1); return 1; } /* BINDINGS */ /*** Hashes a password with Argon2i, Argon2d, or Argon2id, producing an encoded hash. @function hash_encoded @param[type=string] plain Plain string to hash_encoded. @param[type=string] salt Salt to use to hash the plain string. @param[type=table] options Options with which to hash the plain string. See `options`. This parameter is optional, if values are omitted the default ones will be used. @treturn string `encoded`: Encoded hash computed by Argon2, or `nil` if an error occurred. @treturn string `err`: `nil`, or a string describing the error if any. @usage local hash, err = argon2.hash_encoded("password", "somesalt") if err then error("could not hash_encoded: " .. err) end -- with options and variant local hash, err = argon2.hash_encoded("password", "somesalt", { t_cost = 4, m_cost = math.pow(2, 16), -- 65536 KiB variant = argon2.variants.argon2_d }) */ static int largon2_hash_encoded(lua_State *L) { const char *plain, *salt; char *encoded, *err_msg; size_t plainlen, saltlen; size_t encoded_len; uint32_t t_cost; uint32_t m_cost; uint32_t hash_len; uint32_t parallelism; argon2_type variant; argon2_error_codes ret_code; largon2_config_t *cfg; luaL_Buffer buf; plain = luaL_checklstring(L, 1, &plainlen); salt = luaL_checklstring(L, 2, &saltlen); cfg = largon2_arg_init(L, 3); t_cost = cfg->t_cost; m_cost = cfg->m_cost; parallelism = cfg->parallelism; hash_len = cfg->hash_len; variant = cfg->variant; if (!lua_isnil(L, 3)) { if (!lua_istable(L, 3)) { luaL_argerror(L, 3, "expected to be a table"); } lua_getfield(L, 3, "t_cost"); largon2_integer_opt(L, -1, 3, &t_cost, "t_cost"); lua_pop(L, 1); lua_getfield(L, 3, "m_cost"); largon2_integer_opt(L, -1, 3, &m_cost, "m_cost"); lua_pop(L, 1); lua_getfield(L, 3, "parallelism"); largon2_integer_opt(L, -1, 3, &parallelism, "parallelism"); lua_pop(L, 1); lua_getfield(L, 3, "hash_len"); largon2_integer_opt(L, -1, 3, &hash_len, "hash_len"); lua_pop(L, 1); lua_getfield(L, 3, "variant"); if (!lua_isnil(L, -1)) { if (!lua_islightuserdata(L, -1)) { char errmsg[64]; sprintf(errmsg, "expected variant to be a number, got %s", luaL_typename(L, -1)); luaL_argerror(L, 3, errmsg); } variant = (argon2_type) lua_touserdata(L, -1); } lua_pop(L, 1); } encoded_len = argon2_encodedlen(t_cost, m_cost, parallelism, saltlen, hash_len, variant); encoded = luaL_buffinitsize(L, &buf, encoded_len); if (variant == Argon2_d) { ret_code = argon2d_hash_encoded(t_cost, m_cost, parallelism, plain, plainlen, salt, saltlen, hash_len, encoded, encoded_len); } else if (variant == Argon2_id) { ret_code = argon2id_hash_encoded(t_cost, m_cost, parallelism, plain, plainlen, salt, saltlen, hash_len, encoded, encoded_len); } else { ret_code = argon2i_hash_encoded(t_cost, m_cost, parallelism, plain, plainlen, salt, saltlen, hash_len, encoded, encoded_len); } luaL_pushresultsize(&buf, encoded_len - 1); if (ret_code != ARGON2_OK) { err_msg = (char *) argon2_error_message(ret_code); lua_pushnil(L); lua_pushstring(L, err_msg); return 2; } return 1; } /*** Verifies a password against an encoded string. @function verify @param[type=string] encoded Encoded string to verify the plain password against. @param[type=string] password Plain password to verify. @treturn boolean `ok`: `true` if the password matches, `false` if it is a mismatch. If an error occurs during the verification, will be `nil`. @treturn string `err`: `nil`, or a string describing the error if any. A password mismatch will not return an error, but will return `ok = false` instead. @usage local ok, err = argon2.verify(argon2i_hash, "password") if err then -- failure to verify (*not* a password mismatch) error("could not verify: " .. err) end if not ok then -- password mismatch error("The password does not match the supplied hash") end -- with a argon2d hash local ok, err = argon2.verify(argon2d_hash, "password") */ static int largon2_verify(lua_State *L) { const char *plain, *encoded; size_t plainlen; argon2_type variant; argon2_error_codes ret_code; char *err_msg; if (lua_gettop(L) != 2) { return luaL_error(L, "expecting 2 arguments, but got %d", lua_gettop(L)); } encoded = luaL_checkstring(L, 1); plain = luaL_checklstring(L, 2, &plainlen); if (strstr(encoded, "argon2d")) { variant = Argon2_d; } else if (strstr(encoded, "argon2id")) { variant = Argon2_id; } else { variant = Argon2_i; } ret_code = argon2_verify(encoded, plain, plainlen, variant); if (ret_code == ARGON2_VERIFY_MISMATCH) { lua_pushboolean(L, 0); return 1; } if (ret_code != ARGON2_OK) { err_msg = (char *) argon2_error_message(ret_code); lua_pushnil(L); lua_pushstring(L, err_msg); return 2; } lua_pushboolean(L, 1); return 1; } /* MODULE */ static void largon2_push_argon2_variants_table(lua_State *L) { lua_newtable(L); lua_pushlightuserdata(L, (void *) Argon2_i); lua_setfield(L, -2, "argon2_i"); lua_pushlightuserdata(L, (void *) Argon2_d); lua_setfield(L, -2, "argon2_d"); lua_pushlightuserdata(L, (void *) Argon2_id); lua_setfield(L, -2, "argon2_id"); return; } static const luaL_Reg largon2[] = { { "verify", largon2_verify }, { "hash_encoded", largon2_hash_encoded }, { "t_cost", largon2_cfg_t_cost }, { "m_cost", largon2_cfg_m_cost }, { "parallelism", largon2_cfg_parallelism }, { "hash_len", largon2_cfg_hash_len }, { "variant", largon2_cfg_variant }, { NULL, NULL } }; int luaopen_argon2(lua_State *L) { lua_newtable(L); largon2_create_config(L); luaL_setfuncs(L, largon2, 1); /* push argon2.variants table */ largon2_push_argon2_variants_table(L); lua_setfield(L, -2, "variants"); lua_pushliteral(L, "3.0.1"); lua_setfield(L, -2, "_VERSION"); lua_pushliteral(L, "Thibault Charbonnier"); lua_setfield(L, -2, "_AUTHOR"); lua_pushliteral(L, "MIT"); lua_setfield(L, -2, "_LICENSE"); lua_pushliteral(L, "https://github.com/thibaultcha/lua-argon2"); lua_setfield(L, -2, "_URL"); return 1; }
15,899
506
jart/cosmopolitan
false
cosmopolitan/tool/net/lre.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/macros.internal.h" #include "libc/str/str.h" #include "third_party/lua/lauxlib.h" #include "third_party/regex/regex.h" struct ReErrno { int err; char doc[64]; }; static void LuaSetIntField(lua_State *L, const char *k, lua_Integer v) { lua_pushinteger(L, v); lua_setfield(L, -2, k); } static int LuaReReturnError(lua_State *L, regex_t *r, int rc) { struct ReErrno *e; lua_pushnil(L); e = lua_newuserdatauv(L, sizeof(struct ReErrno), 0); luaL_setmetatable(L, "re.Errno"); e->err = rc; regerror(rc, r, e->doc, sizeof(e->doc)); return 2; } static regex_t *LuaReCompileImpl(lua_State *L, const char *p, int f) { int rc; regex_t *r; r = lua_newuserdatauv(L, sizeof(regex_t), 0); luaL_setmetatable(L, "re.Regex"); f &= REG_EXTENDED | REG_ICASE | REG_NEWLINE | REG_NOSUB; f ^= REG_EXTENDED; if ((rc = regcomp(r, p, f)) == REG_OK) { return r; } else { LuaReReturnError(L, r, rc); return NULL; } } static int LuaReSearchImpl(lua_State *L, regex_t *r, const char *s, int f) { int rc, i, n; regmatch_t *m; luaL_Buffer tmp; n = 1 + r->re_nsub; m = (regmatch_t *)luaL_buffinitsize(L, &tmp, n * sizeof(regmatch_t)); m->rm_so = 0; m->rm_eo = 0; if ((rc = regexec(r, s, n, m, f >> 8)) == REG_OK) { for (i = 0; i < n; ++i) { lua_pushlstring(L, s + m[i].rm_so, m[i].rm_eo - m[i].rm_so); } return n; } else { return LuaReReturnError(L, r, rc); } } //////////////////////////////////////////////////////////////////////////////// // re static int LuaReSearch(lua_State *L) { int f; regex_t *r; const char *p, *s; p = luaL_checkstring(L, 1); s = luaL_checkstring(L, 2); f = luaL_optinteger(L, 3, 0); if (f & ~(REG_EXTENDED | REG_ICASE | REG_NEWLINE | REG_NOSUB | REG_NOTBOL << 8 | REG_NOTEOL << 8)) { luaL_argerror(L, 3, "invalid flags"); unreachable; } if ((r = LuaReCompileImpl(L, p, f))) { return LuaReSearchImpl(L, r, s, f); } else { return 2; } } static int LuaReCompile(lua_State *L) { int f; regex_t *r; const char *p; p = luaL_checkstring(L, 1); f = luaL_optinteger(L, 2, 0); if (f & ~(REG_EXTENDED | REG_ICASE | REG_NEWLINE | REG_NOSUB)) { luaL_argerror(L, 2, "invalid flags"); unreachable; } if ((r = LuaReCompileImpl(L, p, f))) { return 1; } else { return 2; } } //////////////////////////////////////////////////////////////////////////////// // re.Regex static int LuaReRegexSearch(lua_State *L) { int f; regex_t *r; const char *s; r = luaL_checkudata(L, 1, "re.Regex"); s = luaL_checkstring(L, 2); f = luaL_optinteger(L, 3, 0); if (f & ~(REG_NOTBOL << 8 | REG_NOTEOL << 8)) { luaL_argerror(L, 3, "invalid flags"); unreachable; } return LuaReSearchImpl(L, r, s, f); } static int LuaReRegexGc(lua_State *L) { regex_t *r; r = luaL_checkudata(L, 1, "re.Regex"); regfree(r); return 0; } static const luaL_Reg kLuaRe[] = { {"compile", LuaReCompile}, // {"search", LuaReSearch}, // {NULL, NULL}, // }; static const luaL_Reg kLuaReRegexMeth[] = { {"search", LuaReRegexSearch}, // {NULL, NULL}, // }; static const luaL_Reg kLuaReRegexMeta[] = { {"__gc", LuaReRegexGc}, // {NULL, NULL}, // }; static void LuaReRegexObj(lua_State *L) { luaL_newmetatable(L, "re.Regex"); luaL_setfuncs(L, kLuaReRegexMeta, 0); luaL_newlibtable(L, kLuaReRegexMeth); luaL_setfuncs(L, kLuaReRegexMeth, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } //////////////////////////////////////////////////////////////////////////////// // re.Errno static struct ReErrno *GetReErrno(lua_State *L) { return luaL_checkudata(L, 1, "re.Errno"); } // re.Errno:errno() // └─→ errno:int static int LuaReErrnoErrno(lua_State *L) { lua_pushinteger(L, GetReErrno(L)->err); return 1; } // re.Errno:doc() // └─→ description:str static int LuaReErrnoDoc(lua_State *L) { lua_pushstring(L, GetReErrno(L)->doc); return 1; } static const luaL_Reg kLuaReErrnoMeth[] = { {"errno", LuaReErrnoErrno}, // {"doc", LuaReErrnoDoc}, // {0}, // }; static const luaL_Reg kLuaReErrnoMeta[] = { {"__tostring", LuaReErrnoDoc}, // {0}, // }; static void LuaReErrnoObj(lua_State *L) { luaL_newmetatable(L, "re.Errno"); luaL_setfuncs(L, kLuaReErrnoMeta, 0); luaL_newlibtable(L, kLuaReErrnoMeth); luaL_setfuncs(L, kLuaReErrnoMeth, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } //////////////////////////////////////////////////////////////////////////////// _Alignas(1) static const struct thatispacked { const char s[8]; char x; } kReMagnums[] = { {"BASIC", REG_EXTENDED}, // compile flag {"ICASE", REG_ICASE}, // compile flag {"NEWLINE", REG_NEWLINE}, // compile flag {"NOSUB", REG_NOSUB}, // compile flag {"NOMATCH", REG_NOMATCH}, // error {"BADPAT", REG_BADPAT}, // error {"ECOLLATE", REG_ECOLLATE}, // error {"ECTYPE", REG_ECTYPE}, // error {"EESCAPE", REG_EESCAPE}, // error {"ESUBREG", REG_ESUBREG}, // error {"EBRACK", REG_EBRACK}, // error {"EPAREN", REG_EPAREN}, // error {"EBRACE", REG_EBRACE}, // error {"BADBR", REG_BADBR}, // error {"ERANGE", REG_ERANGE}, // error {"ESPACE", REG_ESPACE}, // error {"BADRPT", REG_BADRPT}, // error }; int LuaRe(lua_State *L) { int i; char buf[9]; luaL_newlib(L, kLuaRe); LuaSetIntField(L, "NOTBOL", REG_NOTBOL << 8); // search flag LuaSetIntField(L, "NOTEOL", REG_NOTEOL << 8); // search flag for (i = 0; i < ARRAYLEN(kReMagnums); ++i) { memcpy(buf, kReMagnums[i].s, 8); buf[8] = 0; LuaSetIntField(L, buf, kReMagnums[i].x); } LuaReRegexObj(L); LuaReErrnoObj(L); return 1; }
7,733
246
jart/cosmopolitan
false
cosmopolitan/tool/net/redbean-static.c
#define STATIC #define REDBEAN "redbean-static" #include "tool/net/redbean.c"
78
4
jart/cosmopolitan
false
cosmopolitan/tool/net/redbean.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 "ape/sections.internal.h" #include "libc/assert.h" #include "libc/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/pledge.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/flock.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/timespec.h" #include "libc/dce.h" #include "libc/dns/dns.h" #include "libc/dns/hoststxt.h" #include "libc/dos.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/intrin/atomic.h" #include "libc/intrin/bits.h" #include "libc/intrin/bsr.h" #include "libc/intrin/likely.h" #include "libc/intrin/nomultics.internal.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/appendresourcereport.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/alloca.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/crc32.h" #include "libc/nexgen32e/nt2sysv.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/nexgen32e/x86feature.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/thread.h" #include "libc/runtime/clktck.h" #include "libc/runtime/internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/sock/goodsocket.internal.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/sock/struct/sockaddr.h" #include "libc/stdio/append.h" #include "libc/stdio/hex.internal.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/slice.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/dt.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/inaddr.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rusage.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/consts/timer.h" #include "libc/sysv/consts/w.h" #include "libc/sysv/errfuns.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "libc/zip.h" #include "net/http/escape.h" #include "net/http/http.h" #include "net/http/ip.h" #include "net/http/tokenbucket.h" #include "net/http/url.h" #include "net/https/https.h" #include "third_party/getopt/getopt.h" #include "third_party/lua/cosmo.h" #include "third_party/lua/lauxlib.h" #include "third_party/lua/lrepl.h" #include "third_party/lua/lualib.h" #include "third_party/lua/lunix.h" #include "third_party/mbedtls/ctr_drbg.h" #include "third_party/mbedtls/debug.h" #include "third_party/mbedtls/iana.h" #include "third_party/mbedtls/net_sockets.h" #include "third_party/mbedtls/oid.h" #include "third_party/mbedtls/san.h" #include "third_party/mbedtls/ssl.h" #include "third_party/mbedtls/ssl_ticket.h" #include "third_party/mbedtls/x509.h" #include "third_party/mbedtls/x509_crt.h" #include "third_party/zlib/zlib.h" #include "tool/args/args.h" #include "tool/build/lib/case.h" #include "tool/net/lfinger.h" #include "tool/net/lfuncs.h" #include "tool/net/ljson.h" #include "tool/net/lpath.h" #include "tool/net/luacheck.h" #include "tool/net/sandbox.h" STATIC_STACK_SIZE(0x40000); STATIC_YOINK("zip_uri_support"); #if !IsTiny() #ifdef __x86_64__ STATIC_YOINK("ShowCrashReportsEarly"); #endif #endif /** * @fileoverview redbean - single-file distributable web server * * redbean makes it possible to share web applications that run offline * as a single-file αcτµαlly pδrταblε εxεcµταblε zip archive which * contains your assets. All you need to do is download the redbean.com * program below, change the filename to .zip, add your content in a zip * editing tool, and then change the extension back to .com. * * redbean can serve 1 million+ gzip encoded responses per second on a * cheap personal computer. That performance is thanks to zip and gzip * using the same compression format, which enables kernelspace copies. * Another reason redbean goes fast is that it's a tiny static binary, * which makes fork memory paging nearly free. * * redbean is also easy to modify to suit your own needs. The program * itself is written as a single .c file. It embeds the Lua programming * language and SQLite which let you write dynamic pages. */ #ifndef REDBEAN #define REDBEAN "redbean" #endif #define VERSION 0x020200 #define HASH_LOAD_FACTOR /* 1. / */ 4 #define MONITOR_MICROS 150000 #define READ(F, P, N) readv(F, &(struct iovec){P, N}, 1) #define WRITE(F, P, N) writev(F, &(struct iovec){P, N}, 1) #define LockInc(P) (*(_Atomic(typeof(*(P))) *)(P))++ #define LockDec(P) (*(_Atomic(typeof(*(P))) *)(P))-- #define AppendCrlf(P) mempcpy(P, "\r\n", 2) #define HasHeader(H) (!!cpm.msg.headers[H].a) #define HeaderData(H) (inbuf.p + cpm.msg.headers[H].a) #define HeaderLength(H) (cpm.msg.headers[H].b - cpm.msg.headers[H].a) #define HeaderEqualCase(H, S) \ SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H)) #define TRACE_BEGIN \ do { \ if (!IsTiny()) { \ if (funtrace) { \ ftrace_enabled(+1); \ } \ if (systrace) { \ strace_enabled(+1); \ } \ } \ } while (0) #define TRACE_END \ do { \ if (!IsTiny()) { \ if (funtrace) { \ ftrace_enabled(-1); \ } \ if (systrace) { \ strace_enabled(-1); \ } \ } \ } while (0) // letters not used: INOQYnoqwxy // digits not used: 0123456789 // puncts not used: !"#$&'()+,-./;<=>@[\]^_`{|}~ #define GETOPTS \ "*%BEJSVXZabdfghijkmsuvzA:C:D:F:G:H:K:L:M:P:R:T:U:W:c:e:l:p:r:t:w:" static const uint8_t kGzipHeader[] = { 0x1F, // MAGNUM 0x8B, // MAGNUM 0x08, // CM: DEFLATE 0x00, // FLG: NONE 0x00, // MTIME: NONE 0x00, // 0x00, // 0x00, // 0x00, // XFL kZipOsUnix, // OS }; static const char *const kIndexPaths[] = { #ifndef STATIC "index.lua", #endif "index.html", }; static const char *const kAlpn[] = { "http/1.1", NULL, }; struct Buffer { size_t n, c; char *p; }; struct TlsBio { int fd, c; unsigned a, b; unsigned char t[4000]; unsigned char u[1430]; }; struct Strings { size_t n, c; struct String { size_t n; const char *s; } * p; }; struct DeflateGenerator { int t; void *b; size_t i; uint32_t c; uint32_t z; z_stream s; struct Asset *a; }; static struct Ips { size_t n; uint32_t *p; } ips; static struct Ports { size_t n; uint16_t *p; } ports; static struct Servers { size_t n; struct Server { int fd; struct sockaddr_in addr; } * p; } servers; static struct Freelist { size_t n, c; void **p; } freelist; static struct Unmaplist { size_t n, c; struct Unmap { int f; void *p; size_t n; } * p; } unmaplist; static struct Psks { size_t n; struct Psk { char *key; size_t key_len; char *identity; size_t identity_len; char *s; } * p; } psks; static struct Suites { size_t n; uint16_t *p; } suites; static struct Certs { size_t n; struct Cert *p; } certs; static struct Redirects { size_t n; struct Redirect { int code; struct String path; struct String location; } * p; } redirects; static struct Assets { uint32_t n; struct Asset { bool istext; uint32_t hash; uint64_t cf; uint64_t lf; int64_t lastmodified; char *lastmodifiedstr; struct File { struct String path; struct stat st; } * file; } * p; } assets; static struct TrustedIps { size_t n; struct TrustedIp { uint32_t ip; uint32_t mask; } * p; } trustedips; struct TokenBucket { signed char cidr; signed char reject; signed char ignore; signed char ban; struct timespec replenish; union { atomic_schar *b; atomic_uint_fast64_t *w; }; } tokenbucket; struct Blackhole { struct sockaddr_un addr; int fd; } blackhole; static struct Shared { int workers; struct timespec nowish; struct timespec lastreindex; struct timespec lastmeltdown; char currentdate[32]; struct rusage server; struct rusage children; struct Counters { #define C(x) long x; #include "tool/net/counters.inc" #undef C } c; pthread_spinlock_t montermlock; } * shared; static const char kCounterNames[] = #define C(x) #x "\0" #include "tool/net/counters.inc" #undef C ; typedef ssize_t (*reader_f)(int, void *, size_t); typedef ssize_t (*writer_f)(int, struct iovec *, int); struct ClearedPerMessage { bool istext; bool branded; bool hascontenttype; bool gotcachecontrol; bool gotxcontenttypeoptions; int frags; int statuscode; int isyielding; char *outbuf; char *content; size_t gzipped; size_t contentlength; char *luaheaderp; const char *referrerpolicy; size_t msgsize; ssize_t (*generator)(struct iovec[3]); struct Strings loops; struct HttpMessage msg; } cpm; static bool suiteb; static bool killed; static bool zombied; static bool usingssl; static bool funtrace; static bool systrace; static bool meltdown; static bool unsecure; static bool norsagen; static bool printport; static bool daemonize; static bool logrusage; static bool logbodies; static bool requiressl; static bool isterminal; static bool sslcliused; static bool loglatency; static bool terminated; static bool uniprocess; static bool invalidated; static bool logmessages; static bool isinitialized; static bool checkedmethod; static bool sslinitialized; static bool sslfetchverify; static bool selfmodifiable; static bool interpretermode; static bool sslclientverify; static bool connectionclose; static bool hasonloglatency; static bool hasonworkerstop; static bool isexitingworker; static bool hasonworkerstart; static bool leakcrashreports; static bool hasonhttprequest; static bool ishandlingrequest; static bool listeningonport443; static bool hasonprocesscreate; static bool hasonprocessdestroy; static bool loggednetworkorigin; static bool ishandlingconnection; static bool hasonclientconnection; static bool evadedragnetsurveillance; static int zfd; static int gmtoff; static int client; static int mainpid; static int sandboxed; static int changeuid; static int changegid; static int maxworkers; static int shutdownsig; static int sslpskindex; static int oldloglevel; static int messageshandled; static int sslticketlifetime; static uint32_t clientaddrsize; static atomic_int terminatemonitor; static size_t zsize; static lua_State *GL; static lua_State *YL; static uint8_t *zmap; static uint8_t *zbase; static uint8_t *zcdir; static size_t hdrsize; static size_t amtread; static char *replstack; static reader_f reader; static writer_f writer; static char *extrahdrs; static const char *zpath; static const char *brand; static char *monitorstack; static char gzip_footer[8]; static long maxpayloadsize; static const char *pidpath; static const char *logpath; static uint32_t *interfaces; static const char *histpath; static struct pollfd *polls; static size_t payloadlength; static int64_t cacheseconds; static const char *cachedirective; static const char *monitortty; static const char *serverheader; static struct Strings stagedirs; static struct Strings hidepaths; static const char *launchbrowser; static const char ctIdx = 'c'; // a pseudo variable to get address of static struct spawn replth; static struct spawn monitorth; static struct Buffer inbuf_actual; static struct Buffer inbuf; static struct Buffer oldin; static struct Buffer hdrbuf; static struct timeval timeout; static struct Buffer effectivepath; static struct timespec heartbeatinterval; static struct Url url; static struct stat zst; static struct timespec startread; static struct timespec lastrefresh; static struct timespec startserver; static struct timespec startrequest; static struct timespec lastheartbeat; static struct timespec startconnection; static struct sockaddr_in clientaddr; static struct sockaddr_in *serveraddr; static mbedtls_ssl_config conf; static mbedtls_ssl_context ssl; static mbedtls_ctr_drbg_context rng; static mbedtls_ssl_ticket_context ssltick; static mbedtls_ssl_config confcli; static mbedtls_ssl_context sslcli; static mbedtls_ctr_drbg_context rngcli; static struct TlsBio g_bio; static char slashpath[PATH_MAX]; static struct DeflateGenerator dg; static char *Route(const char *, size_t, const char *, size_t); static char *RouteHost(const char *, size_t, const char *, size_t); static char *RoutePath(const char *, size_t); static char *HandleAsset(struct Asset *, const char *, size_t); static char *ServeAsset(struct Asset *, const char *, size_t); static char *SetStatus(unsigned, const char *); static void TlsInit(void); static void OnChld(void) { zombied = true; } static void OnUsr1(void) { invalidated = true; } static void OnUsr2(void) { meltdown = true; } static void OnTerm(int sig) { if (!terminated) { shutdownsig = sig; terminated = true; } else { killed = true; } } static void OnInt(int sig) { OnTerm(sig); } static void OnHup(int sig) { if (daemonize) { OnUsr1(); } else { OnTerm(sig); } } static void Free(void *p) { free(*(void **)p); *(void **)p = 0; } static long ParseInt(const char *s) { return strtol(s, 0, 0); } static void *FreeLater(void *p) { if (p) { if (++freelist.n > freelist.c) { freelist.c = freelist.n + (freelist.n >> 1); freelist.p = xrealloc(freelist.p, freelist.c * sizeof(*freelist.p)); } freelist.p[freelist.n - 1] = p; } return p; } static void UnmapLater(int f, void *p, size_t n) { if (++unmaplist.n > unmaplist.c) { unmaplist.c = unmaplist.n + (unmaplist.n >> 1); unmaplist.p = xrealloc(unmaplist.p, unmaplist.c * sizeof(*unmaplist.p)); } unmaplist.p[unmaplist.n - 1].f = f; unmaplist.p[unmaplist.n - 1].p = p; unmaplist.p[unmaplist.n - 1].n = n; } static void CollectGarbage(void) { __log_level = oldloglevel; DestroyHttpMessage(&cpm.msg); while (freelist.n) { free(freelist.p[--freelist.n]); } while (unmaplist.n) { --unmaplist.n; LOGIFNEG1(munmap(unmaplist.p[unmaplist.n].p, unmaplist.p[unmaplist.n].n)); LOGIFNEG1(close(unmaplist.p[unmaplist.n].f)); } } static void UseOutput(void) { cpm.content = FreeLater(cpm.outbuf); cpm.contentlength = appendz(cpm.outbuf).i; cpm.outbuf = 0; } static void DropOutput(void) { FreeLater(cpm.outbuf); cpm.outbuf = 0; } static bool ShouldAvoidGzip(void) { return (IsGenuineBlink() && !X86_HAVE(JIT)); } static char *MergePaths(const char *p, size_t n, const char *q, size_t m, size_t *z) { char *r; if (n && p[n - 1] == '/') --n; if (m && q[0] == '/') ++q, --m; r = xmalloc(n + 1 + m + 1); mempcpy(mempcpy(mempcpy(mempcpy(r, p, n), "/", 1), q, m), "", 1); if (z) *z = n + 1 + m; return r; } static long FindRedirect(const char *s, size_t n) { int c, m, l, r, z; l = 0; r = redirects.n - 1; while (l <= r) { m = (l + r) >> 1; c = CompareSlices(redirects.p[m].path.s, redirects.p[m].path.n, s, n); if (c < 0) { l = m + 1; } else if (c > 0) { r = m - 1; } else { return m; } } return -1; } static mbedtls_x509_crt *GetTrustedCertificate(mbedtls_x509_name *name) { size_t i; for (i = 0; i < certs.n; ++i) { if (certs.p[i].cert && !mbedtls_x509_name_cmp(name, &certs.p[i].cert->subject)) { return certs.p[i].cert; } } return 0; } static void UseCertificate(mbedtls_ssl_config *c, struct Cert *kp, const char *role) { VERBOSEF("(ssl) using %s certificate %`'s for HTTPS %s", mbedtls_pk_get_name(&kp->cert->pk), _gc(FormatX509Name(&kp->cert->subject)), role); CHECK_EQ(0, mbedtls_ssl_conf_own_cert(c, kp->cert, kp->key)); } static void AppendCert(mbedtls_x509_crt *cert, mbedtls_pk_context *key) { certs.p = realloc(certs.p, ++certs.n * sizeof(*certs.p)); certs.p[certs.n - 1].cert = cert; certs.p[certs.n - 1].key = key; } static void InternCertificate(mbedtls_x509_crt *cert, mbedtls_x509_crt *prev) { int r; size_t i; if (cert->next) InternCertificate(cert->next, cert); if (prev) { if (mbedtls_x509_crt_check_parent(prev, cert, 1)) { DEBUGF("(ssl) unbundling %`'s from %`'s", _gc(FormatX509Name(&prev->subject)), _gc(FormatX509Name(&cert->subject))); prev->next = 0; } else if ((r = mbedtls_x509_crt_check_signature(prev, cert, 0))) { WARNF("(ssl) invalid signature for %`'s -> %`'s (-0x%04x)", _gc(FormatX509Name(&prev->subject)), _gc(FormatX509Name(&cert->subject)), -r); } } if (mbedtls_x509_time_is_past(&cert->valid_to)) { WARNF("(ssl) certificate %`'s is expired", _gc(FormatX509Name(&cert->subject))); } else if (mbedtls_x509_time_is_future(&cert->valid_from)) { WARNF("(ssl) certificate %`'s is from the future", _gc(FormatX509Name(&cert->subject))); } for (i = 0; i < certs.n; ++i) { if (!certs.p[i].cert && certs.p[i].key && !mbedtls_pk_check_pair(&cert->pk, certs.p[i].key)) { certs.p[i].cert = cert; return; } } LogCertificate("loaded certificate", cert); if (!cert->next && !IsSelfSigned(cert) && cert->max_pathlen) { for (i = 0; i < certs.n; ++i) { if (!certs.p[i].cert) continue; if (mbedtls_pk_can_do(&cert->pk, certs.p[i].cert->sig_pk) && !mbedtls_x509_crt_check_parent(cert, certs.p[i].cert, 1) && !IsSelfSigned(certs.p[i].cert)) { if (ChainCertificate(cert, certs.p[i].cert)) break; } } } if (!IsSelfSigned(cert)) { for (i = 0; i < certs.n; ++i) { if (!certs.p[i].cert) continue; if (certs.p[i].cert->next) continue; if (certs.p[i].cert->max_pathlen && mbedtls_pk_can_do(&certs.p[i].cert->pk, cert->sig_pk) && !mbedtls_x509_crt_check_parent(certs.p[i].cert, cert, 1)) { ChainCertificate(certs.p[i].cert, cert); } } } AppendCert(cert, 0); } static void ProgramCertificate(const char *p, size_t n) { int rc; unsigned char *waqapi; mbedtls_x509_crt *cert; waqapi = malloc(n + 1); memcpy(waqapi, p, n); waqapi[n] = 0; cert = calloc(1, sizeof(mbedtls_x509_crt)); rc = mbedtls_x509_crt_parse(cert, waqapi, n + 1); mbedtls_platform_zeroize(waqapi, n); free(waqapi); if (rc < 0) { WARNF("(ssl) failed to load certificate (grep -0x%04x)", rc); return; } else if (rc > 0) { VERBOSEF("(ssl) certificate bundle partially loaded"); } InternCertificate(cert, 0); } static void ProgramPrivateKey(const char *p, size_t n) { int rc; size_t i; unsigned char *waqapi; mbedtls_pk_context *key; waqapi = malloc(n + 1); memcpy(waqapi, p, n); waqapi[n] = 0; key = calloc(1, sizeof(mbedtls_pk_context)); rc = mbedtls_pk_parse_key(key, waqapi, n + 1, 0, 0); mbedtls_platform_zeroize(waqapi, n); free(waqapi); if (rc != 0) FATALF("(ssl) error: load key (grep -0x%04x)", -rc); for (i = 0; i < certs.n; ++i) { if (certs.p[i].cert && !certs.p[i].key && !mbedtls_pk_check_pair(&certs.p[i].cert->pk, key)) { certs.p[i].key = key; return; } } VERBOSEF("(ssl) loaded private key"); AppendCert(0, key); } static void ProgramFile(const char *path, void program(const char *, size_t)) { char *p; size_t n; DEBUGF("(srvr) ProgramFile(%`'s)", path); if ((p = xslurp(path, &n))) { program(p, n); mbedtls_platform_zeroize(p, n); free(p); } else { FATALF("(srvr) error: failed to read file %`'s", path); } } static void ProgramPort(long port) { if (!(0 <= port && port <= 65535)) { FATALF("(cfg) error: bad port: %d", port); } if (port == 443) listeningonport443 = true; ports.p = realloc(ports.p, ++ports.n * sizeof(*ports.p)); ports.p[ports.n - 1] = port; } static void ProgramMaxPayloadSize(long x) { maxpayloadsize = MAX(1450, x); } static void ProgramSslTicketLifetime(long x) { sslticketlifetime = x; } static void ProgramAddr(const char *addr) { ssize_t rc; int64_t ip; if ((ip = ParseIp(addr, -1)) == -1) { if (!IsTiny()) { struct addrinfo *ai = NULL; struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP}; if ((rc = getaddrinfo(addr, "0", &hint, &ai)) != EAI_SUCCESS) { FATALF("(cfg) error: bad addr: %s (EAI_%s)", addr, gai_strerror(rc)); } ip = ntohl(ai->ai_addr4->sin_addr.s_addr); freeaddrinfo(ai); } else { FATALF("(cfg) error: ProgramAddr() needs an IP in MODE=tiny: %s", addr); } } ips.p = realloc(ips.p, ++ips.n * sizeof(*ips.p)); ips.p[ips.n - 1] = ip; } static void ProgramRedirect(int code, const char *sp, size_t sn, const char *dp, size_t dn) { long i, j; struct Redirect r; if (code && code != 301 && code != 302 && code != 307 && code != 308) { FATALF("(cfg) error: unsupported redirect code %d", code); } if (!(FreeLater(EncodeHttpHeaderValue(dp, dn, 0)))) { FATALF("(cfg) error: invalid location %s", dp); } r.code = code; r.path.s = sp; r.path.n = sn; r.location.s = dp; r.location.n = dn; if ((i = FindRedirect(r.path.s, r.path.n)) != -1) { redirects.p[i] = r; } else { i = redirects.n; redirects.p = xrealloc(redirects.p, (i + 1) * sizeof(*redirects.p)); for (j = i; j; --j) { if (CompareSlices(r.path.s, r.path.n, redirects.p[j - 1].path.s, redirects.p[j - 1].path.n) < 0) { redirects.p[j] = redirects.p[j - 1]; } else { break; } } redirects.p[j] = r; ++redirects.n; } } static void ProgramRedirectArg(int code, const char *s) { size_t n; const char *p; n = strlen(s); if (!(p = memchr(s, '=', n))) { FATALF("(cfg) error: redirect arg missing '='"); } ProgramRedirect(code, s, p - s, p + 1, n - (p - s + 1)); } static void ProgramTrustedIp(uint32_t ip, int cidr) { uint32_t mask; mask = 0xffffffffu << (32 - cidr); trustedips.p = xrealloc(trustedips.p, ++trustedips.n * sizeof(*trustedips.p)); trustedips.p[trustedips.n - 1].ip = ip; trustedips.p[trustedips.n - 1].mask = mask; } static bool IsTrustedIp(uint32_t ip) { int i; uint32_t *p; if (interfaces) { for (p = interfaces; *p; ++p) { if (ip == *p && !IsTestnetIp(ip)) { DEBUGF("(token) ip is trusted because it's %s", "a local interface"); return true; } } } if (trustedips.n) { for (i = 0; i < trustedips.n; ++i) { if ((ip & trustedips.p[i].mask) == trustedips.p[i].ip) { DEBUGF("(token) ip is trusted because it's %s", "whitelisted"); return true; } } return false; } else if (IsPrivateIp(ip) && !IsTestnetIp(ip)) { DEBUGF("(token) ip is trusted because it's %s", "private"); return true; } else if (IsLoopbackIp(ip)) { DEBUGF("(token) ip is trusted because it's %s", "loopback"); return true; } else { return false; } } static void DescribeAddress(char buf[40], uint32_t addr, uint16_t port) { char *p; const char *s; p = buf; p = FormatUint32(p, (addr & 0xFF000000) >> 030), *p++ = '.'; p = FormatUint32(p, (addr & 0x00FF0000) >> 020), *p++ = '.'; p = FormatUint32(p, (addr & 0x0000FF00) >> 010), *p++ = '.'; p = FormatUint32(p, (addr & 0x000000FF) >> 000), *p++ = ':'; p = FormatUint32(p, port); *p = '\0'; assert(p - buf < 40); } static inline int GetServerAddr(uint32_t *ip, uint16_t *port) { *ip = ntohl(serveraddr->sin_addr.s_addr); if (port) *port = ntohs(serveraddr->sin_port); return 0; } static inline int GetClientAddr(uint32_t *ip, uint16_t *port) { *ip = ntohl(clientaddr.sin_addr.s_addr); if (port) *port = ntohs(clientaddr.sin_port); return 0; } static inline int GetRemoteAddr(uint32_t *ip, uint16_t *port) { char str[40]; GetClientAddr(ip, port); if (HasHeader(kHttpXForwardedFor)) { if (IsTrustedIp(*ip)) { if (ParseForwarded(HeaderData(kHttpXForwardedFor), HeaderLength(kHttpXForwardedFor), ip, port) == -1) { VERBOSEF("could not parse x-forwarded-for %`'.*s len=%ld", HeaderLength(kHttpXForwardedFor), HeaderData(kHttpXForwardedFor), HeaderLength(kHttpXForwardedFor)); return -1; } } else { WARNF( "%hhu.%hhu.%hhu.%hhu isn't authorized to send x-forwarded-for %`'.*s", *ip >> 24, *ip >> 16, *ip >> 8, *ip, HeaderLength(kHttpXForwardedFor), HeaderData(kHttpXForwardedFor)); } } return 0; } static char *DescribeClient(void) { char str[40]; uint16_t port; uint32_t client; static char description[128]; GetClientAddr(&client, &port); if (HasHeader(kHttpXForwardedFor) && IsTrustedIp(client)) { DescribeAddress(str, client, port); snprintf(description, sizeof(description), "%'.*s via %s", HeaderLength(kHttpXForwardedFor), HeaderData(kHttpXForwardedFor), str); } else { DescribeAddress(description, client, port); } return description; } static char *DescribeServer(void) { uint32_t ip; uint16_t port; static char serveraddrstr[40]; GetServerAddr(&ip, &port); DescribeAddress(serveraddrstr, ip, port); return serveraddrstr; } static void ProgramBrand(const char *s) { char *p; free(brand); free(serverheader); if (!(p = EncodeHttpHeaderValue(s, -1, 0))) { FATALF("(cfg) error: brand isn't latin1 encodable: %`'s", s); } brand = strdup(s); serverheader = xasprintf("Server: %s\r\n", p); free(p); } static void ProgramUid(long x) { changeuid = x; } static void ProgramGid(long x) { changegid = x; } #define MINTIMEOUT 10 static void ProgramTimeout(long ms) { ldiv_t d; if (ms < 0) { timeout.tv_sec = ms; /* -(keepalive seconds) */ timeout.tv_usec = 0; } else { if (ms < MINTIMEOUT) { FATALF("(cfg) error: timeout needs to be %dms or greater", MINTIMEOUT); } d = ldiv(ms, 1000); timeout.tv_sec = d.quot; timeout.tv_usec = d.rem * 1000; } } static void ProgramCache(long x, const char *s) { cacheseconds = x; if (s) cachedirective = s; } static void SetDefaults(void) { ProgramBrand(_gc(xasprintf("%s/%hhd.%hhd.%hhd", REDBEAN, VERSION >> 020, VERSION >> 010, VERSION >> 000))); __log_level = kLogInfo; maxpayloadsize = 64 * 1024; ProgramCache(-1, "must-revalidate"); ProgramTimeout(60 * 1000); ProgramSslTicketLifetime(24 * 60 * 60); sslfetchverify = true; } static void AddString(struct Strings *l, const char *s, size_t n) { if (++l->n > l->c) { l->c = l->n + (l->n >> 1); l->p = realloc(l->p, l->c * sizeof(*l->p)); } l->p[l->n - 1].s = s; l->p[l->n - 1].n = n; } static bool HasString(struct Strings *l, const char *s, size_t n) { size_t i; for (i = 0; i < l->n; ++i) { if (SlicesEqual(l->p[i].s, l->p[i].n, s, n)) { return true; } } return false; } static void UpdateLuaPath(const char *s) { #ifndef STATIC lua_State *L = GL; int n = lua_gettop(L); lua_getglobal(L, "package"); if (lua_istable(L, -1)) { lua_getfield(L, -1, "path"); lua_pushstring(L, _gc(xasprintf("%s;%s/.lua/?.lua;%s/.lua/?/init.lua", luaL_optstring(L, -1, ""), s, s))); lua_setfield(L, -3, "path"); } lua_settop(L, n); #endif } static void ProgramDirectory(const char *path) { char *s; size_t n; struct stat st; if (stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) { FATALF("(cfg) error: not a directory: %`'s", path); } s = strdup(path); n = strlen(s); INFOF("(cfg) program directory: %s", s); AddString(&stagedirs, s, n); UpdateLuaPath(s); } static void ProgramHeader(const char *s) { char *p, *v, *h; if ((p = strchr(s, ':')) && IsValidHttpToken(s, p - s) && (v = EncodeLatin1(p + 1, -1, 0, kControlC0 | kControlC1 | kControlWs))) { switch (GetHttpHeader(s, p - s)) { case kHttpDate: case kHttpConnection: case kHttpContentLength: case kHttpContentEncoding: case kHttpContentRange: case kHttpLocation: FATALF("(cfg) error: can't program header: %`'s", s); case kHttpServer: ProgramBrand(p + 1); break; default: p = xasprintf("%s%.*s:%s\r\n", extrahdrs ? extrahdrs : "", p - s, s, v); free(extrahdrs); extrahdrs = p; break; } free(v); } else { FATALF("(cfg) error: illegal header: %`'s", s); } } static void ProgramLogPath(const char *s) { int fd; logpath = strdup(s); fd = open(logpath, O_APPEND | O_WRONLY | O_CREAT, 0640); if (fd == -1) { WARNF("(srvr) open(%`'s) failed: %m", logpath); return; } if (fd != 2) { dup2(fd, 2); close(fd); } } static void ProgramPidPath(const char *s) { pidpath = strdup(s); } static bool IsServerFd(int fd) { size_t i; for (i = 0; i < servers.n; ++i) { if (servers.p[i].fd == fd) { return true; } } return false; } static void ChangeUser(void) { if (changegid) { if (setgid(changegid)) { FATALF("(cfg) setgid() failed: %m"); } } // order matters if (changeuid) { if (setuid(changeuid)) { FATALF("(cfg) setuid() failed: %m"); } } } static void Daemonize(void) { if (fork() > 0) exit(0); setsid(); if (fork() > 0) _exit(0); umask(0); } static void LogLuaError(char *hook, char *err) { ERRORF("(lua) failed to run %s: %s", hook, err); } // handles `-e CODE` (frontloads web server code) // handles `-i -e CODE` (interprets expression and exits) static void LuaEvalCode(const char *code) { lua_State *L = GL; int status = luaL_loadstring(L, code); if (status != LUA_OK || LuaCallWithTrace(L, 0, 0, NULL) != LUA_OK) { LogLuaError("lua code", lua_tostring(L, -1)); lua_pop(L, 1); // pop error exit(1); } AssertLuaStackIsAt(L, 0); } // handle `-F PATH` arg static void LuaEvalFile(const char *path) { char *f = _gc(xslurp(path, 0)); if (!f) FATALF("(cfg) error: failed to read file %`'s", path); LuaEvalCode(f); } static bool LuaOnClientConnection(void) { bool dropit = false; #ifndef STATIC uint32_t ip, serverip; uint16_t port, serverport; lua_State *L = GL; lua_getglobal(L, "OnClientConnection"); GetClientAddr(&ip, &port); GetServerAddr(&serverip, &serverport); lua_pushinteger(L, ip); lua_pushinteger(L, port); lua_pushinteger(L, serverip); lua_pushinteger(L, serverport); if (LuaCallWithTrace(L, 4, 1, NULL) == LUA_OK) { dropit = lua_toboolean(L, -1); } else { LogLuaError("OnClientConnection", lua_tostring(L, -1)); } lua_pop(L, 1); // pop result or error AssertLuaStackIsAt(L, 0); #endif return dropit; } static void LuaOnLogLatency(long reqtime, long contime) { #ifndef STATIC lua_State *L = GL; int n = lua_gettop(L); lua_getglobal(L, "OnLogLatency"); lua_pushinteger(L, reqtime); lua_pushinteger(L, contime); if (LuaCallWithTrace(L, 2, 0, NULL) != LUA_OK) { LogLuaError("OnLogLatency", lua_tostring(L, -1)); lua_pop(L, 1); // pop error } AssertLuaStackIsAt(L, n); #endif } static void LuaOnProcessCreate(int pid) { #ifndef STATIC uint32_t ip, serverip; uint16_t port, serverport; lua_State *L = GL; lua_getglobal(L, "OnProcessCreate"); GetClientAddr(&ip, &port); GetServerAddr(&serverip, &serverport); lua_pushinteger(L, pid); lua_pushinteger(L, ip); lua_pushinteger(L, port); lua_pushinteger(L, serverip); lua_pushinteger(L, serverport); if (LuaCallWithTrace(L, 5, 0, NULL) != LUA_OK) { LogLuaError("OnProcessCreate", lua_tostring(L, -1)); lua_pop(L, 1); // pop error } AssertLuaStackIsAt(L, 0); #endif } static bool LuaOnServerListen(int fd, uint32_t ip, uint16_t port) { bool nouse = false; #ifndef STATIC lua_State *L = GL; lua_getglobal(L, "OnServerListen"); lua_pushinteger(L, fd); lua_pushinteger(L, ip); lua_pushinteger(L, port); if (LuaCallWithTrace(L, 3, 1, NULL) == LUA_OK) { nouse = lua_toboolean(L, -1); } else { LogLuaError("OnServerListen", lua_tostring(L, -1)); } lua_pop(L, 1); // pop result or error AssertLuaStackIsAt(L, 0); #endif return nouse; } static void LuaOnProcessDestroy(int pid) { #ifndef STATIC lua_State *L = GL; lua_getglobal(L, "OnProcessDestroy"); lua_pushinteger(L, pid); if (LuaCallWithTrace(L, 1, 0, NULL) != LUA_OK) { LogLuaError("OnProcessDestroy", lua_tostring(L, -1)); lua_pop(L, 1); // pop error } AssertLuaStackIsAt(L, 0); #endif } static inline bool IsHookDefined(const char *s) { #ifndef STATIC lua_State *L = GL; bool res = !!lua_getglobal(L, s); lua_pop(L, 1); return res; #else return false; #endif } static void CallSimpleHook(const char *s) { #ifndef STATIC lua_State *L = GL; int n = lua_gettop(L); lua_getglobal(L, s); if (LuaCallWithTrace(L, 0, 0, NULL) != LUA_OK) { LogLuaError(s, lua_tostring(L, -1)); lua_pop(L, 1); // pop error } AssertLuaStackIsAt(L, n); #endif } static void CallSimpleHookIfDefined(const char *s) { if (IsHookDefined(s)) { CallSimpleHook(s); } } static void ReportWorkerExit(int pid, int ws) { int workers; workers = atomic_fetch_sub(&shared->workers, 1) - 1; if (WIFEXITED(ws)) { if (WEXITSTATUS(ws)) { LockInc(&shared->c.failedchildren); WARNF("(stat) %d exited with %d (%,d workers remain)", pid, WEXITSTATUS(ws), workers); } else { DEBUGF("(stat) %d exited (%,d workers remain)", pid, workers); } } else { LockInc(&shared->c.terminatedchildren); WARNF("(stat) %d terminated with %s (%,d workers remain)", pid, strsignal(WTERMSIG(ws)), workers); } } static void ReportWorkerResources(int pid, struct rusage *ru) { char *s, *b = 0; if (logrusage || LOGGABLE(kLogDebug)) { AppendResourceReport(&b, ru, "\n"); if (b) { if ((s = IndentLines(b, appendz(b).i - 1, 0, 1))) { LOGF(kLogDebug, "(stat) resource report for pid %d\n%s", pid, s); free(s); } free(b); } } } static void HandleWorkerExit(int pid, int ws, struct rusage *ru) { LockInc(&shared->c.connectionshandled); rusage_add(&shared->children, ru); ReportWorkerExit(pid, ws); ReportWorkerResources(pid, ru); if (hasonprocessdestroy) { LuaOnProcessDestroy(pid); } } static void KillGroupImpl(int sig) { LOGIFNEG1(kill(0, sig)); } static void KillGroup(void) { KillGroupImpl(SIGTERM); } static void WaitAll(void) { int ws, pid; struct rusage ru; for (;;) { if ((pid = wait4(-1, &ws, 0, &ru)) != -1) { HandleWorkerExit(pid, ws, &ru); } else { if (errno == ECHILD) { errno = 0; break; } if (errno == EINTR) { if (killed) { killed = false; terminated = false; WARNF("(srvr) server shall terminate harder"); KillGroup(); } errno = 0; continue; } DIEF("(srvr) wait error: %m"); } } } static void ReapZombies(void) { int ws, pid; struct rusage ru; do { zombied = false; if ((pid = wait4(-1, &ws, WNOHANG, &ru)) != -1) { if (pid) { HandleWorkerExit(pid, ws, &ru); } else { break; } } else { if (errno == ECHILD) { errno = 0; break; } if (errno == EINTR) { errno = 0; continue; } DIEF("(srvr) wait error: %m"); } } while (!terminated); } static ssize_t ReadAll(int fd, char *p, size_t n) { ssize_t rc; size_t i, got; for (i = 0; i < n;) { rc = READ(fd, p + i, n - i); if (rc != -1) { got = rc; i += got; } else if (errno != EINTR) { WARNF("(file) read error: %m"); return -1; } } return i; } static bool IsTakingTooLong(void) { return meltdown && timespec_cmp(timespec_sub(timespec_real(), startread), (struct timespec){2}) >= 0; } static ssize_t WritevAll(int fd, struct iovec *iov, int iovlen) { int i; ssize_t rc; size_t wrote, total; i = 0; total = 0; do { if (i) { while (i < iovlen && !iov[i].iov_len) ++i; if (i == iovlen) break; } if ((rc = writev(fd, iov + i, iovlen - i)) != -1) { wrote = rc; total += wrote; do { if (wrote >= iov[i].iov_len) { wrote -= iov[i++].iov_len; } else { iov[i].iov_base = (char *)iov[i].iov_base + wrote; iov[i].iov_len -= wrote; wrote = 0; } } while (wrote); } else if (errno == EINTR) { errno = 0; LockInc(&shared->c.writeinterruputs); if (killed || IsTakingTooLong()) { return total ? total : -1; } } else { return total ? total : -1; } } while (i < iovlen); return total; } static int TlsFlush(struct TlsBio *bio, const unsigned char *buf, size_t len) { struct iovec v[2]; if (len || bio->c > 0) { v[0].iov_base = bio->u; v[0].iov_len = MAX(0, bio->c); v[1].iov_base = buf; v[1].iov_len = len; if (WritevAll(bio->fd, v, 2) != -1) { if (bio->c > 0) bio->c = 0; } else if (errno == EINTR) { errno = 0; return MBEDTLS_ERR_NET_CONN_RESET; } else if (errno == EAGAIN) { errno = 0; return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { WARNF("(ssl) TlsSend error: %m"); return MBEDTLS_ERR_NET_SEND_FAILED; } } return 0; } static int TlsSend(void *ctx, const unsigned char *buf, size_t len) { int rc; struct iovec v[2]; struct TlsBio *bio = ctx; if (bio->c >= 0 && bio->c + len <= sizeof(bio->u)) { memcpy(bio->u + bio->c, buf, len); bio->c += len; return len; } if ((rc = TlsFlush(bio, buf, len)) < 0) return rc; return len; } static int TlsRecvImpl(void *ctx, unsigned char *p, size_t n, uint32_t o) { int r; ssize_t s; struct iovec v[2]; struct TlsBio *bio = ctx; if ((r = TlsFlush(bio, 0, 0)) < 0) return r; if (bio->a < bio->b) { r = MIN(n, bio->b - bio->a); memcpy(p, bio->t + bio->a, r); if ((bio->a += r) == bio->b) bio->a = bio->b = 0; return r; } v[0].iov_base = p; v[0].iov_len = n; v[1].iov_base = bio->t; v[1].iov_len = sizeof(bio->t); while ((r = readv(bio->fd, v, 2)) == -1) { if (errno == EINTR) { errno = 0; return MBEDTLS_ERR_SSL_WANT_READ; } else if (errno == EAGAIN) { errno = 0; return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { WARNF("(ssl) tls read() error: %m"); return MBEDTLS_ERR_NET_RECV_FAILED; } } if (r > n) bio->b = r - n; return MIN(n, r); } static int TlsRecv(void *ctx, unsigned char *buf, size_t len, uint32_t tmo) { int rc; struct TlsBio *bio = ctx; if (oldin.n) { rc = MIN(oldin.n, len); memcpy(buf, oldin.p, rc); oldin.p += rc; oldin.n -= rc; return rc; } return TlsRecvImpl(ctx, buf, len, tmo); } static ssize_t SslRead(int fd, void *buf, size_t size) { int rc; rc = mbedtls_ssl_read(&ssl, buf, size); if (!rc) { errno = ECONNRESET; rc = -1; } else if (rc < 0) { if (rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { rc = 0; } else if (rc == MBEDTLS_ERR_NET_CONN_RESET || rc == MBEDTLS_ERR_SSL_TIMEOUT) { errno = ECONNRESET; rc = -1; } else if (rc == MBEDTLS_ERR_SSL_WANT_READ) { errno = EINTR; rc = -1; errno = 0; } else if (rc == MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) { WARNF("(ssl) %s SslRead error -0x%04x (%s)", DescribeClient(), -rc, "fatal alert message"); errno = EIO; rc = -1; } else if (rc == MBEDTLS_ERR_SSL_INVALID_RECORD) { WARNF("(ssl) %s SslRead error -0x%04x (%s)", DescribeClient(), -rc, "invalid record"); errno = EIO; rc = -1; } else if (rc == MBEDTLS_ERR_SSL_INVALID_MAC) { WARNF("(ssl) %s SslRead error -0x%04x (%s)", DescribeClient(), -rc, "hmac verification failed"); errno = EIO; rc = -1; } else { WARNF("(ssl) %s SslRead error -0x%04x", DescribeClient(), -rc); errno = EIO; rc = -1; } } return rc; } static ssize_t SslWrite(int fd, struct iovec *iov, int iovlen) { int i; size_t n; ssize_t rc; const unsigned char *p; for (i = 0; i < iovlen; ++i) { p = iov[i].iov_base; n = iov[i].iov_len; while (n) { if ((rc = mbedtls_ssl_write(&ssl, p, n)) > 0) { p += rc; n -= rc; } else if (rc == MBEDTLS_ERR_NET_CONN_RESET) { errno = ECONNRESET; return -1; } else if (rc == MBEDTLS_ERR_SSL_TIMEOUT) { errno = ETIMEDOUT; return -1; } else { WARNF("(ssl) %s SslWrite error -0x%04x", DescribeClient(), -rc); errno = EIO; return -1; } } } return 0; } static void NotifyClose(void) { #ifndef UNSECURE if (usingssl) { DEBUGF("(ssl) SSL notifying close"); mbedtls_ssl_close_notify(&ssl); } #endif } static void WipeSigningKeys(void) { size_t i; if (uniprocess) return; for (i = 0; i < certs.n; ++i) { if (!certs.p[i].key) continue; if (!certs.p[i].cert) continue; if (!certs.p[i].cert->ca_istrue) continue; mbedtls_pk_free(certs.p[i].key); Free(&certs.p[i].key); } } static void PsksDestroy(void) { size_t i; for (i = 0; i < psks.n; ++i) { mbedtls_platform_zeroize(psks.p[i].key, psks.p[i].key_len); free(psks.p[i].key); free(psks.p[i].identity); } Free(&psks.p); psks.n = 0; } static void CertsDestroy(void) { size_t i; // break up certificate chains to prevent double free for (i = 0; i < certs.n; ++i) { if (certs.p[i].cert) { certs.p[i].cert->next = 0; } } for (i = 0; i < certs.n; ++i) { mbedtls_x509_crt_free(certs.p[i].cert); free(certs.p[i].cert); mbedtls_pk_free(certs.p[i].key); free(certs.p[i].key); } Free(&certs.p); certs.n = 0; } static void WipeServingKeys(void) { size_t i; if (uniprocess) return; mbedtls_ssl_ticket_free(&ssltick); mbedtls_ssl_key_cert_free(conf.key_cert), conf.key_cert = 0; CertsDestroy(); PsksDestroy(); } static bool CertHasCommonName(const mbedtls_x509_crt *cert, const void *s, size_t n) { const mbedtls_x509_name *name; for (name = &cert->subject; name; name = name->next) { if (!MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid)) { if (SlicesEqualCase(s, n, name->val.p, name->val.len)) { return true; } break; } } return false; } static bool TlsRouteFind(mbedtls_pk_type_t type, mbedtls_ssl_context *ssl, const unsigned char *host, size_t size, int64_t ip) { int i; for (i = 0; i < certs.n; ++i) { if (IsServerCert(certs.p + i, type) && (((certs.p[i].cert->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) && (ip == -1 ? CertHasHost(certs.p[i].cert, host, size) : CertHasIp(certs.p[i].cert, ip))) || CertHasCommonName(certs.p[i].cert, host, size))) { CHECK_EQ( 0, mbedtls_ssl_set_hs_own_cert(ssl, certs.p[i].cert, certs.p[i].key)); DEBUGF("(ssl) TlsRoute(%s, %`'.*s) %s %`'s", mbedtls_pk_type_name(type), size, host, mbedtls_pk_get_name(&certs.p[i].cert->pk), _gc(FormatX509Name(&certs.p[i].cert->subject))); return true; } } return false; } static bool TlsRouteFirst(mbedtls_pk_type_t type, mbedtls_ssl_context *ssl) { int i; for (i = 0; i < certs.n; ++i) { if (IsServerCert(certs.p + i, type)) { CHECK_EQ( 0, mbedtls_ssl_set_hs_own_cert(ssl, certs.p[i].cert, certs.p[i].key)); DEBUGF("(ssl) TlsRoute(%s) %s %`'s", mbedtls_pk_type_name(type), mbedtls_pk_get_name(&certs.p[i].cert->pk), _gc(FormatX509Name(&certs.p[i].cert->subject))); return true; } } return false; } static int TlsRoute(void *ctx, mbedtls_ssl_context *ssl, const unsigned char *host, size_t size) { int64_t ip; bool ok1, ok2; ip = ParseIp((const char *)host, size); ok1 = TlsRouteFind(MBEDTLS_PK_ECKEY, ssl, host, size, ip); ok2 = TlsRouteFind(MBEDTLS_PK_RSA, ssl, host, size, ip); if (!ok1 && !ok2) { WARNF("(ssl) TlsRoute(%`'.*s) not found", size, host); ok1 = TlsRouteFirst(MBEDTLS_PK_ECKEY, ssl); ok2 = TlsRouteFirst(MBEDTLS_PK_RSA, ssl); } return ok1 || ok2 ? 0 : -1; } static int TlsRoutePsk(void *ctx, mbedtls_ssl_context *ssl, const unsigned char *identity, size_t identity_len) { size_t i; for (i = 0; i < psks.n; ++i) { if (SlicesEqual((void *)identity, identity_len, psks.p[i].identity, psks.p[i].identity_len)) { DEBUGF("(ssl) TlsRoutePsk(%`'.*s)", identity_len, identity); mbedtls_ssl_set_hs_psk(ssl, psks.p[i].key, psks.p[i].key_len); // keep track of selected psk to report its identity sslpskindex = i + 1; // use index+1 to check against 0 (when not set) return 0; } } WARNF("(ssl) TlsRoutePsk(%`'.*s) not found", identity_len, identity); return -1; } static bool TlsSetup(void) { int r; oldin.p = inbuf.p; oldin.n = amtread; inbuf.p += amtread; inbuf.n -= amtread; inbuf.c = amtread; amtread = 0; g_bio.fd = client; g_bio.a = 0; g_bio.b = 0; g_bio.c = 0; sslpskindex = 0; for (;;) { if (!(r = mbedtls_ssl_handshake(&ssl)) && TlsFlush(&g_bio, 0, 0) != -1) { LockInc(&shared->c.sslhandshakes); g_bio.c = -1; usingssl = true; reader = SslRead; writer = SslWrite; WipeServingKeys(); VERBOSEF("(ssl) shaken %s %s %s%s %s", DescribeClient(), mbedtls_ssl_get_ciphersuite(&ssl), mbedtls_ssl_get_version(&ssl), ssl.session->compression ? " COMPRESSED" : "", ssl.curve ? ssl.curve->name : "uncurved"); DEBUGF("(ssl) client ciphersuite preference was %s", _gc(FormatSslClientCiphers(&ssl))); return true; } else if (r == MBEDTLS_ERR_SSL_WANT_READ) { LockInc(&shared->c.handshakeinterrupts); if (terminated || killed || IsTakingTooLong()) { return false; } } else { LockInc(&shared->c.sslhandshakefails); mbedtls_ssl_session_reset(&ssl); switch (r) { case MBEDTLS_ERR_SSL_CONN_EOF: DEBUGF("(ssl) %s SSL handshake EOF", DescribeClient()); return false; case MBEDTLS_ERR_NET_CONN_RESET: DEBUGF("(ssl) %s SSL handshake reset", DescribeClient()); return false; case MBEDTLS_ERR_SSL_TIMEOUT: LockInc(&shared->c.ssltimeouts); DEBUGF("(ssl) %s %s", DescribeClient(), "ssltimeouts"); return false; case MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN: LockInc(&shared->c.sslnociphers); WARNF("(ssl) %s %s %s", DescribeClient(), "sslnociphers", _gc(FormatSslClientCiphers(&ssl))); return false; case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE: LockInc(&shared->c.sslcantciphers); WARNF("(ssl) %s %s %s", DescribeClient(), "sslcantciphers", _gc(FormatSslClientCiphers(&ssl))); return false; case MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION: LockInc(&shared->c.sslnoversion); WARNF("(ssl) %s %s %s", DescribeClient(), "sslnoversion", mbedtls_ssl_get_version(&ssl)); return false; case MBEDTLS_ERR_SSL_INVALID_MAC: LockInc(&shared->c.sslshakemacs); WARNF("(ssl) %s %s", DescribeClient(), "sslshakemacs"); return false; case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE: LockInc(&shared->c.sslnoclientcert); WARNF("(ssl) %s %s", DescribeClient(), "sslnoclientcert"); NotifyClose(); return false; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: LockInc(&shared->c.sslverifyfailed); WARNF("(ssl) %s SSL %s", DescribeClient(), _gc(DescribeSslVerifyFailure( ssl.session_negotiate->verify_result))); return false; case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE: switch (ssl.fatal_alert) { case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN: LockInc(&shared->c.sslunknowncert); DEBUGF("(ssl) %s %s", DescribeClient(), "sslunknowncert"); return false; case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA: LockInc(&shared->c.sslunknownca); DEBUGF("(ssl) %s %s", DescribeClient(), "sslunknownca"); return false; default: WARNF("(ssl) %s SSL shakealert %s", DescribeClient(), GetAlertDescription(ssl.fatal_alert)); return false; } default: WARNF("(ssl) %s SSL handshake failed -0x%04x", DescribeClient(), -r); return false; } } } } static void ConfigureCertificate(mbedtls_x509write_cert *cw, struct Cert *ca, int usage, int type) { int r; const char *s; bool isduplicate; size_t i, j, k, nsan; struct HostsTxt *htxt; struct mbedtls_san *san; const mbedtls_x509_name *xname; char *name, *subject, *issuer, notbefore[16], notafter[16], hbuf[256]; san = 0; nsan = 0; name = 0; htxt = GetHostsTxt(); strcpy(hbuf, "localhost"); gethostname(hbuf, sizeof(hbuf)); for (i = 0; i < htxt->entries.i; ++i) { for (j = 0; j < ips.n; ++j) { if (IsLoopbackIp(ips.p[j])) continue; if (ips.p[j] == READ32BE(htxt->entries.p[i].ip)) { isduplicate = false; s = htxt->strings.p + htxt->entries.p[i].name; if (!name) name = s; for (k = 0; k < nsan; ++k) { if (san[k].tag == MBEDTLS_X509_SAN_DNS_NAME && !strcasecmp(s, san[k].val)) { isduplicate = true; break; } } if (!isduplicate) { san = realloc(san, (nsan += 2) * sizeof(*san)); san[nsan - 2].tag = MBEDTLS_X509_SAN_DNS_NAME; san[nsan - 2].val = s; san[nsan - 1].tag = MBEDTLS_X509_SAN_DNS_NAME; san[nsan - 1].val = _gc(xasprintf("*.%s", s)); } } } } for (i = 0; i < ips.n; ++i) { if (IsLoopbackIp(ips.p[i])) continue; san = realloc(san, ++nsan * sizeof(*san)); san[nsan - 1].tag = MBEDTLS_X509_SAN_IP_ADDRESS; san[nsan - 1].ip4 = ips.p[i]; } ChooseCertificateLifetime(notbefore, notafter); subject = xasprintf("CN=%s", name ? name : hbuf); if (ca) { issuer = calloc(1, 1000); CHECK_GT(mbedtls_x509_dn_gets(issuer, 1000, &ca->cert->subject), 0); } else { issuer = strdup(subject); } if ((r = mbedtls_x509write_crt_set_subject_alternative_name(cw, san, nsan)) || (r = mbedtls_x509write_crt_set_validity(cw, notbefore, notafter)) || (r = mbedtls_x509write_crt_set_basic_constraints(cw, false, -1)) || #if defined(MBEDTLS_SHA1_C) (r = mbedtls_x509write_crt_set_subject_key_identifier(cw)) || (r = mbedtls_x509write_crt_set_authority_key_identifier(cw)) || #endif (r = mbedtls_x509write_crt_set_key_usage(cw, usage)) || (r = mbedtls_x509write_crt_set_ext_key_usage(cw, type)) || (r = mbedtls_x509write_crt_set_subject_name(cw, subject)) || (r = mbedtls_x509write_crt_set_issuer_name(cw, issuer))) { FATALF("(ssl) configure certificate (grep -0x%04x)", -r); } free(subject); free(issuer); free(san); } static struct Cert GetKeySigningKey(void) { size_t i; for (i = 0; i < certs.n; ++i) { if (!certs.p[i].key) continue; if (!certs.p[i].cert) continue; if (!certs.p[i].cert->ca_istrue) continue; if (mbedtls_x509_crt_check_key_usage(certs.p[i].cert, MBEDTLS_X509_KU_KEY_CERT_SIGN)) { continue; } return certs.p[i]; } return (struct Cert){0}; } static struct Cert GenerateEcpCertificate(struct Cert *ca) { mbedtls_pk_context *key; mbedtls_md_type_t md_alg; mbedtls_x509write_cert wcert; md_alg = suiteb ? MBEDTLS_MD_SHA384 : MBEDTLS_MD_SHA256; key = InitializeKey(ca, &wcert, md_alg, MBEDTLS_PK_ECKEY); CHECK_EQ(0, mbedtls_ecp_gen_key( suiteb ? MBEDTLS_ECP_DP_SECP384R1 : MBEDTLS_ECP_DP_SECP256R1, mbedtls_pk_ec(*key), GenerateHardRandom, 0)); GenerateCertificateSerial(&wcert); ConfigureCertificate(&wcert, ca, MBEDTLS_X509_KU_DIGITAL_SIGNATURE, MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER | MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT); return FinishCertificate(ca, &wcert, key); } static struct Cert GenerateRsaCertificate(struct Cert *ca) { mbedtls_pk_context *key; mbedtls_md_type_t md_alg; mbedtls_x509write_cert wcert; md_alg = suiteb ? MBEDTLS_MD_SHA384 : MBEDTLS_MD_SHA256; key = InitializeKey(ca, &wcert, md_alg, MBEDTLS_PK_RSA); CHECK_EQ(0, mbedtls_rsa_gen_key(mbedtls_pk_rsa(*key), GenerateHardRandom, 0, suiteb ? 4096 : 2048, 65537)); GenerateCertificateSerial(&wcert); ConfigureCertificate( &wcert, ca, MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_ENCIPHERMENT, MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER | MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT); return FinishCertificate(ca, &wcert, key); } static void LoadCertificates(void) { size_t i; struct Cert ksk, ecp, rsa; bool havecert, haveclientcert; havecert = false; haveclientcert = false; for (i = 0; i < certs.n; ++i) { if (certs.p[i].key && certs.p[i].cert && !certs.p[i].cert->ca_istrue && !mbedtls_x509_crt_check_key_usage(certs.p[i].cert, MBEDTLS_X509_KU_DIGITAL_SIGNATURE)) { if (!mbedtls_x509_crt_check_extended_key_usage( certs.p[i].cert, MBEDTLS_OID_SERVER_AUTH, MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH))) { LogCertificate("using server certificate", certs.p[i].cert); UseCertificate(&conf, certs.p + i, "server"); havecert = true; } if (!mbedtls_x509_crt_check_extended_key_usage( certs.p[i].cert, MBEDTLS_OID_CLIENT_AUTH, MBEDTLS_OID_SIZE(MBEDTLS_OID_CLIENT_AUTH))) { LogCertificate("using client certificate", certs.p[i].cert); UseCertificate(&confcli, certs.p + i, "client"); haveclientcert = true; } } } if (!havecert && (!psks.n || ksk.key)) { if ((ksk = GetKeySigningKey()).key) { DEBUGF("(ssl) generating ssl certificates using %`'s", _gc(FormatX509Name(&ksk.cert->subject))); } else { VERBOSEF("(ssl) could not find non-CA SSL certificate key pair with" " -addext keyUsage=digitalSignature" " -addext extendedKeyUsage=serverAuth"); VERBOSEF("(ssl) could not find CA key signing key pair with" " -addext keyUsage=keyCertSign"); VERBOSEF("(ssl) generating self-signed ssl certificates"); } #ifdef MBEDTLS_ECP_C ecp = GenerateEcpCertificate(ksk.key ? &ksk : 0); if (!havecert) UseCertificate(&conf, &ecp, "server"); if (!haveclientcert && ksk.key) { UseCertificate(&confcli, &ecp, "client"); } AppendCert(ecp.cert, ecp.key); #endif #ifdef MBEDTLS_RSA_C if (!norsagen) { rsa = GenerateRsaCertificate(ksk.key ? &ksk : 0); if (!havecert) UseCertificate(&conf, &rsa, "server"); if (!haveclientcert && ksk.key) { UseCertificate(&confcli, &rsa, "client"); } AppendCert(rsa.cert, rsa.key); } #endif } WipeSigningKeys(); } static bool ClientAcceptsGzip(void) { return cpm.msg.version >= 10 && /* RFC1945 § 3.5 */ HeaderHas(&cpm.msg, inbuf.p, kHttpAcceptEncoding, "gzip", 4); } char *FormatUnixHttpDateTime(char *s, int64_t t) { struct tm tm; gmtime_r(&t, &tm); FormatHttpDateTime(s, &tm); return s; } static void UpdateCurrentDate(struct timespec now) { int64_t t; struct tm tm; t = now.tv_sec; shared->nowish = now; gmtime_r(&t, &tm); FormatHttpDateTime(shared->currentdate, &tm); } static int64_t GetGmtOffset(int64_t t) { struct tm tm; localtime_r(&t, &tm); return tm.tm_gmtoff; } forceinline bool IsCompressed(struct Asset *a) { return !a->file && ZIP_LFILE_COMPRESSIONMETHOD(zbase + a->lf) == kZipCompressionDeflate; } forceinline int GetMode(struct Asset *a) { return a->file ? a->file->st.st_mode : GetZipCfileMode(zbase + a->cf); } forceinline bool IsCompressionMethodSupported(int method) { return method == kZipCompressionNone || method == kZipCompressionDeflate; } static inline unsigned Hash(const void *p, unsigned long n) { unsigned h, i; for (h = i = 0; i < n; i++) { h += ((unsigned char *)p)[i]; h *= 0x9e3779b1; } return MAX(1, h); } static void FreeAssets(void) { size_t i; for (i = 0; i < assets.n; ++i) { Free(&assets.p[i].lastmodifiedstr); } Free(&assets.p); assets.n = 0; } static void FreeStrings(struct Strings *l) { size_t i; for (i = 0; i < l->n; ++i) { Free(&l->p[i].s); } Free(&l->p); l->n = 0; } static void IndexAssets(void) { uint64_t cf; struct Asset *p; struct timespec lm; uint32_t i, n, m, step, hash; DEBUGF("(zip) indexing assets (inode %#lx)", zst.st_ino); FreeAssets(); CHECK_GE(HASH_LOAD_FACTOR, 2); CHECK(READ32LE(zcdir) == kZipCdir64HdrMagic || READ32LE(zcdir) == kZipCdirHdrMagic); n = GetZipCdirRecords(zcdir); m = _roundup2pow(MAX(1, n) * HASH_LOAD_FACTOR); p = xcalloc(m, sizeof(struct Asset)); for (cf = GetZipCdirOffset(zcdir); n--; cf += ZIP_CFILE_HDRSIZE(zbase + cf)) { CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(zbase + cf)); if (!IsCompressionMethodSupported( ZIP_CFILE_COMPRESSIONMETHOD(zbase + cf))) { WARNF("(zip) don't understand zip compression method %d used by %`'.*s", ZIP_CFILE_COMPRESSIONMETHOD(zbase + cf), ZIP_CFILE_NAMESIZE(zbase + cf), ZIP_CFILE_NAME(zbase + cf)); continue; } hash = Hash(ZIP_CFILE_NAME(zbase + cf), ZIP_CFILE_NAMESIZE(zbase + cf)); step = 0; do { i = (hash + (step * (step + 1)) >> 1) & (m - 1); ++step; } while (p[i].hash); GetZipCfileTimestamps(zbase + cf, &lm, 0, 0, gmtoff); p[i].hash = hash; p[i].cf = cf; p[i].lf = GetZipCfileOffset(zbase + cf); p[i].istext = !!(ZIP_CFILE_INTERNALATTRIBUTES(zbase + cf) & kZipIattrText); p[i].lastmodified = lm.tv_sec; p[i].lastmodifiedstr = FormatUnixHttpDateTime(xmalloc(30), lm.tv_sec); } assets.p = p; assets.n = m; } static bool OpenZip(bool force) { int fd; size_t n; struct stat st; uint8_t *m, *b, *d, *p; if (stat(zpath, &st) != -1) { if (force || st.st_ino != zst.st_ino || st.st_size > zst.st_size) { if (st.st_ino == zst.st_ino) { fd = zfd; } else if ((fd = open(zpath, O_RDWR)) == -1) { WARNF("(zip) open() error: %m"); return false; } if ((m = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != MAP_FAILED) { n = st.st_size; if ((p = FindEmbeddedApe(m, n))) { b = p; n -= p - m; } else { b = m; } if ((d = GetZipCdir(b, n))) { if (zmap) { LOGIFNEG1(munmap(zmap, zbase + zsize - zmap)); } zmap = m; zbase = b; zsize = n; zcdir = d; DCHECK(IsZipCdir32(zbase, zsize, zcdir - zbase) || IsZipCdir64(zbase, zsize, zcdir - zbase)); memcpy(&zst, &st, sizeof(st)); IndexAssets(); return true; } else { WARNF("(zip) couldn't locate central directory"); } } else { WARNF("(zip) mmap() error: %m"); } } } else { // avoid noise if we setuid to user who can't see executable if (errno == EACCES) { VERBOSEF("(zip) stat(%`'s) error: %m", zpath); } else { WARNF("(zip) stat(%`'s) error: %m", zpath); } } return false; } static struct Asset *GetAssetZip(const char *path, size_t pathlen) { uint32_t i, step, hash; if (pathlen > 1 && path[0] == '/') ++path, --pathlen; hash = Hash(path, pathlen); for (step = 0;; ++step) { i = (hash + (step * (step + 1)) >> 1) & (assets.n - 1); if (!assets.p[i].hash) return NULL; if (hash == assets.p[i].hash && pathlen == ZIP_CFILE_NAMESIZE(zbase + assets.p[i].cf) && memcmp(path, ZIP_CFILE_NAME(zbase + assets.p[i].cf), pathlen) == 0) { return &assets.p[i]; } } } static struct Asset *GetAssetFile(const char *path, size_t pathlen) { size_t i; struct Asset *a; if (stagedirs.n) { a = FreeLater(xcalloc(1, sizeof(struct Asset))); a->file = FreeLater(xmalloc(sizeof(struct File))); for (i = 0; i < stagedirs.n; ++i) { LockInc(&shared->c.stats); a->file->path.s = FreeLater(MergePaths(stagedirs.p[i].s, stagedirs.p[i].n, path, pathlen, &a->file->path.n)); if (stat(a->file->path.s, &a->file->st) != -1) { a->lastmodifiedstr = FormatUnixHttpDateTime( FreeLater(xmalloc(30)), (a->lastmodified = a->file->st.st_mtim.tv_sec)); return a; } else { LockInc(&shared->c.statfails); } } } return NULL; } static struct Asset *GetAsset(const char *path, size_t pathlen) { char *path2; struct Asset *a; if (!(a = GetAssetFile(path, pathlen))) { if (!(a = GetAssetZip(path, pathlen))) { if (pathlen > 1 && path[pathlen - 1] != '/' && pathlen + 1 <= sizeof(slashpath)) { memcpy(mempcpy(slashpath, path, pathlen), "/", 1); a = GetAssetZip(slashpath, pathlen + 1); } } } return a; } static char *AppendHeader(char *p, const char *k, const char *v) { if (!v) return p; return AppendCrlf(stpcpy(stpcpy(stpcpy(p, k), ": "), v)); } static char *AppendContentType(char *p, const char *ct) { p = stpcpy(p, "Content-Type: "); p = stpcpy(p, ct); if ((cpm.istext = _startswith(ct, "text/"))) { if (!strchr(ct + 5, ';')) { p = stpcpy(p, "; charset=utf-8"); } if (!cpm.referrerpolicy && _startswith(ct + 5, "html")) { cpm.referrerpolicy = "no-referrer-when-downgrade"; } } cpm.hascontenttype = true; return AppendCrlf(p); } static char *AppendExpires(char *p, int64_t t) { struct tm tm; gmtime_r(&t, &tm); p = stpcpy(p, "Expires: "); p = FormatHttpDateTime(p, &tm); return AppendCrlf(p); } static char *AppendCache(char *p, int64_t seconds, char *directive) { if (seconds < 0) return p; p = stpcpy(p, "Cache-Control: max-age="); p = FormatUint64(p, seconds); if (!seconds) { p = stpcpy(p, ", no-store"); } else if (directive && *directive) { p = stpcpy(p, ", "); p = stpcpy(p, directive); } p = AppendCrlf(p); return AppendExpires(p, shared->nowish.tv_sec + seconds); } static inline char *AppendContentLength(char *p, size_t n) { p = stpcpy(p, "Content-Length: "); p = FormatUint64(p, n); return AppendCrlf(p); } static char *AppendContentRange(char *p, long a, long b, long c) { p = stpcpy(p, "Content-Range: bytes "); if (a >= 0 && b > 0) { p = FormatUint64(p, a); *p++ = '-'; p = FormatUint64(p, a + b - 1); } else { *p++ = '*'; } *p++ = '/'; p = FormatUint64(p, c); return AppendCrlf(p); } static bool Inflate(void *dp, size_t dn, const void *sp, size_t sn) { LockInc(&shared->c.inflates); return !__inflate(dp, dn, sp, sn); } static bool Verify(void *data, size_t size, uint32_t crc) { uint32_t got; LockInc(&shared->c.verifies); if (crc == (got = crc32_z(0, data, size))) { return true; } else { LockInc(&shared->c.thiscorruption); WARNF("(zip) corrupt zip file at %`'.*s had crc 0x%08x but expected 0x%08x", cpm.msg.uri.b - cpm.msg.uri.a, inbuf.p + cpm.msg.uri.a, got, crc); return false; } } static void *Deflate(const void *data, size_t size, size_t *out_size) { void *res; z_stream zs = {0}; LockInc(&shared->c.deflates); CHECK_EQ(Z_OK, deflateInit2(&zs, 4, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY)); zs.next_in = data; zs.avail_in = size; zs.avail_out = compressBound(size); zs.next_out = res = xmalloc(zs.avail_out); CHECK_EQ(Z_STREAM_END, deflate(&zs, Z_FINISH)); CHECK_EQ(Z_OK, deflateEnd(&zs)); *out_size = zs.total_out; return xrealloc(res, zs.total_out); } static void *LoadAsset(struct Asset *a, size_t *out_size) { int mode; size_t size; uint8_t *data; if (S_ISDIR(GetMode(a))) { WARNF("(srvr) can't load directory"); return NULL; } if (!a->file) { size = GetZipLfileUncompressedSize(zbase + a->lf); if (size == SIZE_MAX || !(data = malloc(size + 1))) return NULL; if (IsCompressed(a)) { if (!Inflate(data, size, ZIP_LFILE_CONTENT(zbase + a->lf), GetZipCfileCompressedSize(zbase + a->cf))) { free(data); return NULL; } } else { memcpy(data, ZIP_LFILE_CONTENT(zbase + a->lf), size); } if (!Verify(data, size, ZIP_LFILE_CRC32(zbase + a->lf))) { free(data); return NULL; } data[size] = '\0'; if (out_size) *out_size = size; return data; } else { LockInc(&shared->c.slurps); return xslurp(a->file->path.s, out_size); } } static wontreturn void PrintUsage(int fd, int rc) { size_t n; const char *p; struct Asset *a; if (!(a = GetAssetZip("/help.txt", 9)) || !(p = LoadAsset(a, &n))) { fprintf(stderr, "error: /help.txt is not a zip asset\n"); exit(1); } if (IsTiny()) { write(fd, p, strlen(p)); } else { __paginate(fd, p); } exit(rc); } static void AppendLogo(void) { size_t n; char *p, *q; struct Asset *a; if ((a = GetAsset("/redbean.png", 12)) && (p = LoadAsset(a, &n))) { if ((q = EncodeBase64(p, n, &n))) { appends(&cpm.outbuf, "<img alt=\"[logo]\" src=\"data:image/png;base64,"); appendd(&cpm.outbuf, q, n); appends(&cpm.outbuf, "\">\r\n"); free(q); } free(p); } } static ssize_t Send(struct iovec *iov, int iovlen) { ssize_t rc; if ((rc = writer(client, iov, iovlen)) == -1) { if (errno == ECONNRESET) { LockInc(&shared->c.writeresets); DEBUGF("(rsp) %s write reset", DescribeClient()); } else if (errno == EAGAIN) { LockInc(&shared->c.writetimeouts); WARNF("(rsp) %s write timeout", DescribeClient()); errno = 0; } else { LockInc(&shared->c.writeerrors); if (errno == EBADF) { // don't warn on close/bad fd DEBUGF("(rsp) %s write badf", DescribeClient()); } else { WARNF("(rsp) %s write error: %m", DescribeClient()); } } connectionclose = true; } return rc; } static bool IsSslCompressed(void) { return usingssl && ssl.session->compression; } static char *CommitOutput(char *p) { uint32_t crc; size_t outbuflen; if (!cpm.contentlength) { outbuflen = appendz(cpm.outbuf).i; if (cpm.istext && !cpm.isyielding && outbuflen >= 100) { if (!IsTiny() && !IsSslCompressed()) { p = stpcpy(p, "Vary: Accept-Encoding\r\n"); } if (!IsTiny() && // !IsSslCompressed() && // ClientAcceptsGzip() && // !ShouldAvoidGzip()) { cpm.gzipped = outbuflen; crc = crc32_z(0, cpm.outbuf, outbuflen); WRITE32LE(gzip_footer + 0, crc); WRITE32LE(gzip_footer + 4, outbuflen); cpm.content = FreeLater(Deflate(cpm.outbuf, outbuflen, &cpm.contentlength)); DropOutput(); } else { UseOutput(); } } else { UseOutput(); } } else { DropOutput(); } return p; } static char *ServeDefaultErrorPage(char *p, unsigned code, const char *reason, const char *details) { p = AppendContentType(p, "text/html; charset=ISO-8859-1"); reason = FreeLater(EscapeHtml(reason, -1, 0)); appends(&cpm.outbuf, "\ <!doctype html>\r\n\ <title>"); appendf(&cpm.outbuf, "%d %s", code, reason); appends(&cpm.outbuf, "\ </title>\r\n\ <style>\r\n\ html { color: #111; font-family: sans-serif; }\r\n\ img { vertical-align: middle; }\r\n\ </style>\r\n\ <h1>\r\n"); AppendLogo(); appendf(&cpm.outbuf, "%d %s\r\n", code, reason); appends(&cpm.outbuf, "</h1>\r\n"); if (details) { appendf(&cpm.outbuf, "<pre>%s</pre>\r\n", FreeLater(EscapeHtml(details, -1, 0))); } UseOutput(); return p; } static char *ServeErrorImpl(unsigned code, const char *reason, const char *details) { size_t n; char *p, *s; struct Asset *a; LockInc(&shared->c.errors); DropOutput(); p = SetStatus(code, reason); s = xasprintf("/%d.html", code); a = GetAsset(s, strlen(s)); free(s); if (!a) { return ServeDefaultErrorPage(p, code, reason, details); } else if (a->file) { LockInc(&shared->c.slurps); cpm.content = FreeLater(xslurp(a->file->path.s, &cpm.contentlength)); return AppendContentType(p, "text/html; charset=utf-8"); } else { cpm.content = (char *)ZIP_LFILE_CONTENT(zbase + a->lf); cpm.contentlength = GetZipCfileCompressedSize(zbase + a->cf); if (IsCompressed(a)) { n = GetZipLfileUncompressedSize(zbase + a->lf); if ((s = FreeLater(malloc(n))) && Inflate(s, n, cpm.content, cpm.contentlength)) { cpm.content = s; cpm.contentlength = n; } else { return ServeDefaultErrorPage(p, code, reason, details); } } if (Verify(cpm.content, cpm.contentlength, ZIP_LFILE_CRC32(zbase + a->lf))) { return AppendContentType(p, "text/html; charset=utf-8"); } else { return ServeDefaultErrorPage(p, code, reason, details); } } } static char *ServeErrorWithDetail(unsigned code, const char *reason, const char *details) { ERRORF("(srvr) server error: %d %s", code, reason); return ServeErrorImpl(code, reason, details); } static char *ServeError(unsigned code, const char *reason) { return ServeErrorWithDetail(code, reason, NULL); } static char *ServeFailure(unsigned code, const char *reason) { ERRORF("(srvr) failure: %d %s %s HTTP%02d %.*s %`'.*s %`'.*s %`'.*s %`'.*s", code, reason, DescribeClient(), cpm.msg.version, cpm.msg.xmethod.b - cpm.msg.xmethod.a, inbuf.p + cpm.msg.xmethod.a, HeaderLength(kHttpHost), HeaderData(kHttpHost), cpm.msg.uri.b - cpm.msg.uri.a, inbuf.p + cpm.msg.uri.a, HeaderLength(kHttpReferer), HeaderData(kHttpReferer), HeaderLength(kHttpUserAgent), HeaderData(kHttpUserAgent)); return ServeErrorImpl(code, reason, NULL); } static ssize_t YieldGenerator(struct iovec v[3]) { int nresults, status; if (cpm.isyielding > 1) { do { if (!YL || lua_status(YL) != LUA_YIELD) return 0; // done yielding cpm.contentlength = 0; status = lua_resume(YL, NULL, 0, &nresults); if (status != LUA_OK && status != LUA_YIELD) { LogLuaError("resume", lua_tostring(YL, -1)); lua_pop(YL, 1); return -1; } lua_pop(YL, nresults); if (!cpm.contentlength) UseOutput(); // continue yielding if nothing to return to keep generator running } while (!cpm.contentlength); } DEBUGF("(lua) yielded with %ld bytes generated", cpm.contentlength); cpm.isyielding++; v[0].iov_base = cpm.content; v[0].iov_len = cpm.contentlength; return cpm.contentlength; } static void OnLuaServerPageCtrlc(int i) { lua_sigint(GL, i); } static int LuaCallWithYield(lua_State *L) { int status; // since yield may happen in OnHttpRequest and in ServeLua, // need to fully restart the yield generator; // the second set of headers is not going to be sent struct sigaction sa, saold; lua_State *co = lua_newthread(L); if (__replmode) { sa.sa_flags = SA_RESETHAND; sa.sa_handler = OnLuaServerPageCtrlc; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, &saold); } status = LuaCallWithTrace(L, 0, 0, co); if (__replmode) { sigaction(SIGINT, &saold, 0); } if (status == LUA_YIELD) { CHECK_GT(lua_gettop(L), 0); // make sure that coroutine is anchored YL = co; cpm.generator = YieldGenerator; if (!cpm.isyielding) cpm.isyielding = 1; status = LUA_OK; } return status; } static ssize_t DeflateGenerator(struct iovec v[3]) { int i, rc; size_t no; void *res; int level; i = 0; if (!dg.t) { v[0].iov_base = kGzipHeader; v[0].iov_len = sizeof(kGzipHeader); ++dg.t; ++i; } else if (dg.t == 3) { return 0; } if (dg.t != 2) { CHECK_EQ(0, dg.s.avail_in); dg.s.next_in = (void *)(cpm.content + dg.i); dg.s.avail_in = MIN(dg.z, cpm.contentlength - dg.i); dg.c = crc32_z(dg.c, dg.s.next_in, dg.s.avail_in); dg.i += dg.s.avail_in; } dg.s.next_out = dg.b; dg.s.avail_out = dg.z; no = dg.s.avail_in; rc = deflate(&dg.s, dg.i < cpm.contentlength ? Z_SYNC_FLUSH : Z_FINISH); if (rc != Z_OK && rc != Z_STREAM_END) { DIEF("(zip) deflate()→%d oldin:%,zu/%,zu in:%,zu/%,zu out:%,zu/%,zu", rc, no, dg.z, dg.s.avail_in, dg.z, dg.s.avail_out, dg.z); } else { NOISEF("(zip) deflate()→%d oldin:%,zu/%,zu in:%,zu/%,zu out:%,zu/%,zu", rc, no, dg.z, dg.s.avail_in, dg.z, dg.s.avail_out, dg.z); } no = dg.z - dg.s.avail_out; if (no) { v[i].iov_base = dg.b; v[i].iov_len = no; ++i; } if (rc == Z_OK) { CHECK_GT(no, 0); if (dg.s.avail_out) { dg.t = 1; } else { dg.t = 2; } } else if (rc == Z_STREAM_END) { CHECK_EQ(cpm.contentlength, dg.i); CHECK_EQ(Z_OK, deflateEnd(&dg.s)); WRITE32LE(gzip_footer + 0, dg.c); WRITE32LE(gzip_footer + 4, cpm.contentlength); v[i].iov_base = gzip_footer; v[i].iov_len = sizeof(gzip_footer); dg.t = 3; } return v[0].iov_len + v[1].iov_len + v[2].iov_len; } static char *ServeAssetCompressed(struct Asset *a) { char *p; uint32_t crc; LockInc(&shared->c.deflates); LockInc(&shared->c.compressedresponses); DEBUGF("(srvr) ServeAssetCompressed()"); dg.t = 0; dg.i = 0; dg.c = 0; if (usingssl) { dg.z = 512 + (_rand64() & 1023); } else { dg.z = 65536; } cpm.gzipped = -1; // signal generator usage with the exact size unknown cpm.generator = DeflateGenerator; bzero(&dg.s, sizeof(dg.s)); CHECK_EQ(Z_OK, deflateInit2(&dg.s, 4, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY)); dg.b = FreeLater(malloc(dg.z)); p = SetStatus(200, "OK"); p = stpcpy(p, "Content-Encoding: gzip\r\n"); return p; } static ssize_t InflateGenerator(struct iovec v[3]) { int i, rc; size_t no; void *res; i = 0; if (!dg.t) { ++dg.t; } else if (dg.t == 3) { return 0; } if (dg.t != 2) { CHECK_EQ(0, dg.s.avail_in); dg.s.next_in = (void *)(cpm.content + dg.i); dg.s.avail_in = MIN(dg.z, cpm.contentlength - dg.i); dg.i += dg.s.avail_in; } dg.s.next_out = dg.b; dg.s.avail_out = dg.z; rc = inflate(&dg.s, Z_NO_FLUSH); if (rc != Z_OK && rc != Z_STREAM_END) DIEF("(zip) inflate()→%d", rc); no = dg.z - dg.s.avail_out; if (no) { v[i].iov_base = dg.b; v[i].iov_len = no; dg.c = crc32_z(dg.c, dg.b, no); ++i; } if (rc == Z_OK) { CHECK_GT(no, 0); dg.t = dg.s.avail_out ? 1 : 2; } else if (rc == Z_STREAM_END) { CHECK_EQ(Z_OK, inflateEnd(&dg.s)); CHECK_EQ(ZIP_CFILE_CRC32(zbase + dg.a->cf), dg.c); dg.t = 3; } return v[0].iov_len + v[1].iov_len + v[2].iov_len; } static char *ServeAssetDecompressed(struct Asset *a) { char *p; size_t size; uint32_t crc; LockInc(&shared->c.inflates); LockInc(&shared->c.decompressedresponses); size = GetZipCfileUncompressedSize(zbase + a->cf); DEBUGF("(srvr) ServeAssetDecompressed(%ld)→%ld", cpm.contentlength, size); if (cpm.msg.method == kHttpHead) { cpm.content = 0; cpm.contentlength = size; return SetStatus(200, "OK"); } else if (!IsTiny()) { dg.t = 0; dg.i = 0; dg.c = 0; dg.a = a; dg.z = 65536; CHECK_EQ(Z_OK, inflateInit2(&dg.s, -MAX_WBITS)); cpm.generator = InflateGenerator; dg.b = FreeLater(malloc(dg.z)); return SetStatus(200, "OK"); } else if ((p = FreeLater(malloc(size))) && Inflate(p, size, cpm.content, cpm.contentlength) && Verify(p, size, ZIP_CFILE_CRC32(zbase + a->cf))) { cpm.content = p; cpm.contentlength = size; return SetStatus(200, "OK"); } else { return ServeError(500, "Internal Server Error"); } } static inline char *ServeAssetIdentity(struct Asset *a, const char *ct) { LockInc(&shared->c.identityresponses); DEBUGF("(srvr) ServeAssetIdentity(%`'s)", ct); return SetStatus(200, "OK"); } static inline char *ServeAssetPrecompressed(struct Asset *a) { size_t size; uint32_t crc; DEBUGF("(srvr) ServeAssetPrecompressed()"); LockInc(&shared->c.precompressedresponses); crc = ZIP_CFILE_CRC32(zbase + a->cf); size = GetZipCfileUncompressedSize(zbase + a->cf); cpm.gzipped = size; WRITE32LE(gzip_footer + 0, crc); WRITE32LE(gzip_footer + 4, size); return SetStatus(200, "OK"); } static char *ServeAssetRange(struct Asset *a) { char *p; long rangestart, rangelength; DEBUGF("(srvr) ServeAssetRange()"); if (ParseHttpRange(HeaderData(kHttpRange), HeaderLength(kHttpRange), cpm.contentlength, &rangestart, &rangelength) && rangestart >= 0 && rangelength >= 0 && rangestart < cpm.contentlength && rangestart + rangelength <= cpm.contentlength) { LockInc(&shared->c.partialresponses); p = SetStatus(206, "Partial Content"); p = AppendContentRange(p, rangestart, rangelength, cpm.contentlength); cpm.content += rangestart; cpm.contentlength = rangelength; return p; } else { LockInc(&shared->c.badranges); WARNF("(client) bad range %`'.*s", HeaderLength(kHttpRange), HeaderData(kHttpRange)); p = SetStatus(416, "Range Not Satisfiable"); p = AppendContentRange(p, -1, -1, cpm.contentlength); cpm.content = ""; cpm.contentlength = 0; return p; } } static char *GetAssetPath(uint8_t *zcf, size_t *out_size) { char *p1, *p2; size_t n1, n2; p1 = ZIP_CFILE_NAME(zcf); n1 = ZIP_CFILE_NAMESIZE(zcf); p2 = xmalloc(1 + n1 + 1); n2 = 1 + n1 + 1; p2[0] = '/'; memcpy(p2 + 1, p1, n1); p2[1 + n1] = '\0'; if (out_size) *out_size = 1 + n1; return p2; } static bool IsHiddenPath(const char *s, size_t n) { size_t i; for (i = 0; i < hidepaths.n; ++i) { if (n >= hidepaths.p[i].n && !memcmp(s, hidepaths.p[i].s, hidepaths.p[i].n)) { return true; } } return false; } static char *GetBasicAuthorization(size_t *z) { size_t n; const char *p, *q; struct HttpSlice *g; g = cpm.msg.headers + (HasHeader(kHttpProxyAuthorization) ? kHttpProxyAuthorization : kHttpAuthorization); p = inbuf.p + g->a; n = g->b - g->a; if ((q = memchr(p, ' ', n)) && SlicesEqualCase(p, q - p, "Basic", 5)) { return DecodeBase64(q + 1, n - (q + 1 - p), z); } else { return NULL; } } static const char *GetSystemUrlLauncherCommand(void) { if (IsWindows()) { return "explorer"; } else if (IsXnu()) { return "open"; } else { return "xdg-open"; } } static void LaunchBrowser(const char *path) { int pid, ws; struct in_addr addr; const char *u, *prog; sigset_t chldmask, savemask; struct sigaction ignore, saveint, savequit; uint16_t port = 80; path = firstnonnull(path, "/"); // use the first server address if there is at least one server if (servers.n) { addr = servers.p[0].addr.sin_addr; port = ntohs(servers.p[0].addr.sin_port); } // assign a loopback address if no server or unknown server address if (!servers.n || !addr.s_addr) addr.s_addr = htonl(INADDR_LOOPBACK); if (*path != '/') path = _gc(xasprintf("/%s", path)); if ((prog = commandv(GetSystemUrlLauncherCommand(), _gc(malloc(PATH_MAX)), PATH_MAX))) { u = _gc(xasprintf("http://%s:%d%s", inet_ntoa(addr), port, path)); DEBUGF("(srvr) opening browser with command %`'s %s", prog, u); ignore.sa_flags = 0; ignore.sa_handler = SIG_IGN; sigemptyset(&ignore.sa_mask); sigaction(SIGINT, &ignore, &saveint); sigaction(SIGQUIT, &ignore, &savequit); sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); sigprocmask(SIG_BLOCK, &chldmask, &savemask); CHECK_NE(-1, (pid = fork())); if (!pid) { setpgrp(); // ctrl-c'ing redbean shouldn't kill browser sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); execv(prog, (char *const[]){prog, u, 0}); _Exit(127); } while (wait4(pid, &ws, 0, 0) == -1) { CHECK_EQ(EINTR, errno); errno = 0; } sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); if (!(WIFEXITED(ws) && WEXITSTATUS(ws) == 0)) { WARNF("(srvr) command %`'s exited with %d", GetSystemUrlLauncherCommand(), WIFEXITED(ws) ? WEXITSTATUS(ws) : 128 + WEXITSTATUS(ws)); } } else { WARNF("(srvr) can't launch browser because %`'s isn't installed", GetSystemUrlLauncherCommand()); } } static char *BadMethod(void) { LockInc(&shared->c.badmethods); return stpcpy(ServeError(405, "Method Not Allowed"), "Allow: GET, HEAD\r\n"); } static int GetDecimalWidth(long x) { return LengthInt64Thousands(x); } static int GetOctalWidth(int x) { return !x ? 1 : x < 8 ? 2 : 1 + _bsr(x) / 3; } static const char *DescribeCompressionRatio(char rb[8], uint8_t *zcf) { long percent; if (ZIP_CFILE_COMPRESSIONMETHOD(zcf) == kZipCompressionNone) { return "n/a"; } else { percent = lround(100 - (double)GetZipCfileCompressedSize(zcf) / GetZipCfileUncompressedSize(zcf) * 100); sprintf(rb, "%ld%%", MIN(999, MAX(-999, percent))); return rb; } } static char *ServeListing(void) { long x; ldiv_t y; int w[3]; uint8_t *zcf; struct tm tm; const char *and; struct rusage ru; char *p, *q, *path; struct timespec lastmod; char rb[8], tb[20], *rp[6]; size_t i, n, pathlen, rn[6]; LockInc(&shared->c.listingrequests); if (cpm.msg.method != kHttpGet && cpm.msg.method != kHttpHead) return BadMethod(); appends(&cpm.outbuf, "\ <!doctype html>\r\n\ <meta charset=\"utf-8\">\r\n\ <title>redbean zip listing</title>\r\n\ <style>\r\n\ html { color: #111; font-family: sans-serif; }\r\n\ a { text-decoration: none; }\r\n\ pre a:hover { color: #00e; border-bottom: 1px solid #ccc; }\r\n\ h1 a { color: #111; }\r\n\ img { vertical-align: middle; }\r\n\ footer { color: #555; font-size: 10pt; }\r\n\ td { padding-right: 3em; }\r\n\ .eocdcomment { max-width: 800px; color: #333; font-size: 11pt; }\r\n\ </style>\r\n\ <header><h1>\r\n"); AppendLogo(); rp[0] = EscapeHtml(brand, -1, &rn[0]); appendd(&cpm.outbuf, rp[0], rn[0]); free(rp[0]); appendf(&cpm.outbuf, "</h1>\r\n" "<div class=\"eocdcomment\">%.*s</div>\r\n" "<hr>\r\n" "</header>\r\n" "<pre>\r\n", strnlen(GetZipCdirComment(zcdir), GetZipCdirCommentSize(zcdir)), GetZipCdirComment(zcdir)); bzero(w, sizeof(w)); n = GetZipCdirRecords(zcdir); for (zcf = zbase + GetZipCdirOffset(zcdir); n--; zcf += ZIP_CFILE_HDRSIZE(zcf)) { CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(zcf)); path = GetAssetPath(zcf, &pathlen); if (!IsHiddenPath(path, pathlen)) { w[0] = min(80, max(w[0], strwidth(path, 0) + 2)); w[1] = max(w[1], GetOctalWidth(GetZipCfileMode(zcf))); w[2] = max(w[2], GetDecimalWidth(GetZipCfileUncompressedSize(zcf))); } free(path); } n = GetZipCdirRecords(zcdir); for (zcf = zbase + GetZipCdirOffset(zcdir); n--; zcf += ZIP_CFILE_HDRSIZE(zcf)) { CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(zcf)); path = GetAssetPath(zcf, &pathlen); if (!IsHiddenPath(path, pathlen)) { rp[0] = VisualizeControlCodes(path, pathlen, &rn[0]); rp[1] = EscapePath(path, pathlen, &rn[1]); rp[2] = EscapeHtml(rp[1], rn[1], &rn[2]); rp[3] = VisualizeControlCodes( ZIP_CFILE_COMMENT(zcf), strnlen(ZIP_CFILE_COMMENT(zcf), ZIP_CFILE_COMMENTSIZE(zcf)), &rn[3]); rp[4] = EscapeHtml(rp[0], rn[0], &rn[4]); GetZipCfileTimestamps(zcf, &lastmod, 0, 0, gmtoff); localtime_r(&lastmod.tv_sec, &tm); iso8601(tb, &tm); if (IsCompressionMethodSupported(ZIP_CFILE_COMPRESSIONMETHOD(zcf)) && IsAcceptablePath(path, pathlen)) { appendf(&cpm.outbuf, "<a href=\"%.*s\">%-*.*s</a> %s %0*o %4s %,*ld %'s\r\n", rn[2], rp[2], w[0], rn[4], rp[4], tb, w[1], GetZipCfileMode(zcf), DescribeCompressionRatio(rb, zcf), w[2], GetZipCfileUncompressedSize(zcf), rp[3]); } else { appendf(&cpm.outbuf, "%-*.*s %s %0*o %4s %,*ld %'s\r\n", w[0], rn[4], rp[4], tb, w[1], GetZipCfileMode(zcf), DescribeCompressionRatio(rb, zcf), w[2], GetZipCfileUncompressedSize(zcf), rp[3]); } free(rp[4]); free(rp[3]); free(rp[2]); free(rp[1]); free(rp[0]); } free(path); } appends(&cpm.outbuf, "\ </pre><footer><hr>\r\n\ <table border=\"0\"><tr>\r\n\ <td valign=\"top\">\r\n\ <a href=\"/statusz\">/statusz</a>\r\n\ "); if (shared->c.connectionshandled) { appends(&cpm.outbuf, "says your redbean<br>\r\n"); AppendResourceReport(&cpm.outbuf, &shared->children, "<br>\r\n"); } appends(&cpm.outbuf, "<td valign=\"top\">\r\n"); and = ""; x = timespec_sub(timespec_real(), startserver).tv_sec; y = ldiv(x, 24L * 60 * 60); if (y.quot) { appendf(&cpm.outbuf, "%,ld day%s ", y.quot, y.quot == 1 ? "" : "s"); and = "and "; } y = ldiv(y.rem, 60 * 60); if (y.quot) { appendf(&cpm.outbuf, "%,ld hour%s ", y.quot, y.quot == 1 ? "" : "s"); and = "and "; } y = ldiv(y.rem, 60); if (y.quot) { appendf(&cpm.outbuf, "%,ld minute%s ", y.quot, y.quot == 1 ? "" : "s"); and = "and "; } appendf(&cpm.outbuf, "%s%,ld second%s of operation<br>\r\n", and, y.rem, y.rem == 1 ? "" : "s"); x = shared->c.messageshandled; appendf(&cpm.outbuf, "%,ld message%s handled<br>\r\n", x, x == 1 ? "" : "s"); x = shared->c.connectionshandled; appendf(&cpm.outbuf, "%,ld connection%s handled<br>\r\n", x, x == 1 ? "" : "s"); x = shared->workers; appendf(&cpm.outbuf, "%,ld connection%s active<br>\r\n", x, x == 1 ? "" : "s"); appends(&cpm.outbuf, "</table>\r\n"); appends(&cpm.outbuf, "</footer>\r\n"); p = SetStatus(200, "OK"); p = AppendContentType(p, "text/html"); if (cpm.msg.version >= 11) { p = stpcpy(p, "Cache-Control: no-store\r\n"); } return CommitOutput(p); } static const char *MergeNames(const char *a, const char *b) { return FreeLater(xasprintf("%s.%s", a, b)); } static void AppendLong1(const char *a, long x) { if (x) appendf(&cpm.outbuf, "%s: %ld\r\n", a, x); } static void AppendLong2(const char *a, const char *b, long x) { if (x) appendf(&cpm.outbuf, "%s.%s: %ld\r\n", a, b, x); } static void AppendTimeval(const char *a, struct timeval *tv) { AppendLong2(a, "tv_sec", tv->tv_sec); AppendLong2(a, "tv_usec", tv->tv_usec); } static void AppendRusage(const char *a, struct rusage *ru) { AppendTimeval(MergeNames(a, "ru_utime"), &ru->ru_utime); AppendTimeval(MergeNames(a, "ru_stime"), &ru->ru_stime); AppendLong2(a, "ru_maxrss", ru->ru_maxrss); AppendLong2(a, "ru_ixrss", ru->ru_ixrss); AppendLong2(a, "ru_idrss", ru->ru_idrss); AppendLong2(a, "ru_isrss", ru->ru_isrss); AppendLong2(a, "ru_minflt", ru->ru_minflt); AppendLong2(a, "ru_majflt", ru->ru_majflt); AppendLong2(a, "ru_nswap", ru->ru_nswap); AppendLong2(a, "ru_inblock", ru->ru_inblock); AppendLong2(a, "ru_oublock", ru->ru_oublock); AppendLong2(a, "ru_msgsnd", ru->ru_msgsnd); AppendLong2(a, "ru_msgrcv", ru->ru_msgrcv); AppendLong2(a, "ru_nsignals", ru->ru_nsignals); AppendLong2(a, "ru_nvcsw", ru->ru_nvcsw); AppendLong2(a, "ru_nivcsw", ru->ru_nivcsw); } static void ServeCounters(void) { const long *c; const char *s; for (c = (const long *)&shared->c, s = kCounterNames; *s; ++c, s += strlen(s) + 1) { AppendLong1(s, *c); } } static char *ServeStatusz(void) { char *p; LockInc(&shared->c.statuszrequests); if (cpm.msg.method != kHttpGet && cpm.msg.method != kHttpHead) { return BadMethod(); } AppendLong1("pid", getpid()); AppendLong1("ppid", getppid()); AppendLong1("now", timespec_real().tv_sec); AppendLong1("nowish", shared->nowish.tv_sec); AppendLong1("gmtoff", gmtoff); AppendLong1("CLK_TCK", CLK_TCK); AppendLong1("startserver", startserver.tv_sec); AppendLong1("lastmeltdown", shared->lastmeltdown.tv_sec); AppendLong1("workers", shared->workers); AppendLong1("assets.n", assets.n); #ifndef STATIC lua_State *L = GL; AppendLong1("lua.memory", lua_gc(L, LUA_GCCOUNT) * 1024 + lua_gc(L, LUA_GCCOUNTB)); #endif ServeCounters(); AppendRusage("server", &shared->server); AppendRusage("children", &shared->children); p = SetStatus(200, "OK"); p = AppendContentType(p, "text/plain"); if (cpm.msg.version >= 11) { p = stpcpy(p, "Cache-Control: no-store\r\n"); } return CommitOutput(p); } static char *RedirectSlash(void) { size_t n, i; char *p, *e; LockInc(&shared->c.redirects); p = SetStatus(307, "Temporary Redirect"); p = stpcpy(p, "Location: "); e = EscapePath(url.path.p, url.path.n, &n); p = mempcpy(p, e, n); p = stpcpy(p, "/"); for (i = 0; i < url.params.n; ++i) { p = stpcpy(p, i == 0 ? "?" : "&"); p = mempcpy(p, url.params.p[i].key.p, url.params.p[i].key.n); if (url.params.p[i].val.p) { p = stpcpy(p, "="); p = mempcpy(p, url.params.p[i].val.p, url.params.p[i].val.n); } } p = stpcpy(p, "\r\n"); free(e); return p; } static char *ServeIndex(const char *path, size_t pathlen) { size_t i, n; char *p, *q; for (p = 0, i = 0; !p && i < ARRAYLEN(kIndexPaths); ++i) { q = MergePaths(path, pathlen, kIndexPaths[i], strlen(kIndexPaths[i]), &n); p = RoutePath(q, n); free(q); } return p; } static char *GetLuaResponse(void) { return cpm.luaheaderp ? cpm.luaheaderp : SetStatus(200, "OK"); } static bool ShouldServeCrashReportDetails(void) { uint32_t ip; uint16_t port; if (leakcrashreports) { return true; } else { return !GetRemoteAddr(&ip, &port) && (IsLoopbackIp(ip) || IsPrivateIp(ip)); } } static char *LuaOnHttpRequest(void) { char *error; lua_State *L = GL; effectivepath.p = url.path.p; effectivepath.n = url.path.n; lua_settop(L, 0); // clear Lua stack, as it needs to start fresh lua_getglobal(L, "OnHttpRequest"); if (LuaCallWithYield(L) == LUA_OK) { return CommitOutput(GetLuaResponse()); } else { LogLuaError("OnHttpRequest", lua_tostring(L, -1)); error = ServeErrorWithDetail( 500, "Internal Server Error", ShouldServeCrashReportDetails() ? lua_tostring(L, -1) : NULL); lua_pop(L, 1); // pop error return error; } } static char *ServeLua(struct Asset *a, const char *s, size_t n) { char *code; size_t codelen; lua_State *L = GL; LockInc(&shared->c.dynamicrequests); effectivepath.p = s; effectivepath.n = n; if ((code = FreeLater(LoadAsset(a, &codelen)))) { int status = luaL_loadbuffer(L, code, codelen, FreeLater(xasprintf("@%s", FreeLater(strndup(s, n))))); if (status == LUA_OK && LuaCallWithYield(L) == LUA_OK) { return CommitOutput(GetLuaResponse()); } else { char *error; LogLuaError("lua code", lua_tostring(L, -1)); error = ServeErrorWithDetail( 500, "Internal Server Error", ShouldServeCrashReportDetails() ? lua_tostring(L, -1) : NULL); lua_pop(L, 1); // pop error return error; } } return ServeError(500, "Internal Server Error"); } static char *HandleRedirect(struct Redirect *r) { int code; struct Asset *a; if (!r->code && (a = GetAsset(r->location.s, r->location.n))) { LockInc(&shared->c.rewrites); DEBUGF("(rsp) internal redirect to %`'s", r->location.s); if (!HasString(&cpm.loops, r->location.s, r->location.n)) { AddString(&cpm.loops, r->location.s, r->location.n); return RoutePath(r->location.s, r->location.n); } else { LockInc(&shared->c.loops); return SetStatus(508, "Loop Detected"); } } else if (cpm.msg.version < 10) { return ServeError(505, "HTTP Version Not Supported"); } else { LockInc(&shared->c.redirects); code = r->code; if (!code) code = 307; DEBUGF("(rsp) %d redirect to %`'s", code, r->location.s); return AppendHeader( SetStatus(code, GetHttpReason(code)), "Location", FreeLater(EncodeHttpHeaderValue(r->location.s, r->location.n, 0))); } } static char *HandleFolder(const char *path, size_t pathlen) { char *p; if (url.path.n && url.path.p[url.path.n - 1] != '/' && SlicesEqual(path, pathlen, url.path.p, url.path.n)) { return RedirectSlash(); } if ((p = ServeIndex(path, pathlen))) { return p; } else { LockInc(&shared->c.forbiddens); WARNF("(srvr) directory %`'.*s lacks index page", pathlen, path); return ServeError(403, "Forbidden"); } } static bool Reindex(void) { if (OpenZip(false)) { LockInc(&shared->c.reindexes); return true; } else { return false; } } static const char *LuaCheckPath(lua_State *L, int idx, size_t *pathlen) { const char *path; if (lua_isnoneornil(L, idx)) { path = url.path.p; *pathlen = url.path.n; } else { path = luaL_checklstring(L, idx, pathlen); if (!IsReasonablePath(path, *pathlen)) { WARNF("(srvr) bad path %`'.*s", *pathlen, path); luaL_argerror(L, idx, "bad path"); unreachable; } } return path; } static const char *LuaCheckHost(lua_State *L, int idx, size_t *hostlen) { const char *host; if (lua_isnoneornil(L, idx)) { host = url.host.p; *hostlen = url.host.n; } else { host = luaL_checklstring(L, idx, hostlen); if (!IsAcceptableHost(host, *hostlen)) { WARNF("(srvr) bad host %`'.*s", *hostlen, host); luaL_argerror(L, idx, "bad host"); unreachable; } } return host; } static void OnlyCallFromInitLua(lua_State *L, const char *api) { if (isinitialized) { luaL_error(L, "%s() should be called %s", api, "from the global scope of .init.lua"); unreachable; } } static void OnlyCallFromMainProcess(lua_State *L, const char *api) { if (__isworker) { luaL_error(L, "%s() should be called %s", api, "from .init.lua or the repl"); unreachable; } } static void OnlyCallDuringConnection(lua_State *L, const char *api) { if (!ishandlingconnection) { luaL_error(L, "%s() can only be called %s", api, "while handling a connection"); unreachable; } } static void OnlyCallDuringRequest(lua_State *L, const char *api) { if (!ishandlingrequest) { luaL_error(L, "%s() can only be called %s", api, "while handling a request"); unreachable; } } static int LuaServe(lua_State *L, const char *api, char *impl(void)) { OnlyCallDuringRequest(L, api); cpm.luaheaderp = impl(); return 0; } static int LuaServeListing(lua_State *L) { return LuaServe(L, "ServeListing", ServeListing); } static int LuaServeStatusz(lua_State *L) { return LuaServe(L, "ServeStatusz", ServeStatusz); } static int LuaServeAsset(lua_State *L) { size_t pathlen; struct Asset *a; const char *path; OnlyCallDuringRequest(L, "ServeAsset"); path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen)) && !S_ISDIR(GetMode(a))) { cpm.luaheaderp = ServeAsset(a, path, pathlen); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } static int LuaServeIndex(lua_State *L) { size_t pathlen; const char *path; OnlyCallDuringRequest(L, "ServeIndex"); path = LuaCheckPath(L, 1, &pathlen); lua_pushboolean(L, !!(cpm.luaheaderp = ServeIndex(path, pathlen))); return 1; } static int LuaServeRedirect(lua_State *L) { size_t loclen; const char *location, *eval; int code; OnlyCallDuringRequest(L, "ServeRedirect"); code = luaL_checkinteger(L, 1); if (!(300 <= code && code <= 399)) { luaL_argerror(L, 1, "bad status code"); unreachable; } location = luaL_checklstring(L, 2, &loclen); if (cpm.msg.version < 10) { (void)ServeError(505, "HTTP Version Not Supported"); lua_pushboolean(L, false); } else { if (!(eval = EncodeHttpHeaderValue(location, loclen, 0))) { luaL_argerror(L, 2, "invalid location"); unreachable; } VERBOSEF("(rsp) %d redirect to %`'s", code, location); cpm.luaheaderp = AppendHeader(SetStatus(code, GetHttpReason(code)), "Location", eval); free(eval); lua_pushboolean(L, true); } return 1; } static int LuaRoutePath(lua_State *L) { size_t pathlen; const char *path; OnlyCallDuringRequest(L, "RoutePath"); path = LuaCheckPath(L, 1, &pathlen); lua_pushboolean(L, !!(cpm.luaheaderp = RoutePath(path, pathlen))); return 1; } static int LuaRouteHost(lua_State *L) { size_t hostlen, pathlen; const char *host, *path; OnlyCallDuringRequest(L, "RouteHost"); host = LuaCheckHost(L, 1, &hostlen); path = LuaCheckPath(L, 2, &pathlen); lua_pushboolean(L, !!(cpm.luaheaderp = RouteHost(host, hostlen, path, pathlen))); return 1; } static int LuaRoute(lua_State *L) { size_t hostlen, pathlen; const char *host, *path; OnlyCallDuringRequest(L, "Route"); host = LuaCheckHost(L, 1, &hostlen); path = LuaCheckPath(L, 2, &pathlen); lua_pushboolean(L, !!(cpm.luaheaderp = Route(host, hostlen, path, pathlen))); return 1; } static int LuaProgramTrustedIp(lua_State *L) { lua_Integer ip, cidr; uint32_t ip32, imask; ip = luaL_checkinteger(L, 1); cidr = luaL_optinteger(L, 2, 32); if (!(0 <= ip && ip <= 0xffffffff)) { luaL_argerror(L, 1, "ip out of range"); unreachable; } if (!(0 <= cidr && cidr <= 32)) { luaL_argerror(L, 2, "cidr should be 0 .. 32"); unreachable; } ip32 = ip; imask = ~(0xffffffffu << (32 - cidr)); if (ip32 & imask) { luaL_argerror(L, 1, "ip address isn't the network address; " "it has bits masked by the cidr"); unreachable; } ProgramTrustedIp(ip, cidr); return 0; } static int LuaIsTrusted(lua_State *L) { lua_Integer ip; ip = luaL_checkinteger(L, 1); if (!(0 <= ip && ip <= 0xffffffff)) { luaL_argerror(L, 1, "ip out of range"); unreachable; } lua_pushboolean(L, IsTrustedIp(ip)); return 1; } static int LuaRespond(lua_State *L, char *R(unsigned, const char *)) { char *p; int code; size_t reasonlen; const char *reason; OnlyCallDuringRequest(L, "Respond"); code = luaL_checkinteger(L, 1); if (!(100 <= code && code <= 999)) { luaL_argerror(L, 1, "bad status code"); unreachable; } if (lua_isnoneornil(L, 2)) { cpm.luaheaderp = R(code, GetHttpReason(code)); } else { reason = lua_tolstring(L, 2, &reasonlen); if ((p = EncodeHttpHeaderValue(reason, MIN(reasonlen, 128), 0))) { cpm.luaheaderp = R(code, p); free(p); } else { luaL_argerror(L, 2, "invalid"); unreachable; } } return 0; } static int LuaSetStatus(lua_State *L) { return LuaRespond(L, SetStatus); } static int LuaGetStatus(lua_State *L) { OnlyCallDuringRequest(L, "GetStatus"); if (!cpm.statuscode) { lua_pushnil(L); } else { lua_pushinteger(L, cpm.statuscode); } return 1; } static int LuaGetSslIdentity(lua_State *L) { const mbedtls_x509_crt *cert; OnlyCallDuringRequest(L, "GetSslIdentity"); if (!usingssl) { lua_pushnil(L); } else { if (sslpskindex) { CHECK((sslpskindex - 1) >= 0 && (sslpskindex - 1) < psks.n); lua_pushlstring(L, psks.p[sslpskindex - 1].identity, psks.p[sslpskindex - 1].identity_len); } else { cert = mbedtls_ssl_get_peer_cert(&ssl); lua_pushstring(L, cert ? _gc(FormatX509Name(&cert->subject)) : ""); } } return 1; } static int LuaServeError(lua_State *L) { return LuaRespond(L, ServeError); } static int LuaLoadAsset(lua_State *L) { void *data; struct Asset *a; const char *path; size_t size, pathlen; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen))) { if (!a->file && !IsCompressed(a)) { /* fast path: this avoids extra copy */ data = ZIP_LFILE_CONTENT(zbase + a->lf); size = GetZipLfileUncompressedSize(zbase + a->lf); if (Verify(data, size, ZIP_LFILE_CRC32(zbase + a->lf))) { lua_pushlstring(L, data, size); return 1; } // any error from Verify has already been reported } else if ((data = LoadAsset(a, &size))) { lua_pushlstring(L, data, size); free(data); return 1; } else { WARNF("(srvr) could not load asset: %`'.*s", pathlen, path); } } else { WARNF("(srvr) could not find asset: %`'.*s", pathlen, path); } return 0; } static void GetDosLocalTime(int64_t utcunixts, uint16_t *out_time, uint16_t *out_date) { struct tm tm; CHECK_NOTNULL(localtime_r(&utcunixts, &tm)); *out_time = DOS_TIME(tm.tm_hour, tm.tm_min, tm.tm_sec); *out_date = DOS_DATE(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday + 1); } static void StoreAsset(char *path, size_t pathlen, char *data, size_t datalen, int mode) { int64_t ft; int i; uint32_t crc; char *comp, *p; struct timespec now; struct Asset *a; struct iovec v[13]; uint8_t *cdir, era; const char *use; uint16_t gflags, iattrs, mtime, mdate, dosmode, method, disk; size_t oldcdirsize, oldcdiroffset, records, cdiroffset, cdirsize, complen, uselen; if (IsOpenbsd() || IsNetbsd() || IsWindows()) { FATALF("(cfg) StoreAsset() not available on Windows/NetBSD/OpenBSD yet"); } INFOF("(srvr) storing asset %`'s", path); disk = gflags = iattrs = 0; if (_isutf8(path, pathlen)) gflags |= kZipGflagUtf8; if (_istext(data, datalen)) iattrs |= kZipIattrText; crc = crc32_z(0, data, datalen); if (datalen < 100) { method = kZipCompressionNone; comp = 0; use = data; uselen = datalen; era = kZipEra1989; } else { comp = Deflate(data, datalen, &complen); if (complen < datalen) { method = kZipCompressionDeflate; use = comp; uselen = complen; era = kZipEra1993; } else { method = kZipCompressionNone; use = data; uselen = datalen; era = kZipEra1989; } } ////////////////////////////////////////////////////////////////////////////// if (-1 == fcntl(zfd, F_SETLKW, &(struct flock){F_WRLCK})) { WARNF("(srvr) can't place write lock on file descriptor %d: %s", zfd, strerror(errno)); return; } OpenZip(false); now = timespec_real(); a = GetAssetZip(path, pathlen); if (!mode) mode = a ? GetMode(a) : 0644; if (!(mode & S_IFMT)) mode |= S_IFREG; if (pathlen > 1 && path[0] == '/') ++path, --pathlen; dosmode = !(mode & 0200) ? kNtFileAttributeReadonly : 0; ft = (now.tv_sec + MODERNITYSECONDS) * HECTONANOSECONDS; GetDosLocalTime(now.tv_sec, &mtime, &mdate); // local file header if (uselen >= 0xffffffff || datalen >= 0xffffffff) { era = kZipEra2001; v[2].iov_base = p = alloca((v[2].iov_len = 2 + 2 + 8 + 8)); p = WRITE16LE(p, kZipExtraZip64); p = WRITE16LE(p, 8 + 8); p = WRITE64LE(p, uselen); p = WRITE64LE(p, datalen); } else { v[2].iov_len = 0; v[2].iov_base = 0; } v[0].iov_base = p = alloca((v[0].iov_len = kZipLfileHdrMinSize)); p = WRITE32LE(p, kZipLfileHdrMagic); *p++ = era; *p++ = kZipOsDos; p = WRITE16LE(p, gflags); p = WRITE16LE(p, method); p = WRITE16LE(p, mtime); p = WRITE16LE(p, mdate); p = WRITE32LE(p, crc); p = WRITE32LE(p, MIN(uselen, 0xffffffff)); p = WRITE32LE(p, MIN(datalen, 0xffffffff)); p = WRITE16LE(p, pathlen); p = WRITE16LE(p, v[2].iov_len); v[1].iov_len = pathlen; v[1].iov_base = path; // file data v[3].iov_len = uselen; v[3].iov_base = use; // old central directory entries oldcdirsize = GetZipCdirSize(zcdir); oldcdiroffset = GetZipCdirOffset(zcdir); if (a) { // to remove an existing asset, // first copy the central directory part before its record v[4].iov_base = zbase + oldcdiroffset; v[4].iov_len = a->cf - oldcdiroffset; // and then the rest of the central directory v[5].iov_base = zbase + oldcdiroffset + (v[4].iov_len + ZIP_CFILE_HDRSIZE(zbase + a->cf)); v[5].iov_len = oldcdirsize - (v[4].iov_len + ZIP_CFILE_HDRSIZE(zbase + a->cf)); } else { v[4].iov_base = zbase + oldcdiroffset; v[4].iov_len = oldcdirsize; v[5].iov_base = 0; v[5].iov_len = 0; } // new central directory entry if (uselen >= 0xffffffff || datalen >= 0xffffffff || zsize >= 0xffffffff) { v[8].iov_base = p = alloca((v[8].iov_len = 2 + 2 + 8 + 8 + 8)); p = WRITE16LE(p, kZipExtraZip64); p = WRITE16LE(p, 8 + 8 + 8); p = WRITE64LE(p, uselen); p = WRITE64LE(p, datalen); p = WRITE64LE(p, zsize); } else { v[8].iov_len = 0; v[8].iov_base = 0; } v[9].iov_base = p = alloca((v[9].iov_len = 2 + 2 + 4 + 2 + 2 + 8 + 8 + 8)); p = WRITE16LE(p, kZipExtraNtfs); p = WRITE16LE(p, 4 + 2 + 2 + 8 + 8 + 8); p = WRITE32LE(p, 0); p = WRITE16LE(p, 1); p = WRITE16LE(p, 8 + 8 + 8); p = WRITE64LE(p, ft); p = WRITE64LE(p, ft); p = WRITE64LE(p, ft); v[6].iov_base = p = alloca((v[6].iov_len = kZipCfileHdrMinSize)); p = WRITE32LE(p, kZipCfileHdrMagic); *p++ = kZipCosmopolitanVersion; *p++ = kZipOsUnix; *p++ = era; *p++ = kZipOsDos; p = WRITE16LE(p, gflags); p = WRITE16LE(p, method); p = WRITE16LE(p, mtime); p = WRITE16LE(p, mdate); p = WRITE32LE(p, crc); p = WRITE32LE(p, MIN(uselen, 0xffffffff)); p = WRITE32LE(p, MIN(datalen, 0xffffffff)); p = WRITE16LE(p, pathlen); p = WRITE16LE(p, v[8].iov_len + v[9].iov_len); p = WRITE16LE(p, 0); p = WRITE16LE(p, disk); p = WRITE16LE(p, iattrs); p = WRITE16LE(p, dosmode); p = WRITE16LE(p, mode); p = WRITE32LE(p, MIN(zsize, 0xffffffff)); v[7].iov_len = pathlen; v[7].iov_base = path; // zip64 end of central directory cdiroffset = zsize + v[0].iov_len + v[1].iov_len + v[2].iov_len + v[3].iov_len; cdirsize = v[4].iov_len + v[5].iov_len + v[6].iov_len + v[7].iov_len + v[8].iov_len + v[9].iov_len; records = GetZipCdirRecords(zcdir) + !a; if (records >= 0xffff || cdiroffset >= 0xffffffff || cdirsize >= 0xffffffff) { v[10].iov_base = p = alloca((v[10].iov_len = kZipCdir64HdrMinSize + kZipCdir64LocatorSize)); p = WRITE32LE(p, kZipCdir64HdrMagic); p = WRITE64LE(p, 2 + 2 + 4 + 4 + 8 + 8 + 8 + 8); p = WRITE16LE(p, kZipCosmopolitanVersion); p = WRITE16LE(p, kZipEra2001); p = WRITE32LE(p, disk); p = WRITE32LE(p, disk); p = WRITE64LE(p, records); p = WRITE64LE(p, records); p = WRITE64LE(p, cdirsize); p = WRITE64LE(p, cdiroffset); p = WRITE32LE(p, kZipCdir64LocatorMagic); p = WRITE32LE(p, disk); p = WRITE64LE(p, cdiroffset + cdirsize); p = WRITE32LE(p, disk); } else { v[10].iov_len = 0; v[10].iov_base = 0; } // end of central directory v[12].iov_base = GetZipCdirComment(zcdir); v[12].iov_len = GetZipCdirCommentSize(zcdir); v[11].iov_base = p = alloca((v[11].iov_len = kZipCdirHdrMinSize)); p = WRITE32LE(p, kZipCdirHdrMagic); p = WRITE16LE(p, disk); p = WRITE16LE(p, disk); p = WRITE16LE(p, MIN(records, 0xffff)); p = WRITE16LE(p, MIN(records, 0xffff)); p = WRITE32LE(p, MIN(cdirsize, 0xffffffff)); p = WRITE32LE(p, MIN(cdiroffset, 0xffffffff)); p = WRITE16LE(p, v[12].iov_len); CHECK_NE(-1, lseek(zfd, zbase + zsize - zmap, SEEK_SET)); CHECK_NE(-1, WritevAll(zfd, v, 13)); CHECK_NE(-1, fcntl(zfd, F_SETLK, &(struct flock){F_UNLCK})); ////////////////////////////////////////////////////////////////////////////// OpenZip(false); free(comp); } static void StoreFile(char *path) { char *p; size_t plen, tlen; struct stat st; char *target = path; if (_startswith(target, "./")) target += 2; tlen = strlen(target); if (!IsReasonablePath(target, tlen)) FATALF("(cfg) error: can't store %`'s: contains '.' or '..' segments", target); if (lstat(path, &st) == -1) FATALF("(cfg) error: can't stat %`'s: %m", path); if (!(p = xslurp(path, &plen))) FATALF("(cfg) error: can't read %`'s: %m", path); StoreAsset(target, tlen, p, plen, st.st_mode & 0777); free(p); } static void StorePath(const char *dirpath) { DIR *d; char *path; struct dirent *e; if (!isdirectory(dirpath) && !_endswith(dirpath, "/")) return StoreFile(dirpath); if (!(d = opendir(dirpath))) FATALF("(cfg) error: can't open %`'s", dirpath); while ((e = readdir(d))) { if (strcmp(e->d_name, ".") == 0) continue; if (strcmp(e->d_name, "..") == 0) continue; path = _gc(xjoinpaths(dirpath, e->d_name)); if (e->d_type == DT_DIR) { StorePath(path); } else { StoreFile(path); } } closedir(d); } static int LuaStoreAsset(lua_State *L) { const char *path, *data; size_t pathlen, datalen; int mode; path = LuaCheckPath(L, 1, &pathlen); if (pathlen > 0xffff) { return luaL_argerror(L, 1, "path too long"); } data = luaL_checklstring(L, 2, &datalen); mode = luaL_optinteger(L, 3, 0); StoreAsset(path, pathlen, data, datalen, mode); return 0; } static void ReseedRng(mbedtls_ctr_drbg_context *r, const char *s) { #ifndef UNSECURE if (unsecure) return; CHECK_EQ(0, mbedtls_ctr_drbg_reseed(r, (void *)s, strlen(s))); #endif } static void LogMessage(const char *d, const char *s, size_t n) { size_t n2, n3; char *s2, *s3; if (!LOGGABLE(kLogInfo)) return; while (n && (s[n - 1] == '\r' || s[n - 1] == '\n')) --n; if ((s2 = DecodeLatin1(s, n, &n2))) { if ((s3 = IndentLines(s2, n2, &n3, 1))) { INFOF("(stat) %s %,ld byte message\r\n%.*s", d, n, n3, s3); free(s3); } free(s2); } } static void LogBody(const char *d, const char *s, size_t n) { char *s2, *s3; size_t n2, n3; if (!n) return; if (!LOGGABLE(kLogInfo)) return; while (n && (s[n - 1] == '\r' || s[n - 1] == '\n')) --n; if ((s2 = VisualizeControlCodes(s, n, &n2))) { if ((s3 = IndentLines(s2, n2, &n3, 1))) { INFOF("(stat) %s %,ld byte payload\r\n%.*s", d, n, n3, s3); free(s3); } free(s2); } } static int LuaNilError(lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); lua_pushnil(L); lua_pushvfstring(L, fmt, argp); va_end(argp); return 2; } static int LuaNilTlsError(lua_State *L, const char *s, int r) { return LuaNilError(L, "tls %s failed (%s %s)", s, IsTiny() ? "grep" : GetTlsError(r), _gc(xasprintf("-0x%04x", -r))); } #include "tool/net/fetch.inc" static int LuaGetDate(lua_State *L) { lua_pushinteger(L, shared->nowish.tv_sec); return 1; } static int LuaGetHttpVersion(lua_State *L) { OnlyCallDuringRequest(L, "GetHttpVersion"); lua_pushinteger(L, cpm.msg.version); return 1; } static int LuaGetRedbeanVersion(lua_State *L) { lua_pushinteger(L, VERSION); return 1; } static int LuaGetMethod(lua_State *L) { OnlyCallDuringRequest(L, "GetMethod"); if (cpm.msg.method) { lua_pushstring(L, kHttpMethod[cpm.msg.method]); } else { lua_pushlstring(L, inbuf.p + cpm.msg.xmethod.a, cpm.msg.xmethod.b - cpm.msg.xmethod.a); } return 1; } static int LuaGetAddr(lua_State *L, int GetAddr(uint32_t *, uint16_t *)) { uint32_t ip; uint16_t port; if (!GetAddr(&ip, &port)) { lua_pushinteger(L, ip); lua_pushinteger(L, port); return 2; } else { lua_pushnil(L); return 1; } } static int LuaGetServerAddr(lua_State *L) { OnlyCallDuringConnection(L, "GetServerAddr"); return LuaGetAddr(L, GetServerAddr); } static int LuaGetClientAddr(lua_State *L) { OnlyCallDuringConnection(L, "GetClientAddr"); return LuaGetAddr(L, GetClientAddr); } static int LuaGetRemoteAddr(lua_State *L) { OnlyCallDuringRequest(L, "GetRemoteAddr"); return LuaGetAddr(L, GetRemoteAddr); } static int LuaLog(lua_State *L) { int level, line; lua_Debug ar; const char *msg, *module; level = luaL_checkinteger(L, 1); if (LOGGABLE(level)) { msg = luaL_checkstring(L, 2); if (lua_getstack(L, 1, &ar) && lua_getinfo(L, "Sl", &ar)) { module = ar.short_src; line = ar.currentline; } else { module = _gc(strndup(effectivepath.p, effectivepath.n)); line = -1; } flogf(level, module, line, NULL, "%s", msg); } return 0; } static int LuaEncodeSmth(lua_State *L, int Encoder(lua_State *, char **, int, struct EncoderConfig)) { char *p = 0; int useoutput = false; struct EncoderConfig conf = { .maxdepth = 64, .sorted = true, .pretty = false, .indent = " ", }; if (lua_istable(L, 2)) { lua_settop(L, 2); // discard any extra arguments lua_getfield(L, 2, "useoutput"); // ignore useoutput outside of request handling if (ishandlingrequest && lua_isboolean(L, -1)) { useoutput = lua_toboolean(L, -1); } lua_getfield(L, 2, "maxdepth"); if (!lua_isnoneornil(L, -1)) { lua_Integer n = lua_tointeger(L, -1); n = MAX(0, MIN(n, SHRT_MAX)); conf.maxdepth = n; } lua_getfield(L, 2, "sorted"); if (!lua_isnoneornil(L, -1)) { conf.sorted = lua_toboolean(L, -1); } lua_getfield(L, 2, "pretty"); if (!lua_isnoneornil(L, -1)) { conf.pretty = lua_toboolean(L, -1); lua_getfield(L, 2, "indent"); if (!lua_isnoneornil(L, -1)) { conf.indent = luaL_checkstring(L, -1); } } } lua_settop(L, 1); // keep the passed argument on top if (Encoder(L, useoutput ? &cpm.outbuf : &p, -1, conf) == -1) { free(p); return 2; } if (useoutput) { lua_pushboolean(L, true); } else { lua_pushstring(L, p); free(p); } return 1; } static int LuaEncodeJson(lua_State *L) { return LuaEncodeSmth(L, LuaEncodeJsonData); } static int LuaEncodeLua(lua_State *L) { return LuaEncodeSmth(L, LuaEncodeLuaData); } static int LuaDecodeJson(lua_State *L) { size_t n; const char *p; struct DecodeJson r; p = luaL_checklstring(L, 1, &n); r = DecodeJson(L, p, n); if (UNLIKELY(!r.rc)) { lua_pushnil(L); lua_pushstring(L, "unexpected eof"); return 2; } if (UNLIKELY(r.rc == -1)) { lua_pushnil(L); lua_pushstring(L, r.p); return 2; } r = DecodeJson(L, r.p, n - (r.p - p)); if (UNLIKELY(r.rc)) { lua_pushnil(L); lua_pushstring(L, "junk after expression"); return 2; } return 1; } static int LuaGetUrl(lua_State *L) { char *p; size_t n; OnlyCallDuringRequest(L, "GetUrl"); p = EncodeUrl(&url, &n); lua_pushlstring(L, p, n); free(p); return 1; } static int LuaGetScheme(lua_State *L) { OnlyCallDuringRequest(L, "GetScheme"); LuaPushUrlView(L, &url.scheme); return 1; } static int LuaGetPath(lua_State *L) { OnlyCallDuringRequest(L, "GetPath"); LuaPushUrlView(L, &url.path); return 1; } static int LuaGetEffectivePath(lua_State *L) { OnlyCallDuringRequest(L, "GetEffectivePath"); lua_pushlstring(L, effectivepath.p, effectivepath.n); return 1; } static int LuaGetFragment(lua_State *L) { OnlyCallDuringRequest(L, "GetFragment"); LuaPushUrlView(L, &url.fragment); return 1; } static int LuaGetUser(lua_State *L) { size_t n; const char *p, *q; OnlyCallDuringRequest(L, "GetUser"); if (url.user.p) { LuaPushUrlView(L, &url.user); } else if ((p = GetBasicAuthorization(&n))) { if (!(q = memchr(p, ':', n))) q = p + n; lua_pushlstring(L, p, q - p); free(p); } else { lua_pushnil(L); } return 1; } static int LuaGetPass(lua_State *L) { size_t n; const char *p, *q; OnlyCallDuringRequest(L, "GetPass"); if (url.user.p) { LuaPushUrlView(L, &url.pass); } else if ((p = GetBasicAuthorization(&n))) { if ((q = memchr(p, ':', n))) { lua_pushlstring(L, q + 1, p + n - (q + 1)); } else { lua_pushnil(L); } free(p); } else { lua_pushnil(L); } return 1; } static int LuaGetHost(lua_State *L) { char b[16]; OnlyCallDuringRequest(L, "GetHost"); if (url.host.n) { lua_pushlstring(L, url.host.p, url.host.n); } else { inet_ntop(AF_INET, &serveraddr->sin_addr.s_addr, b, sizeof(b)); lua_pushstring(L, b); } return 1; } static int LuaGetPort(lua_State *L) { int i, x = 0; OnlyCallDuringRequest(L, "GetPort"); for (i = 0; i < url.port.n; ++i) x = url.port.p[i] - '0' + x * 10; if (!x) x = ntohs(serveraddr->sin_port); lua_pushinteger(L, x); return 1; } static int LuaGetBody(lua_State *L) { OnlyCallDuringRequest(L, "GetBody"); lua_pushlstring(L, inbuf.p + hdrsize, payloadlength); return 1; } static int LuaGetResponseBody(lua_State *L) { char *s = ""; // response can be gzipped (>0), text (=0), or generator (<0) int size = cpm.gzipped > 0 ? cpm.gzipped // original size : cpm.gzipped == 0 ? cpm.contentlength : 0; OnlyCallDuringRequest(L, "GetResponseBody"); if (cpm.gzipped > 0 && (!(s = FreeLater(malloc(cpm.gzipped))) || !Inflate(s, cpm.gzipped, cpm.content, cpm.contentlength))) { return LuaNilError(L, "failed to decompress response"); } lua_pushlstring(L, cpm.gzipped > 0 ? s // return decompressed : cpm.gzipped == 0 ? cpm.content : "", size); return 1; } static int LuaGetHeader(lua_State *L) { int h; const char *key; size_t i, keylen; OnlyCallDuringRequest(L, "GetHeader"); key = luaL_checklstring(L, 1, &keylen); if ((h = GetHttpHeader(key, keylen)) != -1) { if (cpm.msg.headers[h].a) { return LuaPushHeader(L, &cpm.msg, inbuf.p, h); } } else { for (i = 0; i < cpm.msg.xheaders.n; ++i) { if (SlicesEqualCase( key, keylen, inbuf.p + cpm.msg.xheaders.p[i].k.a, cpm.msg.xheaders.p[i].k.b - cpm.msg.xheaders.p[i].k.a)) { LuaPushLatin1(L, inbuf.p + cpm.msg.xheaders.p[i].v.a, cpm.msg.xheaders.p[i].v.b - cpm.msg.xheaders.p[i].v.a); return 1; } } } lua_pushnil(L); return 1; } static int LuaGetHeaders(lua_State *L) { OnlyCallDuringRequest(L, "GetHeaders"); return LuaPushHeaders(L, &cpm.msg, inbuf.p); } static int LuaSetHeader(lua_State *L) { int h; ssize_t rc; char *p, *q; const char *key, *val, *eval; size_t i, keylen, vallen, evallen; OnlyCallDuringRequest(L, "SetHeader"); key = luaL_checklstring(L, 1, &keylen); val = luaL_optlstring(L, 2, 0, &vallen); if (!val) return 0; if ((h = GetHttpHeader(key, keylen)) == -1) { if (!IsValidHttpToken(key, keylen)) { luaL_argerror(L, 1, "invalid"); unreachable; } } if (!(eval = EncodeHttpHeaderValue(val, vallen, &evallen))) { luaL_argerror(L, 2, "invalid"); unreachable; } p = GetLuaResponse(); while (p - hdrbuf.p + keylen + 2 + evallen + 2 + 512 > hdrbuf.n) { hdrbuf.n += hdrbuf.n >> 1; q = xrealloc(hdrbuf.p, hdrbuf.n); cpm.luaheaderp = p = q + (p - hdrbuf.p); hdrbuf.p = q; } switch (h) { case kHttpConnection: connectionclose = SlicesEqualCase(eval, evallen, "close", 5); break; case kHttpContentType: p = AppendContentType(p, eval); break; case kHttpReferrerPolicy: cpm.referrerpolicy = FreeLater(strdup(eval)); break; case kHttpServer: cpm.branded = true; p = AppendHeader(p, "Server", eval); break; case kHttpExpires: case kHttpCacheControl: cpm.gotcachecontrol = true; p = AppendHeader(p, key, eval); break; case kHttpXContentTypeOptions: cpm.gotxcontenttypeoptions = true; p = AppendHeader(p, key, eval); break; default: p = AppendHeader(p, key, eval); break; } cpm.luaheaderp = p; free(eval); return 0; } static int LuaGetCookie(lua_State *L) { char *cookie = 0, *cookietmpl, *cookieval; OnlyCallDuringRequest(L, "GetCookie"); cookietmpl = _gc(xasprintf(" %s=", luaL_checkstring(L, 1))); if (HasHeader(kHttpCookie)) { appends(&cookie, " "); // prepend space to simplify cookie search appendd(&cookie, HeaderData(kHttpCookie), HeaderLength(kHttpCookie)); } if (cookie && (cookieval = strstr(cookie, cookietmpl))) { cookieval += strlen(cookietmpl); lua_pushlstring(L, cookieval, strchrnul(cookieval, ';') - cookieval); } else { lua_pushnil(L); } if (cookie) free(cookie); return 1; } static int LuaSetCookie(lua_State *L) { const char *key, *val; size_t keylen, vallen; char *expires, *samesite = ""; char *buf = 0; bool ishostpref, issecurepref; const char *hostpref = "__Host-"; const char *securepref = "__Secure-"; OnlyCallDuringRequest(L, "SetCookie"); key = luaL_checklstring(L, 1, &keylen); val = luaL_checklstring(L, 2, &vallen); if (!IsValidHttpToken(key, keylen)) { luaL_argerror(L, 1, "invalid"); unreachable; } if (!IsValidCookieValue(val, vallen)) { luaL_argerror(L, 2, "invalid"); unreachable; } ishostpref = keylen > strlen(hostpref) && SlicesEqual(key, strlen(hostpref), hostpref, strlen(hostpref)); issecurepref = keylen > strlen(securepref) && SlicesEqual(key, strlen(securepref), securepref, strlen(securepref)); if ((ishostpref || issecurepref) && !usingssl) { luaL_argerror( L, 1, _gc(xasprintf("%s and %s prefixes require SSL", hostpref, securepref))); unreachable; } appends(&buf, key); appends(&buf, "="); appends(&buf, val); if (lua_istable(L, 3)) { if (lua_getfield(L, 3, "expires") != LUA_TNIL || lua_getfield(L, 3, "Expires") != LUA_TNIL) { if (lua_isnumber(L, -1)) { expires = FormatUnixHttpDateTime(FreeLater(xmalloc(30)), lua_tonumber(L, -1)); } else { expires = lua_tostring(L, -1); if (!ParseHttpDateTime(expires, -1)) { luaL_argerror(L, 3, "invalid data format in Expires"); unreachable; } } appends(&buf, "; Expires="); appends(&buf, expires); } if ((lua_getfield(L, 3, "maxage") == LUA_TNUMBER || lua_getfield(L, 3, "MaxAge") == LUA_TNUMBER) && lua_isinteger(L, -1)) { appends(&buf, "; Max-Age="); appends(&buf, lua_tostring(L, -1)); } if (lua_getfield(L, 3, "samesite") == LUA_TSTRING || lua_getfield(L, 3, "SameSite") == LUA_TSTRING) { samesite = lua_tostring(L, -1); // also used in the Secure check appends(&buf, "; SameSite="); appends(&buf, samesite); } // Secure attribute is required for __Host and __Secure prefixes // as well as for the SameSite=None if (ishostpref || issecurepref || !strcmp(samesite, "None") || ((lua_getfield(L, 3, "secure") == LUA_TBOOLEAN || lua_getfield(L, 3, "Secure") == LUA_TBOOLEAN) && lua_toboolean(L, -1))) { appends(&buf, "; Secure"); } if (!ishostpref && (lua_getfield(L, 3, "domain") == LUA_TSTRING || lua_getfield(L, 3, "Domain") == LUA_TSTRING)) { appends(&buf, "; Domain="); appends(&buf, lua_tostring(L, -1)); } if (ishostpref || lua_getfield(L, 3, "path") == LUA_TSTRING || lua_getfield(L, 3, "Path") == LUA_TSTRING) { appends(&buf, "; Path="); appends(&buf, ishostpref ? "/" : lua_tostring(L, -1)); } if ((lua_getfield(L, 3, "httponly") == LUA_TBOOLEAN || lua_getfield(L, 3, "HttpOnly") == LUA_TBOOLEAN) && lua_toboolean(L, -1)) { appends(&buf, "; HttpOnly"); } } DEBUGF("(srvr) Set-Cookie: %s", buf); // empty the stack and push header name/value lua_settop(L, 0); lua_pushliteral(L, "Set-Cookie"); lua_pushstring(L, buf); free(buf); return LuaSetHeader(L); } static int LuaHasParam(lua_State *L) { size_t i, n; const char *s; OnlyCallDuringRequest(L, "HasParam"); s = luaL_checklstring(L, 1, &n); for (i = 0; i < url.params.n; ++i) { if (SlicesEqual(s, n, url.params.p[i].key.p, url.params.p[i].key.n)) { lua_pushboolean(L, true); return 1; } } lua_pushboolean(L, false); return 1; } static int LuaGetParam(lua_State *L) { size_t i, n; const char *s; OnlyCallDuringRequest(L, "GetParam"); s = luaL_checklstring(L, 1, &n); for (i = 0; i < url.params.n; ++i) { if (SlicesEqual(s, n, url.params.p[i].key.p, url.params.p[i].key.n)) { if (url.params.p[i].val.p) { lua_pushlstring(L, url.params.p[i].val.p, url.params.p[i].val.n); return 1; } else { break; } } } lua_pushnil(L); return 1; } static int LuaGetParams(lua_State *L) { OnlyCallDuringRequest(L, "GetParams"); LuaPushUrlParams(L, &url.params); return 1; } static int LuaWrite(lua_State *L) { size_t size; const char *data; OnlyCallDuringRequest(L, "Write"); if (!lua_isnil(L, 1)) { data = luaL_checklstring(L, 1, &size); appendd(&cpm.outbuf, data, size); } return 0; } static dontinline int LuaProgramInt(lua_State *L, void P(long)) { P(luaL_checkinteger(L, 1)); return 0; } static int LuaProgramPort(lua_State *L) { OnlyCallFromInitLua(L, "ProgramPort"); return LuaProgramInt(L, ProgramPort); } static int LuaProgramCache(lua_State *L) { OnlyCallFromMainProcess(L, "ProgramCache"); ProgramCache(luaL_checkinteger(L, 1), luaL_optstring(L, 2, NULL)); return 0; } static int LuaProgramTimeout(lua_State *L) { OnlyCallFromInitLua(L, "ProgramTimeout"); return LuaProgramInt(L, ProgramTimeout); } static int LuaProgramUid(lua_State *L) { OnlyCallFromInitLua(L, "ProgramUid"); return LuaProgramInt(L, ProgramUid); } static int LuaProgramGid(lua_State *L) { OnlyCallFromInitLua(L, "ProgramGid"); return LuaProgramInt(L, ProgramGid); } static int LuaProgramMaxPayloadSize(lua_State *L) { OnlyCallFromInitLua(L, "ProgramMaxPayloadSize"); return LuaProgramInt(L, ProgramMaxPayloadSize); } static int LuaGetClientFd(lua_State *L) { OnlyCallDuringConnection(L, "GetClientFd"); lua_pushinteger(L, client); return 1; } static int LuaIsClientUsingSsl(lua_State *L) { OnlyCallDuringConnection(L, "IsClientUsingSsl"); lua_pushboolean(L, usingssl); return 1; } static int LuaProgramSslTicketLifetime(lua_State *L) { OnlyCallFromInitLua(L, "ProgramSslTicketLifetime"); return LuaProgramInt(L, ProgramSslTicketLifetime); } static int LuaProgramUniprocess(lua_State *L) { OnlyCallFromInitLua(L, "ProgramUniprocess"); if (!lua_isboolean(L, 1) && !lua_isnoneornil(L, 1)) { return luaL_argerror(L, 1, "invalid uniprocess mode; boolean expected"); } lua_pushboolean(L, uniprocess); if (lua_isboolean(L, 1)) uniprocess = lua_toboolean(L, 1); return 1; } static int LuaProgramHeartbeatInterval(lua_State *L) { int64_t millis; OnlyCallFromMainProcess(L, "ProgramHeartbeatInterval"); if (!lua_isnoneornil(L, 1)) { millis = luaL_checkinteger(L, 1); millis = MAX(100, millis); heartbeatinterval = timespec_frommillis(millis); } lua_pushinteger(L, timespec_tomillis(heartbeatinterval)); return 1; } static int LuaProgramMaxWorkers(lua_State *L) { OnlyCallFromMainProcess(L, "ProgramMaxWorkers"); if (!lua_isinteger(L, 1) && !lua_isnoneornil(L, 1)) { return luaL_argerror(L, 1, "invalid number of workers; integer expected"); } lua_pushinteger(L, maxworkers); if (lua_isinteger(L, 1)) maxworkers = lua_tointeger(L, 1); maxworkers = MAX(maxworkers, 1); return 1; } static int LuaProgramAddr(lua_State *L) { uint32_t ip; OnlyCallFromInitLua(L, "ProgramAddr"); if (lua_isinteger(L, 1)) { ip = luaL_checkinteger(L, 1); ips.p = realloc(ips.p, ++ips.n * sizeof(*ips.p)); ips.p[ips.n - 1] = ip; } else { ProgramAddr(luaL_checkstring(L, 1)); } return 0; } static dontinline int LuaProgramString(lua_State *L, void P(const char *)) { P(luaL_checkstring(L, 1)); return 0; } static int LuaProgramBrand(lua_State *L) { OnlyCallFromMainProcess(L, "ProgramBrand"); return LuaProgramString(L, ProgramBrand); } static int LuaProgramDirectory(lua_State *L) { return LuaProgramString(L, ProgramDirectory); } static int LuaProgramLogPath(lua_State *L) { OnlyCallFromInitLua(L, "ProgramLogPath"); return LuaProgramString(L, ProgramLogPath); } static int LuaProgramPidPath(lua_State *L) { OnlyCallFromInitLua(L, "ProgramPidPath"); return LuaProgramString(L, ProgramPidPath); } static int LuaProgramSslPresharedKey(lua_State *L) { struct Psk psk; size_t n1, n2, i; const char *p1, *p2; OnlyCallFromMainProcess(L, "ProgramSslPresharedKey"); p1 = luaL_checklstring(L, 1, &n1); p2 = luaL_checklstring(L, 2, &n2); if (!n1 || n1 > MBEDTLS_PSK_MAX_LEN || !n2) { luaL_argerror(L, 1, "bad preshared key length"); unreachable; } psk.key = memcpy(malloc(n1), p1, n1); psk.key_len = n1; psk.identity = memcpy(malloc(n2), p2, n2); psk.identity_len = n2; for (i = 0; i < psks.n; ++i) { if (SlicesEqual(psk.identity, psk.identity_len, psks.p[i].identity, psks.p[i].identity_len)) { mbedtls_platform_zeroize(psks.p[i].key, psks.p[i].key_len); free(psks.p[i].key); free(psks.p[i].identity); psks.p[i] = psk; return 0; } } psks.p = realloc(psks.p, ++psks.n * sizeof(*psks.p)); psks.p[psks.n - 1] = psk; return 0; } static int LuaProgramSslCiphersuite(lua_State *L) { mbedtls_ssl_ciphersuite_t *suite; OnlyCallFromInitLua(L, "ProgramSslCiphersuite"); if (!(suite = GetCipherSuite(luaL_checkstring(L, 1)))) { luaL_argerror(L, 1, "unsupported or unknown ciphersuite"); unreachable; } suites.p = realloc(suites.p, (++suites.n + 1) * sizeof(*suites.p)); suites.p[suites.n - 1] = suite->id; suites.p[suites.n - 0] = 0; return 0; } static int LuaProgramPrivateKey(lua_State *L) { size_t n; const char *p; OnlyCallFromInitLua(L, "ProgramPrivateKey"); p = luaL_checklstring(L, 1, &n); ProgramPrivateKey(p, n); return 0; } static int LuaProgramCertificate(lua_State *L) { size_t n; const char *p; OnlyCallFromInitLua(L, "ProgramCertificate"); p = luaL_checklstring(L, 1, &n); ProgramCertificate(p, n); return 0; } static int LuaProgramHeader(lua_State *L) { ProgramHeader( _gc(xasprintf("%s: %s", luaL_checkstring(L, 1), luaL_checkstring(L, 2)))); return 0; } static int LuaProgramRedirect(lua_State *L) { int code; const char *from, *to; code = luaL_checkinteger(L, 1); from = luaL_checkstring(L, 2); to = luaL_checkstring(L, 3); ProgramRedirect(code, strdup(from), strlen(from), strdup(to), strlen(to)); return 0; } static dontinline int LuaProgramBool(lua_State *L, bool *b) { *b = lua_toboolean(L, 1); return 0; } static int LuaProgramSslClientVerify(lua_State *L) { OnlyCallFromInitLua(L, "ProgramSslClientVerify"); return LuaProgramBool(L, &sslclientverify); } static int LuaProgramSslRequired(lua_State *L) { OnlyCallFromInitLua(L, "ProgramSslRequired"); return LuaProgramBool(L, &requiressl); } static int LuaProgramSslFetchVerify(lua_State *L) { OnlyCallFromMainProcess(L, "ProgramSslFetchVerify"); return LuaProgramBool(L, &sslfetchverify); } static int LuaProgramSslInit(lua_State *L) { OnlyCallFromInitLua(L, "SslInit"); TlsInit(); return 0; } static int LuaProgramLogMessages(lua_State *L) { return LuaProgramBool(L, &logmessages); } static int LuaProgramLogBodies(lua_State *L) { return LuaProgramBool(L, &logbodies); } static int LuaEvadeDragnetSurveillance(lua_State *L) { return LuaProgramBool(L, &evadedragnetsurveillance); } static int LuaHidePath(lua_State *L) { size_t pathlen; const char *path; path = luaL_checklstring(L, 1, &pathlen); AddString(&hidepaths, memcpy(malloc(pathlen), path, pathlen), pathlen); return 0; } static int LuaIsHiddenPath(lua_State *L) { size_t n; const char *s; s = luaL_checklstring(L, 1, &n); lua_pushboolean(L, IsHiddenPath(s, n)); return 1; } static int LuaGetZipPaths(lua_State *L) { char *path; uint8_t *zcf; size_t i, n, pathlen, prefixlen; char *prefix = luaL_optlstring(L, 1, "", &prefixlen); lua_newtable(L); i = 0; n = GetZipCdirRecords(zcdir); for (zcf = zbase + GetZipCdirOffset(zcdir); n--; zcf += ZIP_CFILE_HDRSIZE(zcf)) { CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(zcf)); path = GetAssetPath(zcf, &pathlen); if (prefixlen == 0 || _startswith(path, prefix)) { lua_pushlstring(L, path, pathlen); lua_seti(L, -2, ++i); } free(path); } return 1; } static int LuaGetAssetMode(lua_State *L) { size_t pathlen; struct Asset *a; const char *path; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen))) { lua_pushinteger(L, GetMode(a)); } else { lua_pushnil(L); } return 1; } static int LuaGetAssetLastModifiedTime(lua_State *L) { size_t pathlen; struct Asset *a; const char *path; struct timespec lm; int64_t zuluseconds; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen))) { if (a->file) { zuluseconds = a->file->st.st_mtim.tv_sec; } else { GetZipCfileTimestamps(zbase + a->cf, &lm, 0, 0, gmtoff); zuluseconds = lm.tv_sec; } lua_pushinteger(L, zuluseconds); } else { lua_pushnil(L); } return 1; } static int LuaGetAssetSize(lua_State *L) { size_t pathlen; struct Asset *a; const char *path; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen))) { if (a->file) { lua_pushinteger(L, a->file->st.st_size); } else { lua_pushinteger(L, GetZipLfileUncompressedSize(zbase + a->lf)); } } else { lua_pushnil(L); } return 1; } static int LuaIsAssetCompressed(lua_State *L) { size_t pathlen; struct Asset *a; const char *path; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAsset(path, pathlen))) { lua_pushboolean(L, IsCompressed(a)); } else { lua_pushnil(L); } return 1; } static bool Blackhole(uint32_t ip) { char buf[4]; if (blackhole.fd <= 0) return false; WRITE32BE(buf, ip); if (sendto(blackhole.fd, &buf, 4, 0, (struct sockaddr *)&blackhole.addr, sizeof(blackhole.addr)) != -1) { return true; } else { VERBOSEF("(token) sendto(%s) failed: %m", blackhole.addr.sun_path); errno = 0; return false; } } static int LuaBlackhole(lua_State *L) { lua_Integer ip; ip = luaL_checkinteger(L, 1); if (!(0 <= ip && ip <= 0xffffffff)) { luaL_argerror(L, 1, "ip out of range"); unreachable; } lua_pushboolean(L, Blackhole(ip)); return 1; } wontreturn static void Replenisher(void) { struct timespec ts; VERBOSEF("(token) replenish worker started"); signal(SIGINT, OnTerm); signal(SIGHUP, OnTerm); signal(SIGTERM, OnTerm); signal(SIGUSR1, SIG_IGN); // make sure reload won't kill this signal(SIGUSR2, SIG_IGN); // make sure meltdown won't kill this ts = timespec_real(); while (!terminated) { if (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &ts, 0)) { errno = 0; continue; } ReplenishTokens(tokenbucket.w, (1ul << tokenbucket.cidr) / 8); ts = timespec_add(ts, tokenbucket.replenish); DEBUGF("(token) replenished tokens"); } VERBOSEF("(token) replenish worker exiting"); _Exit(0); } static int LuaAcquireToken(lua_State *L) { uint32_t ip; if (!tokenbucket.cidr) { luaL_error(L, "ProgramTokenBucket() needs to be called first"); unreachable; } GetClientAddr(&ip, 0); lua_pushinteger(L, AcquireToken(tokenbucket.b, luaL_optinteger(L, 1, ip), tokenbucket.cidr)); return 1; } static int LuaCountTokens(lua_State *L) { uint32_t ip; if (!tokenbucket.cidr) { luaL_error(L, "ProgramTokenBucket() needs to be called first"); unreachable; } GetClientAddr(&ip, 0); lua_pushinteger(L, CountTokens(tokenbucket.b, luaL_optinteger(L, 1, ip), tokenbucket.cidr)); return 1; } static int LuaProgramTokenBucket(lua_State *L) { if (tokenbucket.cidr) { luaL_error(L, "ProgramTokenBucket() can only be called once"); unreachable; } lua_Number replenish = luaL_optnumber(L, 1, 1); // per second lua_Integer cidr = luaL_optinteger(L, 2, 24); lua_Integer reject = luaL_optinteger(L, 3, 30); lua_Integer ignore = luaL_optinteger(L, 4, MIN(reject / 2, 15)); lua_Integer ban = luaL_optinteger(L, 5, MIN(ignore / 10, 1)); if (!(1 / 3600. <= replenish && replenish <= 1e6)) { luaL_argerror(L, 1, "require 1/3600 <= replenish <= 1e6"); unreachable; } if (!(8 <= cidr && cidr <= 32)) { luaL_argerror(L, 2, "require 8 <= cidr <= 32"); unreachable; } if (!(-1 <= reject && reject <= 126)) { luaL_argerror(L, 3, "require -1 <= reject <= 126"); unreachable; } if (!(-1 <= ignore && ignore <= 126)) { luaL_argerror(L, 4, "require -1 <= ignore <= 126"); unreachable; } if (!(-1 <= ban && ban <= 126)) { luaL_argerror(L, 5, "require -1 <= ban <= 126"); unreachable; } if (!(ignore <= reject)) { luaL_argerror(L, 4, "require ignore <= reject"); unreachable; } if (!(ban <= ignore)) { luaL_argerror(L, 5, "require ban <= ignore"); unreachable; } VERBOSEF("(token) deploying %,ld buckets " "(one for every %ld ips) " "each holding 127 tokens which " "replenish %g times per second, " "reject at %d tokens, " "ignore at %d tokens, and " "ban at %d tokens", 1L << cidr, // 4294967296 / (1L << cidr), // replenish, // reject, // ignore, // ban); if (ignore == -1) ignore = -128; if (ban == -1) ban = -128; if (ban >= 0 && (IsLinux() || IsBsd())) { uint32_t testip = 0; blackhole.addr.sun_family = AF_UNIX; strlcpy(blackhole.addr.sun_path, "/var/run/blackhole.sock", sizeof(blackhole.addr.sun_path)); if ((blackhole.fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0)) == -1) { WARNF("(token) socket(AF_UNIX) failed: %m"); ban = -1; } else if (sendto(blackhole.fd, &testip, 4, 0, (struct sockaddr *)&blackhole.addr, sizeof(blackhole.addr)) == -1) { VERBOSEF("(token) error: sendto(%`'s) failed: %m", blackhole.addr.sun_path); VERBOSEF("(token) redbean isn't able to protect your kernel from ddos"); VERBOSEF("(token) please run the blackholed program; see our website!"); } } tokenbucket.b = _mapshared(ROUNDUP(1ul << cidr, FRAMESIZE)); memset(tokenbucket.b, 127, 1ul << cidr); tokenbucket.cidr = cidr; tokenbucket.reject = reject; tokenbucket.ignore = ignore; tokenbucket.ban = ban; tokenbucket.replenish = timespec_fromnanos(1 / replenish * 1e9); int pid = fork(); _npassert(pid != -1); if (!pid) Replenisher(); return 0; } static const char *GetContentTypeExt(const char *path, size_t n) { char *r, *e; int top; lua_State *L = GL; if ((r = FindContentType(path, n))) return r; // extract the last .; use the entire path if none is present if (e = strrchr(path, '.')) path = e + 1; top = lua_gettop(L); lua_pushlightuserdata(L, (void *)&ctIdx); // push address as unique key CHECK_EQ(lua_gettable(L, LUA_REGISTRYINDEX), LUA_TTABLE); lua_pushstring(L, path); if (lua_gettable(L, -2) == LUA_TSTRING) r = FreeLater(strdup(lua_tostring(L, -1))); lua_settop(L, top); return r; } static int LuaProgramContentType(lua_State *L) { const char *ext = luaL_checkstring(L, 1); const char *ct; int n = lua_gettop(L); lua_pushlightuserdata(L, (void *)&ctIdx); // push address as unique key CHECK_EQ(lua_gettable(L, LUA_REGISTRYINDEX), LUA_TTABLE); if (n == 1) { ext = FreeLater(xasprintf(".%s", ext)); if ((ct = GetContentTypeExt(ext, strlen(ext)))) { lua_pushstring(L, ct); } else { lua_pushnil(L); } return 1; } else { ct = luaL_checkstring(L, 2); lua_pushstring(L, ext); lua_pushstring(L, ct); lua_settable(L, -3); // table[ext] = ct return 0; } } static int LuaIsDaemon(lua_State *L) { lua_pushboolean(L, daemonize); return 1; } static int LuaGetAssetComment(lua_State *L) { struct Asset *a; const char *path; size_t pathlen, m; path = LuaCheckPath(L, 1, &pathlen); if ((a = GetAssetZip(path, pathlen)) && (m = strnlen(ZIP_CFILE_COMMENT(zbase + a->cf), ZIP_CFILE_COMMENTSIZE(zbase + a->cf)))) { lua_pushlstring(L, ZIP_CFILE_COMMENT(zbase + a->cf), m); } else { lua_pushnil(L); } return 1; } static int LuaLaunchBrowser(lua_State *L) { OnlyCallFromInitLua(L, "LaunchBrowser"); launchbrowser = strdup(luaL_optstring(L, 1, "/")); return 0; } static bool LuaRunAsset(const char *path, bool mandatory) { int status; struct Asset *a; const char *code; size_t pathlen, codelen; pathlen = strlen(path); if ((a = GetAsset(path, pathlen))) { if ((code = FreeLater(LoadAsset(a, &codelen)))) { lua_State *L = GL; effectivepath.p = path; effectivepath.n = pathlen; DEBUGF("(lua) LuaRunAsset(%`'s)", path); status = luaL_loadbuffer( L, code, codelen, FreeLater(xasprintf("@%s%s", a->file ? "" : "/zip", path))); if (status != LUA_OK || LuaCallWithTrace(L, 0, 0, NULL) != LUA_OK) { LogLuaError("lua code", lua_tostring(L, -1)); lua_pop(L, 1); // pop error if (mandatory) exit(1); } } } return !!a; } // <SORTED> // list of functions that can't be run from the repl static const char *const kDontAutoComplete[] = { "Compress", // deprecated "GetBody", // "GetClientAddr", // "GetClientFd", // "GetComment", // deprecated "GetCookie", // "GetEffectivePath", // "GetFragment", // "GetHeader", // "GetHeaders", // "GetHost", // "GetHttpVersion", // "GetLastModifiedTime", // deprecated "GetMethod", // "GetParam", // "GetParams", // "GetPass", // "GetPath", // "GetPayload", // deprecated "GetPort", // "GetRemoteAddr", // "GetResponseBody", // "GetScheme", // "GetServerAddr", // "GetSslIdentity", // "GetStatus", // "GetUrl", // "GetUser", // "GetVersion", // deprecated "HasParam", // "IsClientUsingSsl", // "IsCompressed", // deprecated "LaunchBrowser", // "LuaProgramSslRequired", // TODO "ProgramAddr", // TODO "ProgramBrand", // "ProgramCertificate", // TODO "ProgramGid", // "ProgramLogPath", // TODO "ProgramMaxPayloadSize", // TODO "ProgramPidPath", // TODO "ProgramPort", // TODO "ProgramPrivateKey", // TODO "ProgramSslCiphersuite", // TODO "ProgramSslClientVerify", // TODO "ProgramSslTicketLifetime", // "ProgramTimeout", // TODO "ProgramUid", // "ProgramUniprocess", // "Respond", // "Route", // "RouteHost", // "RoutePath", // "ServeAsset", // "ServeIndex", // "ServeListing", // "ServeRedirect", // "ServeStatusz", // "SetCookie", // "SetHeader", // "SslInit", // TODO "Uncompress", // deprecated "Write", // }; // </SORTED> static const luaL_Reg kLuaFuncs[] = { {"Barf", LuaBarf}, // {"Benchmark", LuaBenchmark}, // {"Bsf", LuaBsf}, // {"Bsr", LuaBsr}, // {"CategorizeIp", LuaCategorizeIp}, // {"Compress", LuaCompress}, // {"Crc32", LuaCrc32}, // {"Crc32c", LuaCrc32c}, // {"Decimate", LuaDecimate}, // {"DecodeBase64", LuaDecodeBase64}, // {"DecodeJson", LuaDecodeJson}, // {"DecodeLatin1", LuaDecodeLatin1}, // {"Deflate", LuaDeflate}, // {"EncodeBase64", LuaEncodeBase64}, // {"EncodeJson", LuaEncodeJson}, // {"EncodeLatin1", LuaEncodeLatin1}, // {"EncodeLua", LuaEncodeLua}, // {"EncodeUrl", LuaEncodeUrl}, // {"EscapeFragment", LuaEscapeFragment}, // {"EscapeHost", LuaEscapeHost}, // {"EscapeHtml", LuaEscapeHtml}, // {"EscapeIp", LuaEscapeIp}, // {"EscapeLiteral", LuaEscapeLiteral}, // {"EscapeParam", LuaEscapeParam}, // {"EscapePass", LuaEscapePass}, // {"EscapePath", LuaEscapePath}, // {"EscapeSegment", LuaEscapeSegment}, // {"EscapeUser", LuaEscapeUser}, // {"Fetch", LuaFetch}, // {"FormatHttpDateTime", LuaFormatHttpDateTime}, // {"FormatIp", LuaFormatIp}, // {"GetAssetComment", LuaGetAssetComment}, // {"GetAssetLastModifiedTime", LuaGetAssetLastModifiedTime}, // {"GetAssetMode", LuaGetAssetMode}, // {"GetAssetSize", LuaGetAssetSize}, // {"GetBody", LuaGetBody}, // {"GetClientAddr", LuaGetClientAddr}, // {"GetClientFd", LuaGetClientFd}, // {"GetCookie", LuaGetCookie}, // {"GetCpuCore", LuaGetCpuCore}, // {"GetCpuCount", LuaGetCpuCount}, // {"GetCpuNode", LuaGetCpuNode}, // {"GetCryptoHash", LuaGetCryptoHash}, // {"GetDate", LuaGetDate}, // {"GetEffectivePath", LuaGetEffectivePath}, // {"GetFragment", LuaGetFragment}, // {"GetHeader", LuaGetHeader}, // {"GetHeaders", LuaGetHeaders}, // {"GetHost", LuaGetHost}, // {"GetHostIsa", LuaGetHostIsa}, // {"GetHostOs", LuaGetHostOs}, // {"GetHttpReason", LuaGetHttpReason}, // {"GetHttpVersion", LuaGetHttpVersion}, // {"GetLogLevel", LuaGetLogLevel}, // {"GetMethod", LuaGetMethod}, // {"GetMonospaceWidth", LuaGetMonospaceWidth}, // {"GetParam", LuaGetParam}, // {"GetParams", LuaGetParams}, // {"GetPass", LuaGetPass}, // {"GetPath", LuaGetPath}, // {"GetPort", LuaGetPort}, // {"GetRandomBytes", LuaGetRandomBytes}, // {"GetRedbeanVersion", LuaGetRedbeanVersion}, // {"GetRemoteAddr", LuaGetRemoteAddr}, // {"GetResponseBody", LuaGetResponseBody}, // {"GetScheme", LuaGetScheme}, // {"GetServerAddr", LuaGetServerAddr}, // {"GetStatus", LuaGetStatus}, // {"GetTime", LuaGetTime}, // {"GetUrl", LuaGetUrl}, // {"GetUser", LuaGetUser}, // {"GetZipPaths", LuaGetZipPaths}, // {"HasControlCodes", LuaHasControlCodes}, // {"HasParam", LuaHasParam}, // {"HidePath", LuaHidePath}, // {"IndentLines", LuaIndentLines}, // {"Inflate", LuaInflate}, // {"IsAcceptableHost", LuaIsAcceptableHost}, // {"IsAcceptablePath", LuaIsAcceptablePath}, // {"IsAcceptablePort", LuaIsAcceptablePort}, // {"IsAssetCompressed", LuaIsAssetCompressed}, // {"IsClientUsingSsl", LuaIsClientUsingSsl}, // {"IsDaemon", LuaIsDaemon}, // {"IsHeaderRepeatable", LuaIsHeaderRepeatable}, // {"IsHiddenPath", LuaIsHiddenPath}, // {"IsLoopbackIp", LuaIsLoopbackIp}, // {"IsPrivateIp", LuaIsPrivateIp}, // {"IsPublicIp", LuaIsPublicIp}, // {"IsReasonablePath", LuaIsReasonablePath}, // {"IsTrustedIp", LuaIsTrusted}, // undocumented {"IsValidHttpToken", LuaIsValidHttpToken}, // {"LaunchBrowser", LuaLaunchBrowser}, // {"Lemur64", LuaLemur64}, // {"LoadAsset", LuaLoadAsset}, // {"Log", LuaLog}, // {"Md5", LuaMd5}, // {"MeasureEntropy", LuaMeasureEntropy}, // {"ParseHost", LuaParseHost}, // {"ParseHttpDateTime", LuaParseHttpDateTime}, // {"ParseIp", LuaParseIp}, // {"ParseParams", LuaParseParams}, // {"ParseUrl", LuaParseUrl}, // {"Popcnt", LuaPopcnt}, // {"ProgramAddr", LuaProgramAddr}, // {"ProgramBrand", LuaProgramBrand}, // {"ProgramCache", LuaProgramCache}, // {"ProgramContentType", LuaProgramContentType}, // {"ProgramDirectory", LuaProgramDirectory}, // {"ProgramGid", LuaProgramGid}, // {"ProgramHeader", LuaProgramHeader}, // {"ProgramHeartbeatInterval", LuaProgramHeartbeatInterval}, // {"ProgramLogBodies", LuaProgramLogBodies}, // {"ProgramLogMessages", LuaProgramLogMessages}, // {"ProgramLogPath", LuaProgramLogPath}, // {"ProgramMaxPayloadSize", LuaProgramMaxPayloadSize}, // {"ProgramMaxWorkers", LuaProgramMaxWorkers}, // {"ProgramPidPath", LuaProgramPidPath}, // {"ProgramPort", LuaProgramPort}, // {"ProgramRedirect", LuaProgramRedirect}, // {"ProgramTimeout", LuaProgramTimeout}, // {"ProgramTrustedIp", LuaProgramTrustedIp}, // undocumented {"ProgramUid", LuaProgramUid}, // {"ProgramUniprocess", LuaProgramUniprocess}, // {"Rand64", LuaRand64}, // {"Rdrand", LuaRdrand}, // {"Rdseed", LuaRdseed}, // {"Rdtsc", LuaRdtsc}, // {"ResolveIp", LuaResolveIp}, // {"Route", LuaRoute}, // {"RouteHost", LuaRouteHost}, // {"RoutePath", LuaRoutePath}, // {"ServeAsset", LuaServeAsset}, // {"ServeError", LuaServeError}, // {"ServeIndex", LuaServeIndex}, // {"ServeListing", LuaServeListing}, // {"ServeRedirect", LuaServeRedirect}, // {"ServeStatusz", LuaServeStatusz}, // {"SetCookie", LuaSetCookie}, // {"SetHeader", LuaSetHeader}, // {"SetLogLevel", LuaSetLogLevel}, // {"SetStatus", LuaSetStatus}, // {"Sha1", LuaSha1}, // {"Sha224", LuaSha224}, // {"Sha256", LuaSha256}, // {"Sha384", LuaSha384}, // {"Sha512", LuaSha512}, // {"Sleep", LuaSleep}, // {"Slurp", LuaSlurp}, // {"StoreAsset", LuaStoreAsset}, // {"Uncompress", LuaUncompress}, // {"Underlong", LuaUnderlong}, // {"VisualizeControlCodes", LuaVisualizeControlCodes}, // {"Write", LuaWrite}, // {"bin", LuaBin}, // {"hex", LuaHex}, // {"oct", LuaOct}, // #ifndef UNSECURE {"AcquireToken", LuaAcquireToken}, // {"Blackhole", LuaBlackhole}, // undocumented {"CountTokens", LuaCountTokens}, // {"EvadeDragnetSurveillance", LuaEvadeDragnetSurveillance}, // {"GetSslIdentity", LuaGetSslIdentity}, // {"ProgramCertificate", LuaProgramCertificate}, // {"ProgramPrivateKey", LuaProgramPrivateKey}, // {"ProgramSslCiphersuite", LuaProgramSslCiphersuite}, // {"ProgramSslClientVerify", LuaProgramSslClientVerify}, // {"ProgramSslFetchVerify", LuaProgramSslFetchVerify}, // {"ProgramSslInit", LuaProgramSslInit}, // {"ProgramSslPresharedKey", LuaProgramSslPresharedKey}, // {"ProgramSslRequired", LuaProgramSslRequired}, // {"ProgramSslTicketLifetime", LuaProgramSslTicketLifetime}, // {"ProgramTokenBucket", LuaProgramTokenBucket}, // #endif // deprecated {"GetPayload", LuaGetBody}, // {"GetComment", LuaGetAssetComment}, // {"GetVersion", LuaGetHttpVersion}, // {"IsCompressed", LuaIsAssetCompressed}, // {"GetLastModifiedTime", LuaGetAssetLastModifiedTime}, // }; static const luaL_Reg kLuaLibs[] = { {"argon2", luaopen_argon2}, // {"lsqlite3", luaopen_lsqlite3}, // {"maxmind", LuaMaxmind}, // {"finger", LuaFinger}, // {"path", LuaPath}, // {"re", LuaRe}, // {"unix", LuaUnix}, // }; static void LuaSetArgv(lua_State *L) { int i, j = -1; lua_newtable(L); lua_pushstring(L, __argv[0]); lua_seti(L, -2, j++); if (!interpretermode) { lua_pushstring(L, "/zip/.init.lua"); lua_seti(L, -2, j++); } for (i = optind; i < __argc; ++i) { lua_pushstring(L, __argv[i]); lua_seti(L, -2, j++); } lua_pushvalue(L, -1); lua_setglobal(L, "argv"); // deprecated lua_setglobal(L, "arg"); } static void LuaSetConstant(lua_State *L, const char *s, long x) { lua_pushinteger(L, x); lua_setglobal(L, s); } static char *GetDefaultLuaPath(void) { char *s; size_t i; for (s = 0, i = 0; i < stagedirs.n; ++i) { appendf(&s, "%s/.lua/?.lua;%s/.lua/?/init.lua;", stagedirs.p[i].s, stagedirs.p[i].s); } appends(&s, "/zip/.lua/?.lua;/zip/.lua/?/init.lua"); return s; } static void LuaStart(void) { #ifndef STATIC size_t i; lua_State *L = GL = luaL_newstate(); g_lua_path_default = GetDefaultLuaPath(); luaL_openlibs(L); for (i = 0; i < ARRAYLEN(kLuaLibs); ++i) { luaL_requiref(L, kLuaLibs[i].name, kLuaLibs[i].func, 1); lua_pop(L, 1); } for (i = 0; i < ARRAYLEN(kLuaFuncs); ++i) { lua_pushcfunction(L, kLuaFuncs[i].func); lua_setglobal(L, kLuaFuncs[i].name); } LuaSetConstant(L, "kLogDebug", kLogDebug); LuaSetConstant(L, "kLogVerbose", kLogVerbose); LuaSetConstant(L, "kLogInfo", kLogInfo); LuaSetConstant(L, "kLogWarn", kLogWarn); LuaSetConstant(L, "kLogError", kLogError); LuaSetConstant(L, "kLogFatal", kLogFatal); LuaSetConstant(L, "kUrlPlus", kUrlPlus); LuaSetConstant(L, "kUrlLatin1", kUrlLatin1); // create a list of custom content types lua_pushlightuserdata(L, (void *)&ctIdx); // push address as unique key lua_newtable(L); lua_settable(L, LUA_REGISTRYINDEX); // registry[&ctIdx] = {} #endif } static bool ShouldAutocomplete(const char *s) { int c, m, l, r; l = 0; r = ARRAYLEN(kDontAutoComplete) - 1; while (l <= r) { m = (l + r) >> 1; c = strcmp(kDontAutoComplete[m], s); if (c < 0) { l = m + 1; } else if (c > 0) { r = m - 1; } else { return false; } } return true; } static void HandleCompletions(const char *p, linenoiseCompletions *c) { size_t i, j; for (j = i = 0; i < c->len; ++i) { if (ShouldAutocomplete(c->cvec[i])) { c->cvec[j++] = c->cvec[i]; } else { free(c->cvec[i]); } } c->len = j; } static void LuaPrint(lua_State *L) { int i, n; char *b = 0; const char *s; n = lua_gettop(L); if (n > 0) { for (i = 1; i <= n; i++) { if (i > 1) appendw(&b, '\t'); struct EncoderConfig conf = { .maxdepth = 64, .sorted = true, .pretty = true, .indent = " ", }; LuaEncodeLuaData(L, &b, i, conf); } appendw(&b, '\n'); WRITE(1, b, appendz(b).i); free(b); } } static void EnableRawMode(void) { if (lua_repl_isterminal) { strace_enabled(-1); linenoiseEnableRawMode(0); strace_enabled(+1); } } static void DisableRawMode(void) { strace_enabled(-1); linenoiseDisableRawMode(); strace_enabled(+1); } static int LuaInterpreter(lua_State *L) { int i, n, sig, status; const char *script; if (optind < __argc) { script = __argv[optind]; if (!strcmp(script, "-")) script = 0; if ((status = luaL_loadfile(L, script)) == LUA_OK) { lua_getglobal(L, "arg"); n = luaL_len(L, -1); luaL_checkstack(L, n + 3, "too many script args"); for (i = 1; i <= n; i++) lua_rawgeti(L, -i, i); lua_remove(L, -i); // remove arg table from stack TRACE_BEGIN; status = lua_runchunk(L, n, LUA_MULTRET); TRACE_END; } return lua_report(L, status); } else { lua_repl_blocking = true; lua_repl_completions_callback = HandleCompletions; lua_initrepl(GL, "redbean"); EnableRawMode(); for (;;) { status = lua_loadline(L); if (status == -1) break; // eof if (status == -2) { if (errno == EINTR) { if ((sig = linenoiseGetInterrupt())) { kill(0, sig); } } fprintf(stderr, "i/o error: %m\n"); exit(1); } if (status == LUA_OK) { TRACE_BEGIN; status = lua_runchunk(GL, 0, LUA_MULTRET); TRACE_END; } if (status == LUA_OK) { LuaPrint(GL); } else { lua_report(GL, status); } } DisableRawMode(); lua_freerepl(); lua_settop(GL, 0); // clear stack if ((sig = linenoiseGetInterrupt())) { raise(sig); } return status; } } static void LuaDestroy(void) { #ifndef STATIC lua_State *L = GL; lua_close(L); free(g_lua_path_default); #endif } static void MemDestroy(void) { FreeAssets(); CollectGarbage(); inbuf.p = 0, inbuf.n = 0, inbuf.c = 0; Free(&inbuf_actual.p), inbuf_actual.n = inbuf_actual.c = 0; Free(&unmaplist.p), unmaplist.n = unmaplist.c = 0; Free(&freelist.p), freelist.n = freelist.c = 0; Free(&hdrbuf.p), hdrbuf.n = hdrbuf.c = 0; Free(&servers.p), servers.n = 0; Free(&ports.p), ports.n = 0; Free(&ips.p), ips.n = 0; Free(&cpm.outbuf); FreeStrings(&stagedirs); FreeStrings(&hidepaths); Free(&launchbrowser); Free(&serverheader); Free(&trustedips.p); Free(&interfaces); Free(&extrahdrs); Free(&pidpath); Free(&logpath); Free(&brand); Free(&polls); } static void LuaInit(void) { #ifndef STATIC lua_State *L = GL; LuaSetArgv(L); if (interpretermode) { int rc = LuaInterpreter(L); LuaDestroy(); MemDestroy(); if (IsModeDbg()) { CheckForMemoryLeaks(); } exit(rc); } if (LuaRunAsset("/.init.lua", true)) { hasonhttprequest = IsHookDefined("OnHttpRequest"); hasonclientconnection = IsHookDefined("OnClientConnection"); hasonprocesscreate = IsHookDefined("OnProcessCreate"); hasonprocessdestroy = IsHookDefined("OnProcessDestroy"); hasonworkerstart = IsHookDefined("OnWorkerStart"); hasonworkerstop = IsHookDefined("OnWorkerStop"); hasonloglatency = IsHookDefined("OnLogLatency"); } else { DEBUGF("(srvr) no /.init.lua defined"); } #endif } static void LuaReload(void) { #ifndef STATIC if (!LuaRunAsset("/.reload.lua", false)) { DEBUGF("(srvr) no /.reload.lua defined"); } #endif } static const char *DescribeClose(void) { if (killed) return "killed"; if (meltdown) return "meltdown"; if (terminated) return "terminated"; if (connectionclose) return "connection closed"; return "destroyed"; } static void LogClose(const char *reason) { if (amtread || meltdown || killed) { LockInc(&shared->c.fumbles); INFOF("(stat) %s %s with %,ld unprocessed and %,d handled (%,d workers)", DescribeClient(), reason, amtread, messageshandled, shared->workers); } else { DEBUGF("(stat) %s %s with %,d messages handled", DescribeClient(), reason, messageshandled); } } static ssize_t SendString(const char *s) { size_t n; ssize_t rc; struct iovec iov; n = strlen(s); iov.iov_base = s; iov.iov_len = n; if (logmessages) { LogMessage("sending", s, n); } for (;;) { if ((rc = writer(client, &iov, 1)) != -1 || errno != EINTR) { return rc; } errno = 0; } } static ssize_t SendContinue(void) { return SendString("\ HTTP/1.1 100 Continue\r\n\ \r\n"); } static ssize_t SendTimeout(void) { return SendString("\ HTTP/1.1 408 Request Timeout\r\n\ Connection: close\r\n\ Content-Length: 0\r\n\ \r\n"); } static ssize_t SendServiceUnavailable(void) { return SendString("\ HTTP/1.1 503 Service Unavailable\r\n\ Connection: close\r\n\ Content-Length: 0\r\n\ \r\n"); } static ssize_t SendTooManyRequests(void) { return SendString("\ HTTP/1.1 429 Too Many Requests\r\n\ Connection: close\r\n\ Content-Type: text/plain\r\n\ Content-Length: 22\r\n\ \r\n\ 429 Too Many Requests\n"); } static void EnterMeltdownMode(void) { if (timespec_cmp(timespec_sub(timespec_real(), shared->lastmeltdown), (struct timespec){1}) < 0) { return; } WARNF("(srvr) server is melting down (%,d workers)", shared->workers); LOGIFNEG1(kill(0, SIGUSR2)); shared->lastmeltdown = timespec_real(); ++shared->c.meltdowns; } static char *HandlePayloadDisconnect(void) { LockInc(&shared->c.payloaddisconnects); LogClose("payload disconnect"); return ServeFailure(400, "Bad Request"); /* XXX */ } static char *HandlePayloadDrop(void) { LockInc(&shared->c.dropped); LogClose(DescribeClose()); return ServeFailure(503, "Service Unavailable"); } static char *HandleBadContentLength(void) { LockInc(&shared->c.badlengths); return ServeFailure(400, "Bad Content Length"); } static char *HandleLengthRequired(void) { LockInc(&shared->c.missinglengths); return ServeFailure(411, "Length Required"); } static char *HandleVersionNotSupported(void) { LockInc(&shared->c.http12); return ServeFailure(505, "HTTP Version Not Supported"); } static char *HandleConnectRefused(void) { LockInc(&shared->c.connectsrefused); return ServeFailure(501, "Not Implemented"); } static char *HandleExpectFailed(void) { LockInc(&shared->c.expectsrefused); return ServeFailure(417, "Expectation Failed"); } static char *HandleHugePayload(void) { LockInc(&shared->c.hugepayloads); return ServeFailure(413, "Payload Too Large"); } static char *HandleTransferRefused(void) { LockInc(&shared->c.transfersrefused); return ServeFailure(501, "Not Implemented"); } static char *HandleMapFailed(struct Asset *a, int fd) { LockInc(&shared->c.mapfails); WARNF("(srvr) mmap(%`'s) error: %m", a->file->path); close(fd); return ServeError(500, "Internal Server Error"); } static void LogAcceptError(const char *s) { LockInc(&shared->c.accepterrors); WARNF("(srvr) %s accept error: %s", DescribeServer(), s); } static char *HandleOpenFail(struct Asset *a) { LockInc(&shared->c.openfails); WARNF("(srvr) open(%`'s) error: %m", a->file->path); if (errno == ENFILE) { LockInc(&shared->c.enfiles); return ServeError(503, "Service Unavailable"); } else if (errno == EMFILE) { LockInc(&shared->c.emfiles); return ServeError(503, "Service Unavailable"); } else { return ServeError(500, "Internal Server Error"); } } static char *HandlePayloadReadError(void) { if (errno == ECONNRESET) { LockInc(&shared->c.readresets); LogClose("payload reset"); return ServeFailure(400, "Bad Request"); /* XXX */ } else if (errno == EAGAIN || errno == EWOULDBLOCK) { LockInc(&shared->c.readtimeouts); LogClose("payload read timeout"); return ServeFailure(408, "Request Timeout"); } else { LockInc(&shared->c.readerrors); INFOF("(clnt) %s payload read error: %m", DescribeClient()); return ServeFailure(500, "Internal Server Error"); } } static void HandleForkFailure(void) { LockInc(&shared->c.forkerrors); LockInc(&shared->c.dropped); EnterMeltdownMode(); SendServiceUnavailable(); close(client); WARNF("(srvr) too many processes: %m"); } static void HandleFrag(size_t got) { LockInc(&shared->c.frags); DEBUGF("(stat) %s fragged msg added %,ld bytes to %,ld byte buffer", DescribeClient(), amtread, got); } static void HandleReload(void) { LockInc(&shared->c.reloads); Reindex(); LuaReload(); } static void HandleHeartbeat(void) { size_t i; sigset_t mask; UpdateCurrentDate(timespec_real()); Reindex(); getrusage(RUSAGE_SELF, &shared->server); #ifndef STATIC CallSimpleHookIfDefined("OnServerHeartbeat"); CollectGarbage(); #endif for (i = 1; i < servers.n; ++i) { if (polls[i].fd < 0) { polls[i].fd = -polls[i].fd; } } } // returns 0 on success or response on error static char *OpenAsset(struct Asset *a) { int fd; void *data; size_t size; struct stat *st; if (a->file->st.st_size) { size = a->file->st.st_size; if (cpm.msg.method == kHttpHead) { cpm.content = 0; cpm.contentlength = size; } else { OpenAgain: if ((fd = open(a->file->path.s, O_RDONLY)) != -1) { data = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0); if (data != MAP_FAILED) { LockInc(&shared->c.maps); UnmapLater(fd, data, size); cpm.content = data; cpm.contentlength = size; } else if ((st = _gc(malloc(sizeof(struct stat)))) && fstat(fd, st) != -1 && (data = malloc(st->st_size))) { /* probably empty file or zipos handle */ LockInc(&shared->c.slurps); FreeLater(data); if (ReadAll(fd, data, st->st_size) != -1) { cpm.content = data; cpm.contentlength = st->st_size; close(fd); } else { return HandleMapFailed(a, fd); } } else { return HandleMapFailed(a, fd); } } else if (errno == EINTR) { errno = 0; goto OpenAgain; } else { return HandleOpenFail(a); } } } else { cpm.content = ""; cpm.contentlength = 0; } return 0; } static char *ServeServerOptions(void) { char *p; LockInc(&shared->c.serveroptions); p = SetStatus(200, "OK"); #ifdef STATIC p = stpcpy(p, "Allow: GET, HEAD, OPTIONS\r\n"); #else p = stpcpy(p, "Accept: */*\r\n" "Accept-Charset: utf-8,ISO-8859-1;q=0.7,*;q=0.5\r\n" "Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS\r\n"); #endif return p; } static void SendContinueIfNeeded(void) { if (cpm.msg.version >= 11 && HeaderEqualCase(kHttpExpect, "100-continue")) { LockInc(&shared->c.continues); SendContinue(); } } static char *ReadMore(void) { size_t got; ssize_t rc; LockInc(&shared->c.frags); if ((rc = reader(client, inbuf.p + amtread, inbuf.n - amtread)) != -1) { if (!(got = rc)) return HandlePayloadDisconnect(); amtread += got; } else if (errno == EINTR) { LockInc(&shared->c.readinterrupts); if (killed || ((meltdown || terminated) && timespec_cmp(timespec_sub(timespec_real(), startread), (struct timespec){1}) >= 0)) { return HandlePayloadDrop(); } } else { return HandlePayloadReadError(); } return NULL; } static char *SynchronizeLength(void) { char *p; if (hdrsize + payloadlength > amtread) { if (hdrsize + payloadlength > inbuf.n) return HandleHugePayload(); SendContinueIfNeeded(); while (amtread < hdrsize + payloadlength) { if ((p = ReadMore())) return p; } } cpm.msgsize = hdrsize + payloadlength; return NULL; } static char *SynchronizeChunked(void) { char *p; ssize_t transferlength; struct HttpUnchunker u = {0}; SendContinueIfNeeded(); while (!(transferlength = Unchunk(&u, inbuf.p + hdrsize, amtread - hdrsize, &payloadlength))) { if ((p = ReadMore())) return p; } if (transferlength == -1) return HandleHugePayload(); cpm.msgsize = hdrsize + transferlength; return NULL; } static char *SynchronizeStream(void) { int64_t cl; if (HasHeader(kHttpTransferEncoding) && !HeaderEqualCase(kHttpTransferEncoding, "identity")) { if (HeaderEqualCase(kHttpTransferEncoding, "chunked")) { return SynchronizeChunked(); } else { return HandleTransferRefused(); } } else if (HasHeader(kHttpContentLength)) { if ((cl = ParseContentLength(HeaderData(kHttpContentLength), HeaderLength(kHttpContentLength))) != -1) { payloadlength = cl; return SynchronizeLength(); } else { return HandleBadContentLength(); } } else if (cpm.msg.method == kHttpPost || cpm.msg.method == kHttpPut) { return HandleLengthRequired(); } else { cpm.msgsize = hdrsize; payloadlength = 0; return NULL; } } static void ParseRequestParameters(void) { uint32_t ip; FreeLater(ParseUrl(inbuf.p + cpm.msg.uri.a, cpm.msg.uri.b - cpm.msg.uri.a, &url, kUrlPlus | kUrlLatin1)); if (!url.host.p) { if (HasHeader(kHttpXForwardedHost) && // !GetRemoteAddr(&ip, 0) && IsTrustedIp(ip)) { FreeLater(ParseHost(HeaderData(kHttpXForwardedHost), HeaderLength(kHttpXForwardedHost), &url)); } else if (HasHeader(kHttpHost)) { FreeLater( ParseHost(HeaderData(kHttpHost), HeaderLength(kHttpHost), &url)); } else { FreeLater(ParseHost(DescribeServer(), -1, &url)); } } else if (!url.path.n) { url.path.p = "/"; url.path.n = 1; } if (!url.scheme.n) { if (usingssl) { url.scheme.p = "https"; url.scheme.n = 5; } else { url.scheme.p = "http"; url.scheme.n = 4; } } } static bool HasAtMostThisElement(int h, const char *s) { size_t i, n; struct HttpHeader *x; if (HasHeader(h)) { n = strlen(s); if (!SlicesEqualCase(s, n, HeaderData(h), HeaderLength(h))) { return false; } for (i = 0; i < cpm.msg.xheaders.n; ++i) { x = cpm.msg.xheaders.p + i; if (GetHttpHeader(inbuf.p + x->k.a, x->k.b - x->k.a) == h && !SlicesEqualCase(inbuf.p + x->v.a, x->v.b - x->v.a, s, n)) { return false; } } } return true; } static char *HandleRequest(void) { char *p; if (cpm.msg.version == 11) { LockInc(&shared->c.http11); } else if (cpm.msg.version < 10) { LockInc(&shared->c.http09); } else if (cpm.msg.version == 10) { LockInc(&shared->c.http10); } else { return HandleVersionNotSupported(); } if ((p = SynchronizeStream())) return p; if (logbodies) LogBody("received", inbuf.p + hdrsize, payloadlength); if (cpm.msg.version < 11 || HeaderEqualCase(kHttpConnection, "close")) { connectionclose = true; } if (cpm.msg.method == kHttpOptions && SlicesEqual(inbuf.p + cpm.msg.uri.a, cpm.msg.uri.b - cpm.msg.uri.a, "*", 1)) { return ServeServerOptions(); } if (cpm.msg.method == kHttpConnect) { return HandleConnectRefused(); } if (!HasAtMostThisElement(kHttpExpect, "100-continue")) { return HandleExpectFailed(); } ParseRequestParameters(); if (!url.host.n || !url.path.n || url.path.p[0] != '/' || !IsAcceptablePath(url.path.p, url.path.n) || !IsAcceptableHost(url.host.p, url.host.n) || !IsAcceptablePort(url.port.p, url.port.n)) { free(url.params.p); LockInc(&shared->c.urisrefused); return ServeFailure(400, "Bad URI"); } INFOF("(req) received %s HTTP%02d %.*s %s %`'.*s %`'.*s", DescribeClient(), cpm.msg.version, cpm.msg.xmethod.b - cpm.msg.xmethod.a, inbuf.p + cpm.msg.xmethod.a, FreeLater(EncodeUrl(&url, 0)), HeaderLength(kHttpReferer), HeaderData(kHttpReferer), HeaderLength(kHttpUserAgent), HeaderData(kHttpUserAgent)); if (HasHeader(kHttpContentType) && IsMimeType(HeaderData(kHttpContentType), HeaderLength(kHttpContentType), "application/x-www-form-urlencoded")) { FreeLater(ParseParams(inbuf.p + hdrsize, payloadlength, &url.params)); } FreeLater(url.params.p); #ifndef STATIC if (hasonhttprequest) return LuaOnHttpRequest(); #endif return Route(url.host.p, url.host.n, url.path.p, url.path.n); } static char *Route(const char *host, size_t hostlen, const char *path, size_t pathlen) { char *p; // reset the redirect loop check, as it can only be looping inside // this function (as it always serves something); otherwise // successful RoutePath and Route may fail with "508 loop detected" cpm.loops.n = 0; if (hostlen && (p = RouteHost(host, hostlen, path, pathlen))) { return p; } if (SlicesEqual(path, pathlen, "/", 1)) { if ((p = ServeIndex("/", 1))) return p; return ServeListing(); } else if ((p = RoutePath(path, pathlen))) { return p; } else if (SlicesEqual(path, pathlen, "/statusz", 8)) { return ServeStatusz(); } else { LockInc(&shared->c.notfounds); return ServeError(404, "Not Found"); } } static char *RoutePath(const char *path, size_t pathlen) { int m; long r; char *p; struct Asset *a; DEBUGF("(srvr) RoutePath(%`'.*s)", pathlen, path); if ((a = GetAsset(path, pathlen))) { // only allow "read other" permissions for security // and consistency with handling of "external" files // in this and other webservers if ((m = GetMode(a)) & 0004) { if (!S_ISDIR(m)) { return HandleAsset(a, path, pathlen); } else { return HandleFolder(path, pathlen); } } else { LockInc(&shared->c.forbiddens); WARNF("(srvr) asset %`'.*s %#o isn't readable", pathlen, path, m); return ServeError(403, "Forbidden"); } } else if ((r = FindRedirect(path, pathlen)) != -1) { return HandleRedirect(redirects.p + r); } else { return NULL; } } static char *RouteHost(const char *host, size_t hostlen, const char *path, size_t pathlen) { size_t hn, hm; char *hp, *p, b[96]; if (hostlen) { hn = 1 + hostlen + url.path.n; hm = 3 + 1 + hn; hp = hm <= sizeof(b) ? b : FreeLater(xmalloc(hm)); hp[0] = '/'; mempcpy(mempcpy(hp + 1, host, hostlen), path, pathlen); if ((p = RoutePath(hp, hn))) return p; if (!isdigit(host[0])) { if (hostlen > 4 && READ32LE(host) == ('w' | 'w' << 8 | 'w' << 16 | '.' << 24)) { mempcpy(mempcpy(hp + 1, host + 4, hostlen - 4), path, pathlen); if ((p = RoutePath(hp, hn - 4))) return p; } else { mempcpy(mempcpy(mempcpy(hp + 1, "www.", 4), host, hostlen), path, pathlen); if ((p = RoutePath(hp, hn + 4))) return p; } } } return NULL; } static inline bool IsLua(struct Asset *a) { size_t n; const char *p; if (a->file && a->file->path.n >= 4 && READ32LE(a->file->path.s + a->file->path.n - 4) == ('.' | 'l' << 8 | 'u' << 16 | 'a' << 24)) { return true; } p = ZIP_CFILE_NAME(zbase + a->cf); n = ZIP_CFILE_NAMESIZE(zbase + a->cf); return n > 4 && READ32LE(p + n - 4) == ('.' | 'l' << 8 | 'u' << 16 | 'a' << 24); } static char *HandleAsset(struct Asset *a, const char *path, size_t pathlen) { char *p; #ifndef STATIC if (IsLua(a)) return ServeLua(a, path, pathlen); #endif if (cpm.msg.method == kHttpGet || cpm.msg.method == kHttpHead) { LockInc(&shared->c.staticrequests); p = ServeAsset(a, path, pathlen); if (!cpm.gotxcontenttypeoptions) { p = stpcpy(p, "X-Content-Type-Options: nosniff\r\n"); } return p; } else { return BadMethod(); } } static const char *GetContentType(struct Asset *a, const char *path, size_t n) { const char *r; if (a->file && (r = GetContentTypeExt(a->file->path.s, a->file->path.n))) { return r; } return firstnonnull( GetContentTypeExt(path, n), firstnonnull(GetContentTypeExt(ZIP_CFILE_NAME(zbase + a->cf), ZIP_CFILE_NAMESIZE(zbase + a->cf)), a->istext ? "text/plain" : "application/octet-stream")); } static bool IsNotModified(struct Asset *a) { if (cpm.msg.version < 10) return false; if (!HasHeader(kHttpIfModifiedSince)) return false; return a->lastmodified <= ParseHttpDateTime(HeaderData(kHttpIfModifiedSince), HeaderLength(kHttpIfModifiedSince)); } static char *ServeAsset(struct Asset *a, const char *path, size_t pathlen) { char *p; uint32_t crc; const char *ct; ct = GetContentType(a, path, pathlen); if (IsNotModified(a)) { LockInc(&shared->c.notmodifieds); p = SetStatus(304, "Not Modified"); } else { if (!a->file) { cpm.content = (char *)ZIP_LFILE_CONTENT(zbase + a->lf); cpm.contentlength = GetZipCfileCompressedSize(zbase + a->cf); } else if ((p = OpenAsset(a))) { return p; } if (IsCompressed(a)) { if (ClientAcceptsGzip()) { p = ServeAssetPrecompressed(a); } else { p = ServeAssetDecompressed(a); } } else if (cpm.msg.version >= 11 && HasHeader(kHttpRange)) { p = ServeAssetRange(a); } else if (!a->file) { LockInc(&shared->c.identityresponses); DEBUGF("(zip) ServeAssetZipIdentity(%`'s)", ct); if (Verify(cpm.content, cpm.contentlength, ZIP_LFILE_CRC32(zbase + a->lf))) { p = SetStatus(200, "OK"); } else { return ServeError(500, "Internal Server Error"); } } else if (!IsTiny() && cpm.msg.method != kHttpHead && !IsSslCompressed() && ClientAcceptsGzip() && !ShouldAvoidGzip() && !(a->file && IsNoCompressExt(a->file->path.s, a->file->path.n)) && ((cpm.contentlength >= 100 && _startswithi(ct, "text/")) || (cpm.contentlength >= 1000 && MeasureEntropy(cpm.content, 1000) < 7))) { VERBOSEF("serving compressed asset"); p = ServeAssetCompressed(a); } else { p = ServeAssetIdentity(a, ct); } } p = AppendContentType(p, ct); p = stpcpy(p, "Vary: Accept-Encoding\r\n"); p = AppendHeader(p, "Last-Modified", a->lastmodifiedstr); if (cpm.msg.version >= 11) { if (!cpm.gotcachecontrol) { p = AppendCache(p, cacheseconds, cachedirective); } if (!IsCompressed(a)) { p = stpcpy(p, "Accept-Ranges: bytes\r\n"); } } return p; } static char *SetStatus(unsigned code, const char *reason) { if (cpm.msg.version == 10) { if (code == 307) code = 302; if (code == 308) code = 301; } cpm.statuscode = code; cpm.hascontenttype = false; // reset, as the headers are reset. // istext is `true`, as the default content type // is text/html, which will be set later cpm.istext = true; cpm.gotxcontenttypeoptions = 0; cpm.gotcachecontrol = 0; cpm.referrerpolicy = 0; cpm.branded = 0; stpcpy(hdrbuf.p, "HTTP/1.0 000 "); hdrbuf.p[7] += cpm.msg.version & 1; hdrbuf.p[9] += code / 100; hdrbuf.p[10] += code / 10 % 10; hdrbuf.p[11] += code % 10; VERBOSEF("(rsp) %d %s", code, reason); return AppendCrlf(stpcpy(hdrbuf.p + 13, reason)); } static inline bool MustNotIncludeMessageBody(void) { /* RFC2616 § 4.4 */ return cpm.msg.method == kHttpHead || (100 <= cpm.statuscode && cpm.statuscode <= 199) || cpm.statuscode == 204 || cpm.statuscode == 304; } static bool TransmitResponse(char *p) { int iovlen; struct iovec iov[4]; long actualcontentlength; if (cpm.msg.version >= 10) { actualcontentlength = cpm.contentlength; if (cpm.gzipped) { actualcontentlength += sizeof(kGzipHeader) + sizeof(gzip_footer); p = stpcpy(p, "Content-Encoding: gzip\r\n"); } p = AppendContentLength(p, actualcontentlength); p = AppendCrlf(p); CHECK_LE(p - hdrbuf.p, hdrbuf.n); if (logmessages) { LogMessage("sending", hdrbuf.p, p - hdrbuf.p); } iov[0].iov_base = hdrbuf.p; iov[0].iov_len = p - hdrbuf.p; iovlen = 1; if (!MustNotIncludeMessageBody()) { if (cpm.gzipped) { iov[iovlen].iov_base = kGzipHeader; iov[iovlen].iov_len = sizeof(kGzipHeader); ++iovlen; } iov[iovlen].iov_base = cpm.content; iov[iovlen].iov_len = cpm.contentlength; ++iovlen; if (cpm.gzipped) { iov[iovlen].iov_base = gzip_footer; iov[iovlen].iov_len = sizeof(gzip_footer); ++iovlen; } } } else { iov[0].iov_base = cpm.content; iov[0].iov_len = cpm.contentlength; iovlen = 1; } Send(iov, iovlen); LockInc(&shared->c.messageshandled); ++messageshandled; return true; } static bool StreamResponse(char *p) { int rc; struct iovec iov[6]; char *s, chunkbuf[23]; assert(!MustNotIncludeMessageBody()); if (cpm.msg.version >= 11) { p = stpcpy(p, "Transfer-Encoding: chunked\r\n"); } else { assert(connectionclose); } p = AppendCrlf(p); CHECK_LE(p - hdrbuf.p, hdrbuf.n); if (logmessages) { LogMessage("sending", hdrbuf.p, p - hdrbuf.p); } bzero(iov, sizeof(iov)); if (cpm.msg.version >= 10) { iov[0].iov_base = hdrbuf.p; iov[0].iov_len = p - hdrbuf.p; } if (cpm.msg.version >= 11) { iov[5].iov_base = "\r\n"; iov[5].iov_len = 2; } for (;;) { iov[2].iov_base = 0; iov[2].iov_len = 0; iov[3].iov_base = 0; iov[3].iov_len = 0; iov[4].iov_base = 0; iov[4].iov_len = 0; if ((rc = cpm.generator(iov + 2)) <= 0) break; if (cpm.msg.version >= 11) { s = chunkbuf; s += uint64toarray_radix16(rc, s); s = AppendCrlf(s); iov[1].iov_base = chunkbuf; iov[1].iov_len = s - chunkbuf; } if (Send(iov, 6) == -1) break; iov[0].iov_base = 0; iov[0].iov_len = 0; } if (rc != -1) { if (cpm.msg.version >= 11) { iov[0].iov_base = "0\r\n\r\n"; iov[0].iov_len = 5; Send(iov, 1); } } else { connectionclose = true; } return true; } static bool HandleMessageActual(void) { int rc; long reqtime, contime; char *p; struct timespec now; if ((rc = ParseHttpMessage(&cpm.msg, inbuf.p, amtread)) != -1) { if (!rc) return false; hdrsize = rc; if (logmessages) { LogMessage("received", inbuf.p, hdrsize); } p = HandleRequest(); } else { LockInc(&shared->c.badmessages); connectionclose = true; if ((p = DumpHexc(inbuf.p, MIN(amtread, 256), 0))) { INFOF("(clnt) %s sent garbage %s", DescribeClient(), p); } return true; } if (!cpm.msgsize) { amtread = 0; connectionclose = true; LockInc(&shared->c.synchronizationfailures); DEBUGF("(clnt) could not synchronize message stream"); } if (cpm.msg.version >= 10) { p = AppendCrlf(stpcpy(stpcpy(p, "Date: "), shared->currentdate)); if (!cpm.branded) p = stpcpy(p, serverheader); if (extrahdrs) p = stpcpy(p, extrahdrs); if (connectionclose) { p = stpcpy(p, "Connection: close\r\n"); } else if (timeout.tv_sec < 0 && cpm.msg.version >= 11) { p = stpcpy(p, "Connection: keep-alive\r\n"); } } // keep content-type update *before* referrerpolicy // https://datatracker.ietf.org/doc/html/rfc2616#section-7.2.1 if (!cpm.hascontenttype && cpm.contentlength > 0) { p = AppendContentType(p, "text/html"); } if (cpm.referrerpolicy) { p = stpcpy(p, "Referrer-Policy: "); p = stpcpy(p, cpm.referrerpolicy); p = stpcpy(p, "\r\n"); } if (loglatency || LOGGABLE(kLogDebug) || hasonloglatency) { now = timespec_real(); reqtime = timespec_tomicros(timespec_sub(now, startrequest)); contime = timespec_tomicros(timespec_sub(now, startconnection)); if (hasonloglatency) LuaOnLogLatency(reqtime, contime); if (loglatency || LOGGABLE(kLogDebug)) LOGF(kLogDebug, "(stat) %`'.*s latency r: %,ldµs c: %,ldµs", cpm.msg.uri.b - cpm.msg.uri.a, inbuf.p + cpm.msg.uri.a, reqtime, contime); } if (!cpm.generator) { return TransmitResponse(p); } else { return StreamResponse(p); } } static bool HandleMessage(void) { bool r; ishandlingrequest = true; r = HandleMessageActual(); ishandlingrequest = false; return r; } static void InitRequest(void) { assert(!cpm.outbuf); bzero(&cpm, sizeof(cpm)); } static bool IsSsl(unsigned char c) { if (c == 22) return true; if (!(c & 128)) return false; /* RHEL5 sends SSLv2 hello but supports TLS */ DEBUGF("(ssl) %s SSLv2 hello D:", DescribeClient()); return true; } static void HandleMessages(void) { char *p; bool once; ssize_t rc; size_t got; for (once = false;;) { InitRequest(); startread = timespec_real(); for (;;) { if (!cpm.msg.i && amtread) { startrequest = timespec_real(); if (HandleMessage()) break; } if ((rc = reader(client, inbuf.p + amtread, inbuf.n - amtread)) != -1) { startrequest = timespec_real(); got = rc; amtread += got; if (amtread) { #ifndef UNSECURE if (!once) { once = true; if (!unsecure) { if (IsSsl(inbuf.p[0])) { if (TlsSetup()) { continue; } else { return; } } else if (requiressl) { INFOF("(clnt) %s didn't send an ssl hello", DescribeClient()); return; } else { WipeServingKeys(); } } } #endif DEBUGF("(stat) %s read %,zd bytes", DescribeClient(), got); if (HandleMessage()) { break; } else if (got) { HandleFrag(got); } } if (!got) { NotifyClose(); LogClose("disconnect"); return; } } else if (errno == EINTR) { LockInc(&shared->c.readinterrupts); errno = 0; } else if (errno == EAGAIN) { LockInc(&shared->c.readtimeouts); if (amtread) SendTimeout(); NotifyClose(); LogClose("read timeout"); return; } else if (errno == ECONNRESET) { LockInc(&shared->c.readresets); LogClose("read reset"); return; } else { LockInc(&shared->c.readerrors); if (errno == EBADF) { // don't warn on close/bad fd LogClose("read badf"); } else { WARNF("(clnt) %s read error: %m", DescribeClient()); } return; } if (killed || (terminated && !amtread) || (meltdown && (!amtread || timespec_cmp(timespec_sub(timespec_real(), startread), (struct timespec){1}) >= 0))) { if (amtread) { LockInc(&shared->c.dropped); SendServiceUnavailable(); } NotifyClose(); LogClose(DescribeClose()); return; } if (invalidated) { HandleReload(); invalidated = false; } } if (cpm.msgsize == amtread) { amtread = 0; if (killed) { LogClose(DescribeClose()); return; } else if (connectionclose || terminated || meltdown) { NotifyClose(); LogClose(DescribeClose()); return; } } else { CHECK_LT(cpm.msgsize, amtread); LockInc(&shared->c.pipelinedrequests); DEBUGF("(stat) %,ld pipelinedrequest bytes", amtread - cpm.msgsize); memmove(inbuf.p, inbuf.p + cpm.msgsize, amtread - cpm.msgsize); amtread -= cpm.msgsize; if (killed) { LogClose(DescribeClose()); return; } else if (connectionclose) { NotifyClose(); LogClose(DescribeClose()); return; } } CollectGarbage(); if (invalidated) { HandleReload(); invalidated = false; } } } static void CloseServerFds(void) { size_t i; for (i = 0; i < servers.n; ++i) { close(servers.p[i].fd); } } static int ExitWorker(void) { if (IsModeDbg() && !sandboxed) { isexitingworker = true; return eintr(); } if (monitortty) { terminatemonitor = true; _join(&monitorth); } _Exit(0); } static void UnveilRedbean(void) { size_t i; for (i = 0; i < stagedirs.n; ++i) { unveil(stagedirs.p[i].s, "r"); } unveil(0, 0); } static int EnableSandbox(void) { __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM | PLEDGE_STDERR_LOGGING; switch (sandboxed) { case 0: return 0; case 1: // -S DEBUGF("(stat) applying '%s' sandbox policy", "online"); UnveilRedbean(); return pledge("stdio rpath inet dns id", 0); case 2: // -SS DEBUGF("(stat) applying '%s' sandbox policy", "offline"); UnveilRedbean(); return pledge("stdio rpath id", 0); default: // -SSS DEBUGF("(stat) applying '%s' sandbox policy", "contained"); UnveilRedbean(); return pledge("stdio", 0); } } static int MemoryMonitor(void *arg, int tid) { static struct termios oldterm; static int tty; sigset_t ss; bool done, ok; size_t intervals; struct winsize ws; unsigned char rez; struct termios term; char *b, *addr, title[128]; struct MemoryInterval *mi, *mi2; long i, j, k, n, x, y, pi, gen, pages; int rc, id, color, color2, workers; id = atomic_load_explicit(&shared->workers, memory_order_relaxed); DEBUGF("(memv) started for pid %d on tid %d", getpid(), gettid()); sigemptyset(&ss); sigaddset(&ss, SIGHUP); sigaddset(&ss, SIGINT); sigaddset(&ss, SIGQUIT); sigaddset(&ss, SIGTERM); sigaddset(&ss, SIGPIPE); sigaddset(&ss, SIGUSR1); sigaddset(&ss, SIGUSR2); sigprocmask(SIG_BLOCK, &ss, 0); pthread_spin_lock(&shared->montermlock); if (!id) { if ((tty = open(monitortty, O_RDWR | O_NOCTTY)) != -1) { ioctl(tty, TCGETS, &oldterm); term = oldterm; term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); term.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); term.c_oflag |= OPOST | ONLCR; term.c_iflag |= IUTF8; term.c_cflag |= CS8; term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; ioctl(tty, TCSETS, &term); WRITE(tty, "\e[?25l", 6); } } pthread_spin_unlock(&shared->montermlock); if (tty != -1) { for (gen = 0, mi = 0, b = 0; !terminatemonitor;) { workers = atomic_load_explicit(&shared->workers, memory_order_relaxed); if (id) id = MAX(1, MIN(id, workers)); if (!id && workers) { usleep(50000); continue; } ++gen; intervals = atomic_load_explicit(&_mmi.i, memory_order_relaxed); if ((mi2 = realloc(mi, (intervals += 3) * sizeof(*mi)))) { mi = mi2; mi[0].x = (intptr_t)__executable_start >> 16; mi[0].size = _etext - __executable_start; mi[0].flags = 0; mi[1].x = (intptr_t)_etext >> 16; mi[1].size = _edata - _etext; mi[1].flags = 0; mi[2].x = (intptr_t)_edata >> 16; mi[2].size = _end - _edata; mi[2].flags = 0; __mmi_lock(); if (_mmi.i == intervals - 3) { memcpy(mi + 3, _mmi.p, _mmi.i * sizeof(*mi)); ok = true; } else { ok = false; } __mmi_unlock(); if (!ok) { VERBOSEF("(memv) retrying due to contention on mmap table"); continue; } ws.ws_col = 80; ws.ws_row = 40; _getttysize(tty, &ws); appendr(&b, 0); appends(&b, "\e[H\e[1m"); for (pi = k = x = y = i = 0; i < intervals; ++i) { addr = (char *)((int64_t)((uint64_t)mi[i].x << 32) >> 16); color = 0; appendf(&b, "\e[0m%lx", addr); pages = (mi[i].size + PAGESIZE - 1) / PAGESIZE; for (j = 0; j < pages; ++j) { rc = mincore(addr + j * PAGESIZE, PAGESIZE, &rez); if (!rc) { if (rez & 1) { if (mi[i].flags & MAP_SHARED) { color2 = 105; } else { color2 = 42; } } else { color2 = 41; } } else { errno = 0; color2 = 0; } if (color != color2) { color = color2; appendf(&b, "\e[%dm", color); } if (mi[i].flags & MAP_ANONYMOUS) { appendw(&b, ' '); } else { appendw(&b, '/'); } } } appendf(&b, "\e[0m ID=%d PID=%d WS=%dx%d WORKERS=%d MODE=" MODE " GEN=%ld\e[J", id, getpid(), ws.ws_col, ws.ws_row, workers, gen); pthread_spin_lock(&shared->montermlock); WRITE(tty, b, appendz(b).i); appendr(&b, 0); usleep(MONITOR_MICROS); pthread_spin_unlock(&shared->montermlock); } else { // running out of memory temporarily is a real possibility here // the right thing to do, is stand aside and let lua try to fix WARNF("(memv) we require more vespene gas"); usleep(MONITOR_MICROS); } } if (!id) { appendr(&b, 0); appends(&b, "\e[H\e[J\e[?25h"); WRITE(tty, b, appendz(b).i); ioctl(tty, TCSETS, &oldterm); } DEBUGF("(memv) exiting..."); close(tty); free(mi); free(b); } DEBUGF("(memv) done"); return 0; } static void MonitorMemory(void) { if (_spawn(MemoryMonitor, 0, &monitorth) == -1) { WARNF("(memv) failed to start memory monitor %m"); } } static int HandleConnection(size_t i) { uint32_t ip; int pid, tok, rc = 0; clientaddrsize = sizeof(clientaddr); if ((client = accept4(servers.p[i].fd, (struct sockaddr *)&clientaddr, &clientaddrsize, SOCK_CLOEXEC)) != -1) { LockInc(&shared->c.accepts); GetClientAddr(&ip, 0); if (tokenbucket.cidr && tokenbucket.reject >= 0) { if (!IsTrustedIp(ip)) { tok = AcquireToken(tokenbucket.b, ip, tokenbucket.cidr); if (tok <= tokenbucket.ban && tokenbucket.ban >= 0) { WARNF("(token) banning %hhu.%hhu.%hhu.%hhu who only has %d tokens", ip >> 24, ip >> 16, ip >> 8, ip, tok); LockInc(&shared->c.bans); Blackhole(ip); close(client); return 0; } else if (tok <= tokenbucket.ignore && tokenbucket.ignore >= 0) { DEBUGF("(token) ignoring %hhu.%hhu.%hhu.%hhu who only has %d tokens", ip >> 24, ip >> 16, ip >> 8, ip, tok); LockInc(&shared->c.ignores); close(client); return 0; } else if (tok < tokenbucket.reject) { WARNF("(token) rejecting %hhu.%hhu.%hhu.%hhu who only has %d tokens", ip >> 24, ip >> 16, ip >> 8, ip, tok); LockInc(&shared->c.rejects); SendTooManyRequests(); close(client); return 0; } else { DEBUGF("(token) %hhu.%hhu.%hhu.%hhu has %d tokens", ip >> 24, ip >> 16, ip >> 8, ip, tok - 1); } } else { DEBUGF("(token) won't acquire token for trusted ip %hhu.%hhu.%hhu.%hhu", ip >> 24, ip >> 16, ip >> 8, ip); } } else { DEBUGF("(token) can't acquire accept() token for client"); } startconnection = timespec_real(); if (UNLIKELY(maxworkers) && shared->workers >= maxworkers) { EnterMeltdownMode(); SendServiceUnavailable(); close(client); return 0; } VERBOSEF("(srvr) accept %s via %s", DescribeClient(), DescribeServer()); messageshandled = 0; if (hasonclientconnection && LuaOnClientConnection()) { close(client); return 0; } if (uniprocess) { pid = -1; connectionclose = true; } else { switch ((pid = fork())) { case 0: if (!IsTiny() && monitortty) { MonitorMemory(); } meltdown = false; __isworker = true; connectionclose = false; if (!IsTiny() && systrace) { kStartTsc = rdtsc(); } TRACE_BEGIN; if (sandboxed) { CHECK_NE(-1, EnableSandbox()); } if (hasonworkerstart) { CallSimpleHook("OnWorkerStart"); } break; case -1: HandleForkFailure(); return 0; default: LockInc(&shared->workers); close(client); ReseedRng(&rng, "parent"); if (hasonprocesscreate) { LuaOnProcessCreate(pid); } return 0; } } if (!pid && !IsWindows()) { CloseServerFds(); } HandleMessages(); DEBUGF("(stat) %s closing after %,ldµs", DescribeClient(), timespec_tomicros(timespec_sub(timespec_real(), startconnection))); if (!pid) { if (hasonworkerstop) { CallSimpleHook("OnWorkerStop"); } rc = ExitWorker(); } else { close(client); oldin.p = 0; oldin.n = 0; if (inbuf.c) { inbuf.p -= inbuf.c; inbuf.n += inbuf.c; inbuf.c = 0; } #ifndef UNSECURE if (usingssl) { usingssl = false; reader = read; writer = WritevAll; mbedtls_ssl_session_reset(&ssl); } #endif } CollectGarbage(); } else { if (errno == EINTR || errno == EAGAIN) { LockInc(&shared->c.acceptinterrupts); } else if (errno == ENFILE) { LockInc(&shared->c.enfiles); LogAcceptError("enfile: too many open files"); meltdown = true; } else if (errno == EMFILE) { LockInc(&shared->c.emfiles); LogAcceptError("emfile: ran out of open file quota"); meltdown = true; } else if (errno == ENOMEM) { LockInc(&shared->c.enomems); LogAcceptError("enomem: ran out of memory"); meltdown = true; } else if (errno == ENOBUFS) { LockInc(&shared->c.enobufs); LogAcceptError("enobuf: ran out of buffer"); meltdown = true; } else if (errno == ENONET) { LockInc(&shared->c.enonets); LogAcceptError("enonet: network gone"); polls[i].fd = -polls[i].fd; } else if (errno == ENETDOWN) { LockInc(&shared->c.enetdowns); LogAcceptError("enetdown: network down"); polls[i].fd = -polls[i].fd; } else if (errno == ECONNABORTED) { LockInc(&shared->c.accepterrors); LockInc(&shared->c.acceptresets); WARNF("(srvr) %S accept error: %s", DescribeServer(), "acceptreset: connection reset before accept"); } else if (errno == ENETUNREACH || errno == EHOSTUNREACH || errno == EOPNOTSUPP || errno == ENOPROTOOPT || errno == EPROTO) { LockInc(&shared->c.accepterrors); LockInc(&shared->c.acceptflakes); WARNF("(srvr) accept error: %s ephemeral accept error: %m", DescribeServer()); } else { DIEF("(srvr) %s accept error: %m", DescribeServer()); } errno = 0; } return rc; } static void MakeExecutableModifiable(void) { #ifdef __x86_64__ int ft; size_t n; extern char ape_rom_vaddr[] __attribute__((__weak__)); if (!(SUPPORT_VECTOR & (_HOSTMETAL | _HOSTWINDOWS | _HOSTXNU))) return; if (IsWindows()) return; // TODO if (IsOpenbsd()) return; // TODO if (IsNetbsd()) return; // TODO if (_endswith(zpath, ".com.dbg")) return; close(zfd); ft = ftrace_enabled(0); if ((zfd = _OpenExecutable()) == -1) { WARNF("(srvr) can't open executable for modification: %m"); } if (ft > 0) { __ftrace = 0; ftrace_install(); ftrace_enabled(ft); } #else // TODO #endif } static int HandleReadline(void) { int status; lua_State *L = GL; for (;;) { status = lua_loadline(L); if (status < 0) { if (status == -1) { OnTerm(SIGHUP); // eof VERBOSEF("(repl) eof"); return -1; } else if (errno == EINTR) { errno = 0; VERBOSEF("(repl) interrupt"); shutdownsig = SIGINT; OnInt(SIGINT); kill(0, SIGINT); return -1; } else if (errno == EAGAIN) { errno = 0; return 0; } else { WARNF("(srvr) unexpected terminal error %d% m", status); errno = 0; return 0; } } DisableRawMode(); lua_repl_lock(); if (status == LUA_OK) { status = lua_runchunk(L, 0, LUA_MULTRET); } if (status == LUA_OK) { LuaPrint(L); } else { lua_report(L, status); } lua_repl_unlock(); EnableRawMode(); } } static int HandlePoll(int ms) { int rc, nfds; size_t pollid, serverid; if ((nfds = poll(polls, 1 + servers.n, ms)) != -1) { if (nfds) { // handle pollid/o events for (pollid = 0; pollid < 1 + servers.n; ++pollid) { if (!polls[pollid].revents) continue; if (polls[pollid].fd < 0) continue; if (polls[pollid].fd) { // handle listen socket lua_repl_lock(); serverid = pollid - 1; assert(0 <= serverid && serverid < servers.n); serveraddr = &servers.p[serverid].addr; ishandlingconnection = true; rc = HandleConnection(serverid); ishandlingconnection = false; lua_repl_unlock(); if (rc == -1) return -1; #ifndef STATIC } else { // handle standard input rc = HandleReadline(); if (rc == -1) return rc; #endif } } #ifndef STATIC } else if (__replmode) { // handle refresh repl line if (!IsWindows()) { rc = HandleReadline(); if (rc < 0) return rc; } else { strace_enabled(-1); linenoiseRefreshLine(lua_repl_linenoise); strace_enabled(+1); } #endif } } else { if (errno == EINTR || errno == EAGAIN) { LockInc(&shared->c.pollinterrupts); } else if (errno == ENOMEM) { LockInc(&shared->c.enomems); WARNF("(srvr) poll error: ran out of memory"); meltdown = true; } else { DIEF("(srvr) poll error: %m"); } errno = 0; } return 0; } static void Listen(void) { char ipbuf[16]; size_t i, j, n; uint32_t ip, port, addrsize, *ifp; bool hasonserverlisten = IsHookDefined("OnServerListen"); if (!ports.n) { ProgramPort(8080); } if (!ips.n) { if (interfaces && *interfaces) { for (ifp = interfaces; *ifp; ++ifp) { sprintf(ipbuf, "%hhu.%hhu.%hhu.%hhu", *ifp >> 24, *ifp >> 16, *ifp >> 8, *ifp); ProgramAddr(ipbuf); } } else { ProgramAddr("0.0.0.0"); } } servers.p = malloc(ips.n * ports.n * sizeof(*servers.p)); for (n = i = 0; i < ips.n; ++i) { for (j = 0; j < ports.n; ++j, ++n) { bzero(servers.p + n, sizeof(*servers.p)); servers.p[n].addr.sin_family = AF_INET; servers.p[n].addr.sin_port = htons(ports.p[j]); servers.p[n].addr.sin_addr.s_addr = htonl(ips.p[i]); if ((servers.p[n].fd = GoodSocket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP, true, &timeout)) == -1) { DIEF("(srvr) socket: %m"); } if (hasonserverlisten && LuaOnServerListen(servers.p[n].fd, ips.p[i], ports.p[j])) { close(servers.p[n].fd); n--; // skip this server instance continue; } if (bind(servers.p[n].fd, (struct sockaddr *)&servers.p[n].addr, sizeof(servers.p[n].addr)) == -1) { DIEF("(srvr) bind error: %m: %hhu.%hhu.%hhu.%hhu:%hu", ips.p[i] >> 24, ips.p[i] >> 16, ips.p[i] >> 8, ips.p[i], ports.p[j]); } if (listen(servers.p[n].fd, 10) == -1) { DIEF("(srvr) listen error: %m"); } addrsize = sizeof(servers.p[n].addr); if (getsockname(servers.p[n].fd, (struct sockaddr *)&servers.p[n].addr, &addrsize) == -1) { DIEF("(srvr) getsockname error: %m"); } port = ntohs(servers.p[n].addr.sin_port); ip = ntohl(servers.p[n].addr.sin_addr.s_addr); if (ip == INADDR_ANY) ip = INADDR_LOOPBACK; INFOF("(srvr) listen http://%hhu.%hhu.%hhu.%hhu:%d", ip >> 24, ip >> 16, ip >> 8, ip, port); if (printport && !ports.p[j]) { printf("%d\r\n", port); fflush(stdout); } } } // shrink allocated memory in case some of the sockets were skipped if (n < ips.n * ports.n) servers.p = realloc(servers.p, n * sizeof(*servers.p)); servers.n = n; polls = malloc((1 + n) * sizeof(*polls)); polls[0].fd = -1; polls[0].events = POLLIN; polls[0].revents = 0; for (i = 0; i < n; ++i) { polls[1 + i].fd = servers.p[i].fd; polls[1 + i].events = POLLIN; polls[1 + i].revents = 0; } } static void HandleShutdown(void) { CloseServerFds(); INFOF("(srvr) received %s", strsignal(shutdownsig)); if (shutdownsig != SIGINT && shutdownsig != SIGQUIT) { if (!killed) terminated = false; INFOF("(srvr) killing process group"); KillGroup(); } WaitAll(); INFOF("(srvr) shutdown complete"); } // this function coroutines with linenoise int EventLoop(int ms) { struct timespec t; DEBUGF("(repl) event loop"); while (!terminated) { errno = 0; if (zombied) { lua_repl_lock(); ReapZombies(); lua_repl_unlock(); } else if (invalidated) { lua_repl_lock(); HandleReload(); lua_repl_unlock(); invalidated = false; } else if (meltdown) { lua_repl_lock(); EnterMeltdownMode(); lua_repl_unlock(); meltdown = false; } else if (timespec_cmp(timespec_sub((t = timespec_real()), lastheartbeat), heartbeatinterval) >= 0) { lastheartbeat = t; HandleHeartbeat(); } else if (HandlePoll(ms) == -1) { break; } } return -1; } static void ReplEventLoop(void) { lua_State *L = GL; DEBUGF("ReplEventLoop()"); polls[0].fd = 0; lua_repl_completions_callback = HandleCompletions; lua_initrepl(L, "redbean"); EnableRawMode(); EventLoop(100); DisableRawMode(); lua_freerepl(); lua_settop(L, 0); // clear stack polls[0].fd = -1; } static int WindowsReplThread(void *arg, int tid) { int sig; lua_State *L = GL; DEBUGF("(repl) started windows thread"); lua_repl_blocking = true; lua_repl_completions_callback = HandleCompletions; lua_initrepl(L, "redbean"); EnableRawMode(); while (!terminated) { if (HandleReadline() == -1) { break; } } DisableRawMode(); lua_freerepl(); lua_repl_lock(); lua_settop(L, 0); // clear stack lua_repl_unlock(); if ((sig = linenoiseGetInterrupt())) { raise(sig); } DEBUGF("(repl) terminating windows thread"); return 0; } static void InstallSignalHandler(int sig, void *handler) { struct sigaction sa = {.sa_sigaction = handler}; if (sigaction(sig, &sa, 0) == -1) WARNF("(srvr) failed to set signal handler #%d: %m", sig); } static void SigInit(void) { InstallSignalHandler(SIGINT, OnInt); InstallSignalHandler(SIGHUP, OnHup); InstallSignalHandler(SIGTERM, OnTerm); InstallSignalHandler(SIGCHLD, OnChld); InstallSignalHandler(SIGUSR1, OnUsr1); InstallSignalHandler(SIGUSR2, OnUsr2); InstallSignalHandler(SIGPIPE, SIG_IGN); } static void TlsInit(void) { #ifndef UNSECURE int suite; if (unsecure) return; if (suiteb && !X86_HAVE(AES)) { WARNF("(srvr) requested suite b crypto, but aes-ni is not present"); } if (!sslinitialized) { InitializeRng(&rng); InitializeRng(&rngcli); suite = suiteb ? MBEDTLS_SSL_PRESET_SUITEB : MBEDTLS_SSL_PRESET_SUITEC; mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, suite); mbedtls_ssl_config_defaults(&confcli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, suite); } // the following setting can be re-applied even when SSL/TLS is initialized if (suites.n) { mbedtls_ssl_conf_ciphersuites(&conf, suites.p); mbedtls_ssl_conf_ciphersuites(&confcli, suites.p); } if (psks.n) { mbedtls_ssl_conf_psk_cb(&conf, TlsRoutePsk, 0); DCHECK_EQ(0, mbedtls_ssl_conf_psk(&confcli, psks.p[0].key, psks.p[0].key_len, psks.p[0].identity, psks.p[0].identity_len)); } if (sslticketlifetime > 0) { mbedtls_ssl_ticket_setup(&ssltick, mbedtls_ctr_drbg_random, &rng, MBEDTLS_CIPHER_AES_256_GCM, sslticketlifetime); mbedtls_ssl_conf_session_tickets_cb(&conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse, &ssltick); } if (sslinitialized) return; sslinitialized = true; LoadCertificates(); mbedtls_ssl_conf_sni(&conf, TlsRoute, 0); mbedtls_ssl_conf_dbg(&conf, TlsDebug, 0); mbedtls_ssl_conf_dbg(&confcli, TlsDebug, 0); mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &rng); mbedtls_ssl_conf_rng(&confcli, mbedtls_ctr_drbg_random, &rngcli); if (sslclientverify) { mbedtls_ssl_conf_ca_chain(&conf, GetSslRoots(), 0); mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED); } if (sslfetchverify) { mbedtls_ssl_conf_ca_chain(&confcli, GetSslRoots(), 0); mbedtls_ssl_conf_authmode(&confcli, MBEDTLS_SSL_VERIFY_REQUIRED); } else { mbedtls_ssl_conf_authmode(&confcli, MBEDTLS_SSL_VERIFY_NONE); } mbedtls_ssl_set_bio(&ssl, &g_bio, TlsSend, 0, TlsRecv); conf.disable_compression = confcli.disable_compression = true; DCHECK_EQ(0, mbedtls_ssl_conf_alpn_protocols(&conf, kAlpn)); DCHECK_EQ(0, mbedtls_ssl_conf_alpn_protocols(&confcli, kAlpn)); DCHECK_EQ(0, mbedtls_ssl_setup(&ssl, &conf)); DCHECK_EQ(0, mbedtls_ssl_setup(&sslcli, &confcli)); #endif } static void TlsDestroy(void) { #ifndef UNSECURE if (unsecure) return; mbedtls_ssl_free(&ssl); mbedtls_ssl_free(&sslcli); mbedtls_ctr_drbg_free(&rng); mbedtls_ctr_drbg_free(&rngcli); mbedtls_ssl_config_free(&conf); mbedtls_ssl_config_free(&confcli); mbedtls_ssl_ticket_free(&ssltick); CertsDestroy(); PsksDestroy(); Free(&suites.p), suites.n = 0; #endif } static void GetOpts(int argc, char *argv[]) { int opt; bool got_e_arg = false; bool storeasset = false; // only generate ecp cert under blinkenlights (rsa is slow) norsagen = IsGenuineBlink(); while ((opt = getopt(argc, argv, GETOPTS)) != -1) { switch (opt) { CASE('S', ++sandboxed); CASE('v', ++__log_level); CASE('s', --__log_level); CASE('X', unsecure = true); CASE('%', norsagen = true); CASE('Z', systrace = true); CASE('b', logbodies = true); CASE('z', printport = true); CASE('d', daemonize = true); CASE('a', logrusage = true); CASE('J', requiressl = true); CASE('u', uniprocess = true); CASE('g', loglatency = true); CASE('m', logmessages = true); CASE('w', launchbrowser = strdup(optarg)); CASE('l', ProgramAddr(optarg)); CASE('H', ProgramHeader(optarg)); CASE('L', ProgramLogPath(optarg)); CASE('P', ProgramPidPath(optarg)); CASE('D', ProgramDirectory(optarg)); CASE('U', ProgramUid(atoi(optarg))); CASE('G', ProgramGid(atoi(optarg))); CASE('p', ProgramPort(ParseInt(optarg))); CASE('R', ProgramRedirectArg(0, optarg)); case 'c':; // accept "num" or "num,directive" char *p; long ret = strtol(optarg, &p, 0); ProgramCache(ret, *p ? p + 1 : NULL); // skip separator, if any break; CASE('r', ProgramRedirectArg(307, optarg)); CASE('t', ProgramTimeout(ParseInt(optarg))); CASE('h', PrintUsage(1, EXIT_SUCCESS)); CASE('M', ProgramMaxPayloadSize(ParseInt(optarg))); #if !IsTiny() CASE('W', monitortty = optarg); case 'f': funtrace = true; if (ftrace_install() == -1) { WARNF("(srvr) ftrace failed to install %m"); } break; #endif #ifndef STATIC CASE('F', LuaEvalFile(optarg)); CASE('*', selfmodifiable = true); CASE('i', interpretermode = true); CASE('E', leakcrashreports = true); case 'e': got_e_arg = true; LuaEvalCode(optarg); break; case 'A': if (!storeasset) { storeasset = true; MakeExecutableModifiable(); } StorePath(optarg); break; #endif #ifndef UNSECURE CASE('B', suiteb = true); CASE('V', ++mbedtls_debug_threshold); CASE('k', sslfetchverify = false); CASE('j', sslclientverify = true); CASE('T', ProgramSslTicketLifetime(ParseInt(optarg))); CASE('C', ProgramFile(optarg, ProgramCertificate)); CASE('K', ProgramFile(optarg, ProgramPrivateKey)); #endif default: PrintUsage(2, EX_USAGE); } } // if storing asset(s) is requested, don't need to continue if (storeasset) exit(0); // we don't want to drop into a repl after using -e in -i mode if (interpretermode && got_e_arg) exit(0); } void RedBean(int argc, char *argv[]) { char ibuf[21]; int fd; if (IsLinux()) { // disable weird linux capabilities for (int e = errno, i = 0;; ++i) { if (prctl(PR_CAPBSET_DROP, i) == -1) { errno = e; break; } } // disable sneak privilege since we don't use them // seccomp will fail later if this fails prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); } reader = read; writer = WritevAll; gmtoff = GetGmtOffset((lastrefresh = startserver = timespec_real()).tv_sec); mainpid = getpid(); heartbeatinterval.tv_sec = 5; CHECK_GT(CLK_TCK, 0); CHECK_NE(MAP_FAILED, (shared = mmap(NULL, ROUNDUP(sizeof(struct Shared), FRAMESIZE), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0))); if (daemonize) { for (int i = 0; i < 256; ++i) { close(i); } open("/dev/null", O_RDONLY); open("/dev/null", O_WRONLY); open("/dev/null", O_WRONLY); } zpath = GetProgramExecutableName(); CHECK_NE(-1, (zfd = open(zpath, O_RDONLY))); CHECK_NE(-1, fstat(zfd, &zst)); OpenZip(true); SetDefaults(); // this can fail with EPERM if we're running under pledge() if (!interpretermode && !(interfaces = GetHostIps())) { WARNF("(srvr) failed to query system network interface addresses: %m"); } LuaStart(); GetOpts(argc, argv); #ifndef STATIC if (selfmodifiable) { MakeExecutableModifiable(); } #endif LuaInit(); oldloglevel = __log_level; if (uniprocess) { shared->workers = 1; } if (daemonize) { if (!logpath) ProgramLogPath("/dev/null"); dup2(2, 1); } SigInit(); Listen(); TlsInit(); if (launchbrowser) { LaunchBrowser(launchbrowser); } if (daemonize) { Daemonize(); } if (pidpath) { fd = open(pidpath, O_CREAT | O_WRONLY, 0644); WRITE(fd, ibuf, FormatInt32(ibuf, getpid()) - ibuf); close(fd); } ChangeUser(); UpdateCurrentDate(timespec_real()); CollectGarbage(); hdrbuf.n = 4 * 1024; hdrbuf.p = xmalloc(hdrbuf.n); inbuf_actual.n = maxpayloadsize; inbuf_actual.p = xmalloc(inbuf_actual.n); inbuf = inbuf_actual; isinitialized = true; CallSimpleHookIfDefined("OnServerStart"); if (!IsTiny()) { if (monitortty && (daemonize || uniprocess)) { monitortty = 0; } if (monitortty) { MonitorMemory(); } } #ifdef STATIC EventLoop(timespec_tomillis(heartbeatinterval)); #else GetHostsTxt(); // for effect GetResolvConf(); // for effect if (daemonize || uniprocess || !linenoiseIsTerminal()) { EventLoop(timespec_tomillis(heartbeatinterval)); } else if (IsWindows()) { CHECK_NE(-1, _spawn(WindowsReplThread, 0, &replth)); EventLoop(100); } else { ReplEventLoop(); } #endif if (!isexitingworker) { if (!IsTiny()) { terminatemonitor = true; _join(&monitorth); } #ifndef STATIC _join(&replth); #endif HandleShutdown(); CallSimpleHookIfDefined("OnServerStop"); } if (!IsTiny()) { LuaDestroy(); TlsDestroy(); MemDestroy(); } } int main(int argc, char *argv[]) { #if !IsTiny() && !defined(__x86_64__) ShowCrashReports(); #endif LoadZipArgs(&argc, &argv); RedBean(argc, argv); // try to detect memory leaks upon: // 1. main process exit // 2. unwound worker exit if (IsModeDbg()) { if (isexitingworker) { if (IsWindows()) { // TODO(jart): Get windows worker leak detector working again. return 0; CloseServerFds(); } _join(&replth); linenoiseDisableRawMode(); linenoiseHistoryFree(); } CheckForMemoryLeaks(); } return 0; }
223,844
7,518
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/seekable.txt
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
52
27
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/sql.lua
-- See .init.lua for CREATE TABLE setup. for row in db:nrows("SELECT * FROM test") do Write(row.id.." "..row.content.."<br>") end
133
5
jart/cosmopolitan
false