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/libc/x/xspawn.h | #ifndef COSMOPOLITAN_LIBC_X_XSPAWN_H_
#define COSMOPOLITAN_LIBC_X_XSPAWN_H_
#include "libc/calls/struct/rusage.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int xspawn(struct rusage *);
int xvspawn(void (*)(void *), void *, struct rusage *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_X_XSPAWN_H_ */
| 371 | 13 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xcalloc.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/x/x.h"
/**
* Allocates initialized memory, or dies.
*/
void *xcalloc(size_t count, size_t size) {
void *res = calloc(count, size);
if (!res) xdie();
return res;
}
| 2,049 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xstripexts.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/conv.h"
#include "libc/x/x.h"
/**
* Removes file extensions.
*
* @param s is mutated
* @return s
*/
char *xstripexts(const char *s) {
return stripexts(xstrdup(s));
}
| 2,029 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xstripext.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/conv.h"
#include "libc/x/x.h"
/**
* Removes file extension.
*
* @param s is mutated
* @return s
*/
char *xstripext(const char *s) {
return stripext(xstrdup(s));
}
| 2,026 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xreadlinkat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/mem/mem.h"
#include "libc/sysv/errfuns.h"
#include "libc/x/x.h"
/**
* Reads symbolic link.
*
* @return nul-terminated string, or null w/ errno
* @see readlinkat()
*/
char *xreadlinkat(int dirfd, const char *path) {
ssize_t rc;
size_t n, c;
char *p, *q;
c = PAGESIZE;
p = xmalloc(c);
if ((rc = readlinkat(dirfd, path, p, c)) != -1) {
if ((n = rc) < c) {
p[n] = 0;
if ((q = realloc(p, n + 1))) p = q;
return p;
} else {
enametoolong();
}
}
free(p);
return 0;
}
| 2,400 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xreadlink.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/sysv/consts/at.h"
#include "libc/x/x.h"
/**
* Reads symbolic link.
*
* @return nul-terminated string, or null w/ errno
* @see readlink()
*/
char *xreadlink(const char *path) {
return xreadlinkat(AT_FDCWD, path);
}
| 2,073 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xiso8601.h | #ifndef COSMOPOLITAN_LIBC_X_XISO8601_H_
#define COSMOPOLITAN_LIBC_X_XISO8601_H_
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
char *xiso8601i(int) mallocesque;
char *xiso8601tv(struct timeval *) mallocesque;
char *xiso8601ts(struct timespec *) mallocesque;
#if __STDC_VERSION__ + 0 >= 201112
#define xiso8601(TS) \
_Generic(*(TS), struct timeval : xiso8601tv, default : xiso8601ts)(TS)
#endif /* C11 */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_X_XISO8601_H_ */
| 613 | 20 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xvasprintf.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/fmt.h"
#include "libc/x/x.h"
#include "libc/x/xasprintf.h"
/**
* Returns dynamically formatted string.
*
* @return fully formatted string, which must be free()'d
* @see xasprintf()
*/
char *(xvasprintf)(const char *fmt, va_list va) {
char *buf;
if ((vasprintf)(&buf, fmt, va) == -1) xdie();
return buf;
}
| 2,172 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xbasename.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/fmt/conv.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/x/x.h"
/**
* Returns base portion of path.
*/
char *xbasename(const char *path) {
char *base;
path = xstrdup(path);
base = xstrdup(basename(path));
free(path);
return base;
}
| 2,126 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xstrdup.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/likely.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Allocates new copy of string, or dies.
*/
char *xstrdup(const char *s) {
size_t len = strlen(s);
char *s2 = malloc(len + 1);
if (UNLIKELY(!s2)) xdie();
return memcpy(s2, s, len + 1);
}
| 2,144 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xwrite.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/x/x.h"
/**
* Writes data uninterruptibly.
*
* @return 0 on success, or -1 w/ errno
*/
int xwrite(int fd, const void *p, uint64_t n) {
int64_t i;
uint64_t m;
const char *buf;
buf = p;
while (n) {
m = n;
do {
i = write(fd, buf, m);
} while (i < 0 && errno == EINTR);
if (i < 0) return -1;
buf += i;
n -= i;
}
return 0;
}
| 2,273 | 44 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xgetline.h | #ifndef COSMOPOLITAN_LIBC_X_XGETLINE_H_
#define COSMOPOLITAN_LIBC_X_XGETLINE_H_
#include "libc/stdio/stdio.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
char *xgetline(struct FILE *) paramsnonnull() mallocesque;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_X_XGETLINE_H_ */
| 343 | 12 | jart/cosmopolitan | false |
cosmopolitan/libc/x/unbingbuf.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/fmt/bing.internal.h"
#include "libc/log/check.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
/**
* Decodes human-readable CP437 glyphs into binary, e.g.
*
* char binged[5];
* char golden[5] = "\0\1\2\3\4";
* unbingbuf(binged, sizeof(binged), u" âºâ»â¥â¦", -1);
* CHECK_EQ(0, memcmp(binged, golden, 5));
*
* @param buf is caller owned
* @param size is byte length of buf
* @param glyphs is UCS-2 encoded CP437 representation of binary data
* @param fill if -1 will memset any remaining buffer space
* @note no NUL terminator is added to end of buf
* @see tunbing(), unbingstr(), unbing()
*/
void *unbingbuf(void *buf, size_t size, const char16_t *glyphs, int fill) {
int b;
char *p, *pe;
for (p = buf, pe = p + size; p < pe && *glyphs; ++p, ++glyphs) {
*p = (b = unbing(*glyphs)) & 0xff;
/* DCHECK_NE(-1, b, "%`'hc â IBMCP437\n", *glyphs); */
}
if (fill != -1) memset(p, fill, pe - p);
return buf;
}
| 2,879 | 51 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xload.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/atomic.h"
#include "libc/intrin/kmalloc.h"
#include "libc/runtime/internal.h"
#include "libc/x/x.h"
#include "third_party/zlib/zlib.h"
/**
* Inflates data once atomically, e.g.
*
* void *GetData(void) {
* static _Atomic(void *) ptr;
* static const unsigned char rodata[] = {...};
* return xload(&ptr, rodata, 112, 1024);
* }
*
* The above is an example of how this helper may be used to have lazy
* loading of big infrequently accessed image data.
*
* @param a points to your static pointer holder
* @param p is read-only data compressed using raw deflate
* @param n is byte length of deflated data
* @param m is byte length of inflated data
* @return pointer to inflated data
* @threadsafe
*/
void *xload(_Atomic(void *) *a, const void *p, size_t n, size_t m) {
void *r, *z;
if ((r = atomic_load_explicit(a, memory_order_acquire))) return r;
if (!(r = kmalloc(m))) return 0;
if (__inflate(r, m, p, n)) return 0;
z = 0;
if (!atomic_compare_exchange_strong_explicit(a, &z, r, memory_order_release,
memory_order_relaxed)) {
r = z;
}
return r;
}
| 3,013 | 56 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xloadzd.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/fmt/leb128.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/kmalloc.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/crc32.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
#include "libc/x/x.h"
#include "third_party/zlib/zlib.h"
/**
* Loads δzd encoded data once atomically.
*
* @param a points to your static pointer holder
* @param p is read-only data compressed using raw deflate
* @param n is byte length of deflated data
* @param m is byte length of inflated data
* @param c is number of items in array
* @param z is byte length of items
* @param s is crc32 checksum
* @return pointer to decoded data
* @threadsafe
*/
void *xloadzd(_Atomic(void *) *a, const void *p, size_t n, size_t m, size_t c,
size_t z, uint32_t s) {
size_t i;
char *q, *b;
void *r, *g;
int64_t x, y;
if ((r = atomic_load_explicit(a, memory_order_acquire))) return r;
_unassert(z == 2 || z == 4);
if (!(b = q = malloc(m))) return 0;
if (__inflate(q, m, p, n)) {
free(q);
return 0;
}
if (!(r = kmalloc(c * z))) {
free(q);
return 0;
}
for (x = i = 0; i < c; ++i) {
b += unzleb64(b, 10, &y);
x += y;
if (z == 2) {
((uint16_t *)r)[i] = x;
} else {
((uint32_t *)r)[i] = x;
}
}
free(q);
assert(crc32_z(0, r, c * z) == s);
g = 0;
if (!atomic_compare_exchange_strong_explicit(a, &g, r, memory_order_relaxed,
memory_order_relaxed)) {
r = g;
}
return r;
}
| 3,398 | 78 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xjoinpaths.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/safemacros.internal.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Joins paths, e.g.
*
* "a" + "b" â "a/b"
* "a/" + "b" â "a/b"
* "a" + "b/" â "a/b/"
* "a" + "/b" â "/b"
* "." + "b" â "b"
* "" + "b" â "b"
*
* @return newly allocated string of resulting path
*/
char *xjoinpaths(const char *path, const char *other) {
if (!*other) {
return xstrdup(path);
} else if (!*path) {
return xstrdup(other);
} else if (_isabspath(other) || !strcmp(path, ".")) {
return xstrdup(other);
} else if (_endswith(path, "/")) {
return xstrcat(path, other);
} else {
return xstrcat(path, (uintptr_t)'/', other);
}
}
| 2,582 | 49 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xsigaction.h | #ifndef COSMOPOLITAN_LIBC_X_XSIGACTION_H_
#define COSMOPOLITAN_LIBC_X_XSIGACTION_H_
#include "libc/calls/struct/sigaction.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int xsigaction(int, void *, uint64_t, uint64_t, struct sigaction *);
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
#define xsigaction(SIG, HANDLER, FLAGS, MASK, OLD) \
({ \
__SIGACTION_YOINK(SIG); \
xsigaction(SIG, HANDLER, FLAGS, MASK, OLD); \
})
#endif
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_X_XSIGACTION_H_ */
| 646 | 20 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xvalloc.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/x/x.h"
/**
* Allocates frame-aligned memory, or dies.
*/
void *xvalloc(size_t size) {
void *res = valloc(size);
if (!res) xdie();
return res;
}
| 2,030 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xvspawn.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/errno.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/sig.h"
#include "libc/x/xsigaction.h"
#include "libc/x/xspawn.h"
/**
* Spawns process using vfork().
*
* @param f is child callback
* @param r if provided gets accounting data
* @return wstatus, or -1 w/ errno
*/
int xvspawn(void f(void *), void *ctx, struct rusage *r) {
int pid, wstatus;
sigset_t chldmask, savemask;
struct sigaction saveint, savequit;
xsigaction(SIGINT, SIG_IGN, 0, 0, &saveint);
xsigaction(SIGQUIT, SIG_IGN, 0, 0, &savequit);
sigemptyset(&chldmask);
sigaddset(&chldmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &chldmask, &savemask);
if ((pid = vfork()) != -1) {
if (!pid) {
xsigaction(SIGINT, SIG_DFL, 0, 0, 0);
xsigaction(SIGQUIT, SIG_DFL, 0, 0, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
f(ctx);
_Exit(127);
}
while (wait4(pid, &wstatus, 0, r) == -1) {
if (errno != EINTR) {
wstatus = -1;
break;
}
}
sigaction(SIGINT, &saveint, 0);
sigaction(SIGQUIT, &savequit, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
return wstatus;
} else {
return -1;
}
}
| 3,155 | 67 | jart/cosmopolitan | false |
cosmopolitan/libc/x/utf8to16.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/str/thompike.h"
#include "libc/str/utf16.h"
#include "libc/x/x.h"
/**
* Transcodes UTF-8 to UTF-16.
*
* @param p is input value
* @param n if -1 implies strlen
* @param z if non-NULL receives output length
*/
char16_t *utf8to16(const char *p, size_t n, size_t *z) {
size_t i;
wint_t x, a, b;
char16_t *r, *q;
unsigned m, j, w;
if (z) *z = 0;
if (n == -1) n = p ? strlen(p) : 0;
if ((q = r = malloc((n + 16) * sizeof(char16_t) * 2 + sizeof(char16_t)))) {
for (i = 0; i < n;) {
#if defined(__SSE2__) && defined(__GNUC__) && !defined(__STRICT_ANSI__)
if (i + 16 < n) {
typedef char xmm_t __attribute__((__vector_size__(16), __aligned__(1)));
xmm_t vi, vz = {0};
do {
vi = *(const xmm_t *)(p + i);
*(xmm_t *)(q + 0) = __builtin_ia32_punpcklbw128(vi, vz);
*(xmm_t *)(q + 8) = __builtin_ia32_punpckhbw128(vi, vz);
if (!(m = __builtin_ia32_pmovmskb128(vi > vz) ^ 0xffff)) {
i += 16;
q += 16;
} else {
m = __builtin_ctzl(m);
i += m;
q += m;
break;
}
} while (i + 16 < n);
}
#endif
x = p[i++] & 0xff;
if (x >= 0300) {
a = ThomPikeByte(x);
m = ThomPikeLen(x) - 1;
if (i + m <= n) {
for (j = 0;;) {
b = p[i + j] & 0xff;
if (!ThomPikeCont(b)) break;
a = ThomPikeMerge(a, b);
if (++j == m) {
x = a;
i += j;
break;
}
}
}
}
w = EncodeUtf16(x);
*q++ = w;
if ((w >>= 16)) *q++ = w;
}
if (z) *z = q - r;
*q++ = '\0';
if ((q = realloc(r, (q - r) * sizeof(char16_t)))) r = q;
}
return r;
}
| 3,684 | 88 | jart/cosmopolitan | false |
cosmopolitan/libc/x/rmrf.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/dirent.h"
#include "libc/calls/struct/stat.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/s.h"
#include "libc/x/x.h"
static int rmrfdir(const char *dirpath) {
int rc;
DIR *d;
char *path;
struct dirent *e;
if (!(d = opendir(dirpath))) return -1;
while ((e = readdir(d))) {
if (!strcmp(e->d_name, ".")) continue;
if (!strcmp(e->d_name, "..")) continue;
_npassert(!strchr(e->d_name, '/'));
path = xjoinpaths(dirpath, e->d_name);
if (e->d_type == DT_DIR) {
rc = rmrfdir(path);
} else {
rc = unlink(path);
}
free(path);
if (rc == -1) {
closedir(d);
return -1;
}
}
rc = closedir(d);
rc |= rmdir(dirpath);
return rc;
}
/**
* Recursively removes file or directory.
*
* @return 0 on success, or -1 w/ errno
*/
int rmrf(const char *path) {
int e;
struct stat st;
e = errno;
if (stat(path, &st) == -1) {
if (errno == ENOENT) {
errno = e;
return 0;
} else {
return -1;
}
}
if (!S_ISDIR(st.st_mode)) {
return unlink(path);
} else {
return rmrfdir(path);
}
}
| 3,164 | 82 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xstrmul.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/str/str.h"
#include "libc/x/x.h"
/**
* Multiplies string.
*/
char *xstrmul(const char *s, size_t n) {
char *p;
size_t i, m, size;
m = strlen(s);
p = xcalloc(n + 1, m);
for (i = 0; i < n; ++i) memcpy(p + i * m, s, m);
p[i * m] = '\0';
return p;
}
| 2,142 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xbarf.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/str/str.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/o.h"
/**
* Writes data to file.
*
* @param size can be -1 to strlen(data)
* @return 0 on success or -1 w/ errno
* @note this is uninterruptible
*/
int xbarf(const char *path, const void *data, size_t size) {
char *p;
ssize_t rc;
int fd, res;
size_t i, wrote;
res = 0;
p = data;
if (size == -1) size = data ? strlen(data) : 0;
if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644)) != -1) {
if (ftruncate(fd, size) != -1) {
if (size > 2 * 1024 * 1024) {
fadvise(fd, 0, size, MADV_SEQUENTIAL);
}
for (i = 0; i < size; i += wrote) {
TryAgain:
if ((rc = pwrite(fd, p + i, size - i, i)) != -1) {
wrote = rc;
} else if (errno == EINTR) {
goto TryAgain;
} else {
res = -1;
break;
}
}
} else {
res = -1;
}
close(fd);
} else {
res = -1;
}
return res;
}
| 2,890 | 65 | jart/cosmopolitan | false |
cosmopolitan/libc/x/xrealloc.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/x/x.h"
/**
* Allocates/expands/shrinks/frees memory, or die.
*
* This API enables you to do the following:
*
* p = xrealloc(p, n)
*
* The standard behaviors for realloc() still apply:
*
* - `!p` means xmalloc (returns non-NULL)
* - `p && n` means resize (returns non-NULL)
* - `p && !n` means free (returns NULL)
*
* The complexity of resizing is guaranteed to be amortized.
*/
void *xrealloc(void *p, size_t n) {
void *q;
q = realloc(p, n);
if (!q && !(p && !n)) xdie();
return q;
}
| 2,388 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/x/utf16to32.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/str/utf16.h"
#include "libc/x/x.h"
/**
* Transcodes UTF-16 to UTF-32.
*
* @param p is input value
* @param n if -1 implies strlen
* @param z if non-NULL receives output length
*/
wchar_t *utf16to32(const char16_t *p, size_t n, size_t *z) {
wint_t x, y;
wchar_t *r, *q;
unsigned m, j, w;
const char16_t *e;
int16_t v1[8], v2[8], v3[8], vz[8];
if (z) *z = 0;
if (n == -1) n = p ? strlen16(p) : 0;
if ((q = r = malloc(n * 4 + 8 + 1))) {
for (e = p + n; p < e;) {
x = *p++ & 0xffff;
if (!IsUcs2(x)) {
if (p < e) {
y = *p++ & 0xffff;
x = MergeUtf16(x, y);
} else {
x = 0xFFFD;
}
}
*q++ = x;
}
if (z) *z = q - r;
*q++ = '\0';
if ((q = realloc(r, (q - r) * sizeof(*r)))) r = q;
}
return r;
}
| 2,713 | 58 | jart/cosmopolitan | false |
cosmopolitan/libc/x/x.h | #ifndef COSMOPOLITAN_LIBC_X_H_
#define COSMOPOLITAN_LIBC_X_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int xwrite(int, const void *, uint64_t);
void xdie(void) wontreturn;
char *xdtoa(double)
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xdtoaf(float)
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xdtoal(long double)
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xmalloc(size_t) attributeallocsize((1))
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xrealloc(void *, size_t)
attributeallocsize((2)) dontthrow nocallback dontdiscard;
void *xcalloc(size_t, size_t) attributeallocsize((1, 2))
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xvalloc(size_t) attributeallocsize((1)) returnsaligned((FRAMESIZE))
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xmemalign(size_t, size_t) attributeallocalign((1)) attributeallocsize((2))
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xmemalignzero(size_t, size_t) attributeallocalign((1))
attributeallocsize((2)) returnspointerwithnoaliases dontthrow nocallback
dontdiscard returnsnonnull;
char *xstrdup(const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xstrndup(const char *, size_t) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xstrcat(const char *, ...) paramsnonnull((1)) nullterminated()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
#define xstrcat(...) (xstrcat)(__VA_ARGS__, NULL)
char *xstrmul(const char *, size_t) paramsnonnull((1))
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xinet_ntop(int, const void *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void *xunbinga(size_t, const char16_t *)
attributeallocalign((1)) returnspointerwithnoaliases dontthrow nocallback
dontdiscard returnsnonnull dontthrow nocallback dontdiscard returnsnonnull;
void *xunbing(const char16_t *) returnspointerwithnoaliases dontthrow nocallback
dontdiscard returnsnonnull dontthrow nocallback dontdiscard returnsnonnull;
char16_t *utf8to16(const char *, size_t, size_t *) dontdiscard;
char *utf16to8(const char16_t *, size_t, size_t *) dontdiscard;
wchar_t *utf8to32(const char *, size_t, size_t *) dontdiscard;
wchar_t *utf16to32(const char16_t *, size_t, size_t *) dontdiscard;
char *utf32to8(const wchar_t *, size_t, size_t *) dontdiscard;
char *xhomedir(void) dontdiscard;
char *xstripext(const char *) dontdiscard;
char *xstripexts(const char *) dontdiscard;
void *xload(_Atomic(void *) *, const void *, size_t, size_t);
void *xloadzd(_Atomic(void *) *, const void *, size_t, size_t, size_t, size_t,
uint32_t);
int rmrf(const char *);
char *xbasename(const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xdirname(const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xjoinpaths(const char *, const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xreadlink(const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
char *xreadlinkat(int, const char *) paramsnonnull()
returnspointerwithnoaliases dontthrow nocallback dontdiscard returnsnonnull;
void xfixpath(void);
void *xslurp(const char *, size_t *)
paramsnonnull((1)) returnspointerwithnoaliases
returnsaligned((PAGESIZE)) dontdiscard;
int xbarf(const char *, const void *, size_t);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_X_H_ */
| 4,027 | 74 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/accept-sysv.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/dce.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
int sys_accept(int server, void *addr, uint32_t *addrsize) {
int client;
uint32_t size;
union sockaddr_storage_bsd bsd;
if (!IsBsd()) {
client = __sys_accept(server, addr, addrsize, 0);
} else {
size = sizeof(bsd);
if ((client = __sys_accept(server, &bsd, &size, 0)) != -1) {
sockaddr2linux(&bsd, size, addr, addrsize);
}
}
return client;
}
| 2,316 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/epoll.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â â
â wepoll â
â https://github.com/piscisaureus/wepoll â
â â
â Copyright 2012-2020, Bert Belder <[email protected]> â
â All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions are â
â met: â
â â
â * Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â * Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in the â
â documentation and/or other materials provided with the distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS â
â "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT â
â LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR â
â A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT â
â OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, â
â SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT â
â LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, â
â DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY â
â THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT â
â (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE â
â OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/sock/epoll.h"
#include "libc/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/sigset.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/strace.internal.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/afd.h"
#include "libc/nt/enum/filesharemode.h"
#include "libc/nt/enum/ioctl.h"
#include "libc/nt/enum/keyedevent.h"
#include "libc/nt/enum/sio.h"
#include "libc/nt/enum/status.h"
#include "libc/nt/enum/wait.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/iocp.h"
#include "libc/nt/nt/file.h"
#include "libc/nt/nt/key.h"
#include "libc/nt/ntdll.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/afd.h"
#include "libc/nt/struct/criticalsection.h"
#include "libc/nt/struct/objectattributes.h"
#include "libc/nt/struct/overlappedentry.h"
#include "libc/nt/struct/unicodestring.h"
#include "libc/nt/synchronization.h"
#include "libc/nt/winsock.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/epoll.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
/**
* @fileoverview epoll
*
* This is an alternative to poll() that's popular for event driven
* network servers that want >10,000 sockets per machine and don't do
* cpu bound computations that would otherwise block the event loop.
*
* This works on Linux and is polyfilled on Windows. It's worth noting
* that these polyfills depend on Microsoft's internal APIs. However
* these particular NTDLL APIs are also used by libuv, nodejs, etc. so
* we're reasonably certain Microsoft has compatibility policies in
* place where they've promised not to break them.
*
* TODO(jart): Polyfill kqueue for XNU/FreeBSD/OpenBSD.
*/
asm(".ident\t\"\\n\\n\
wepoll (BSD-2)\\n\
Copyright 2012-2020 Bert Belder\\n\
https://github.com/piscisaureus/wepoll\"");
asm(".include \"libc/disclaimer.inc\"");
#define MAX_GROUP_SIZE 32
#define REFLOCK__REF 0x00000001
#define REFLOCK__REF_MASK 0x0fffffff
#define REFLOCK__DESTROY 0x10000000
#define REFLOCK__DESTROY_MASK 0xf0000000
#define REFLOCK__POISON 0x300dead0
#define KNOWN_EVENTS \
(EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | \
EPOLLRDBAND | EPOLLWRNORM | EPOLLWRBAND | EPOLLMSG | EPOLLRDHUP)
#define RTL_CONSTANT_STRING(s) \
{ sizeof(s) - sizeof((s)[0]), sizeof(s), s }
#define RTL_CONSTANT_OBJECT_ATTRIBUTES(ObjectName, Attributes) \
{ sizeof(struct NtObjectAttributes), 0, ObjectName, Attributes, NULL, NULL }
#define RETURN_MAP_ERROR(value) \
do { \
err_map_win_error(); \
return value; \
} while (0)
#define RETURN_SET_ERROR(value, error) \
do { \
err_set_win_error(error); \
return value; \
} while (0)
#define CONTAINOF(ptr, type, member) \
((type *)((uintptr_t)(ptr)-offsetof(type, member)))
#define TREE__ROTATE(cis, trans) \
struct TreeNode *p = node; \
struct TreeNode *q = node->trans; \
struct TreeNode *parent = p->parent; \
if (parent) { \
if (parent->left == p) \
parent->left = q; \
else \
parent->right = q; \
} else { \
tree->root = q; \
} \
q->parent = parent; \
p->parent = q; \
p->trans = q->cis; \
if (p->trans) p->trans->parent = p; \
q->cis = p;
#define TREE__INSERT_OR_DESCEND(side) \
if (parent->side) { \
parent = parent->side; \
} else { \
parent->side = node; \
break; \
}
#define TREE__REBALANCE_AFTER_INSERT(cis, trans) \
struct TreeNode *grandparent = parent->parent; \
struct TreeNode *uncle = grandparent->trans; \
if (uncle && uncle->red) { \
parent->red = uncle->red = false; \
grandparent->red = true; \
node = grandparent; \
} else { \
if (node == parent->trans) { \
tree__rotate_##cis(tree, parent); \
node = parent; \
parent = node->parent; \
} \
parent->red = false; \
grandparent->red = true; \
tree__rotate_##trans(tree, grandparent); \
}
#define TREE__REBALANCE_AFTER_REMOVE(cis, trans) \
struct TreeNode *sibling = parent->trans; \
if (sibling->red) { \
sibling->red = false; \
parent->red = true; \
tree__rotate_##cis(tree, parent); \
sibling = parent->trans; \
} \
if ((sibling->left && sibling->left->red) || \
(sibling->right && sibling->right->red)) { \
if (!sibling->trans || !sibling->trans->red) { \
sibling->cis->red = false; \
sibling->red = true; \
tree__rotate_##trans(tree, sibling); \
sibling = parent->trans; \
} \
sibling->red = parent->red; \
parent->red = sibling->trans->red = false; \
tree__rotate_##cis(tree, parent); \
node = tree->root; \
break; \
} \
sibling->red = true;
#define tree_root(t) (t)->root
#define port_state_to_handle_tree_node(p) (&(p)->handle_tree_node)
#define sock_state_from_queue_node(q) CONTAINOF(q, struct SockState, queue_node)
#define sock_state_to_queue_node(s) (&(s)->queue_node)
#define sock_state_from_tree_node(t) CONTAINOF(t, struct SockState, tree_node)
#define sock_state_to_tree_node(s) (&(s)->tree_node)
#define poll_group_from_queue_node(q) CONTAINOF(q, struct PollGroup, queue_node)
#define poll_group_get_afd_device_handle(pg) (pg)->afd_device_handle
enum PollStatus {
kPollIdle,
kPollPending,
kPollCancelled,
};
struct RefLock {
int state;
};
struct TreeNode {
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
uintptr_t key;
bool red;
};
struct Tree {
struct TreeNode *root;
};
struct TsTree {
struct Tree tree;
intptr_t lock;
};
struct TsTreeNode {
struct TreeNode tree_node;
struct RefLock reflock;
};
struct QueueNode {
struct QueueNode *prev;
struct QueueNode *next;
};
struct Queue {
struct QueueNode head;
};
struct PortState {
int64_t iocp_handle;
struct Tree sock_tree;
struct Queue sock_update_queue;
struct Queue sock_deleted_queue;
struct Queue poll_group_queue;
struct TsTreeNode handle_tree_node;
struct NtCriticalSection lock;
size_t active_poll_count;
};
struct PollGroup {
struct PortState *port_state;
struct QueueNode queue_node;
int64_t afd_device_handle;
size_t group_size;
};
struct SockState {
struct NtIoStatusBlock io_status_block;
struct NtAfdPollInfo poll_info;
struct QueueNode queue_node;
struct TreeNode tree_node;
struct PollGroup *poll_group;
int64_t base_socket;
epoll_data_t user_data;
uint32_t user_events;
uint32_t pending_events;
enum PollStatus poll_status;
bool delete_pending;
};
static const struct NtUnicodeString afd__device_name =
RTL_CONSTANT_STRING(u"\\Device\\Afd\\Wepoll");
static const struct NtObjectAttributes afd__device_attributes =
RTL_CONSTANT_OBJECT_ATTRIBUTES(&afd__device_name, 0);
static int64_t reflock__keyed_event;
static struct TsTree epoll__handle_tree;
static textwindows void err_map_win_error(void) {
errno = __dos2errno(GetLastError());
}
static textwindows void err_set_win_error(uint32_t error) {
SetLastError(error);
errno = __dos2errno(error);
}
static textwindows int err_check_handle(int64_t handle) {
uint32_t flags;
/* GetHandleInformation() succeeds when passed INVALID_HANDLE_VALUE,
so check for this condition explicitly. */
if (handle == kNtInvalidHandleValue) {
RETURN_SET_ERROR(-1, kNtErrorInvalidHandle);
}
if (!GetHandleInformation(handle, &flags)) {
RETURN_MAP_ERROR(-1);
}
return 0;
}
static textwindows void tree_init(struct Tree *tree) {
bzero(tree, sizeof *tree);
}
static textwindows void ts_tree_init(struct TsTree *ts_tree) {
tree_init(&ts_tree->tree);
InitializeSRWLock(&ts_tree->lock);
}
static textwindows int reflock_global_init(void) {
NtStatus status;
if ((status = NtCreateKeyedEvent(&reflock__keyed_event,
kNtKeyedeventAllAccess, NULL, 0)) !=
kNtStatusSuccess) {
RETURN_SET_ERROR(-1, RtlNtStatusToDosError(status));
}
return 0;
}
static textwindows int epoll_global_init(void) {
ts_tree_init(&epoll__handle_tree);
return 0;
}
static textwindows int wepoll_init(void) {
static bool once;
static bool result;
if (!once) {
if (reflock_global_init() < 0 || epoll_global_init() < 0) {
result = false;
} else {
result = true;
}
once = true;
}
return result;
}
static textwindows int afd_create_device_handle(
int64_t iocp_handle, int64_t *afd_device_handle_out) {
NtStatus status;
int64_t afd_device_handle;
struct NtIoStatusBlock iosb;
/* By opening \Device\Afd without specifying any extended attributes,
we'll get a handle that lets us talk to the AFD driver, but that
doesn't have an *associated endpoint (so it's not a socket). */
status = NtCreateFile(&afd_device_handle, kNtSynchronize,
&afd__device_attributes, &iosb, NULL, 0,
kNtFileShareRead | kNtFileShareWrite, 1, 0, NULL, 0);
if (status != kNtStatusSuccess) {
RETURN_SET_ERROR(-1, RtlNtStatusToDosError(status));
}
if (!CreateIoCompletionPort(afd_device_handle, iocp_handle, 0, 0)) {
goto error;
}
if (!SetFileCompletionNotificationModes(afd_device_handle,
kNtFileSkipSetEventOnHandle)) {
goto error;
}
*afd_device_handle_out = afd_device_handle;
return 0;
error:
CloseHandle(afd_device_handle);
RETURN_MAP_ERROR(-1);
}
static textwindows int afd_poll(int64_t afd_device_handle,
struct NtAfdPollInfo *poll_info,
struct NtIoStatusBlock *io_status_block) {
NtStatus status;
/* Blocking operation is not supported.*/
_npassert(io_status_block);
io_status_block->Status = kNtStatusPending;
status =
NtDeviceIoControlFile(afd_device_handle, 0, NULL, io_status_block,
io_status_block, kNtIoctlAfdPoll, poll_info,
sizeof(*poll_info), poll_info, sizeof(*poll_info));
if (status == kNtStatusSuccess) {
return 0;
} else if (status == kNtStatusPending) {
RETURN_SET_ERROR(-1, kNtErrorIoPending);
} else {
RETURN_SET_ERROR(-1, RtlNtStatusToDosError(status));
}
}
static textwindows int afd_cancel_poll(
int64_t afd_device_handle, struct NtIoStatusBlock *io_status_block) {
NtStatus cancel_status;
struct NtIoStatusBlock cancel_iosb;
/* If the poll operation has already completed or has been cancelled
earlier, there's nothing left for us to do. */
if (io_status_block->Status != kNtStatusPending) return 0;
cancel_status =
NtCancelIoFileEx(afd_device_handle, io_status_block, &cancel_iosb);
/* NtCancelIoFileEx() may return STATUS_NOT_FOUND if the operation completed
just before calling NtCancelIoFileEx(). This is not an error. */
if (cancel_status == kNtStatusSuccess || cancel_status == kNtStatusNotFound) {
return 0;
} else {
RETURN_SET_ERROR(-1, RtlNtStatusToDosError(cancel_status));
}
}
static textwindows void queue_node_init(struct QueueNode *node) {
node->prev = node;
node->next = node;
}
static textwindows void queue_init(struct Queue *queue) {
queue_node_init(&queue->head);
}
static textwindows void queue__detach_node(struct QueueNode *node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
forceinline bool queue_is_enqueued(const struct QueueNode *node) {
return node->prev != node;
}
forceinline bool queue_is_empty(const struct Queue *queue) {
return !queue_is_enqueued(&queue->head);
}
static textwindows struct QueueNode *queue_first(const struct Queue *queue) {
return !queue_is_empty(queue) ? queue->head.next : NULL;
}
static textwindows struct QueueNode *queue_last(const struct Queue *queue) {
return !queue_is_empty(queue) ? queue->head.prev : NULL;
}
static textwindows void queue_prepend(struct Queue *queue,
struct QueueNode *node) {
node->next = queue->head.next;
node->prev = &queue->head;
node->next->prev = node;
queue->head.next = node;
}
static textwindows void queue_append(struct Queue *queue,
struct QueueNode *node) {
node->next = &queue->head;
node->prev = queue->head.prev;
node->prev->next = node;
queue->head.prev = node;
}
static textwindows void queue_move_to_start(struct Queue *queue,
struct QueueNode *node) {
queue__detach_node(node);
queue_prepend(queue, node);
}
static textwindows void queue_move_to_end(struct Queue *queue,
struct QueueNode *node) {
queue__detach_node(node);
queue_append(queue, node);
}
static textwindows void queue_remove(struct QueueNode *node) {
queue__detach_node(node);
queue_node_init(node);
}
static textwindows struct PortState *port__alloc(void) {
struct PortState *port_state = malloc(sizeof *port_state);
if (!port_state) RETURN_SET_ERROR(NULL, kNtErrorNotEnoughMemory);
return port_state;
}
static textwindows int64_t port__create_iocp(void) {
int64_t iocp_handle = CreateIoCompletionPort(kNtInvalidHandleValue, 0, 0, 0);
if (!iocp_handle) RETURN_MAP_ERROR(0);
return iocp_handle;
}
static textwindows int port__close_iocp(struct PortState *port_state) {
int64_t iocp_handle = port_state->iocp_handle;
port_state->iocp_handle = 0;
if (!CloseHandle(iocp_handle)) RETURN_MAP_ERROR(-1);
return 0;
}
static textwindows void tree_node_init(struct TreeNode *node) {
bzero(node, sizeof *node);
}
static textwindows void reflock_init(struct RefLock *reflock) {
reflock->state = 0;
}
static textwindows void ts_tree_node_init(struct TsTreeNode *node) {
tree_node_init(&node->tree_node);
reflock_init(&node->reflock);
}
static textwindows void tree__rotate_left(struct Tree *tree,
struct TreeNode *node) {
TREE__ROTATE(left, right)
}
static textwindows void tree__rotate_right(struct Tree *tree,
struct TreeNode *node) {
TREE__ROTATE(right, left)
}
static textwindows int tree_add(struct Tree *tree, struct TreeNode *node,
uintptr_t key) {
struct TreeNode *parent;
parent = tree->root;
if (parent) {
for (;;) {
if (key < parent->key) {
TREE__INSERT_OR_DESCEND(left)
} else if (key > parent->key) {
TREE__INSERT_OR_DESCEND(right)
} else {
return -1;
}
}
} else {
tree->root = node;
}
node->key = key;
node->left = node->right = NULL;
node->parent = parent;
node->red = true;
for (; parent && parent->red; parent = node->parent) {
if (parent == parent->parent->left) {
TREE__REBALANCE_AFTER_INSERT(left, right)
} else {
TREE__REBALANCE_AFTER_INSERT(right, left)
}
}
tree->root->red = false;
return 0;
}
static textwindows int ts_tree_add(struct TsTree *ts_tree,
struct TsTreeNode *node, uintptr_t key) {
int r;
AcquireSRWLockExclusive(&ts_tree->lock);
r = tree_add(&ts_tree->tree, &node->tree_node, key);
ReleaseSRWLockExclusive(&ts_tree->lock);
return r;
}
static textwindows void port__free(struct PortState *port) {
_npassert(port);
free(port);
}
static textwindows struct PortState *port_new(int64_t *iocp_handle_out) {
struct PortState *port_state;
int64_t iocp_handle;
port_state = port__alloc();
if (!port_state) goto err1;
iocp_handle = port__create_iocp();
if (!iocp_handle) goto err2;
bzero(port_state, sizeof *port_state);
port_state->iocp_handle = iocp_handle;
tree_init(&port_state->sock_tree);
queue_init(&port_state->sock_update_queue);
queue_init(&port_state->sock_deleted_queue);
queue_init(&port_state->poll_group_queue);
ts_tree_node_init(&port_state->handle_tree_node);
InitializeCriticalSection(&port_state->lock);
*iocp_handle_out = iocp_handle;
return port_state;
err2:
port__free(port_state);
err1:
return NULL;
}
static textwindows int sock__cancel_poll(struct SockState *sock_state) {
_npassert(sock_state->poll_status == kPollPending);
if (afd_cancel_poll(poll_group_get_afd_device_handle(sock_state->poll_group),
&sock_state->io_status_block) < 0) {
return -1;
}
sock_state->poll_status = kPollCancelled;
sock_state->pending_events = 0;
return 0;
}
static textwindows void port_cancel_socket_update(
struct PortState *port_state, struct SockState *sock_state) {
if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) return;
queue_remove(sock_state_to_queue_node(sock_state));
}
static textwindows struct TreeNode *tree_find(const struct Tree *tree,
uintptr_t key) {
struct TreeNode *node = tree->root;
while (node) {
if (key < node->key) {
node = node->left;
} else if (key > node->key) {
node = node->right;
} else {
return node;
}
}
return NULL;
}
static textwindows struct TsTreeNode *ts_tree__find_node(struct TsTree *ts_tree,
uintptr_t key) {
struct TreeNode *tree_node = tree_find(&ts_tree->tree, key);
if (!tree_node) return NULL;
return CONTAINOF(tree_node, struct TsTreeNode, tree_node);
}
static textwindows void tree_del(struct Tree *tree, struct TreeNode *node) {
bool red;
struct TreeNode *parent, *left, *right, *next;
parent = node->parent;
left = node->left;
right = node->right;
if (!left) {
next = right;
} else if (!right) {
next = left;
} else {
next = right;
while (next->left) next = next->left;
}
if (parent) {
if (parent->left == node) {
parent->left = next;
} else {
parent->right = next;
}
} else {
tree->root = next;
}
if (left && right) {
red = next->red;
next->red = node->red;
next->left = left;
left->parent = next;
if (next != right) {
parent = next->parent;
next->parent = node->parent;
node = next->right;
parent->left = node;
next->right = right;
right->parent = next;
} else {
next->parent = parent;
parent = next;
node = next->right;
}
} else {
red = node->red;
node = next;
}
if (node) node->parent = parent;
if (red) return;
if (node && node->red) {
node->red = false;
return;
}
do {
if (node == tree->root) break;
if (node == parent->left) {
TREE__REBALANCE_AFTER_REMOVE(left, right)
} else {
TREE__REBALANCE_AFTER_REMOVE(right, left)
}
node = parent;
parent = parent->parent;
} while (!node->red);
if (node) node->red = false;
}
static textwindows void reflock__signal_event(void *address) {
NtStatus status =
NtReleaseKeyedEvent(reflock__keyed_event, address, false, NULL);
if (status != kNtStatusSuccess) abort();
}
static textwindows void reflock__await_event(void *address) {
NtStatus status =
NtWaitForKeyedEvent(reflock__keyed_event, address, false, NULL);
if (status != kNtStatusSuccess) abort();
}
static textwindows void reflock_ref(struct RefLock *reflock) {
long state = InterlockedAdd(&reflock->state, REFLOCK__REF);
/* Verify that the counter didn 't overflow and the lock isn' t destroyed.*/
_npassert((state & REFLOCK__DESTROY_MASK) == 0);
}
static textwindows void reflock_unref(struct RefLock *reflock) {
long state = InterlockedAdd(&reflock->state, -REFLOCK__REF);
/* Verify that the lock was referenced and not already destroyed.*/
_npassert((state & REFLOCK__DESTROY_MASK & ~REFLOCK__DESTROY) == 0);
if (state == REFLOCK__DESTROY) reflock__signal_event(reflock);
}
static textwindows struct TsTreeNode *ts_tree_del_and_ref(
struct TsTree *ts_tree, uintptr_t key) {
struct TsTreeNode *ts_tree_node;
AcquireSRWLockExclusive(&ts_tree->lock);
ts_tree_node = ts_tree__find_node(ts_tree, key);
if (ts_tree_node != NULL) {
tree_del(&ts_tree->tree, &ts_tree_node->tree_node);
reflock_ref(&ts_tree_node->reflock);
}
ReleaseSRWLockExclusive(&ts_tree->lock);
return ts_tree_node;
}
static textwindows struct TsTreeNode *ts_tree_find_and_ref(
struct TsTree *ts_tree, uintptr_t key) {
struct TsTreeNode *ts_tree_node;
AcquireSRWLockShared(&ts_tree->lock);
ts_tree_node = ts_tree__find_node(ts_tree, key);
if (ts_tree_node != NULL) reflock_ref(&ts_tree_node->reflock);
ReleaseSRWLockShared(&ts_tree->lock);
return ts_tree_node;
}
static textwindows void ts_tree_node_unref(struct TsTreeNode *node) {
reflock_unref(&node->reflock);
}
static textwindows void reflock_unref_and_destroy(struct RefLock *reflock) {
long state, ref_count;
state = InterlockedAdd(&reflock->state, REFLOCK__DESTROY - REFLOCK__REF);
ref_count = state & REFLOCK__REF_MASK;
/* Verify that the lock was referenced and not already destroyed. */
_npassert((state & REFLOCK__DESTROY_MASK) == REFLOCK__DESTROY);
if (ref_count != 0) reflock__await_event(reflock);
state = InterlockedExchange(&reflock->state, REFLOCK__POISON);
_npassert(state == REFLOCK__DESTROY);
}
static textwindows void ts_tree_node_unref_and_destroy(
struct TsTreeNode *node) {
reflock_unref_and_destroy(&node->reflock);
}
static textwindows void port_unregister_socket(struct PortState *port_state,
struct SockState *sock_state) {
tree_del(&port_state->sock_tree, sock_state_to_tree_node(sock_state));
}
static textwindows void port_remove_deleted_socket(
struct PortState *port_state, struct SockState *sock_state) {
if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) return;
queue_remove(sock_state_to_queue_node(sock_state));
}
static textwindows struct Queue *port_get_poll_group_queue(
struct PortState *port_state) {
return &port_state->poll_group_queue;
}
static textwindows void poll_group_release(struct PollGroup *poll_group) {
struct PortState *port_state = poll_group->port_state;
struct Queue *poll_group_queue = port_get_poll_group_queue(port_state);
poll_group->group_size--;
_npassert(poll_group->group_size < MAX_GROUP_SIZE);
queue_move_to_end(poll_group_queue, &poll_group->queue_node);
/* Poll groups are currently only freed when the epoll port is closed. */
}
static textwindows void sock__free(struct SockState *sock_state) {
_npassert(sock_state != NULL);
free(sock_state);
}
static textwindows void port_add_deleted_socket(struct PortState *port_state,
struct SockState *sock_state) {
if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) return;
queue_append(&port_state->sock_deleted_queue,
sock_state_to_queue_node(sock_state));
}
static textwindows int sock__delete(struct PortState *port_state,
struct SockState *sock_state, bool force) {
if (!sock_state->delete_pending) {
if (sock_state->poll_status == kPollPending) {
sock__cancel_poll(sock_state);
}
port_cancel_socket_update(port_state, sock_state);
port_unregister_socket(port_state, sock_state);
sock_state->delete_pending = true;
}
/* If the poll request still needs to complete, the sock_state object
can't be free'd yet. `sock_feed_event()` or `port_close()` will
take care of this later. */
if (force || sock_state->poll_status == kPollIdle) {
port_remove_deleted_socket(port_state, sock_state);
poll_group_release(sock_state->poll_group);
sock__free(sock_state);
} else {
/* Free the socket later.*/
port_add_deleted_socket(port_state, sock_state);
}
return 0;
}
static textwindows void sock_delete(struct PortState *port_state,
struct SockState *sock_state) {
sock__delete(port_state, sock_state, false);
}
static textwindows void sock_force_delete(struct PortState *port_state,
struct SockState *sock_state) {
sock__delete(port_state, sock_state, true);
}
static textwindows void poll_group_delete(struct PollGroup *poll_group) {
_npassert(poll_group->group_size == 0);
CloseHandle(poll_group->afd_device_handle);
queue_remove(&poll_group->queue_node);
free(poll_group);
}
static textwindows int port_delete(struct PortState *port_state) {
struct TreeNode *tree_node;
struct QueueNode *queue_node;
struct SockState *sock_state;
struct PollGroup *poll_group;
/* At this point the IOCP port should have been closed.*/
_npassert(!port_state->iocp_handle);
while ((tree_node = tree_root(&port_state->sock_tree)) != NULL) {
sock_state = sock_state_from_tree_node(tree_node);
sock_force_delete(port_state, sock_state);
}
while ((queue_node = queue_first(&port_state->sock_deleted_queue)) != NULL) {
sock_state = sock_state_from_queue_node(queue_node);
sock_force_delete(port_state, sock_state);
}
while ((queue_node = queue_first(&port_state->poll_group_queue)) != NULL) {
poll_group = poll_group_from_queue_node(queue_node);
poll_group_delete(poll_group);
}
_npassert(queue_is_empty(&port_state->sock_update_queue));
DeleteCriticalSection(&port_state->lock);
port__free(port_state);
return 0;
}
static textwindows int64_t port_get_iocp_handle(struct PortState *port_state) {
_npassert(port_state->iocp_handle);
return port_state->iocp_handle;
}
static textwindows struct PollGroup *poll_group__new(
struct PortState *port_state) {
int64_t iocp_handle = port_get_iocp_handle(port_state);
struct Queue *poll_group_queue = port_get_poll_group_queue(port_state);
struct PollGroup *poll_group = malloc(sizeof *poll_group);
if (!poll_group) RETURN_SET_ERROR(NULL, kNtErrorNotEnoughMemory);
bzero(poll_group, sizeof *poll_group);
queue_node_init(&poll_group->queue_node);
poll_group->port_state = port_state;
if (afd_create_device_handle(iocp_handle, &poll_group->afd_device_handle) <
0) {
free(poll_group);
return NULL;
}
queue_append(poll_group_queue, &poll_group->queue_node);
return poll_group;
}
static textwindows struct PollGroup *poll_group_acquire(
struct PortState *port_state) {
struct Queue *poll_group_queue = port_get_poll_group_queue(port_state);
struct PollGroup *poll_group = !queue_is_empty(poll_group_queue)
? CONTAINOF(queue_last(poll_group_queue),
struct PollGroup, queue_node)
: NULL;
if (!poll_group || poll_group->group_size >= MAX_GROUP_SIZE)
poll_group = poll_group__new(port_state);
if (!poll_group) return NULL;
if (++poll_group->group_size == MAX_GROUP_SIZE)
queue_move_to_start(poll_group_queue, &poll_group->queue_node);
return poll_group;
}
static textwindows int port_close(struct PortState *port_state) {
int result;
EnterCriticalSection(&port_state->lock);
result = port__close_iocp(port_state);
LeaveCriticalSection(&port_state->lock);
return result;
}
static textwindows uint32_t sock__epoll_events_to_afd_events(uint32_t e) {
/* Always monitor for kNtAfdPollLocalClose, which is triggered when
the socket is closed with closesocket() or CloseHandle(). */
uint32_t a = kNtAfdPollLocalClose;
if (e & (EPOLLIN | EPOLLRDNORM)) a |= kNtAfdPollReceive | kNtAfdPollAccept;
if (e & (EPOLLPRI | EPOLLRDBAND)) a |= kNtAfdPollReceiveExpedited;
if (e & (EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND)) a |= kNtAfdPollSend;
if (e & (EPOLLIN | EPOLLRDNORM | EPOLLRDHUP)) a |= kNtAfdPollDisconnect;
if (e & EPOLLHUP) a |= kNtAfdPollAbort;
if (e & EPOLLERR) a |= kNtAfdPollConnectFail;
return a;
}
static textwindows uint32_t sock__afd_events_to_epoll_events(uint32_t a) {
uint32_t e = 0;
if (a & (kNtAfdPollReceive | kNtAfdPollAccept)) e |= EPOLLIN | EPOLLRDNORM;
if (a & kNtAfdPollReceiveExpedited) e |= EPOLLPRI | EPOLLRDBAND;
if (a & kNtAfdPollSend) e |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
if (a & kNtAfdPollDisconnect) e |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
if (a & kNtAfdPollAbort) e |= EPOLLHUP;
if (a & kNtAfdPollConnectFail) {
/* Linux reports all these events after connect() has failed. */
e |= EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLRDNORM | EPOLLWRNORM | EPOLLRDHUP;
}
return e;
}
static textwindows int sock_update(struct PortState *port_state,
struct SockState *sock_state) {
_npassert(!sock_state->delete_pending);
if ((sock_state->poll_status == kPollPending) &&
!(sock_state->user_events & KNOWN_EVENTS & ~sock_state->pending_events)) {
/* All the events the user is interested in are already being
monitored by the pending poll operation. It might spuriously
complete because of an event that we're no longer interested in;
when that happens we'll submit a new poll operation with the
updated event mask. */
} else if (sock_state->poll_status == kPollPending) {
/* A poll operation is already pending, but it's not monitoring for
all the *events that the user is interested in .Therefore, cancel
the pending *poll operation; when we receive it's completion
package, a new poll *operation will be submitted with the correct
event mask. */
if (sock__cancel_poll(sock_state) < 0) return -1;
} else if (sock_state->poll_status == kPollCancelled) {
/* The poll operation has already been cancelled, we're still waiting for
it to return.For now, there' s nothing that needs to be done. */
} else if (sock_state->poll_status == kPollIdle) {
/* No poll operation is pending; start one. */
sock_state->poll_info.Exclusive = false;
sock_state->poll_info.NumberOfHandles = 1;
sock_state->poll_info.Timeout = INT64_MAX;
sock_state->poll_info.Handles[0].Handle = (int64_t)sock_state->base_socket;
sock_state->poll_info.Handles[0].Status = 0;
sock_state->poll_info.Handles[0].Events =
sock__epoll_events_to_afd_events(sock_state->user_events);
if (afd_poll(poll_group_get_afd_device_handle(sock_state->poll_group),
&sock_state->poll_info, &sock_state->io_status_block) < 0) {
switch (GetLastError()) {
case kNtErrorIoPending:
/* Overlapped poll operation in progress; this is expected. */
break;
case kNtErrorInvalidHandle:
/* Socket closed; it'll be dropped from the epoll set. */
return sock__delete(port_state, sock_state, false);
default:
/* Other errors are propagated to the caller. */
RETURN_MAP_ERROR(-1);
}
}
/* The poll request was successfully submitted.*/
sock_state->poll_status = kPollPending;
sock_state->pending_events = sock_state->user_events;
} else {
unreachable;
}
port_cancel_socket_update(port_state, sock_state);
return 0;
}
static textwindows int port__update_events(struct PortState *port_state) {
struct QueueNode *queue_node;
struct SockState *sock_state;
struct Queue *sock_update_queue = &port_state->sock_update_queue;
/* Walk queue, submitting new poll requests for sockets needing it */
while (!queue_is_empty(sock_update_queue)) {
queue_node = queue_first(sock_update_queue);
sock_state = sock_state_from_queue_node(queue_node);
if (sock_update(port_state, sock_state) < 0) return -1;
/* sock_update() removes the socket from the update queue.*/
}
return 0;
}
static textwindows void port__update_events_if_polling(
struct PortState *port_state) {
if (port_state->active_poll_count > 0) port__update_events(port_state);
}
static textwindows void port_request_socket_update(
struct PortState *port_state, struct SockState *sock_state) {
if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) return;
queue_append(&port_state->sock_update_queue,
sock_state_to_queue_node(sock_state));
}
static textwindows int sock_feed_event(struct PortState *port_state,
struct NtIoStatusBlock *io_status_block,
struct epoll_event *ev) {
uint32_t epoll_events;
struct SockState *sock_state;
struct NtAfdPollInfo *poll_info;
epoll_events = 0;
sock_state = CONTAINOF(io_status_block, struct SockState, io_status_block);
poll_info = &sock_state->poll_info;
sock_state->poll_status = kPollIdle;
sock_state->pending_events = 0;
if (sock_state->delete_pending) {
/* Socket has been deleted earlier and can now be freed.*/
return sock__delete(port_state, sock_state, false);
} else if (io_status_block->Status == kNtStatusCancelled) {
/* The poll request was cancelled by CancelIoEx.*/
} else if (!NtSuccess(io_status_block->Status)) {
/* The overlapped request itself failed in an unexpected way.*/
epoll_events = EPOLLERR;
} else if (poll_info->NumberOfHandles < 1) {
/* This poll operation succeeded but didn't report any socket events. */
} else if (poll_info->Handles[0].Events & kNtAfdPollLocalClose) {
/* The poll operation reported that the socket was closed.*/
return sock__delete(port_state, sock_state, false);
} else {
/* Events related to our socket were reported.*/
epoll_events =
sock__afd_events_to_epoll_events(poll_info->Handles[0].Events);
}
/* Requeue the socket so a new poll request will be submitted.*/
port_request_socket_update(port_state, sock_state);
/* Filter out events that the user didn't ask for. */
epoll_events &= sock_state->user_events;
/* Return if there are no epoll events to report.*/
if (epoll_events == 0) return 0;
/* If the the socket has the EPOLLONESHOT flag set, unmonitor all
events, even EPOLLERR and EPOLLHUP. But always keep looking for
closed sockets. */
if (sock_state->user_events & EPOLLONESHOT) {
sock_state->user_events = 0;
}
ev->data = sock_state->user_data;
ev->events = epoll_events;
return 1;
}
static textwindows int port__feed_events(struct PortState *port_state,
struct epoll_event *epoll_events,
struct NtOverlappedEntry *iocp_events,
uint32_t iocp_event_count) {
uint32_t i;
int epoll_event_count;
struct epoll_event *ev;
struct NtIoStatusBlock *io_status_block;
epoll_event_count = 0;
for (i = 0; i < iocp_event_count; i++) {
io_status_block = (struct NtIoStatusBlock *)iocp_events[i].lpOverlapped;
ev = &epoll_events[epoll_event_count];
epoll_event_count += sock_feed_event(port_state, io_status_block, ev);
}
return epoll_event_count;
}
static textwindows int port__poll(struct PortState *port_state,
struct epoll_event *epoll_events,
struct NtOverlappedEntry *iocp_events,
uint32_t maxevents, uint32_t timeout) {
bool32 r;
uint32_t completion_count;
if (port__update_events(port_state) < 0) return -1;
port_state->active_poll_count++;
LeaveCriticalSection(&port_state->lock);
r = GetQueuedCompletionStatusEx(port_state->iocp_handle, iocp_events,
maxevents, &completion_count, timeout, false);
EnterCriticalSection(&port_state->lock);
port_state->active_poll_count--;
if (!r) RETURN_MAP_ERROR(-1);
return port__feed_events(port_state, epoll_events, iocp_events,
completion_count);
}
static textwindows int port_wait(struct PortState *port_state,
struct epoll_event *events, int maxevents,
int timeout) {
int result;
uint64_t now, due = 0;
uint32_t gqcs_timeout;
struct NtOverlappedEntry *iocp_events;
struct NtOverlappedEntry stack_iocp_events[64];
/* Check whether `maxevents` is in range.*/
if (maxevents <= 0) RETURN_SET_ERROR(-1, kNtErrorInvalidParameter);
/* Decide whether the IOCP completion list can live on the stack, or
allocate memory for it on the heap. */
if ((size_t)maxevents <= ARRAYLEN(stack_iocp_events)) {
iocp_events = stack_iocp_events;
} else if ((iocp_events = malloc((size_t)maxevents * sizeof(*iocp_events))) ==
NULL) {
iocp_events = stack_iocp_events;
maxevents = ARRAYLEN(stack_iocp_events);
}
/* Compute the timeout for GetQueuedCompletionStatus, and the wait end
time, if the user specified a timeout other than zero or infinite. */
if (timeout > 0) {
due = GetTickCount64() + (uint64_t)timeout;
gqcs_timeout = (uint32_t)timeout;
} else if (timeout == 0) {
gqcs_timeout = 0;
} else {
gqcs_timeout = -1;
}
EnterCriticalSection(&port_state->lock);
/* Dequeue completion packets until either at least one interesting
event has been discovered, or the timeout is reached. */
for (;;) {
result = port__poll(port_state, events, iocp_events, (uint32_t)maxevents,
gqcs_timeout);
if (result < 0 || result > 0) break;
/* Result, error, or time - out. */
if (timeout < 0) continue;
/* When timeout is negative, never time out. */
/* Update time. */
now = GetTickCount64();
/* Do not allow the due time to be in the past. */
if (now >= due) {
SetLastError(kNtWaitTimeout);
break;
}
/* Recompute time-out argument for GetQueuedCompletionStatus. */
gqcs_timeout = (uint32_t)(due - now);
}
port__update_events_if_polling(port_state);
LeaveCriticalSection(&port_state->lock);
if (iocp_events != stack_iocp_events) {
free(iocp_events);
}
if (result >= 0) {
return result;
} else if (GetLastError() == kNtWaitTimeout) {
return 0;
} else {
return -1;
}
}
static textwindows int64_t ws__ioctl_get_bsp_socket(int64_t socket,
uint32_t ioctl) {
uint32_t bytes;
int64_t bsp_socket;
if (WSAIoctl(socket, ioctl, NULL, 0, &bsp_socket, sizeof(bsp_socket), &bytes,
NULL, NULL) != -1) {
return bsp_socket;
} else {
return -1;
}
}
static textwindows int64_t ws_get_base_socket(int64_t socket) {
uint32_t error;
int64_t base_socket;
for (;;) {
base_socket = ws__ioctl_get_bsp_socket(socket, kNtSioBaseHandle);
if (base_socket != -1) {
return base_socket;
}
error = GetLastError();
if (error == WSAENOTSOCK) {
RETURN_SET_ERROR(-1, error);
}
/*
* Even though Microsoft documentation clearly states that Layered
* Spyware Providers must never ever intercept the SIO_BASE_HANDLE
* ioctl, Komodia LSPs (that Lenovo got sued for preinstalling) do
* so anyway in order to redirect decrypted https requests through
* some foreign proxy and inject ads which breaks high-performance
* network event io. However it doesn't handle SIO_BSP_HANDLE_POLL
* which will at least let us obtain the socket associated with the
* next winsock protocol chain entry. If this succeeds, loop around
* and call SIO_BASE_HANDLE again with the returned BSP socket, to
* make sure we unwrap all layers and retrieve the real base socket.
*/
base_socket = ws__ioctl_get_bsp_socket(socket, kNtSioBspHandlePoll);
if (base_socket != -1 && base_socket != socket) {
socket = base_socket;
} else {
RETURN_SET_ERROR(-1, error);
}
}
}
static textwindows struct SockState *sock__alloc(void) {
struct SockState *sock_state = malloc(sizeof *sock_state);
if (!sock_state) RETURN_SET_ERROR(NULL, kNtErrorNotEnoughMemory);
return sock_state;
}
static textwindows int port_register_socket(struct PortState *port_state,
struct SockState *sock_state,
int64_t socket) {
if (tree_add(&port_state->sock_tree, sock_state_to_tree_node(sock_state),
socket) < 0) {
RETURN_SET_ERROR(-1, kNtErrorAlreadyExists);
}
return 0;
}
static textwindows struct SockState *sock_new(struct PortState *port_state,
int64_t socket) {
int64_t base_socket;
struct PollGroup *poll_group;
struct SockState *sock_state;
if (socket == 0 || socket == -1) RETURN_SET_ERROR(0, kNtErrorInvalidHandle);
base_socket = ws_get_base_socket(socket);
if (base_socket == -1) return NULL;
poll_group = poll_group_acquire(port_state);
if (!poll_group) return NULL;
sock_state = sock__alloc();
if (!sock_state) goto err1;
bzero(sock_state, sizeof *sock_state);
sock_state->base_socket = base_socket;
sock_state->poll_group = poll_group;
tree_node_init(&sock_state->tree_node);
queue_node_init(&sock_state->queue_node);
if (port_register_socket(port_state, sock_state, socket) < 0) goto err2;
return sock_state;
err2:
sock__free(sock_state);
err1:
poll_group_release(poll_group);
return NULL;
}
static textwindows int sock_set_event(struct PortState *port_state,
struct SockState *sock_state,
const struct epoll_event *ev) {
/* EPOLLERR and EPOLLHUP are always reported, even when not requested
by the caller. However they are disabled after a event has been
reported for a socket for which the EPOLLONESHOT flag was set. */
uint32_t events = ev->events | EPOLLERR | EPOLLHUP;
sock_state->user_events = events;
sock_state->user_data = ev->data;
if ((events & KNOWN_EVENTS & ~sock_state->pending_events) != 0) {
port_request_socket_update(port_state, sock_state);
}
return 0;
}
static textwindows int port__ctl_add(struct PortState *port_state, int64_t sock,
struct epoll_event *ev) {
struct SockState *sock_state = sock_new(port_state, sock);
if (!sock_state) return -1;
if (sock_set_event(port_state, sock_state, ev) < 0) {
sock_delete(port_state, sock_state);
return -1;
}
port__update_events_if_polling(port_state);
return 0;
}
static textwindows struct SockState *port_find_socket(
struct PortState *port_state, int64_t socket) {
struct TreeNode *tree_node = tree_find(&port_state->sock_tree, socket);
if (!tree_node) RETURN_SET_ERROR(NULL, kNtErrorNotFound);
return sock_state_from_tree_node(tree_node);
}
static textwindows int port__ctl_mod(struct PortState *port_state, int64_t sock,
struct epoll_event *ev) {
struct SockState *sock_state = port_find_socket(port_state, sock);
if (!sock_state) return -1;
if (sock_set_event(port_state, sock_state, ev) < 0) return -1;
port__update_events_if_polling(port_state);
return 0;
}
static textwindows int port__ctl_del(struct PortState *port_state,
int64_t sock) {
struct SockState *sock_state = port_find_socket(port_state, sock);
if (!sock_state) return -1;
sock_delete(port_state, sock_state);
return 0;
}
static textwindows int port__ctl_op(struct PortState *port_state, int op,
int64_t sock, struct epoll_event *ev) {
switch (op) {
case EPOLL_CTL_ADD:
return port__ctl_add(port_state, sock, ev);
case EPOLL_CTL_MOD:
return port__ctl_mod(port_state, sock, ev);
case EPOLL_CTL_DEL:
return port__ctl_del(port_state, sock);
default:
RETURN_SET_ERROR(-1, kNtErrorInvalidParameter);
}
}
static textwindows int port_ctl(struct PortState *port_state, int op,
int64_t sock, struct epoll_event *ev) {
int result;
EnterCriticalSection(&port_state->lock);
result = port__ctl_op(port_state, op, sock, ev);
LeaveCriticalSection(&port_state->lock);
return result;
}
static textwindows struct PortState *port_state_from_handle_tree_node(
struct TsTreeNode *tree_node) {
return CONTAINOF(tree_node, struct PortState, handle_tree_node);
}
static textwindows dontinline int sys_epoll_create1_nt(uint32_t flags) {
int fd;
int64_t ephnd;
struct PortState *port_state;
struct TsTreeNode *tree_node;
if (wepoll_init() < 0) return -1;
fd = __reservefd(-1);
if (fd == -1) return -1;
port_state = port_new(&ephnd);
if (!port_state) {
__releasefd(fd);
return -1;
}
tree_node = port_state_to_handle_tree_node(port_state);
if (ts_tree_add(&epoll__handle_tree, tree_node, (uintptr_t)ephnd) < 0) {
/* This should never happen. */
port_delete(port_state);
err_set_win_error(kNtErrorAlreadyExists);
__releasefd(fd);
return -1;
}
__fds_lock();
g_fds.p[fd].kind = kFdEpoll;
g_fds.p[fd].handle = ephnd;
g_fds.p[fd].flags = flags;
g_fds.p[fd].mode = 0140666;
__fds_unlock();
return fd;
}
static textwindows dontinline int sys_epoll_ctl_nt(int epfd, int op, int fd,
struct epoll_event *ev) {
int r;
struct PortState *port_state;
struct TsTreeNode *tree_node;
if (!IsWindows()) {
return sys_epoll_ctl(epfd, op, fd, ev);
} else {
if (wepoll_init() < 0) return -1;
if (!__isfdopen(fd)) return ebadf();
if (!__isfdkind(epfd, kFdEpoll)) return ebadf();
tree_node = ts_tree_find_and_ref(&epoll__handle_tree, g_fds.p[epfd].handle);
if (!tree_node) {
err_set_win_error(kNtErrorInvalidParameter);
goto err;
}
port_state = port_state_from_handle_tree_node(tree_node);
r = port_ctl(port_state, op, g_fds.p[fd].handle, ev);
ts_tree_node_unref(tree_node);
if (r < 0) goto err;
return 0;
err:
/* On Linux, in the case of epoll_ctl(), EBADF takes priority over
other *errors. Wepoll mimics this behavior. */
err_check_handle(g_fds.p[epfd].handle);
err_check_handle(g_fds.p[fd].handle);
return -1;
}
}
static textwindows dontinline int sys_epoll_wait_nt(int epfd,
struct epoll_event *events,
int maxevents,
int timeoutms) {
int num_events;
struct PortState *port_state;
struct TsTreeNode *tree_node;
if (!__isfdkind(epfd, kFdEpoll)) return ebadf();
if (maxevents <= 0) return einval();
if (wepoll_init() < 0) return -1;
tree_node = ts_tree_find_and_ref(&epoll__handle_tree, g_fds.p[epfd].handle);
if (!tree_node) {
err_set_win_error(kNtErrorInvalidParameter);
goto err;
}
port_state = port_state_from_handle_tree_node(tree_node);
num_events = port_wait(port_state, events, maxevents, timeoutms);
ts_tree_node_unref(tree_node);
if (num_events < 0) goto err;
return num_events;
err:
err_check_handle(g_fds.p[epfd].handle);
return -1;
}
textwindows int sys_close_epoll_nt(int fd) {
struct PortState *port_state;
struct TsTreeNode *tree_node;
if (wepoll_init() < 0) return -1;
tree_node = ts_tree_del_and_ref(&epoll__handle_tree, g_fds.p[fd].handle);
if (!tree_node) {
err_set_win_error(kNtErrorInvalidParameter);
goto err;
}
port_state = port_state_from_handle_tree_node(tree_node);
port_close(port_state);
ts_tree_node_unref_and_destroy(tree_node);
return port_delete(port_state);
err:
err_check_handle(g_fds.p[fd].handle);
return -1;
}
/**
* Creates new epoll instance.
*
* @param size is ignored but must be greater than zero
* @param flags must be zero as there are no supported flags
* @return epoll file descriptor, or -1 on failure
*/
int epoll_create(int size) {
int rc;
if (size <= 0) {
rc = einval();
} else {
rc = epoll_create1(0);
}
STRACE("epoll_create(%d) â %d% m", size, rc);
return rc;
}
/**
* Creates new epoll instance.
*
* @param size is ignored but must be greater than zero
* @param flags must be zero or can have O_CLOEXEC
* @return epoll file descriptor, or -1 on failure
*/
int epoll_create1(int flags) {
int rc;
if (flags & ~O_CLOEXEC) {
rc = einval();
} else if (!IsWindows()) {
rc = __fixupnewfd(sys_epoll_create(1337), flags);
} else {
rc = sys_epoll_create1_nt(flags);
}
STRACE("epoll_create1(%#x) â %d% m", flags, rc);
return rc;
}
/**
* Controls which socket events are monitored.
*
* It is recommended to always explicitly remove a socket from its epoll
* set using EPOLL_CTL_DEL before closing it. As on Linux, your closed
* sockets are automatically removed from the epoll set, but wepoll may
* not be able to detect that a socket was closed until the next call to
* epoll_wait().
*
* @param epfd is file descriptor created by epoll_create()
* @param op can be EPOLL_CTL_{ADD,MOD,DEL}
* @param fd is file descriptor to monitor
* @param ev is ignored if op is EPOLL_CTL_DEL
* @param ev->events can have these flags:
* - `EPOLLIN`: trigger on fd readable
* - `EPOLLOUT`: trigger on fd writeable
* - `EPOLLERR`: trigger on fd error (superfluous: always reported)
* - `EPOLLHUP`: trigger on fd remote hangup (superfluous: always reported)
* - `EPOLLPRI`: trigger on fd exceptional conditions, e.g. oob
* - `EPOLLONESHOT`: report event(s) only once
* - `EPOLLEXCLUSIVE`: not supported on windows
* - `EPOLLWAKEUP`: not supported on windows
* - `EPOLLET`: edge triggered mode (not supported on windows)
* - `EPOLLRDNORM`
* - `EPOLLRDBAND`
* - `EPOLLWRNORM`
* - `EPOLLWRBAND`
* - `EPOLLRDHUP`
* - `EPOLLMSG`
* @error ENOTSOCK on Windows if fd isn't a socket :(
* @return 0 on success, or -1 w/ errno
*/
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *ev) {
int rc;
if (!IsWindows()) {
rc = sys_epoll_ctl(epfd, op, fd, ev);
} else {
rc = sys_epoll_ctl_nt(epfd, op, fd, ev);
}
STRACE("epoll_ctl(%d, %d, %d, %p) â %d% m", epfd, op, fd, ev, rc);
return rc;
}
/**
* Receives socket events.
*
* @param events will receive information about what happened
* @param maxevents is array length of events
* @param timeoutms is milliseconds, 0 to not block, or -1 for forever
* @return number of events stored, 0 on timeout, or -1 w/ errno
* @cancellationpoint
* @norestart
*/
int epoll_wait(int epfd, struct epoll_event *events, int maxevents,
int timeoutms) {
int e, rc;
BEGIN_CANCELLATION_POINT;
if (!IsWindows()) {
e = errno;
rc = sys_epoll_wait(epfd, events, maxevents, timeoutms);
if (rc == -1 && errno == ENOSYS) {
errno = e;
rc = sys_epoll_pwait(epfd, events, maxevents, timeoutms, 0, 0);
}
} else {
rc = sys_epoll_wait_nt(epfd, events, maxevents, timeoutms);
}
END_CANCELLATION_POINT;
STRACE("epoll_wait(%d, %p, %d, %d) â %d% m", epfd, events, maxevents,
timeoutms, rc);
return rc;
}
/**
* Receives socket events.
*
* @param events will receive information about what happened
* @param maxevents is array length of events
* @param timeoutms is milliseconds, 0 to not block, or -1 for forever
* @param sigmask is an optional sigprocmask() to use during call
* @return number of events stored, 0 on timeout, or -1 w/ errno
* @cancellationpoint
* @norestart
*/
int epoll_pwait(int epfd, struct epoll_event *events, int maxevents,
int timeoutms, const sigset_t *sigmask) {
int e, rc;
sigset_t oldmask;
BEGIN_CANCELLATION_POINT;
if (!IsWindows()) {
e = errno;
rc = sys_epoll_pwait(epfd, events, maxevents, timeoutms, sigmask,
sizeof(*sigmask));
if (rc == -1 && errno == ENOSYS) {
errno = e;
if (sigmask) sys_sigprocmask(SIG_SETMASK, sigmask, &oldmask);
rc = sys_epoll_wait(epfd, events, maxevents, timeoutms);
if (sigmask) sys_sigprocmask(SIG_SETMASK, &oldmask, 0);
}
} else {
if (sigmask) __sig_mask(SIG_SETMASK, sigmask, &oldmask);
rc = sys_epoll_wait_nt(epfd, events, maxevents, timeoutms);
if (sigmask) __sig_mask(SIG_SETMASK, &oldmask, 0);
}
END_CANCELLATION_POINT;
STRACE("epoll_pwait(%d, %p, %d, %d) â %d% m", epfd, events, maxevents,
timeoutms, DescribeSigset(0, sigmask), rc);
return rc;
}
| 56,723 | 1,578 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/goodsocket.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/timeval.h"
#include "libc/sock/goodsocket.internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sol.h"
#include "libc/sysv/consts/tcp.h"
static bool Tune(int fd, int a, int b, int x) {
if (!b) return false;
return setsockopt(fd, a, b, &x, sizeof(x)) != -1;
}
/**
* Returns new socket with modern goodness enabled.
*/
int GoodSocket(int family, int type, int protocol, bool isserver,
const struct timeval *timeout) {
int fd;
if ((fd = socket(family, type, protocol)) != -1) {
if (isserver) {
Tune(fd, SOL_TCP, TCP_FASTOPEN, 100);
Tune(fd, SOL_SOCKET, SO_REUSEADDR, 1);
} else {
Tune(fd, SOL_TCP, TCP_FASTOPEN_CONNECT, 1);
}
if (!Tune(fd, SOL_TCP, TCP_QUICKACK, 1)) {
Tune(fd, SOL_TCP, TCP_NODELAY, 1);
}
if (timeout) {
if (timeout->tv_sec < 0) {
Tune(fd, SOL_SOCKET, SO_KEEPALIVE, 1);
Tune(fd, SOL_TCP, TCP_KEEPIDLE, -timeout->tv_sec);
Tune(fd, SOL_TCP, TCP_KEEPINTVL, -timeout->tv_sec);
} else {
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, timeout, sizeof(*timeout));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, timeout, sizeof(*timeout));
}
}
}
return fd;
}
| 3,102 | 60 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/recvmsg.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/msghdr.h"
#include "libc/sock/struct/msghdr.internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
/**
* Sends a message from a socket.
*
* Note: Ancillary data currently isn't polyfilled across platforms.
*
* @param fd is the file descriptor returned by socket()
* @param msg is a pointer to a struct msghdr containing all the allocated
* buffers where to store incoming data.
* @param flags MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
* @return number of bytes received, or -1 w/ errno
* @error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
* EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
ssize_t rc, got;
struct msghdr msg2;
union sockaddr_storage_bsd bsd;
BEGIN_CANCELLATION_POINT;
if (IsAsan() && !__asan_is_valid_msghdr(msg)) {
rc = efault();
} else if (!IsWindows()) {
if (IsBsd() && msg->msg_name) {
memcpy(&msg2, msg, sizeof(msg2));
if (!(rc = sockaddr2bsd(msg->msg_name, msg->msg_namelen, &bsd,
&msg2.msg_namelen))) {
msg2.msg_name = &bsd.sa;
if ((rc = sys_recvmsg(fd, &msg2, flags)) != -1) {
sockaddr2linux(msg2.msg_name, msg2.msg_namelen, msg->msg_name,
&msg->msg_namelen);
}
}
} else {
rc = sys_recvmsg(fd, msg, flags);
}
} else if (__isfdopen(fd)) {
if (!msg->msg_control) {
if (__isfdkind(fd, kFdSocket)) {
rc = sys_recvfrom_nt(&g_fds.p[fd], msg->msg_iov, msg->msg_iovlen, flags,
msg->msg_name, &msg->msg_namelen);
} else if (__isfdkind(fd, kFdFile) && !msg->msg_name) { /* socketpair */
if (!flags) {
if ((got = sys_read_nt(&g_fds.p[fd], msg->msg_iov, msg->msg_iovlen,
-1)) != -1) {
msg->msg_flags = 0;
rc = got;
} else {
rc = -1;
}
} else {
rc = einval(); // flags not supported on nt
}
} else {
rc = enotsock();
}
} else {
rc = einval(); // control msg not supported on nt
}
} else {
rc = ebadf();
}
END_CANCELLATION_POINT;
#if defined(SYSDEBUG) && _DATATRACE
if (__strace > 0 && strace_enabled(0) > 0) {
if (!msg || (rc == -1 && errno == EFAULT)) {
DATATRACE("recvmsg(%d, %p, %#x) â %'ld% m", fd, msg, flags, rc);
} else {
kprintf(STRACE_PROLOGUE "recvmsg(%d, [{");
if (msg->msg_namelen)
kprintf(".name=%#.*hhs, ", msg->msg_namelen, msg->msg_name);
if (msg->msg_controllen)
kprintf(".control=%#.*hhs, ", msg->msg_controllen, msg->msg_control);
if (msg->msg_flags) kprintf(".flags=%#x, ", msg->msg_flags);
kprintf(".iov=%s", DescribeIovec(rc, msg->msg_iov, msg->msg_iovlen));
kprintf("], %#x) â %'ld% m\n", flags, rc);
}
}
#endif
return rc;
}
| 5,220 | 118 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sendmsg.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/msghdr.h"
#include "libc/sock/struct/msghdr.internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
/**
* Sends a message on a socket.
*
* @param fd is the file descriptor returned by socket()
* @param msg is a pointer to a struct msghdr containing all the required
* parameters (the destination address, buffers, ...)
* @param flags MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
* @return number of bytes transmitted, or -1 w/ errno
* @error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
* EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
ssize_t sendmsg(int fd, const struct msghdr *msg, int flags) {
int64_t rc;
struct msghdr msg2;
union sockaddr_storage_bsd bsd;
BEGIN_CANCELLATION_POINT;
if (IsAsan() && !__asan_is_valid_msghdr(msg)) {
rc = efault();
} else if (!IsWindows()) {
if (IsBsd() && msg->msg_name) {
memcpy(&msg2, msg, sizeof(msg2));
if (!(rc = sockaddr2bsd(msg->msg_name, msg->msg_namelen, &bsd,
&msg2.msg_namelen))) {
msg2.msg_name = &bsd.sa;
rc = sys_sendmsg(fd, &msg2, flags);
}
} else {
rc = sys_sendmsg(fd, msg, flags);
}
} else if (__isfdopen(fd)) {
if (msg->msg_control) {
rc = einval(); /* control msg not supported */
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_sendto_nt(fd, msg->msg_iov, msg->msg_iovlen, flags,
msg->msg_name, msg->msg_namelen);
} else if (__isfdkind(fd, kFdFile)) {
rc = sys_write_nt(fd, msg->msg_iov, msg->msg_iovlen, -1);
} else {
rc = enotsock();
}
} else {
rc = ebadf();
}
END_CANCELLATION_POINT;
#if defined(SYSDEBUG) && _DATATRACE
if (__strace > 0 && strace_enabled(0) > 0) {
kprintf(STRACE_PROLOGUE "sendmsg(");
if ((!IsAsan() && kisdangerous(msg)) ||
(IsAsan() && !__asan_is_valid(msg, sizeof(*msg)))) {
kprintf("%p", msg);
} else {
kprintf("{");
kprintf(".name=%#.*hhs, ", msg->msg_namelen, msg->msg_name);
if (msg->msg_controllen)
kprintf(", .control=%#.*hhs, ", msg->msg_controllen, msg->msg_control);
if (msg->msg_flags) kprintf(".flags=%#x, ", msg->msg_flags);
kprintf(", .iov=%s",
DescribeIovec(rc != -1 ? rc : -2, msg->msg_iov, msg->msg_iovlen));
}
kprintf(", %#x) â %'ld% m\n", flags, rc);
}
#endif
return rc;
}
| 4,840 | 107 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/wsablock.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/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/enum/wait.h"
#include "libc/nt/errors.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/errfuns.h"
textwindows int __wsablock(int64_t handle, struct NtOverlapped *overlapped,
uint32_t *flags, bool restartable,
uint32_t timeout) {
int rc;
uint32_t i, got;
if (WSAGetLastError() != kNtErrorIoPending) {
NTTRACE("sock i/o failed %lm");
return __winsockerr();
}
for (;;) {
i = WSAWaitForMultipleEvents(1, &overlapped->hEvent, true,
__SIG_POLLING_INTERVAL_MS, true);
if (i == kNtWaitFailed) {
NTTRACE("WSAWaitForMultipleEvents failed %lm");
return __winsockerr();
} else if (i == kNtWaitTimeout || i == kNtWaitIoCompletion) {
if (_check_interrupts(restartable, g_fds.p)) {
return -1;
}
if (timeout) {
if (timeout <= __SIG_POLLING_INTERVAL_MS) {
return eagain();
}
timeout -= __SIG_POLLING_INTERVAL_MS;
}
} else {
break;
}
}
if (!WSAGetOverlappedResult(handle, overlapped, &got, false, flags)) {
NTTRACE("WSAGetOverlappedResult failed %lm");
return __winsockerr();
}
return got;
}
| 3,199 | 63 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sys_sendfile_freebsd.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 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"
sys_sendfile_freebsd:
jmp sys_sendfile
.endfn sys_sendfile_freebsd,globl
| 1,946 | 24 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/send.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/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/errfuns.h"
/**
* Sends data to network socket.
*
* @param fd is the file descriptor returned by socket()
* @param buf is the data to send, which we'll copy if necessary
* @param size is the byte-length of buf
* @param flags MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
* @return number of bytes transmitted, or -1 w/ errno
* @error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
* EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
ssize_t send(int fd, const void *buf, size_t size, int flags) {
ssize_t rc;
BEGIN_CANCELLATION_POINT;
if (IsAsan() && !__asan_is_valid(buf, size)) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_sendto(fd, buf, size, flags, 0, 0);
} else if (__isfdopen(fd)) {
if (__isfdkind(fd, kFdSocket)) {
rc = sys_send_nt(fd, (struct iovec[]){{buf, size}}, 1, flags);
} else if (__isfdkind(fd, kFdFile)) {
if (flags) {
rc = einval();
} else {
rc = sys_write_nt(fd, (struct iovec[]){{buf, size}}, 1, -1);
}
} else {
rc = enotsock();
}
} else {
rc = ebadf();
}
END_CANCELLATION_POINT;
DATATRACE("send(%d, %#.*hhs%s, %'zu, %#x) â %'ld% lm", fd,
MAX(0, MIN(40, rc)), buf, rc > 40 ? "..." : "", size, flags, rc);
return rc;
}
| 3,589 | 74 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/socketpair.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/dce.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
/**
* Creates bidirectional pipe, e.g.
*
* int sv[2];
* socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
*
* @param family should be AF_UNIX or synonymously AF_LOCAL
* @param type can be SOCK_STREAM or SOCK_DGRAM and additionally,
* may be or'd with SOCK_NONBLOCK, SOCK_CLOEXEC
* @param sv a vector of 2 integers to store the created sockets
* @return 0 if success, -1 in case of error
* @error EFAULT, EPFNOSUPPORT, etc.
* @see libc/sysv/consts.sh
* @asyncsignalsafe
*/
int socketpair(int family, int type, int protocol, int sv[2]) {
if (family == AF_UNSPEC) family = AF_UNIX;
if (!IsWindows()) {
return sys_socketpair(family, type, protocol, sv);
} else {
return sys_socketpair_nt(family, type, protocol, sv);
}
}
| 2,702 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/recv-nt.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/internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/errno.h"
#include "libc/nt/struct/iovec.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
textwindows ssize_t sys_recv_nt(struct Fd *fd, const struct iovec *iov,
size_t iovlen, uint32_t flags) {
int err;
ssize_t rc;
uint32_t got = 0;
struct SockFd *sockfd;
struct NtIovec iovnt[16];
struct NtOverlapped overlapped = {.hEvent = WSACreateEvent()};
if (_check_interrupts(true, g_fds.p)) return -1;
err = errno;
if (!WSARecv(fd->handle, iovnt, __iovec2nt(iovnt, iov, iovlen), &got, &flags,
&overlapped, NULL)) {
rc = got;
} else {
errno = err;
sockfd = (struct SockFd *)fd->extra;
rc = __wsablock(fd->handle, &overlapped, &flags, true, sockfd->rcvtimeo);
}
WSACloseEvent(overlapped.hEvent);
return rc;
}
| 2,844 | 50 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getsockname-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
textwindows int sys_getsockname_nt(struct Fd *fd, void *out_addr,
uint32_t *out_addrsize) {
_npassert(fd->kind == kFdSocket);
if (__sys_getsockname_nt(fd->handle, out_addr, out_addrsize) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 2,302 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sockatmark.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/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/winsock.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/sio.h"
static textwindows int sockatmark_nt(int64_t fd) {
bool32 res;
uint32_t bytes;
if (WSAIoctl(fd, SIOCATMARK, 0, 0, &res, sizeof(res), &bytes, 0, 0) != -1) {
return !res;
} else {
return -1;
}
}
/**
* Returns true if out of band data is available on socket for reading.
*
* @return 1 if OOB'd, 0 if not, or -1 w/ errno
*/
int sockatmark(int fd) {
int rc;
if (!IsWindows()) {
if (sys_ioctl(fd, SIOCATMARK, &rc) == -1) {
rc = -1;
}
} else {
rc = sockatmark_nt(fd);
}
STRACE("sockatmark(%d) â %d% m", fd, rc);
return rc;
}
| 2,610 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getsockopt.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/internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Retrieves socket setting.
*
* @param level can be SOL_SOCKET, IPPROTO_TCP, etc.
* @param optname can be SO_{REUSE{PORT,ADDR},KEEPALIVE,etc.} etc.
* @return 0 on success, or -1 w/ errno
* @error ENOPROTOOPT for unknown (level,optname)
* @error EINVAL if `out_optlen` is invalid somehow
* @error ENOTSOCK if `fd` is valid but not a socket
* @error EBADF if `fd` isn't valid
* @error EFAULT if optval memory isn't valid
* @see libc/sysv/consts.sh for tuning catalogue
* @see setsockopt()
*/
int getsockopt(int fd, int level, int optname, void *out_opt_optval,
uint32_t *out_optlen) {
int rc;
if (level == -1 || !optname) {
rc = enoprotoopt(); /* see libc/sysv/consts.sh */
} else if (IsAsan() && (out_opt_optval && out_optlen &&
(!__asan_is_valid(out_optlen, sizeof(uint32_t)) ||
!__asan_is_valid(out_opt_optval, *out_optlen)))) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_getsockopt(fd, level, optname, out_opt_optval, out_optlen);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_getsockopt_nt(&g_fds.p[fd], level, optname, out_opt_optval,
out_optlen);
} else {
rc = ebadf();
}
#ifdef SYSDEBUG
if (out_opt_optval && out_optlen && rc != -1) {
STRACE("getsockopt(%d, %s, %s, [%#.*hhs], [%d]) â %d% lm", fd,
DescribeSockLevel(level), DescribeSockOptname(level, optname),
*out_optlen, out_opt_optval, *out_optlen, rc);
} else {
STRACE("getsockopt(%d, %s, %s, %p, %p) â %d% lm", fd,
DescribeSockLevel(level), DescribeSockOptname(level, optname),
out_opt_optval, out_optlen, rc);
}
#endif
return rc;
}
| 3,873 | 76 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/gethostips.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/intrin/bits.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/errors.h"
#include "libc/nt/iphlpapi.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sio.h"
#include "libc/sysv/consts/sock.h"
/* TODO(jart): DELETE */
static uint32_t *GetUnixIps(void) {
int fd, n;
uint64_t z;
uint32_t *a;
char *b, *p, *e, c[16];
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) return 0;
a = 0;
n = 0;
z = 15000;
b = malloc(z);
memcpy(c, &z, 8);
memcpy(c + (IsXnu() ? 4 : 8), &b, 8);
if (sys_ioctl(fd, SIOCGIFCONF, &c) != -1) {
for (p = b, e = p + MIN(z, READ32LE(c)); p + 16 + 16 <= e;
p += IsBsd() ? 16 + MAX(16, p[16] & 255) : 40) {
if ((p[IsBsd() ? 17 : 16] & 255) != AF_INET) continue;
a = realloc(a, ++n * sizeof(*a));
a[n - 1] = READ32BE(p + 20);
}
a = realloc(a, ++n * sizeof(*a));
a[n - 1] = 0;
}
close(fd);
free(b);
return a;
}
static textwindows uint32_t *GetWindowsIps(void) {
uint32_t i, z, n, rc, *a;
struct NtIpAdapterUnicastAddress *u;
struct NtIpAdapterAddresses *p, *ifaces;
i = 0;
z = 15000;
do {
if (!(ifaces = malloc(z))) return 0;
rc = GetAdaptersAddresses(AF_INET,
kNtGaaFlagSkipAnycast | kNtGaaFlagSkipMulticast |
kNtGaaFlagSkipDnsServer |
kNtGaaFlagSkipFriendlyName,
0, ifaces, &z);
if (rc != kNtErrorBufferOverflow) break;
free(ifaces);
ifaces = 0;
} while (++i < 3);
if (rc == kNtErrorNoData) {
a = calloc(1, sizeof(*a));
} else if (rc == kNtNoError) {
for (a = 0, n = 0, p = ifaces; p; p = p->Next) {
if (p->OperStatus != kNtIfOperStatusUp) continue;
for (u = p->FirstUnicastAddress; u; u = u->Next) {
if (u->Address.lpSockaddr->sa_family != AF_INET) continue;
a = realloc(a, ++n * sizeof(*a));
a[n - 1] = ntohl(
((struct sockaddr_in *)u->Address.lpSockaddr)->sin_addr.s_addr);
}
}
a = realloc(a, ++n * sizeof(*a));
a[n - 1] = 0;
} else {
__winerr();
a = 0;
}
free(ifaces);
return a;
}
/**
* Returns IP addresses of system.
*
* Normally return values will look like `{0x7f000001, 0x0a0a0a7c, 0}`
* which means the same thing as `{"127.0.0.1", "10.10.10.124", 0}`.
* Returned IPs will IPv4 anycast addresses bound to network interfaces
* which come in a NULL-terminated array with no particular ordering.
*
* uint32_t *ip, *ips = GetIps();
* for (ip = ips; *ip; ++ip) {
* printf("%hhu.%hhu.%hhu.%hhu\n", *ip >> 24, *ip >> 16, *ip >> 8, *ip);
* }
*
* This function supports Windows, Linux, XNU, FreeBSD, NetBSD, OpenBSD.
*
* @return null-terminated ip array on success, or null w/ errno
*/
uint32_t *GetHostIps(void) {
if (!IsWindows()) {
return GetUnixIps();
} else {
return GetWindowsIps();
}
}
| 5,035 | 127 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/winsockblock.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/errno.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
textwindows int64_t __winsockblock(int64_t fh, unsigned eventbit, int64_t rc,
uint32_t timeout) {
int64_t eh;
struct NtWsaNetworkEvents ev;
if (rc != -1) return rc;
if (WSAGetLastError() != EWOULDBLOCK) return __winsockerr();
eh = WSACreateEvent();
bzero(&ev, sizeof(ev));
/* The proper way to reset the state of an event object used with the
WSAEventSelect function is to pass the handle of the event object
to the WSAEnumNetworkEvents function in the hEventObject parameter.
This will reset the event object and adjust the status of active FD
events on the socket in an atomic fashion. -- MSDN */
if (WSAEventSelect(fh, eh, 1u << eventbit) != -1 &&
WSAEnumNetworkEvents(fh, eh, &ev) != -1) {
if (!ev.iErrorCode[eventbit]) {
rc = 0;
} else {
errno = ev.iErrorCode[eventbit];
}
} else {
__winsockerr();
}
WSACloseEvent(eh);
return rc;
}
| 2,951 | 52 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/setsockopt.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/internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/errfuns.h"
static bool setsockopt_polyfill(int *optname) {
if (errno == ENOPROTOOPT && *optname == SO_REUSEPORT /* RHEL5 */) {
*optname = SO_REUSEADDR; /* close enough */
return true; /* fudges errno */
}
return false;
}
/**
* Modifies socket settings.
*
* This function is the ultimate rabbit hole. Basic usage:
*
* int yes = 1;
* setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
*
* @param level can be SOL_SOCKET, SOL_IP, SOL_TCP, etc.
* @param optname can be SO_{REUSE{PORT,ADDR},KEEPALIVE,etc.} etc.
* @return 0 on success, or -1 w/ errno
* @error ENOPROTOOPT for unknown (level,optname)
* @error EINVAL if `optlen` is invalid somehow
* @error ENOTSOCK if `fd` is valid but not a socket
* @error EBADF if `fd` isn't valid
* @error EFAULT if optval memory isn't valid
* @see libc/sysv/consts.sh for tuning catalogue
* @see getsockopt()
*/
int setsockopt(int fd, int level, int optname, const void *optval,
uint32_t optlen) {
int e, rc;
if (level == -1 || !optname) {
rc = enoprotoopt(); /* see libc/sysv/consts.sh */
} else if ((!optval && optlen) ||
(IsAsan() && !__asan_is_valid(optval, optlen))) {
rc = efault();
} else if (!IsWindows()) {
rc = -1;
e = errno;
do {
if (sys_setsockopt(fd, level, optname, optval, optlen) != -1) {
errno = e;
rc = 0;
break;
}
} while (setsockopt_polyfill(&optname));
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_setsockopt_nt(&g_fds.p[fd], level, optname, optval, optlen);
} else {
rc = ebadf();
}
#ifdef SYSDEBUG
if (!(rc == -1 && errno == EFAULT)) {
STRACE("setsockopt(%d, %s, %s, %#.*hhs, %'u) â %d% lm", fd,
DescribeSockLevel(level), DescribeSockOptname(level, optname),
optlen, optval, optlen, rc);
} else {
STRACE("setsockopt(%d, %s, %s, %p, %'u) â %d% lm", fd,
DescribeSockLevel(level), DescribeSockOptname(level, optname),
optval, optlen, rc);
}
#endif
return rc;
}
| 4,283 | 98 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/accept.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/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
/**
* Creates client socket file descriptor for incoming connection.
*
* @param fd is the server socket file descriptor
* @param out_addr will receive the remote address
* @param inout_addrsize provides and receives addr's byte length
* @return client fd which needs close(), or -1 w/ errno
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
int accept(int fd, struct sockaddr *out_addr, uint32_t *inout_addrsize) {
return accept4(fd, out_addr, inout_addrsize, 0);
}
| 2,411 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/internal.h | #ifndef COSMOPOLITAN_LIBC_SOCK_INTERNAL_H_
#define COSMOPOLITAN_LIBC_SOCK_INTERNAL_H_
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/sigset.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/thunk/msabi.h"
#include "libc/nt/winsock.h"
#include "libc/sock/select.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define FD_READ (1 << FD_READ_BIT)
#define FD_READ_BIT 0
#define FD_WRITE (1 << FD_WRITE_BIT)
#define FD_WRITE_BIT 1
#define FD_OOB (1 << FD_OOB_BIT)
#define FD_OOB_BIT 2
#define FD_ACCEPT (1 << FD_ACCEPT_BIT)
#define FD_ACCEPT_BIT 3
#define FD_CONNECT (1 << FD_CONNECT_BIT)
#define FD_CONNECT_BIT 4
#define FD_CLOSE (1 << FD_CLOSE_BIT)
#define FD_CLOSE_BIT 5
/* ------------------------------------------------------------------------------------*/
#define SOCKFD_OVERLAP_BUFSIZ 128
struct SockFd {
int family;
int type;
int protocol;
uint32_t rcvtimeo;
uint32_t sndtimeo;
bool32 (*__msabi ConnectEx)(int64_t s, const struct sockaddr *name,
int namelen, const void *opt_lpSendBuffer,
uint32_t dwSendDataLength,
uint32_t *out_lpdwBytesSent,
struct NtOverlapped *inout_lpOverlapped);
bool32 (*__msabi AcceptEx)(
int64_t sListenSocket, int64_t sAcceptSocket,
void *out_lpOutputBuffer /*[recvlen+local+remoteaddrlen]*/,
uint32_t dwReceiveDataLength, uint32_t dwLocalAddressLength,
uint32_t dwRemoteAddressLength, uint32_t *out_lpdwBytesReceived,
struct NtOverlapped *inout_lpOverlapped);
};
errno_t __dos2errno(uint32_t) _Hide;
int32_t __sys_accept(int32_t, void *, uint32_t *, int) dontdiscard _Hide;
int32_t __sys_accept4(int32_t, void *, uint32_t *, int) dontdiscard _Hide;
int32_t __sys_bind(int32_t, const void *, uint32_t) _Hide;
int32_t __sys_connect(int32_t, const void *, uint32_t) _Hide;
int32_t __sys_getpeername(int32_t, void *, uint32_t *) _Hide;
int32_t __sys_getsockname(int32_t, void *, uint32_t *) _Hide;
int32_t __sys_socket(int32_t, int32_t, int32_t) _Hide;
int32_t __sys_socketpair(int32_t, int32_t, int32_t, int32_t[2]) _Hide;
int32_t sys_accept4(int32_t, void *, uint32_t *, int) dontdiscard _Hide;
int32_t sys_accept(int32_t, void *, uint32_t *) _Hide;
int32_t sys_bind(int32_t, const void *, uint32_t) _Hide;
int32_t sys_connect(int32_t, const void *, uint32_t) _Hide;
int32_t sys_getsockopt(int32_t, int32_t, int32_t, void *, uint32_t *) _Hide;
int32_t sys_listen(int32_t, int32_t) _Hide;
int32_t sys_getsockname(int32_t, void *, uint32_t *) _Hide;
int32_t sys_getpeername(int32_t, void *, uint32_t *) _Hide;
int32_t sys_shutdown(int32_t, int32_t) _Hide;
int32_t sys_socket(int32_t, int32_t, int32_t) _Hide;
int32_t sys_socketpair(int32_t, int32_t, int32_t, int32_t[2]) _Hide;
ssize_t sys_recvfrom(int, void *, size_t, int, void *, uint32_t *) _Hide;
ssize_t sys_sendto(int, const void *, size_t, int, const void *,
uint32_t) _Hide;
int32_t sys_select(int32_t, fd_set *, fd_set *, fd_set *,
struct timeval *) _Hide;
int sys_pselect(int, fd_set *, fd_set *, fd_set *, struct timespec *,
const void *) _Hide;
int sys_setsockopt(int, int, int, const void *, uint32_t) _Hide;
int32_t sys_epoll_create(int32_t) _Hide;
int32_t sys_epoll_ctl(int32_t, int32_t, int32_t, void *) _Hide;
int32_t sys_epoll_wait(int32_t, void *, int32_t, int32_t) _Hide;
int32_t sys_epoll_pwait(int32_t, void *, int32_t, int32_t, const sigset_t *,
size_t);
int sys_socket_nt(int, int, int) _Hide;
/*
int sys_socketpair_nt_stream(int, int, int, int[2]) _Hide;
int sys_socketpair_nt_dgram(int, int, int, int[2]) _Hide;
*/
int sys_socketpair_nt(int, int, int, int[2]) _Hide;
int sys_select_nt(int, fd_set *, fd_set *, fd_set *, struct timeval *,
const sigset_t *) _Hide;
size_t __iovec2nt(struct NtIovec[hasatleast 16], const struct iovec *,
size_t) _Hide;
void WinSockInit(void) _Hide;
int64_t __winsockerr(void) nocallback _Hide;
int __fixupnewsockfd(int, int) _Hide;
int __wsablock(int64_t, struct NtOverlapped *, uint32_t *, bool,
uint32_t) _Hide;
int64_t __winsockblock(int64_t, unsigned, int64_t, uint32_t) _Hide;
struct SockFd *_dupsockfd(struct SockFd *) _Hide;
int64_t GetNtBaseSocket(int64_t) _Hide;
int sys_close_epoll(int) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_INTERNAL_H_ */
| 4,619 | 112 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/setsockopt-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/timeval.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/nt/struct/linger.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/linger.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sol.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_setsockopt_nt(struct Fd *fd, int level, int optname,
const void *optval, uint32_t optlen) {
int64_t ms, micros;
struct timeval *tv;
struct linger *linger;
struct SockFd *sockfd;
union {
uint32_t millis;
struct linger_nt linger;
} u;
if (level == SOL_SOCKET) {
if (optname == SO_LINGER && optval && optlen == sizeof(struct linger)) {
linger = optval;
u.linger.l_onoff = linger->l_onoff;
u.linger.l_linger = MIN(0xFFFF, MAX(0, linger->l_linger));
optval = &u.linger;
optlen = sizeof(u.linger);
} else if ((optname == SO_RCVTIMEO || optname == SO_SNDTIMEO) && optval &&
optlen == sizeof(struct timeval)) {
tv = optval;
if (__builtin_mul_overflow(tv->tv_sec, 1000, &ms) ||
__builtin_add_overflow(tv->tv_usec, 999, µs) ||
__builtin_add_overflow(ms, micros / 1000, &ms) ||
(ms < 0 || ms > 0xffffffff)) {
u.millis = 0xffffffff;
} else {
u.millis = ms;
}
optval = &u.millis;
optlen = sizeof(u.millis);
sockfd = (struct SockFd *)fd->extra;
if (optname == SO_RCVTIMEO) {
sockfd->rcvtimeo = u.millis;
}
if (optname == SO_SNDTIMEO) {
sockfd->sndtimeo = u.millis;
}
return 0;
}
}
if (__sys_setsockopt_nt(fd->handle, level, optname, optval, optlen) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 3,660 | 78 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/bind-sysv.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/dce.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
int sys_bind(int fd, const void *addr, uint32_t addrsize) {
union sockaddr_storage_bsd bsd;
if (!IsBsd()) {
return __sys_bind(fd, addr, addrsize);
} else if (!sockaddr2bsd(addr, addrsize, &bsd, &addrsize)) {
return __sys_bind(fd, &bsd.sa, addrsize);
} else {
return -1;
}
}
| 2,235 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/parseport.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/conv.h"
#include "libc/sock/sock.h"
#include "libc/sysv/errfuns.h"
/* parses string to port number.
*
* @param service is a NULL-terminated string
* @return valid port number or einval()
*
* @see strtoimax
*/
int parseport(const char* service) {
char* end;
int port = strtoimax(service, &end, 0);
if (!service || end == service || *end != '\0' || port < 0 || port > 65535)
return einval();
return port;
}
| 2,279 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/goodsocket.internal.h | #ifndef COSMOPOLITAN_LIBC_SOCK_GOODSOCKET_H_
#define COSMOPOLITAN_LIBC_SOCK_GOODSOCKET_H_
#include "libc/calls/struct/timeval.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int GoodSocket(int, int, int, bool, const struct timeval *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_GOODSOCKET_H_ */
| 369 | 12 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/inet_pton.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/fmt.h"
#include "libc/macros.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/errfuns.h"
static inline void add_set(unsigned __int128 *pResTemp, uint16_t *pCurrentSet,
unsigned *pDigitsLeft) {
*pDigitsLeft -= *pDigitsLeft % 4;
*pResTemp = (*pResTemp << 16) | *pCurrentSet;
*pCurrentSet = 0;
}
static int inet_pton_inet6_impl(const char *src, uint8_t *dst) {
enum STATES {
COLON_OK = 1 << 0,
COLON_WAS = 1 << 1,
DIGIT_OK = 1 << 2,
COLON_OR_DIGIT = COLON_OK | DIGIT_OK,
};
unsigned __int128 res = 0;
unsigned __int128 resTemp = 0;
char c;
enum STATES state = COLON_OR_DIGIT;
unsigned digitsLeft = 32;
bool zeroFound = false;
uint16_t currentSet = 0;
while (c = *src++) {
if (digitsLeft == 0) {
return 0;
}
if (state & COLON_OK) {
if (c == ':') {
if (state & COLON_WAS) {
if (zeroFound) {
return 0;
}
res = resTemp << (4 * digitsLeft);
resTemp = 0;
digitsLeft -= 4;
zeroFound = true;
state = DIGIT_OK;
} else {
if (digitsLeft % 4) {
add_set(&resTemp, ¤tSet, &digitsLeft);
} else if (digitsLeft == 32) {
state = COLON_OK;
} else {
state = COLON_OR_DIGIT;
}
state |= COLON_WAS;
}
continue;
}
}
if (state & DIGIT_OK) {
if ((c >= '0') && ((c < ':') || ((c >= 'A') && (c < 'G')) ||
((c >= 'a') && (c < 'g')))) {
state &= (~COLON_WAS);
uint8_t digit;
if (c < ':') {
digit = c - '0';
} else if (c < 'G') {
digit = c - 'A' + 10;
} else {
digit = c - 'a' + 10;
}
currentSet = (currentSet << 4) | digit;
digitsLeft--;
if (!(digitsLeft % 4)) {
state = COLON_OK;
add_set(&resTemp, ¤tSet, &digitsLeft);
} else if ((state == DIGIT_OK) && (digitsLeft > 4)) {
state = COLON_OR_DIGIT;
}
continue;
} else if ((c == '.') && (digitsLeft >= 5) && (digitsLeft <= 27) &&
(digitsLeft % 4)) {
uint8_t ipv4[4];
const unsigned digitsRead = 4 - digitsLeft % 4;
if (inet_pton(AF_INET, src - (1 + digitsRead), &ipv4) == 1) {
state &= (~COLON_WAS);
digitsLeft += digitsRead;
currentSet = (ipv4[0] << 8) | ipv4[1];
digitsLeft -= 4;
add_set(&resTemp, ¤tSet, &digitsLeft);
currentSet = (ipv4[2] << 8) | ipv4[3];
digitsLeft -= 4;
add_set(&resTemp, ¤tSet, &digitsLeft);
break;
}
}
}
return 0;
}
if (state & COLON_WAS) {
return 0;
} else if (digitsLeft % 4) {
add_set(&resTemp, ¤tSet, &digitsLeft);
}
if (!zeroFound && (digitsLeft != 0)) {
return 0;
}
res |= resTemp;
dst[0] = res >> (15 * 8);
dst[1] = res >> (14 * 8);
dst[2] = res >> (13 * 8);
dst[3] = res >> (12 * 8);
dst[4] = res >> (11 * 8);
dst[5] = res >> (10 * 8);
dst[6] = res >> (9 * 8);
dst[7] = res >> (8 * 8);
dst[8] = res >> (7 * 8);
dst[9] = res >> (6 * 8);
dst[10] = res >> (5 * 8);
dst[11] = res >> (4 * 8);
dst[12] = res >> (3 * 8);
dst[13] = res >> (2 * 8);
dst[14] = res >> (1 * 8);
dst[15] = res >> (0 * 8);
return 1;
}
/**
* Converts internet address string to binary.
*
* @param af can be AF_INET or AF_INET6
* @param src is the ASCII-encoded address
* @param dst is where the binary-encoded net-order address goes
* @return 1 on success, 0 on src malformed, or -1 w/ errno
*/
int inet_pton(int af, const char *src, void *dst) {
uint8_t *p;
int b, c, j;
if (af == AF_INET6) return inet_pton_inet6_impl(src, dst);
if (af != AF_INET) return eafnosupport();
j = 0;
p = dst;
p[0] = 0;
while ((c = *src++)) {
if (isdigit(c)) {
b = c - '0' + p[j] * 10;
p[j] = MIN(255, b);
if (b > 255) return 0;
} else if (c == '.') {
if (++j == 4) return 0;
p[j] = 0;
} else {
return 0;
}
}
return j == 3 ? 1 : 0;
}
| 6,126 | 178 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/htonl.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts network to host short.
*/
uint32_t(htonl)(uint32_t x) {
return bswap_32(x);
}
| 1,993 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/accept-nt.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/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/consts/fio.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_accept_nt(struct Fd *fd, void *addr, uint32_t *addrsize,
int flags) {
int64_t h;
int rc, client, oflags;
struct SockFd *sockfd, *sockfd2;
sockfd = (struct SockFd *)fd->extra;
if (_check_interrupts(true, g_fds.p)) return -1;
for (;;) {
if (!WSAPoll(&(struct sys_pollfd_nt){fd->handle, POLLIN}, 1,
__SIG_POLLING_INTERVAL_MS)) {
if (_check_interrupts(true, g_fds.p)) {
return eintr();
}
continue;
}
if ((h = WSAAccept(fd->handle, addr, (int32_t *)addrsize, 0, 0)) != -1) {
oflags = 0;
if (flags & SOCK_CLOEXEC) oflags |= O_CLOEXEC;
if (flags & SOCK_NONBLOCK) oflags |= O_NONBLOCK;
if ((!(flags & SOCK_NONBLOCK) ||
__sys_ioctlsocket_nt(h, FIONBIO, (uint32_t[]){1}) != -1) &&
(sockfd2 = calloc(1, sizeof(struct SockFd)))) {
__fds_lock();
if ((client = __reservefd_unlocked(-1)) != -1) {
sockfd2->family = sockfd->family;
sockfd2->type = sockfd->type;
sockfd2->protocol = sockfd->protocol;
g_fds.p[client].kind = kFdSocket;
g_fds.p[client].flags = oflags;
g_fds.p[client].mode = 0140666;
g_fds.p[client].handle = h;
g_fds.p[client].extra = (uintptr_t)sockfd2;
__fds_unlock();
return client;
}
__fds_unlock();
free(sockfd2);
}
__sys_closesocket_nt(h);
}
return __winsockerr();
}
}
| 3,741 | 75 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sendto.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
/**
* Sends data over network.
*
* This function blocks unless MSG_DONTWAIT is passed. In that case, the
* non-error EWOULDBLOCK might be returned. It basically means we didn't
* wait around to learn an amount of bytes were written that we know in
* advance are guaranteed to be atomic.
*
* @param fd is the file descriptor returned by socket()
* @param buf is the data to send, which we'll copy if necessary
* @param size is the byte-length of buf
* @param flags MSG_OOB, MSG_DONTROUTE, MSG_PARTIAL, MSG_NOSIGNAL, etc.
* @param opt_addr is a binary ip:port destination override, which is
* mandatory for UDP if connect() wasn't called
* @param addrsize is the byte-length of addr's true polymorphic form
* @return number of bytes transmitted, or -1 w/ errno
* @error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
* EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
ssize_t sendto(int fd, const void *buf, size_t size, int flags,
const struct sockaddr *opt_addr, uint32_t addrsize) {
ssize_t rc;
uint32_t bsdaddrsize;
union sockaddr_storage_bsd bsd;
BEGIN_CANCELLATION_POINT;
if (IsAsan() && (!__asan_is_valid(buf, size) ||
(opt_addr && !__asan_is_valid(opt_addr, addrsize)))) {
rc = efault();
} else {
if (!IsWindows()) {
if (!IsBsd() || !opt_addr) {
rc = sys_sendto(fd, buf, size, flags, opt_addr, addrsize);
} else if (!(rc = sockaddr2bsd(opt_addr, addrsize, &bsd, &bsdaddrsize))) {
rc = sys_sendto(fd, buf, size, flags, &bsd, bsdaddrsize);
}
} else if (__isfdopen(fd)) {
if (__isfdkind(fd, kFdSocket)) {
rc = sys_sendto_nt(fd, (struct iovec[]){{buf, size}}, 1, flags,
opt_addr, addrsize);
} else if (__isfdkind(fd, kFdFile)) {
if (flags) {
rc = einval();
} else if (opt_addr) {
rc = eisconn();
} else {
rc = sys_write_nt(fd, (struct iovec[]){{buf, size}}, 1, -1);
}
} else {
rc = enotsock();
}
} else {
rc = ebadf();
}
}
END_CANCELLATION_POINT;
DATATRACE("sendto(%d, %#.*hhs%s, %'zu, %#x, %p, %u) â %'ld% lm", fd,
MAX(0, MIN(40, rc)), buf, rc > 40 ? "..." : "", size, flags,
opt_addr, addrsize, rc);
return rc;
}
| 4,773 | 100 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getpeername-sysv.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/dce.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
int sys_getpeername(int fd, void *out_addr, uint32_t *out_addrsize) {
int rc;
uint32_t size;
union sockaddr_storage_bsd bsd;
if (!IsBsd()) {
rc = __sys_getpeername(fd, out_addr, out_addrsize);
} else {
size = sizeof(bsd);
if ((rc = __sys_getpeername(fd, &bsd, &size)) != -1) {
sockaddr2linux(&bsd, size, out_addr, out_addrsize);
}
}
return rc;
}
| 2,321 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/kntwsadata.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/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/runtime.h"
#include "libc/nt/winsock.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/internal.h"
#define VERSION 0x0202 /* Windows Vista+ */
/**
* Information about underlying Windows Sockets implementation.
*
* Cosmopolitan automatically calls YOINK() on this symbol when its
* Berkeley Socket wrappers are linked. The latest version of Winsock
* was introduced alongside x64, so this should never fail.
*/
_Hide struct NtWsaData kNtWsaData;
static textwindows void WinSockCleanup(void) {
int i, rc;
rc = WSACleanup();
NTTRACE("WSACleanup() â %d% lm", rc);
}
textwindows noasan void WinSockInit(void) {
int rc;
atexit(WinSockCleanup);
NTTRACE("WSAStartup()");
if ((rc = WSAStartup(VERSION, &kNtWsaData)) != 0 ||
kNtWsaData.wVersion != VERSION) {
ExitProcess(123);
}
}
| 2,789 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/send-nt.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/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sysv/errfuns.h"
textwindows ssize_t sys_send_nt(int fd, const struct iovec *iov, size_t iovlen,
uint32_t flags) {
ssize_t rc;
uint32_t sent = 0;
struct SockFd *sockfd;
struct NtIovec iovnt[16];
struct NtOverlapped overlapped = {.hEvent = WSACreateEvent()};
if (_check_interrupts(true, g_fds.p)) return -1;
if (!WSASend(g_fds.p[fd].handle, iovnt, __iovec2nt(iovnt, iov, iovlen), &sent,
flags, &overlapped, NULL)) {
rc = sent;
} else {
sockfd = (struct SockFd *)g_fds.p[fd].extra;
rc = __wsablock(g_fds.p[fd].handle, &overlapped, &flags, true,
sockfd->sndtimeo);
}
WSACloseEvent(overlapped.hEvent);
return rc;
}
| 2,733 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getsockname.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/internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Returns details about network interface kernel granted socket.
* @return 0 on success or -1 w/ errno
* @see getpeername()
*/
int getsockname(int fd, struct sockaddr *out_addr, uint32_t *out_addrsize) {
int rc;
if (!out_addrsize || !out_addrsize ||
(IsAsan() && (!__asan_is_valid(out_addrsize, 4) ||
!__asan_is_valid(out_addr, *out_addrsize)))) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_getsockname(fd, out_addr, out_addrsize);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_getsockname_nt(&g_fds.p[fd], out_addr, out_addrsize);
} else {
rc = ebadf();
}
STRACE("getsockname(%d, [%s]) -> %d% lm", fd,
DescribeSockaddr(out_addr, out_addrsize ? *out_addrsize : 0), rc);
return rc;
}
| 2,962 | 52 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getpeername-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/dce.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sock/yoink.inc"
#include "libc/sysv/errfuns.h"
textwindows int sys_getpeername_nt(struct Fd *fd, void *out_addr,
uint32_t *out_addrsize) {
_npassert(fd->kind == kFdSocket);
if (__sys_getpeername_nt(fd->handle, out_addr, out_addrsize) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 2,343 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/yoink.inc | STATIC_YOINK("kNtWsaData"); // for winmain
STATIC_YOINK("WSAGetLastError"); // for kprintf
STATIC_YOINK("sys_closesocket_nt"); // for close
STATIC_YOINK("sys_recv_nt"); // for readv
STATIC_YOINK("sys_send_nt"); // for writev
| 255 | 6 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/dupsockfd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/mem/mem.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
textwindows struct SockFd *_dupsockfd(struct SockFd *sockfd) {
struct SockFd *newsf;
if ((newsf = calloc(1, sizeof(struct SockFd)))) {
newsf->family = sockfd->family;
newsf->type = sockfd->type;
newsf->protocol = sockfd->protocol;
}
return newsf;
}
| 2,193 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/ipclassify.internal.h | #ifndef COSMOPOLITAN_LIBC_SOCK_IPCLASSIFY_H_
#define COSMOPOLITAN_LIBC_SOCK_IPCLASSIFY_H_
#ifndef __STRICT_ANSI__
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/errfuns.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/**
* Returns true if address is part of standardized test-only subnet.
*/
forceinline bool istestip(int sin_family, void *sin_addr) {
if (sin_family == AF_INET) {
uint32_t ip4net24 = ntohl(*(const uint32_t *)sin_addr) & 0xffffff00u;
if (ip4net24 == INADDR_TESTNET1 || ip4net24 == INADDR_TESTNET2 ||
ip4net24 == INADDR_TESTNET3) {
return true;
}
} else {
eafnosupport();
}
return false;
}
/**
* Returns true if address is part of a local-only subnet.
*/
forceinline bool islocalip(int sin_family, void *sin_addr) {
if (sin_family == AF_INET) {
uint32_t ip4net8 = ntohl(*(const uint32_t *)sin_addr) & 0xff000000u;
if (ip4net8 == 0x7f000000u) {
return true;
}
} else {
eafnosupport();
}
return false;
}
/**
* Returns true if address is part of a well-known private subnet.
*/
forceinline bool isprivateip(int sin_family, void *sin_addr) {
if (sin_family == AF_INET) {
uint32_t ip4 = ntohl(*(const uint32_t *)sin_addr);
if ((0x0a000000u <= ip4 && ip4 <= 0x0affffffu) /* 10.0.0.0/8 */ ||
(0xac100000u <= ip4 && ip4 <= 0xac1fffffu) /* 172.16.0.0/12 */ ||
(0xc0a80000u <= ip4 && ip4 <= 0xc0a8ffffu) /* 192.168.0.0/16 */) {
return true;
}
} else {
eafnosupport();
}
return false;
}
/**
* Returns true if address is most likely part of the public Internet.
*/
forceinline bool ispublicip(int sin_family, void *sin_addr) {
return !islocalip(sin_family, sin_addr) &&
!isprivateip(sin_family, sin_addr) && !istestip(sin_family, sin_addr);
}
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* !ANSI */
#endif /* COSMOPOLITAN_LIBC_SOCK_IPCLASSIFY_H_ */
| 2,012 | 71 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/epoll.h | #ifndef COSMOPOLITAN_LIBC_SOCK_WEPOLL_H_
#define COSMOPOLITAN_LIBC_SOCK_WEPOLL_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#include "libc/calls/struct/sigset.h"
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct thatispacked epoll_event {
uint32_t events;
epoll_data_t data;
};
int epoll_create(int);
int epoll_create1(int);
int epoll_ctl(int, int, int, struct epoll_event *);
int epoll_wait(int, struct epoll_event *, int, int);
int epoll_pwait(int, struct epoll_event *, int, int, const sigset_t *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_WEPOLL_H_ */
| 696 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/syslog.h | #ifndef COSMOPOLITAN_LIBC_SOCK_SYSLOG_H_
#define COSMOPOLITAN_LIBC_SOCK_SYSLOG_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int setlogmask(int);
void openlog(const char *, int, int);
void syslog(int, const char *, ...);
void closelog(void);
void vsyslog(int, const char *, va_list);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_SYSLOG_H_ */
| 416 | 15 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/inet_ntop.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/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Formats internet address to string.
*
* @param af can be AF_INET or AF_INET6
* @param src is the binary-encoded address, e.g. &addr->sin_addr
* @param dst is the output string buffer
* @param size needs to be 16+ for IPv4 and 46+ for IPv6
* @return dst on success or NULL w/ errno
*/
const char *inet_ntop(int af, const void *src, char *dst, uint32_t size) {
char *p;
unsigned char *ip;
int i, t, a, b, c, d;
p = dst;
if (!size) return dst;
if ((ip = src)) {
if (af == AF_INET) {
if (size >= 16) {
p = FormatUint32(p, ip[0]);
*p++ = '.';
p = FormatUint32(p, ip[1]);
*p++ = '.';
p = FormatUint32(p, ip[2]);
*p++ = '.';
p = FormatUint32(p, ip[3]);
*p = '\0';
return dst;
} else {
enospc();
}
} else if (af == AF_INET6) {
if (size >= 46) {
t = 0;
i = 0;
for (i = 0; i < 16; i += 2) {
switch (t) {
case 0:
if (!ip[i] && !ip[i + 1]) {
t = 1;
*p++ = ':';
*p++ = ':';
continue;
} else if (i) {
*p++ = ':';
}
break;
case 1:
if (!ip[i] && !ip[i + 1]) {
continue;
} else {
t = 2;
}
break;
case 2:
*p++ = ':';
break;
default:
unreachable;
}
a = (ip[i + 0] & 0xF0) >> 4;
b = (ip[i + 0] & 0x0F) >> 0;
c = (ip[i + 1] & 0xF0) >> 4;
d = (ip[i + 1] & 0x0F) >> 0;
if (a) *p++ = "0123456789abcdef"[a];
if (a || b) *p++ = "0123456789abcdef"[b];
if (a || b || c) *p++ = "0123456789abcdef"[c];
*p++ = "0123456789abcdef"[d];
}
*p = '\0';
return dst;
} else {
enospc();
}
} else {
eafnosupport();
}
} else {
einval();
}
return 0;
}
| 4,006 | 105 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/shutdown-nt.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/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
textwindows int sys_shutdown_nt(struct Fd *fd, int how) {
if (__sys_shutdown_nt(fd->handle, how) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 2,107 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/recvfrom.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/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Receives data from network.
*
* This function blocks unless MSG_DONTWAIT is passed.
*
* @param fd is the file descriptor returned by socket()
* @param buf is where received network data gets copied
* @param size is the byte capacity of buf
* @param flags can have MSG_{WAITALL,DONTROUTE,PEEK,OOB}, etc.
* @param opt_out_srcaddr receives the binary ip:port of the data's origin
* @param opt_inout_srcaddrsize is srcaddr capacity which gets updated
* @return number of bytes received, 0 on remote close, or -1 w/ errno
* @error EINTR, EHOSTUNREACH, ECONNRESET (UDP ICMP Port Unreachable),
* EPIPE (if MSG_NOSIGNAL), EMSGSIZE, ENOTSOCK, EFAULT, etc.
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
ssize_t recvfrom(int fd, void *buf, size_t size, int flags,
struct sockaddr *opt_out_srcaddr,
uint32_t *opt_inout_srcaddrsize) {
ssize_t rc;
uint32_t sz;
union sockaddr_storage_bsd bsd;
BEGIN_CANCELLATION_POINT;
if (IsAsan() &&
(!__asan_is_valid(buf, size) ||
(opt_out_srcaddr &&
(!__asan_is_valid(opt_inout_srcaddrsize,
sizeof(*opt_inout_srcaddrsize)) ||
!__asan_is_valid(opt_out_srcaddr, *opt_inout_srcaddrsize))))) {
rc = efault();
} else if (!IsWindows()) {
if (!IsBsd() || !opt_out_srcaddr) {
rc = sys_recvfrom(fd, buf, size, flags, opt_out_srcaddr,
opt_inout_srcaddrsize);
} else {
sz = sizeof(bsd);
if ((rc = sys_recvfrom(fd, buf, size, flags, &bsd, &sz)) != -1) {
sockaddr2linux(&bsd, sz, (void *)opt_out_srcaddr,
opt_inout_srcaddrsize);
}
}
} else if (__isfdopen(fd)) {
if (__isfdkind(fd, kFdSocket)) {
rc = sys_recvfrom_nt(&g_fds.p[fd], (struct iovec[]){{buf, size}}, 1,
flags, opt_out_srcaddr, opt_inout_srcaddrsize);
} else if (__isfdkind(fd, kFdFile) && !opt_out_srcaddr) { /* socketpair */
if (flags) {
rc = einval();
} else {
rc = sys_read_nt(&g_fds.p[fd], (struct iovec[]){{buf, size}}, 1, -1);
}
} else {
rc = enotsock();
}
} else {
rc = ebadf();
}
END_CANCELLATION_POINT;
DATATRACE("recvfrom(%d, [%#.*hhs%s], %'zu, %#x) â %'ld% lm", fd,
MAX(0, MIN(40, rc)), buf, rc > 40 ? "..." : "", size, flags, rc);
return rc;
}
| 4,746 | 100 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getpeername.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/internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Returns details about remote end of connected socket.
* @return 0 on success or -1 w/ errno
* @see getsockname()
*/
int getpeername(int fd, struct sockaddr *out_addr, uint32_t *out_addrsize) {
int rc;
if (!out_addr || !out_addrsize ||
(IsAsan() && (!__asan_is_valid(out_addrsize, 4) ||
!__asan_is_valid(out_addr, *out_addrsize)))) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_getpeername(fd, out_addr, out_addrsize);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_getpeername_nt(&g_fds.p[fd], out_addr, out_addrsize);
} else {
rc = ebadf();
}
STRACE("getpeername(%d, [%s]) -> %d% lm", fd,
DescribeSockaddr(out_addr, out_addrsize ? *out_addrsize : 0), rc);
return rc;
}
| 2,949 | 52 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/select.h | #ifndef COSMOPOLITAN_LIBC_SOCK_SELECT_H_
#define COSMOPOLITAN_LIBC_SOCK_SELECT_H_
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/str/str.h"
#define FD_SETSIZE 1024 /* it's 64 on windows */
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef struct fd_set {
unsigned long fds_bits[FD_SETSIZE / (sizeof(long) * CHAR_BIT)];
} fd_set;
#define FD_ISSET(FD, SET) (((SET)->fds_bits[(FD) >> 6] >> ((FD)&63)) & 1)
#define FD_SET(FD, SET) ((SET)->fds_bits[(FD) >> 6] |= 1ull << ((FD)&63))
#define FD_CLR(FD, SET) ((SET)->fds_bits[(FD) >> 6] &= ~(1ull << ((FD)&63)))
#define FD_ZERO(SET) bzero((SET)->fds_bits, sizeof((SET)->fds_bits))
#define FD_SIZE(bits) (((bits) + (sizeof(long) * CHAR_BIT) - 1) / sizeof(long))
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
int pselect(int, fd_set *, fd_set *, fd_set *, const struct timespec *,
const sigset_t *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_SELECT_H_ */
| 1,108 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/ntohl.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts network to host long.
*/
uint32_t(ntohl)(uint32_t x) {
return bswap_32(x);
}
| 1,992 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sendfile.internal.h | #ifndef COSMOPOLITAN_LIBC_SOCK_SENDFILE_INTERNAL_H_
#define COSMOPOLITAN_LIBC_SOCK_SENDFILE_INTERNAL_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int sys_sendfile_xnu(int32_t infd, int32_t outfd, int64_t offset,
int64_t *out_opt_sbytes, const void *opt_hdtr,
int32_t flags) _Hide;
int sys_sendfile_freebsd(int32_t infd, int32_t outfd, int64_t offset,
size_t nbytes, const void *opt_hdtr,
int64_t *out_opt_sbytes, int32_t flags) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_SENDFILE_INTERNAL_H_ */
| 672 | 17 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sockaddr2bsd.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/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/struct/sockaddr6-bsd.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Converts sockaddr (Linux/Windows) â sockaddr_bsd (XNU/BSD).
*/
int sockaddr2bsd(const void *addr, uint32_t addrsize,
union sockaddr_storage_bsd *out_addr, uint32_t *out_addrsize) {
uint32_t len, famsize;
if (addrsize >= sizeof(((struct sockaddr *)addr)->sa_family)) {
if (((struct sockaddr *)addr)->sa_family == AF_INET) {
if (addrsize >= sizeof(struct sockaddr_in)) {
out_addr->sin.sin_len = 0;
out_addr->sin.sin_family = AF_INET;
out_addr->sin.sin_port = ((struct sockaddr_in *)addr)->sin_port;
out_addr->sin.sin_addr = ((struct sockaddr_in *)addr)->sin_addr;
bzero(&out_addr->sin.sin_zero, sizeof(out_addr->sin.sin_zero));
*out_addrsize = sizeof(struct sockaddr_in_bsd);
return 0;
} else {
return einval();
}
} else if (((struct sockaddr *)addr)->sa_family == AF_INET6) {
if (addrsize >= sizeof(struct sockaddr_in6)) {
out_addr->sin6.sin6_len = 0;
out_addr->sin6.sin6_family = AF_INET6;
out_addr->sin6.sin6_port = ((struct sockaddr_in6 *)addr)->sin6_port;
out_addr->sin6.sin6_flowinfo =
((struct sockaddr_in6 *)addr)->sin6_flowinfo;
out_addr->sin6.sin6_addr = ((struct sockaddr_in6 *)addr)->sin6_addr;
out_addr->sin6.sin6_scope_id =
((struct sockaddr_in6 *)addr)->sin6_scope_id;
*out_addrsize = sizeof(struct sockaddr_in6_bsd);
return 0;
} else {
return einval();
}
} else if (((struct sockaddr *)addr)->sa_family == AF_UNIX) {
famsize = sizeof(((struct sockaddr_un *)addr)->sun_family);
if (addrsize >= famsize &&
(len = strnlen(((struct sockaddr_un *)addr)->sun_path,
addrsize - famsize)) <
sizeof(out_addr->sun.sun_path)) {
out_addr->sun.sun_len = 0;
out_addr->sun.sun_family = AF_UNIX;
memcpy(out_addr->sun.sun_path, ((struct sockaddr_un *)addr)->sun_path,
len);
out_addr->sun.sun_path[len] = 0;
*out_addrsize = sizeof(out_addr->sun.sun_len) +
sizeof(out_addr->sun.sun_family) + len;
return 0;
} else {
return einval();
}
} else {
return epfnosupport();
}
} else {
return einval();
}
}
| 4,382 | 84 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sys_sendfile_xnu.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 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"
sys_sendfile_xnu:
jmp sys_sendfile
.endfn sys_sendfile_xnu,globl
| 1,938 | 24 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/syscall_fd.internal.h | #ifndef COSMOPOLITAN_LIBC_SOCK_SYSCALL_INTERNAL_H_
#define COSMOPOLITAN_LIBC_SOCK_SYSCALL_INTERNAL_H_
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/iovec.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int sys_accept_nt(struct Fd *, void *, uint32_t *, int) _Hide;
int sys_bind_nt(struct Fd *, const void *, uint32_t);
int sys_closesocket_nt(struct Fd *) _Hide;
int sys_connect_nt(struct Fd *, const void *, uint32_t) _Hide;
int sys_getpeername_nt(struct Fd *, void *, uint32_t *) _Hide;
int sys_getsockname_nt(struct Fd *, void *, uint32_t *) _Hide;
int sys_getsockopt_nt(struct Fd *, int, int, void *, uint32_t *) _Hide;
int sys_listen_nt(struct Fd *, int) _Hide;
int sys_setsockopt_nt(struct Fd *, int, int, const void *, uint32_t) _Hide;
int sys_shutdown_nt(struct Fd *, int) _Hide;
ssize_t sys_recv_nt(struct Fd *, const struct iovec *, size_t, uint32_t) _Hide;
ssize_t sys_recvfrom_nt(struct Fd *, const struct iovec *, size_t, uint32_t,
void *, uint32_t *) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_SYSCALL_INTERNAL_H_ */
| 1,160 | 25 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/closesocket-nt.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/backtrace.internal.h"
#include "libc/mem/mem.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
/**
* Closes socket on Windows.
*
* This function should only be called by close().
*/
textwindows int sys_closesocket_nt(struct Fd *fd) {
struct SockFd *sockfd;
sockfd = (struct SockFd *)fd->extra;
free(sockfd);
if (__sys_closesocket_nt(fd->handle) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 2,308 | 39 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/bind-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sock/yoink.inc"
#include "libc/sysv/errfuns.h"
textwindows int sys_bind_nt(struct Fd *fd, const void *addr,
uint32_t addrsize) {
_npassert(fd->kind == kFdSocket);
if (__sys_bind_nt(fd->handle, addr, addrsize) != -1) {
return 0;
} else {
return __winsockerr();
}
}
| 2,289 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sendfile.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/nt/enum/filetype.h"
#include "libc/nt/enum/wait.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sendfile.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
// sendfile() isn't specified as raising eintr
static textwindows int SendfileBlock(int64_t handle,
struct NtOverlapped *overlapped) {
int rc;
uint32_t i, got, flags = 0;
if (WSAGetLastError() != kNtErrorIoPending &&
WSAGetLastError() != WSAEINPROGRESS) {
NTTRACE("TransmitFile failed %lm");
return __winsockerr();
}
for (;;) {
i = WSAWaitForMultipleEvents(1, &overlapped->hEvent, true,
__SIG_POLLING_INTERVAL_MS, true);
if (i == kNtWaitFailed) {
NTTRACE("WSAWaitForMultipleEvents failed %lm");
return __winsockerr();
} else if (i == kNtWaitTimeout || i == kNtWaitIoCompletion) {
if (_check_interrupts(true, g_fds.p)) return -1;
#if _NTTRACE
POLLTRACE("WSAWaitForMultipleEvents...");
#endif
} else {
break;
}
}
if (!WSAGetOverlappedResult(handle, overlapped, &got, false, &flags)) {
NTTRACE("WSAGetOverlappedResult failed %lm");
return __winsockerr();
}
return got;
}
static dontinline textwindows ssize_t sys_sendfile_nt(
int outfd, int infd, int64_t *opt_in_out_inoffset, uint32_t uptobytes) {
ssize_t rc;
int64_t ih, oh, pos, eof, offset;
struct NtByHandleFileInformation wst;
if (!__isfdkind(infd, kFdFile)) return ebadf();
if (!__isfdkind(outfd, kFdSocket)) return ebadf();
ih = g_fds.p[infd].handle;
oh = g_fds.p[outfd].handle;
if (!SetFilePointerEx(ih, 0, &pos, SEEK_CUR)) {
return __winerr();
}
if (opt_in_out_inoffset) {
offset = *opt_in_out_inoffset;
} else {
offset = pos;
}
if (GetFileInformationByHandle(ih, &wst)) {
// TransmitFile() returns EINVAL if `uptobytes` goes past EOF.
eof = (uint64_t)wst.nFileSizeHigh << 32 | wst.nFileSizeLow;
if (offset + uptobytes > eof) {
uptobytes = eof - offset;
}
} else {
return ebadf();
}
struct NtOverlapped ov = {
.Pointer = (void *)(intptr_t)offset,
.hEvent = WSACreateEvent(),
};
if (TransmitFile(oh, ih, uptobytes, 0, &ov, 0, 0)) {
rc = uptobytes;
} else {
rc = SendfileBlock(oh, &ov);
}
if (rc != -1) {
if (opt_in_out_inoffset) {
*opt_in_out_inoffset = offset + rc;
_npassert(SetFilePointerEx(ih, pos, 0, SEEK_SET));
} else {
_npassert(SetFilePointerEx(ih, offset + rc, 0, SEEK_SET));
}
}
WSACloseEvent(ov.hEvent);
return rc;
}
static ssize_t sys_sendfile_bsd(int outfd, int infd,
int64_t *opt_in_out_inoffset,
size_t uptobytes) {
ssize_t rc;
int64_t offset, sbytes;
if (opt_in_out_inoffset) {
offset = *opt_in_out_inoffset;
} else if ((offset = lseek(infd, 0, SEEK_CUR)) == -1) {
return -1;
}
if (IsFreebsd()) {
rc = sys_sendfile_freebsd(infd, outfd, offset, uptobytes, 0, &sbytes, 0);
if (rc == -1 && errno == ENOBUFS) errno = ENOMEM;
} else {
sbytes = uptobytes;
rc = sys_sendfile_xnu(infd, outfd, offset, &sbytes, 0, 0);
}
if (rc == -1 && errno == ENOTSOCK) errno = EBADF;
if (rc != -1) {
if (opt_in_out_inoffset) {
*opt_in_out_inoffset += sbytes;
} else {
_npassert(lseek(infd, offset + sbytes, SEEK_SET) == offset + sbytes);
}
return sbytes;
} else {
return -1;
}
}
/**
* Transfers data from file to network.
*
* @param outfd needs to be a socket
* @param infd needs to be a file
* @param opt_in_out_inoffset may be specified for pread()-like behavior
* in which case the file position won't be changed; otherwise, this
* shall read from the file pointer which is advanced accordingly
* @param uptobytes is the maximum number of bytes to send; some platforms
* block until everything's sent, whereas others won't; the behavior of
* zero is undefined; this value may overlap the end of file in which
* case what remains is sent; this is silently reduced to `0x7ffff000`
* @return number of bytes transmitted which may be fewer than requested in
* which case caller must be prepared to call sendfile() again
* @raise ESPIPE on Linux RHEL7+ if offset is used but `infd` isn't seekable,
* otherwise this could be EINVAL
* @raise EPIPE on most systems if socket has been shutdown for reading or
* the remote end closed the connection, otherwise this could be EINVAL
* @raise EBADF if `outfd` isn't a valid writeable stream sock descriptor
* @raise EAGAIN if `O_NONBLOCK` is in play and it would have blocked
* @raise EBADF if `infd` isn't a valid readable file descriptor
* @raise EFAULT if `opt_in_out_inoffset` is a bad pointer
* @raise EINVAL if `*opt_in_out_inoffset` is negative
* @raise EOVERFLOW is documented as possible on Linux
* @raise EIO if `infd` had a low-level i/o error
* @raise ENOMEM if we require more vespene gas
* @raise ENOTCONN if `outfd` isn't connected
* @raise ENOSYS on NetBSD and OpenBSD
* @see copy_file_range() for file â file
* @see splice() for fd â pipe
*/
ssize_t sendfile(int outfd, int infd, int64_t *opt_in_out_inoffset,
size_t uptobytes) {
ssize_t rc;
// We must reduce this due to the uint32_t type conversion on Windows
// which has a maximum of 0x7ffffffe. It also makes sendfile(..., -1)
// less error prone, since Linux may EINVAL if greater than INT64_MAX
uptobytes = MIN(uptobytes, 0x7ffff000);
if (IsAsan() && opt_in_out_inoffset &&
!__asan_is_valid(opt_in_out_inoffset, 8)) {
rc = efault();
} else if (IsLinux()) {
rc = sys_sendfile(outfd, infd, opt_in_out_inoffset, uptobytes);
} else if (IsFreebsd() || IsXnu()) {
rc = sys_sendfile_bsd(outfd, infd, opt_in_out_inoffset, uptobytes);
} else if (IsWindows()) {
rc = sys_sendfile_nt(outfd, infd, opt_in_out_inoffset, uptobytes);
} else {
rc = enosys();
}
STRACE("sendfile(%d, %d, %p, %'zu) â %ld% m", outfd, infd,
DescribeInOutInt64(rc, opt_in_out_inoffset), uptobytes, rc);
return rc;
}
| 8,583 | 209 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/socket-nt.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/internal.h"
#include "libc/calls/state.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/iphlpapi.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/yoink.inc"
#include "libc/sysv/consts/fio.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
/*
* ioctl(SIOCGIFCONFIG) for Windows need to access the following
* functions through weak reference. This ensure those symbols are not
* stripped during final link.
*/
STATIC_YOINK("GetAdaptersAddresses");
STATIC_YOINK("tprecode16to8");
STATIC_YOINK("_dupsockfd");
textwindows int sys_socket_nt(int family, int type, int protocol) {
int64_t h;
struct SockFd *sockfd;
int fd, oflags, truetype;
fd = __reservefd(-1);
if (fd == -1) return -1;
truetype = type & ~(SOCK_CLOEXEC | SOCK_NONBLOCK);
if ((h = WSASocket(family, truetype, protocol, NULL, 0,
kNtWsaFlagOverlapped)) != -1) {
oflags = 0;
if (type & SOCK_CLOEXEC) oflags |= O_CLOEXEC;
if (type & SOCK_NONBLOCK) oflags |= O_NONBLOCK;
if (type & SOCK_NONBLOCK) {
if (__sys_ioctlsocket_nt(h, FIONBIO, (uint32_t[1]){1}) == -1) {
__sys_closesocket_nt(h);
__releasefd(fd);
return __winsockerr();
}
}
sockfd = calloc(1, sizeof(struct SockFd));
sockfd->family = family;
sockfd->type = truetype;
sockfd->protocol = protocol;
__fds_lock();
g_fds.p[fd].kind = kFdSocket;
g_fds.p[fd].flags = oflags;
g_fds.p[fd].mode = 0140666;
g_fds.p[fd].handle = h;
g_fds.p[fd].extra = (uintptr_t)sockfd;
__fds_unlock();
return fd;
} else {
__releasefd(fd);
return __winsockerr();
}
}
| 3,680 | 79 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/fixupnewsockfd.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/syscall_support-sysv.internal.h"
#include "libc/sock/internal.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sock.h"
/**
* Applies non-atomic file descriptor fixups on XNU or ancient Linux.
*
* @param fd of -1 means no-op
*/
int __fixupnewsockfd(int fd, int flags) {
return __fixupnewfd(fd, (((flags & SOCK_CLOEXEC) ? O_CLOEXEC : 0) |
((flags & SOCK_NONBLOCK) ? O_NONBLOCK : 0)));
}
| 2,289 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/connect.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/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Connects socket to remote end.
*
* ProTip: Connectionless sockets, e.g. UDP, can be connected too. The
* benefit is not needing to specify the remote address on each send. It
* also means getsockname() can be called to retrieve routing details.
*
* @return 0 on success or -1 w/ errno
* @cancellationpoint
* @asyncsignalsafe
* @restartable (unless SO_RCVTIMEO)
*/
int connect(int fd, const struct sockaddr *addr, uint32_t addrsize) {
int rc;
BEGIN_CANCELLATION_POINT;
if (addr && !(IsAsan() && !__asan_is_valid(addr, addrsize))) {
if (!IsWindows()) {
rc = sys_connect(fd, addr, addrsize);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_connect_nt(&g_fds.p[fd], addr, addrsize);
} else {
rc = ebadf();
}
} else {
rc = efault();
}
END_CANCELLATION_POINT;
STRACE("connect(%d, %s) â %d% lm", fd, DescribeSockaddr(addr, addrsize), rc);
return rc;
}
| 3,150 | 63 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/connect-sysv.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/dce.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
int sys_connect(int fd, const void *addr, uint32_t addrsize) {
union sockaddr_storage_bsd bsd;
if (!IsBsd()) {
return __sys_connect(fd, addr, addrsize);
} else if (!sockaddr2bsd(addr, addrsize, &bsd, &addrsize)) {
return __sys_connect(fd, &bsd.sa, addrsize);
} else {
return -1;
}
}
| 2,244 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/syslog.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/sock/syslog.h"
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/dprintf.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/internal.h"
#include "libc/macros.internal.h"
#include "libc/nt/events.h"
#include "libc/nt/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/log.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sock.h"
#include "libc/time/struct/tm.h"
/* Note: log_facility should be initialized with LOG_USER by default,
* but since LOG_USER is not a constant value, we cannot initialize it
* here. Set it to -1 to force the public functions to call __initlog()
* for the first time.
*/
static int log_facility = -1;
static char16_t log_ident[32];
static int log_opt;
static int log_mask;
static uint16_t log_id; /* Used for Windows EvtID */
static int64_t log_fd = -1;
static const char *const kLogPaths[] = {
"/dev/log",
// "/var/run/log", // TODO: Help with XNU and FreeBSD.
};
static struct sockaddr_un log_addr = {AF_UNIX, "/dev/log"};
static int64_t Time(int64_t *tp) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
if (tp) *tp = ts.tv_sec;
return ts.tv_sec;
}
static void __initlog() {
log_ident[0] = '\0';
log_opt = LOG_ODELAY;
log_facility = LOG_USER;
log_mask = LOG_PRI(0xff); // Initially use max verbosity
log_fd = -1;
}
forceinline int is_lost_conn(int e) {
return (e == ECONNREFUSED) || (e == ECONNRESET) || (e == ENOTCONN) ||
(e == EPIPE);
}
static void __openlog() {
int i;
if (IsWindows()) {
log_fd = RegisterEventSource(NULL, log_ident);
} else {
log_fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (log_fd >= 0) {
for (i = 0; i < ARRAYLEN(kLogPaths); ++i) {
strcpy(log_addr.sun_path, kLogPaths[i]);
if (!connect(log_fd, (void *)&log_addr, sizeof(log_addr))) {
return;
}
}
printf("ERR: connect(openlog) failed: %s (errno=%d)\n", strerror(errno),
errno);
}
}
}
/**
* Generates a log message which will be distributed by syslogd
*
* Note: no errors are reported if an error occurred while logging
* the message.
*
* @param 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.
* it 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
* @param message the format of the message to be processed by vprintf()
* @param ap the va_list of arguments to be applied to the message
* @asyncsignalsafe
*/
void vsyslog(int priority, const char *message, va_list ap) {
char timebuf[16]; /* Store formatted time */
time_t now;
struct tm tm;
char buf[1024];
int errno_save = errno; /* Save current errno */
int pid;
int l, l2;
int hlen; /* If LOG_CONS is specified, use to store the point in
* the header message after the timestamp */
BLOCK_CANCELLATIONS;
if (log_fd < 0) __openlog();
if (!(priority & LOG_FACMASK)) priority |= log_facility;
/* Build the time string */
now = Time(NULL);
gmtime_r(&now, &tm);
strftime(timebuf, sizeof(timebuf), "%b %e %T", &tm);
pid = (log_opt & LOG_PID) ? getpid() : 0;
/* This is a clever trick to optionally include "[<pid>]"
* only if pid != 0. When pid==0, the while "[%.0d]" is skipped:
* %s%.0d%s -> String, pidValue, String
* Each of those %s:
* - if pid == 0 -> !pid is true (1), so "[" + 1 points to the
* NULL terminator after the "[".
* - if pid != 0 -> !pid is false (0), so the string printed is
* the "[".
*/
l = snprintf(buf, sizeof(buf), "<%d>%s ", priority, timebuf);
hlen = l;
l += snprintf(buf + l, sizeof(buf) - l, "%hs%s%.0d%s: ", log_ident,
"[" + !pid, pid, "]" + !pid);
errno = errno_save;
/* Append user message */
l2 = vsnprintf(buf + l, sizeof(buf) - l, message, ap);
if (l2 >= 0) {
if (l2 >= sizeof(buf) - l) {
l = sizeof(buf) - 1;
} else {
l += l2;
}
if (buf[l - 1] != '\n') {
buf[l++] = '\n';
}
if (!IsWindows()) {
/* Unix:
* - First try to send it to syslogd
* - If fails and LOG_CONS is provided, writes to /dev/console
*/
if (send(log_fd, buf, l, 0) < 0 &&
(!is_lost_conn(errno) ||
connect(log_fd, (void *)&log_addr, sizeof(log_addr)) < 0 ||
send(log_fd, buf, l, 0) < 0) &&
(log_opt & LOG_CONS)) {
int fd = open("/dev/console", O_WRONLY | O_NOCTTY);
if (fd >= 0) {
dprintf(fd, "%.*s", l - hlen, buf + hlen);
close(fd);
}
}
} else {
uint16_t evtType;
uint32_t evtID;
const char *bufArr[] = {
&buf[hlen]}; /* Only print the message without time*/
/* Windows only have 3 usable event types
* Event ID are not supported
* For more information on message types and event IDs, see:
* https://docs.microsoft.com/en-us/windows/win32/eventlog/event-identifiers
*/
priority &= LOG_PRIMASK; // Remove facility from the priority field
if (priority == LOG_EMERG || priority == LOG_ALERT ||
priority == LOG_CRIT) {
evtType = EVENTLOG_ERROR_TYPE;
evtID = 0xe << 28 | (LOG_USER) << 16;
} else if (priority == LOG_WARNING) {
evtType = EVENTLOG_WARNING_TYPE;
evtID = 0xa << 28 | (LOG_USER) << 16;
} else {
/* LOG_NOTICE, LOG_INFO, LOG_DEBUG */
evtType = EVENTLOG_INFORMATION_TYPE;
evtID = 0x6 << 28 | (LOG_USER) << 16;
}
ReportEventA(log_fd, evtType, /* Derived from priority */
0 /* Category unsupported */, evtID, /* Unsupported */
NULL, /* User SID */
1, /* Number of strings */
0, /* Raw data size */
bufArr, /* String(s) */
NULL /* Arguments */);
++log_id;
}
if (log_opt & LOG_PERROR) {
dprintf(2, "%.*s", l - hlen, buf + hlen);
}
}
ALLOW_CANCELLATIONS;
}
/**
* Sets log priority mask
*
* Modifies the log priority mask that determines which calls to
* syslog() may be logged.
* Log priority values are LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
* LOG_WARNING, LOG_NOTICE, LOG_INFO, and LOG_DEBUG.
*
* @param mask the new priority mask to use by syslog()
* @return the previous log priority mask
* @asyncsignalsafe
*/
int setlogmask(int maskpri) {
int ret;
if (log_facility == -1) __initlog();
ret = log_mask;
if (maskpri) log_mask = LOG_PRI(maskpri);
return ret;
}
/**
* Opens a connection to the system logger
*
* Calling this function before calling syslog() is optional and
* only allow customizing the identity, options and facility of
* the messages logged.
*
* @param ident a string that prepends every logged message. If
* it set to NULL, the program name is used.
* @param opt specifies flags which control the operation of openlog().
* Only the following flags are supported:
* LOG_CONS = Write directly to the system console if there is
* an error while sending to the system logger.
* LOG_NDELAY = Open the connection with the system logger
* immediately instead of waiting for the first
* message to be logged.
* LOG_ODELAY = The converse of LOG_NDELAY.
* LOG_PERROR = Also log the message to stderr.
* LOG_PID = Include the caller's PID with each message
* @param facility specifies the default facitlity value that defines
* what kind of program is logging the message.
* Possible values are: LOG_AUTH, LOG_AUTHPRIV,
* LOG_CRON, LOG_DAEMON, LOG_FTP, LOG_LOCAL0 through LOG_LOCAL7,
* LOG_LPR, LOG_MAIL, LOG_NEWS, LOG_SYSLOG, LOG_USER (default),
* LOG_UUCP.
* @asyncsignalsafe
*/
void openlog(const char *ident, int opt, int facility) {
size_t n;
BLOCK_CANCELLATIONS;
if (log_facility == -1) __initlog();
if (!ident) ident = firstnonnull(program_invocation_short_name, "unknown");
tprecode8to16(log_ident, ARRAYLEN(log_ident), ident);
log_opt = opt;
log_facility = facility;
log_id = 0;
if ((opt & LOG_NDELAY) && log_fd < 0) __openlog();
ALLOW_CANCELLATIONS;
}
/**
* Generates a log message which will be distributed by syslogd
*
* Note: no errors are reported if an error occurred while logging
* the message.
*
* @param 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.
* it 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
* @param message the message formatted using the same rules as printf()
* @asyncsignalsafe
*/
void syslog(int priority, const char *message, ...) {
va_list ap;
if (log_facility == -1) {
__initlog();
}
if (LOG_PRI(priority) <= log_mask) {
va_start(ap, message);
vsyslog(priority, message, ap);
va_end(ap);
}
}
/**
* Closes the file descriptor being used to write to the system logger
*
* Use of closelog is optional
* @asyncsignalsafe
*/
void closelog(void) {
if (log_facility == -1) {
__initlog();
}
if (log_fd != -1) {
if (IsWindows()) {
DeregisterEventSource(log_fd);
} else {
close(log_fd);
}
log_fd = -1;
}
}
| 11,972 | 322 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/shutdown.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/internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Disables sends or receives on a socket, without closing.
*
* @param fd is the open file descriptor for the socket
* @param how can be SHUT_RD, SHUT_WR, or SHUT_RDWR
* @return 0 on success or -1 on error
* @asyncsignalsafe
*/
int shutdown(int fd, int how) {
int rc;
if (!IsWindows()) {
rc = sys_shutdown(fd, how);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_shutdown_nt(&g_fds.p[fd], how);
} else {
rc = ebadf();
}
STRACE("shutdown(%d, %d) -> %d% lm", fd, how, rc);
return rc;
}
| 2,632 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/recvfrom-nt.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/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/errno.h"
#include "libc/nt/struct/overlapped.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
textwindows ssize_t sys_recvfrom_nt(struct Fd *fd, const struct iovec *iov,
size_t iovlen, uint32_t flags,
void *opt_out_srcaddr,
uint32_t *opt_inout_srcaddrsize) {
int err;
ssize_t rc;
uint32_t got = 0;
struct SockFd *sockfd;
struct NtIovec iovnt[16];
struct NtOverlapped overlapped = {.hEvent = WSACreateEvent()};
if (_check_interrupts(true, g_fds.p)) return -1;
err = errno;
if (!WSARecvFrom(fd->handle, iovnt, __iovec2nt(iovnt, iov, iovlen), &got,
&flags, opt_out_srcaddr, opt_inout_srcaddrsize, &overlapped,
NULL)) {
rc = got;
} else {
errno = err;
sockfd = (struct SockFd *)fd->extra;
rc = __wsablock(fd->handle, &overlapped, &flags, true, sockfd->rcvtimeo);
}
WSACloseEvent(overlapped.hEvent);
return rc;
}
| 2,976 | 52 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sock.h | #ifndef COSMOPOLITAN_LIBC_SOCK_SOCK_H_
#define COSMOPOLITAN_LIBC_SOCK_SOCK_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § system api » berkeley sockets ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define INET_ADDRSTRLEN 22
#define IFHWADDRLEN 6
uint16_t htons(uint16_t);
uint16_t ntohs(uint16_t);
uint32_t htonl(uint32_t);
uint32_t ntohl(uint32_t);
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
#define htons(x) __builtin_bswap16(x)
#define ntohs(x) __builtin_bswap16(x)
#define htonl(x) __builtin_bswap32(x)
#define ntohl(x) __builtin_bswap32(x)
#endif
const char *inet_ntop(int, const void *, char *, uint32_t);
int inet_pton(int, const char *, void *);
uint32_t inet_addr(const char *);
int parseport(const char *);
uint32_t *GetHostIps(void);
int nointernet(void);
int socket(int, int, int);
int listen(int, int);
int shutdown(int, int);
ssize_t send(int, const void *, size_t, int);
ssize_t recv(int, void *, size_t, int);
ssize_t sendfile(int, int, int64_t *, size_t);
int getsockopt(int, int, int, void *, uint32_t *);
int setsockopt(int, int, int, const void *, uint32_t);
int socketpair(int, int, int, int[2]);
int sockatmark(int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_SOCK_H_ */
| 1,778 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/bind.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/internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Assigns local address and port number to socket, e.g.
*
* struct sockaddr_in in = {AF_INET, htons(12345), {htonl(0x7f000001)}};
* int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
* bind(fd, &in, sizeof(in));
*
* @param fd is the file descriptor returned by socket()
* @param addr is usually the binary-encoded ip:port on which to listen
* @param addrsize is the byte-length of addr's true polymorphic form
* @return 0 on success or -1 w/ errno
* @error ENETDOWN, EPFNOSUPPORT, etc.
* @asyncsignalsafe
*/
int bind(int fd, const struct sockaddr *addr, uint32_t addrsize) {
int rc;
if (!addr || (IsAsan() && !__asan_is_valid(addr, addrsize))) {
rc = efault();
} else if (addrsize >= sizeof(struct sockaddr_in)) {
if (!IsWindows()) {
rc = sys_bind(fd, addr, addrsize);
} else if (__isfdkind(fd, kFdSocket)) {
rc = sys_bind_nt(&g_fds.p[fd], addr, addrsize);
} else {
rc = ebadf();
}
} else {
rc = einval();
}
STRACE("bind(%d, %s) -> %d% lm", fd, DescribeSockaddr(addr, addrsize), rc);
return rc;
}
| 3,276 | 62 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/htons.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts host to network short.
*/
uint16_t(htons)(uint16_t x) {
return bswap_16(x);
}
| 1,993 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/socketpair-sysv.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/dce.h"
#include "libc/errno.h"
#include "libc/sock/internal.h"
#include "libc/sysv/consts/sock.h"
int sys_socketpair(int family, int type, int protocol, int sv[2]) {
int e = errno;
if (__sys_socketpair(family, type, protocol, sv) != -1) return 0;
if ((type & (SOCK_CLOEXEC | SOCK_NONBLOCK)) &&
(errno == EINVAL || errno == EPROTOTYPE || errno == EPROTONOSUPPORT)) {
errno = e;
if (__sys_socketpair(family, type & ~(SOCK_CLOEXEC | SOCK_NONBLOCK),
protocol, sv) != -1) {
__fixupnewsockfd(sv[0], type);
__fixupnewsockfd(sv[1], type);
return 0;
}
}
return -1;
}
| 2,481 | 39 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sockaddr2linux.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/sock/internal.h"
#include "libc/sock/struct/sockaddr.internal.h"
#include "libc/sock/struct/sockaddr6-bsd.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Converts sockaddr_bsd (XNU/BSD) â sockaddr (Linux/Windows).
*/
void sockaddr2linux(const union sockaddr_storage_bsd *addr, uint32_t addrsize,
union sockaddr_storage_linux *out_addr,
uint32_t *inout_addrsize) {
uint32_t len, size;
if (out_addr && inout_addrsize) {
size = *inout_addrsize;
bzero(out_addr, size);
if (addrsize >= sizeof(addr->sa.sa_family)) {
if (addr->sa.sa_family == AF_INET) {
if (addrsize >= sizeof(struct sockaddr_in_bsd) &&
size >= sizeof(struct sockaddr_in)) {
out_addr->sin.sin_family = AF_INET;
out_addr->sin.sin_port = addr->sin.sin_port;
out_addr->sin.sin_addr = addr->sin.sin_addr;
*inout_addrsize = sizeof(struct sockaddr_in);
}
} else if (addr->sa.sa_family == AF_INET6) {
if (addrsize >= sizeof(struct sockaddr_in6_bsd) &&
size >= sizeof(struct sockaddr_in6)) {
out_addr->sin6.sin6_family = AF_INET6;
out_addr->sin6.sin6_port = addr->sin6.sin6_port;
out_addr->sin6.sin6_addr = addr->sin6.sin6_addr;
out_addr->sin6.sin6_flowinfo = addr->sin6.sin6_flowinfo;
out_addr->sin6.sin6_scope_id = addr->sin6.sin6_scope_id;
*inout_addrsize = sizeof(struct sockaddr_in6);
}
} else if (addr->sa.sa_family == AF_UNIX) {
if (addrsize >=
sizeof(addr->sun.sun_len) + sizeof(addr->sun.sun_family) &&
size >= sizeof(out_addr->sun.sun_family)) {
len = strnlen(((struct sockaddr_un *)addr)->sun_path,
MIN(addrsize - (sizeof(addr->sun.sun_len) +
sizeof(addr->sun.sun_family)),
size - sizeof(out_addr->sun.sun_family)));
out_addr->sun.sun_family = AF_UNIX;
if (len) memcpy(out_addr->sun.sun_path, addr->sun.sun_path, len);
*inout_addrsize = sizeof(out_addr->sun.sun_family) + len + 1;
}
}
}
}
}
| 4,123 | 72 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/ntohs.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bswap.h"
#include "libc/sock/sock.h"
/**
* Converts network to host short.
*/
uint16_t(ntohs)(uint16_t x) {
return bswap_16(x);
}
| 1,993 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/inet_aton.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â â
â Musl Libc â
â Copyright © 2005-2014 Rich Felker, et al. â
â â
â Permission is hereby granted, free of charge, to any person obtaining â
â a copy of this software and associated documentation files (the â
â "Software"), to deal in the Software without restriction, including â
â without limitation the rights to use, copy, modify, merge, publish, â
â distribute, sublicense, and/or sell copies of the Software, and to â
â permit persons to whom the Software is furnished to do so, subject to â
â the following conditions: â
â â
â The above copyright notice and this permission notice shall be â
â included in all copies or substantial portions of the Software. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY â
â CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, â
â TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE â
â SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/conv.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/str/str.h"
asm(".ident\t\"\\n\\n\
Musl libc (MIT License)\\n\
Copyright 2005-2014 Rich Felker, et. al.\"");
asm(".include \"libc/disclaimer.inc\"");
/**
* Converts dotted IPv4 address string to network order binary.
*/
int inet_aton(const char *s0, struct in_addr *dest) {
const char *s = s0;
unsigned char *d = (void *)dest;
unsigned long a[4] = {0};
char *z;
int i;
for (i = 0; i < 4; i++) {
a[i] = strtoul(s, &z, 0);
if (z == s || (*z && *z != '.') || !isdigit(*s)) return 0;
if (!*z) break;
s = z + 1;
}
if (i == 4) return 0;
switch (i) {
case 0:
a[1] = a[0] & 0xffffff;
a[0] >>= 24;
case 1:
a[2] = a[1] & 0xffff;
a[1] >>= 16;
case 2:
a[3] = a[2] & 0xff;
a[2] >>= 8;
}
for (i = 0; i < 4; i++) {
if (a[i] > 255) return 0;
d[i] = a[i];
}
return 1;
}
| 3,565 | 71 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/getsockopt-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/struct/timeval.h"
#include "libc/nt/struct/linger.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/linger.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sol.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_getsockopt_nt(struct Fd *fd, int level, int optname,
void *out_opt_optval,
uint32_t *inout_optlen) {
uint64_t ms;
uint32_t in_optlen;
struct SockFd *sockfd;
struct linger_nt linger;
_npassert(fd->kind == kFdSocket);
sockfd = (struct SockFd *)fd->extra;
if (out_opt_optval && inout_optlen) {
in_optlen = *inout_optlen;
} else {
in_optlen = 0;
}
if (level == SOL_SOCKET &&
(optname == SO_RCVTIMEO || optname == SO_SNDTIMEO)) {
if (in_optlen >= sizeof(struct timeval)) {
if (optname == SO_RCVTIMEO) {
ms = sockfd->rcvtimeo;
} else {
ms = sockfd->sndtimeo;
}
((struct timeval *)out_opt_optval)->tv_sec = ms / 1000;
((struct timeval *)out_opt_optval)->tv_usec = ms % 1000 * 1000;
*inout_optlen = sizeof(struct timeval);
return 0;
} else {
return einval();
}
}
// TODO(jart): Use WSAIoctl?
if (__sys_getsockopt_nt(fd->handle, level, optname, out_opt_optval,
inout_optlen) == -1) {
return __winsockerr();
}
if (level == SOL_SOCKET) {
if (optname == SO_LINGER && in_optlen == sizeof(struct linger)) {
linger = *(struct linger_nt *)out_opt_optval;
((struct linger *)out_opt_optval)->l_onoff = !!linger.l_onoff;
((struct linger *)out_opt_optval)->l_linger = linger.l_linger;
*inout_optlen = sizeof(struct linger);
}
}
if (in_optlen == 4 && *inout_optlen == 1) {
// handle cases like this
// getsockopt(8, SOL_TCP, TCP_FASTOPEN, [u"âº"], [1]) â 0
int32_t wut = *(signed char *)out_opt_optval;
memcpy(out_opt_optval, &wut, 4);
*inout_optlen = 4;
}
return 0;
}
| 3,984 | 90 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sock.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 += LIBC_SOCK
LIBC_SOCK_ARTIFACTS += LIBC_SOCK_A
LIBC_SOCK = $(LIBC_SOCK_A_DEPS) $(LIBC_SOCK_A)
LIBC_SOCK_A = o/$(MODE)/libc/sock/sock.a
LIBC_SOCK_A_FILES := $(wildcard libc/sock/*) $(wildcard libc/sock/struct/*)
LIBC_SOCK_A_HDRS = $(filter %.h,$(LIBC_SOCK_A_FILES))
LIBC_SOCK_A_INCS = $(filter %.inc,$(LIBC_SOCK_A_FILES))
LIBC_SOCK_A_SRCS_C = $(filter %.c,$(LIBC_SOCK_A_FILES))
LIBC_SOCK_A_SRCS_S = $(filter %.S,$(LIBC_SOCK_A_FILES))
LIBC_SOCK_A_SRCS = \
$(LIBC_SOCK_A_SRCS_C) \
$(LIBC_SOCK_A_SRCS_S)
LIBC_SOCK_A_OBJS = \
$(LIBC_SOCK_A_SRCS_C:%.c=o/$(MODE)/%.o) \
$(LIBC_SOCK_A_SRCS_S:%.S=o/$(MODE)/%.o)
LIBC_SOCK_A_CHECKS = \
$(LIBC_SOCK_A).pkg \
$(LIBC_SOCK_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_SOCK_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT_ADVAPI32 \
LIBC_NT_IPHLPAPI \
LIBC_NT_KERNEL32 \
LIBC_NT_MSWSOCK \
LIBC_NT_NTDLL \
LIBC_NT_WS2_32 \
LIBC_NT_IPHLPAPI \
LIBC_RUNTIME \
LIBC_STDIO \
LIBC_STR \
LIBC_STR \
LIBC_STUBS \
LIBC_SYSV_CALLS \
LIBC_TIME \
LIBC_SYSV
LIBC_SOCK_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_SOCK_A_DIRECTDEPS),$($(x))))
$(LIBC_SOCK_A): libc/sock/ \
$(LIBC_SOCK_A).pkg \
$(LIBC_SOCK_A_OBJS)
$(LIBC_SOCK_A).pkg: \
$(LIBC_SOCK_A_OBJS) \
$(foreach x,$(LIBC_SOCK_A_DIRECTDEPS),$($(x)_A).pkg)
# these assembly files are safe to build on aarch64
o/$(MODE)/libc/sock/sys_sendfile_xnu.o: libc/sock/sys_sendfile_xnu.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
LIBC_SOCK_LIBS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)))
LIBC_SOCK_SRCS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)_SRCS))
LIBC_SOCK_HDRS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)_HDRS))
LIBC_SOCK_INCS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)_INCS))
LIBC_SOCK_CHECKS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)_CHECKS))
LIBC_SOCK_OBJS = $(foreach x,$(LIBC_SOCK_ARTIFACTS),$($(x)_OBJS))
$(LIBC_SOCK_OBJS): $(BUILD_FILES) libc/sock/sock.mk
.PHONY: o/$(MODE)/libc/sock
o/$(MODE)/libc/sock: $(LIBC_SOCK_CHECKS)
| 2,291 | 74 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/inet_ntoa.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/itoa.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
/**
* Converts IPv4 network address to array.
*/
char *inet_ntoa(struct in_addr in) {
static char buf[16];
char *p = buf;
p = FormatUint32(p, (in.s_addr >> 000) & 255);
*p++ = '.';
p = FormatUint32(p, (in.s_addr >> 010) & 255);
*p++ = '.';
p = FormatUint32(p, (in.s_addr >> 020) & 255);
*p++ = '.';
p = FormatUint32(p, (in.s_addr >> 030) & 255);
return buf;
}
| 2,313 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/sockdebug.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/macros.internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/sock/struct/sockaddr6.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
const char *(DescribeSockaddr)(char buf[128], const struct sockaddr *sa,
size_t sasize) {
int e;
size_t n;
uint16_t port;
char *p, ip[72];
e = errno;
stpcpy(buf, "NULL");
if (sa && sasize >= sizeof(sa->sa_family)) {
stpcpy(buf, DescribeSocketFamily(sa->sa_family));
if (sa->sa_family == AF_INET && sasize >= sizeof(struct sockaddr_in)) {
const struct sockaddr_in *in;
in = (const struct sockaddr_in *)sa;
if (inet_ntop(AF_INET, &in->sin_addr, ip, sizeof(ip))) {
p = buf;
p = stpcpy(p, ip);
*p++ = ':';
p = FormatUint32(p, ntohs(in->sin_port));
}
} else if (sa->sa_family == AF_INET6 &&
sasize >= sizeof(struct sockaddr_in6)) {
const struct sockaddr_in6 *in6;
in6 = (const struct sockaddr_in6 *)sa;
if (inet_ntop(AF_INET6, &in6->sin6_addr, ip, sizeof(ip))) {
p = buf;
*p++ = '[';
p = stpcpy(p, ip);
*p++ = ']';
*p++ = ':';
p = FormatUint32(p, in6->sin6_port);
}
} else if (sa->sa_family == AF_UNIX &&
sasize >= sizeof(struct sockaddr_un)) {
const struct sockaddr_un *unix;
unix = (const struct sockaddr_un *)sa;
n = strnlen(unix->sun_path, sizeof(unix->sun_path));
n = MIN(n, 128 - 1);
memcpy(buf, unix->sun_path, n);
buf[n] = 0;
}
}
errno = e;
return buf;
}
| 3,632 | 75 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/alg.h | #ifndef COSMOPOLITAN_LIBC_SOCK_ALG_H_
#define COSMOPOLITAN_LIBC_SOCK_ALG_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct sockaddr_alg {
uint16_t salg_family;
uint8_t salg_type[14];
uint32_t salg_feat;
uint32_t salg_mask;
uint8_t salg_name[64];
};
struct sockaddr_alg_new {
uint16_t salg_family;
uint8_t salg_type[14];
uint32_t salg_feat;
uint32_t salg_mask;
uint8_t salg_name[]; /* Linux v4.12+ */
};
struct af_alg_iv {
uint32_t ivlen;
uint8_t iv[0];
};
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SOCK_ALG_H_ */
| 614 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/asanmsghdr.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/sock/struct/msghdr.h"
#if IsAsan()
bool __asan_is_valid_msghdr(const struct msghdr *msg) {
if (!__asan_is_valid(msg, sizeof(struct msghdr))) return false;
if (msg->msg_name) {
if (!__asan_is_valid(msg->msg_name, msg->msg_namelen)) return false;
}
if (msg->msg_control) {
if (!__asan_is_valid(msg->msg_control, msg->msg_controllen)) return false;
}
return __asan_is_valid_iov(msg->msg_iov, msg->msg_iovlen);
}
#endif
| 2,350 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/inet_addr.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/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
/**
* Converts dotted IPv4 address string to network order binary.
* @see inet_aton()
*/
uint32_t inet_addr(const char *s) {
struct in_addr in;
if (inet_aton(s, &in)) {
return in.s_addr;
} else {
return -1;
}
}
| 2,134 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/connect-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sock/yoink.inc"
#include "libc/sysv/errfuns.h"
textwindows int sys_connect_nt(struct Fd *fd, const void *addr,
uint32_t addrsize) {
struct SockFd *sockfd;
sockfd = (struct SockFd *)fd->extra;
_npassert(fd->kind == kFdSocket);
return __winsockblock(
fd->handle, FD_CONNECT_BIT,
WSAConnect(fd->handle, addr, addrsize, NULL, NULL, NULL, NULL),
sockfd->rcvtimeo);
}
| 2,400 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/accept4-sysv.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/dce.h"
#include "libc/errno.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.internal.h"
int sys_accept4(int server, void *addr, uint32_t *addrsize, int flags) {
if (!flags) return sys_accept(server, addr, addrsize);
int olderr, client;
union sockaddr_storage_bsd bsd;
uint32_t size = sizeof(bsd);
void *out_addr = !IsBsd() ? addr : &bsd;
uint32_t *out_addrsize = !IsBsd() ? addrsize : &size;
static bool demodernize;
if (demodernize) goto TriedAndTrue;
olderr = errno;
client = __sys_accept4(server, out_addr, out_addrsize, flags);
if (client == -1 && errno == ENOSYS) {
errno = olderr;
demodernize = true;
TriedAndTrue:
client = __fixupnewsockfd(__sys_accept(server, out_addr, out_addrsize, 0),
flags);
}
if (client != -1 && IsBsd()) {
sockaddr2linux(&bsd, size, addr, addrsize);
}
return client;
}
| 2,781 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/socket.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/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
/**
* Creates new system resource for network communication, e.g.
*
* int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
*
* @param family can be AF_UNIX, AF_INET, etc.
* @param type can be SOCK_STREAM (for TCP), SOCK_DGRAM (e.g. UDP), or
* SOCK_RAW (IP) so long as IP_HDRINCL was passed to setsockopt();
* and additionally, may be or'd with SOCK_NONBLOCK, SOCK_CLOEXEC
* @param protocol can be IPPROTO_TCP, IPPROTO_UDP, or IPPROTO_ICMP
* @return socket file descriptor or -1 w/ errno
* @error ENETDOWN, EPFNOSUPPORT, etc.
* @see libc/sysv/consts.sh
* @asyncsignalsafe
*/
int socket(int family, int type, int protocol) {
int rc;
if (family == AF_UNSPEC) family = AF_INET;
if (!IsWindows()) {
rc = sys_socket(family, type, protocol);
} else {
rc = sys_socket_nt(family, type, protocol);
}
STRACE("socket(%s, %s, %s) â %d% lm", DescribeSocketFamily(family),
DescribeSocketType(type), DescribeSocketProtocol(protocol), rc);
return rc;
}
| 3,035 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/sock/iovec2nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/struct/iovec.h"
#include "libc/macros.internal.h"
#include "libc/sock/internal.h"
#include "libc/sysv/consts/iov.h"
/**
* Converts I/O vector from System Five to WIN32 ABI.
*
* @return effective iovlen
* @see IOV_MAX
*/
textwindows size_t __iovec2nt(struct NtIovec iovnt[hasatleast 16],
const struct iovec *iov, size_t iovlen) {
size_t i, limit;
for (limit = 0x7ffff000, i = 0; i < MIN(16, iovlen); ++i) {
iovnt[i].buf = iov[i].iov_base;
if (iov[i].iov_len < limit) {
limit -= (iovnt[i].len = iov[i].iov_len);
} else {
iovnt[i].len = limit;
break;
}
}
return i;
}
| 2,524 | 45 | jart/cosmopolitan | false |