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/dns/servent.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
struct servent *getservent(void) {
return NULL;
}
void setservent(int stayopen) {
}
void endservent(void) {
}
| 2,657 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/hostent.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
struct hostent *gethostent(void) {
return NULL;
}
void sethostent(int stayopen) {
}
void endhostent(void) {
}
| 2,657 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/lookupprotobynumber.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/dns/prototxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/protocols to find name for a given number.
*
* The format of /etc/protocols is like this:
*
* # comment
* # NAME PROTOCOL ALIASES
* ip 0 IP
* icmp 1 ICMP
*
* @param protonum is the protocol number
* @param buf is a buffer to store the official name of the protocol
* @param bufsize is the size of buf
* @param filepath is the location of the protocols file
* (if NULL, uses /etc/protocols)
* @return 0 on success, -1 on error
* @note aliases are not read from the file.
*/
int LookupProtoByNumber(const int protonum, char *buf, size_t bufsize,
const char *filepath) {
FILE *f;
char *line;
int found;
size_t linesize;
const char *path;
char pathbuf[PATH_MAX];
char *name, *number, *comment, *tok;
if (!(path = filepath)) {
path = "/etc/protocols";
if (IsWindows()) {
path =
firstnonnull(GetNtProtocolsTxtPath(pathbuf, ARRAYLEN(pathbuf)), path);
}
}
if (bufsize == 0 || !(f = fopen(path, "r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
number = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && number && protonum == atoi(number)) {
if (!memccpy(buf, name, '\0', bufsize)) {
strcpy(buf, "");
break;
}
found = 1;
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
fclose(f);
return -1;
}
fclose(f);
if (!found) return -1;
return 0;
}
| 4,457 | 98 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getnameinfo.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/resolvconf.h"
#include "libc/dns/servicestxt.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/errfuns.h"
/**
* Resolves name/service for socket address.
*
* @param addr
* @param addrlen
* @param name
* @param namelen
* @param service
* @param servicelen
* @param flags
*
* @return 0 on success or EAI_xxx value
*/
int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, char *name,
socklen_t namelen, char *service, socklen_t servicelen,
int flags) {
char *p, rdomain[1 + sizeof "255.255.255.255.in-addr.arpa"];
char info[NI_MAXHOST + 1];
int rc, port;
uint8_t *ip;
unsigned int valid_flags;
valid_flags =
(NI_NAMEREQD | NI_NUMERICHOST | NI_NUMERICSERV | NI_NOFQDN | NI_DGRAM);
if (flags & ~(valid_flags)) return EAI_BADFLAGS;
if (!name && !service) return EAI_NONAME;
if (addr->sa_family != AF_INET || addrlen < sizeof(struct sockaddr_in))
return EAI_FAMILY;
ip = (uint8_t *)&(((struct sockaddr_in *)addr)->sin_addr);
p = rdomain;
p = FormatUint32(p, ip[3]), *p++ = '.';
p = FormatUint32(p, ip[2]), *p++ = '.';
p = FormatUint32(p, ip[1]), *p++ = '.';
p = FormatUint32(p, ip[0]), stpcpy(p, ".in-addr.arpa");
info[0] = '\0';
if (name != NULL && namelen != 0) {
if ((flags & NI_NUMERICHOST) && (flags & NI_NAMEREQD)) return EAI_NONAME;
if ((flags & NI_NUMERICHOST) &&
inet_ntop(AF_INET, ip, info, sizeof(info)) == NULL)
return EAI_SYSTEM;
else if (!info[0] && ResolveHostsReverse(GetHostsTxt(), AF_INET, ip, info,
sizeof(info)) < 0)
return EAI_SYSTEM;
else if (!info[0] && ResolveDnsReverse(GetResolvConf(), AF_INET, rdomain,
info, sizeof(info)) < 0)
return EAI_SYSTEM;
else if (!info[0] && (flags & NI_NAMEREQD))
return EAI_NONAME;
else if (!info[0] && inet_ntop(AF_INET, ip, info, sizeof(info)) == NULL)
return EAI_SYSTEM;
if (strlen(info) + 1 > namelen) return EAI_OVERFLOW;
strcpy(name, info);
}
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
info[0] = '\0';
if (service != NULL && servicelen != 0) {
if ((flags & NI_NUMERICSERV) ||
LookupServicesByPort(port, ((flags & NI_DGRAM) ? "udp" : "tcp"), 4,
info, sizeof(info), NULL) == -1)
itoa(port, info, 10);
if (strlen(info) + 1 > servicelen) return EAI_OVERFLOW;
strcpy(service, info);
}
return 0;
}
| 5,387 | 115 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getresolvconf.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/dns/resolvconf.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/pushpop.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/stdio.h"
#include "libc/thread/thread.h"
static struct ResolvConf *g_resolvconf;
static struct ResolvConfInitialStaticMemory {
struct ResolvConf rv;
pthread_mutex_t lock;
struct sockaddr_in nameservers[3];
} g_resolvconf_init;
/**
* Returns singleton with DNS server address.
* @threadsafe
*/
const struct ResolvConf *GetResolvConf(void) {
int rc;
FILE *f;
struct ResolvConfInitialStaticMemory *init;
init = &g_resolvconf_init;
pthread_mutex_lock(&init->lock);
if (!g_resolvconf) {
g_resolvconf = &init->rv;
pushmov(&init->rv.nameservers.n, ARRAYLEN(init->nameservers));
init->rv.nameservers.p = init->nameservers;
__cxa_atexit(FreeResolvConf, &g_resolvconf, NULL);
if (!IsWindows()) {
if ((f = fopen("/etc/resolv.conf", "r"))) {
rc = ParseResolvConf(g_resolvconf, f);
} else {
rc = -1;
}
fclose(f);
} else {
rc = GetNtNameServers(g_resolvconf);
}
if (rc == -1 && !IsTiny()) {
/* TODO(jart): Elevate robustness. */
}
}
pthread_mutex_unlock(&init->lock);
return g_resolvconf;
}
/**
* Frees resolv.conf data structure populated by ParseResolvConf().
*/
void FreeResolvConf(struct ResolvConf **rvp) {
if (*rvp) {
if ((*rvp)->nameservers.p != g_resolvconf_init.nameservers) {
free((*rvp)->nameservers.p);
}
if (*rvp != &g_resolvconf_init.rv) {
free(*rvp);
}
*rvp = 0;
}
}
| 3,556 | 85 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/comparednsnames.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
forceinline void FindDnsLabel(const char *A, size_t *i, size_t *n) {
while (*i) {
if (A[*i - 1] == '.') {
if (*i == *n) {
--(*n);
} else {
break;
}
}
--(*i);
}
}
/**
* Compares DNS hostnames in reverse lexicographical asciibetical order.
* @return <0, 0, or >0
* @see test/libc/dns/comparednsnames_test.c (the code that matters)
*/
int CompareDnsNames(const char *A, const char *B) {
int res;
bool first;
size_t n, m, i, j;
if (A == B) return 0;
n = strlen(A);
m = strlen(B);
if (!n || !m || ((A[n - 1] == '.') ^ (B[m - 1] == '.'))) {
if (n && m && A[n - 1] == '.' && strchr(B, '.')) {
--m;
} else if (n && m && B[m - 1] == '.' && strchr(A, '.')) {
--n;
} else {
return A[n ? n - 1 : 0] - B[m ? m - 1 : 0];
}
}
i = n;
j = m;
first = true;
for (;;) {
FindDnsLabel(A, &i, &n);
FindDnsLabel(B, &j, &m);
if (first) {
first = false;
if (!i && j) return 1;
if (!j && i) return -1;
}
if ((res = strncasecmp(&A[i], &B[j], MIN(n - i + 1, m - j + 1)))) {
return res;
}
if (!i || !j) {
return i - j;
}
n = i;
m = j;
}
}
| 3,117 | 78 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/protoent.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
struct protoent *getprotoent(void) {
return NULL;
}
void setprotoent(int stayopen) {
}
void endprotoent(void) {
}
| 2,661 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/netent.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
struct netent *getnetent(void) {
return NULL;
}
struct netent *getnetbyname(const char *name) {
return NULL;
}
struct netent *getnetbyaddr(uint32_t net, int type) {
return NULL;
}
void setnetent(int stayopen) {
}
void endnetent(void) {
}
| 2,791 | 46 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/lookupprotobyname.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/dns/prototxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/protocols to find number for a given name.
*
* @param protoname is a NULL-terminated string
* @param buf is a buffer to store the official name of the protocol
* @param bufsize is the size of buf
* @param filepath is the location of protocols file
* (if NULL, uses /etc/protocols)
* @return -1 on error, or
* positive protocol number
*
* @note aliases are read from file for comparison, but not returned.
* @see LookupProtoByNumber
*/
int LookupProtoByName(const char *protoname, char *buf, size_t bufsize,
const char *filepath) {
FILE *f;
char *line;
const char *path;
size_t linesize;
int found, result;
char pathbuf[PATH_MAX];
char *name, *number, *alias, *comment, *tok;
if (!(path = filepath)) {
path = "/etc/protocols";
if (IsWindows()) {
path =
firstnonnull(GetNtProtocolsTxtPath(pathbuf, ARRAYLEN(pathbuf)), path);
}
}
if (bufsize == 0 || !(f = fopen(path, "r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
result = -1;
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
number = strtok_r(NULL, "/ \t\r\n\v", &tok);
if (name && number) {
alias = name;
while (alias && strcasecmp(alias, protoname) != 0)
alias = strtok_r(NULL, " \t\r\n\v", &tok);
if (alias) /* alias matched with protoname */
{
if (!memccpy(buf, name, '\0', bufsize)) {
strcpy(buf, "");
break;
}
result = atoi(number);
found = 1;
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return result;
}
| 4,567 | 101 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/resolvconf.h | #ifndef COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_
#define COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct Nameservers {
size_t i, n;
struct sockaddr_in *p;
};
struct ResolvConf {
struct Nameservers nameservers;
};
const struct ResolvConf *GetResolvConf(void) returnsnonnull;
int ParseResolvConf(struct ResolvConf *, struct FILE *) paramsnonnull();
void FreeResolvConf(struct ResolvConf **) paramsnonnull();
int GetNtNameServers(struct ResolvConf *) paramsnonnull();
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_RESOLVCONF_H_ */
| 699 | 25 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/freeaddrinfo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
#include "libc/mem/mem.h"
/**
* Frees addresses returned by getaddrinfo().
* @threadsafe
*/
void freeaddrinfo(struct addrinfo *ai) {
struct addrinfo *next;
while (ai) {
/* we assume ai_addr and ai_canonname are shoehorned */
next = ai->ai_next;
free(ai);
ai = next;
}
}
| 2,158 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/gethostbyname.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
struct hostent *gethostbyname(const char *name) {
static struct hostent *ptr0, he0;
static char h_name[DNS_NAME_MAX + 1];
static char *h_aliases[1];
static char *h_addr_list[2];
static char h_addr_list0[4];
struct addrinfo *result = NULL;
if (!ptr0) {
he0.h_name = h_name;
he0.h_aliases = h_aliases;
he0.h_aliases[0] = NULL;
he0.h_addrtype = AF_INET;
he0.h_length = 4;
he0.h_addr_list = h_addr_list;
he0.h_addr_list[0] = h_addr_list0;
he0.h_addr_list[1] = NULL;
ptr0 = &he0;
}
if (getaddrinfo(name, NULL, NULL, &result) || result == NULL) return NULL;
/* if getaddrinfo is successful, result->ai_canonname is non-NULL,
* (see newaddrinfo) but the string can still be empty */
if (result->ai_canonname[0])
memccpy(ptr0->h_name, result->ai_canonname, '\0', DNS_NAME_MAX);
else
memccpy(ptr0->h_name, name, '\0', DNS_NAME_MAX);
*((uint32_t *)ptr0->h_addr_list[0]) = (result->ai_addr4->sin_addr.s_addr);
/* TODO: if result has ai_next, fit multiple entries for h_addr_list */
freeaddrinfo(result);
return ptr0;
}
| 3,724 | 71 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getntprotocolstxtpath.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/prototxt.h"
#include "libc/nt/systeminfo.h"
#include "libc/str/str.h"
textwindows char *GetNtProtocolsTxtPath(char *pathbuf, uint32_t size) {
/* protocol, not plural */
const char *const kWinHostsPath = "\\drivers\\etc\\protocol";
uint32_t len = GetSystemDirectoryA(&pathbuf[0], size);
if (len && len + strlen(kWinHostsPath) + 1 < size) {
if (pathbuf[len] == '\\') pathbuf[len--] = '\0';
memcpy(&pathbuf[len], kWinHostsPath, strlen(kWinHostsPath) + 1);
return &pathbuf[0];
} else {
return NULL;
}
}
| 3,063 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/dns.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_DNS
LIBC_DNS_ARTIFACTS += LIBC_DNS_A
LIBC_DNS = $(LIBC_DNS_A_DEPS) $(LIBC_DNS_A)
LIBC_DNS_A = o/$(MODE)/libc/dns/dns.a
LIBC_DNS_A_FILES := $(wildcard libc/dns/*)
LIBC_DNS_A_HDRS = $(filter %.h,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS_C = $(filter %.c,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS_S = $(filter %.S,$(LIBC_DNS_A_FILES))
LIBC_DNS_A_SRCS = \
$(LIBC_DNS_A_SRCS_S) \
$(LIBC_DNS_A_SRCS_C)
LIBC_DNS_A_OBJS = \
$(LIBC_DNS_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(LIBC_DNS_A_SRCS_C:%.c=o/$(MODE)/%.o)
LIBC_DNS_A_CHECKS = \
$(LIBC_DNS_A).pkg \
$(LIBC_DNS_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_DNS_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_FMT \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
LIBC_INTRIN \
LIBC_STUBS \
LIBC_STR \
LIBC_SYSV \
LIBC_NT_ADVAPI32 \
LIBC_NT_KERNEL32
LIBC_DNS_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_DNS_A_DIRECTDEPS),$($(x))))
$(LIBC_DNS_A): libc/dns/ \
$(LIBC_DNS_A).pkg \
$(LIBC_DNS_A_OBJS)
$(LIBC_DNS_A).pkg: \
$(LIBC_DNS_A_OBJS) \
$(foreach x,$(LIBC_DNS_A_DIRECTDEPS),$($(x)_A).pkg)
LIBC_DNS_LIBS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)))
LIBC_DNS_SRCS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_SRCS))
LIBC_DNS_HDRS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_HDRS))
LIBC_DNS_CHECKS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_CHECKS))
LIBC_DNS_OBJS = $(foreach x,$(LIBC_DNS_ARTIFACTS),$($(x)_OBJS))
$(LIBC_DNS_OBJS): $(BUILD_FILES) libc/dns/dns.mk
.PHONY: o/$(MODE)/libc/dns
o/$(MODE)/libc/dns: $(LIBC_DNS_CHECKS)
| 1,755 | 61 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/lookupservicesbyport.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/dns/servicestxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/services to find name for a given port.
*
* The format of /etc/services is like this:
*
* # comment
* # NAME PORT/PROTOCOL ALIASES
* ftp 21/tcp
* fsp 21/udp fspd
* ssh 22/tcp
*
* @param servport is the port number
* @param servproto is a NULL-terminated string (eg "tcp", "udp")
* (if servproto is an empty string,
* if is filled with the first matching
* protocol)
* @param servprotolen the size of servproto
* @param buf is a buffer to store the official name of the service
* @param bufsize is the size of buf
* @param filepath is the location of the services file
* (if NULL, uses /etc/services)
* @return 0 on success, -1 on error
* @note aliases are not read from the file.
*/
int LookupServicesByPort(const int servport, char *servproto,
size_t servprotolen, char *buf, size_t bufsize,
const char *filepath) {
FILE *f;
char *line;
char pathbuf[PATH_MAX];
const char *path;
size_t linesize;
int found;
char *name, *port, *proto, *comment, *tok;
if (!(path = filepath)) {
path = "/etc/services";
if (IsWindows()) {
path =
firstnonnull(GetNtServicesTxtPath(pathbuf, ARRAYLEN(pathbuf)), path);
}
}
if (servprotolen == 0 || bufsize == 0 || !(f = fopen(path, "r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
strcpy(buf, "");
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
port = strtok_r(NULL, "/ \t\r\n\v", &tok);
proto = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && port && proto && servport == atoi(port)) {
if (!servproto[0] || strncasecmp(proto, servproto, servprotolen) == 0) {
if (!servproto[0] && !memccpy(servproto, proto, '\0', servprotolen)) {
strcpy(servproto, "");
break;
}
if (!memccpy(buf, name, '\0', bufsize)) {
strcpy(buf, "");
break;
}
found = 1;
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return 0;
}
| 5,071 | 112 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/dnsheader.h | #ifndef COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_
#define COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct DnsHeader {
uint16_t id; /* transaction id */
uint8_t bf1; /* bit field 1 */
uint8_t bf2; /* bit field 2 */
uint16_t qdcount; /* question count */
uint16_t ancount; /* answer count */
uint16_t nscount; /* nameserver count */
uint16_t arcount; /* additional record count */
};
void SerializeDnsHeader(uint8_t[restrict 12], const struct DnsHeader *);
void DeserializeDnsHeader(struct DnsHeader *, const uint8_t[restrict 12]);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_DNSHEADER_H_ */
| 724 | 22 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/newaddrinfo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
#define SIZE ROUNDUP(sizeof(struct addrinfo), sizeof(void *))
#define ADDRLEN sizeof(struct sockaddr_in)
struct addrinfo *newaddrinfo(uint16_t port) {
struct addrinfo *ai;
if ((ai = calloc(1, SIZE + ADDRLEN + DNS_NAME_MAX + 1))) {
ai->ai_family = AF_INET;
ai->ai_addrlen = ADDRLEN;
ai->ai_addr4 = (struct sockaddr_in *)((char *)ai + SIZE);
ai->ai_addr4->sin_family = AF_INET;
ai->ai_addr4->sin_port = htons(port);
ai->ai_canonname = (char *)ai + SIZE + ADDRLEN;
}
return ai;
}
| 2,497 | 40 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/ent.h | #ifndef COSMOPOLITAN_LIBC_DNS_ENT_H_
#define COSMOPOLITAN_LIBC_DNS_ENT_H_
#include "libc/dns/dns.h"
#define HOST_NOT_FOUND 1
#define TRY_AGAIN 2
#define NO_RECOVERY 3
#define NO_DATA 4
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct netent {
char *n_name; /* official network name */
char **n_aliases; /* alias list */
int n_addrtype; /* net address type */
uint32_t n_net; /* network number */
};
struct protoent {
char *p_name; /* official protocol name */
char **p_aliases; /* alias list */
int p_proto; /* protocol number */
};
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#define h_addr h_addr_list[0]
struct servent {
char *s_name; /* official service name */
char **s_aliases; /* alias list */
int s_port; /* port number (in network byte order) */
char *s_proto; /* protocol to use */
};
extern int h_errno;
void herror(const char *);
const char *hstrerror(int);
struct netent *getnetent(void);
struct netent *getnetbyname(const char *);
struct netent *getnetbyaddr(uint32_t, int);
void setnetent(int);
void endnetent(void);
struct protoent *getprotoent(void);
struct protoent *getprotobyname(const char *);
struct protoent *getprotobynumber(int);
void setprotoent(int);
void endprotoent(void);
struct hostent *gethostent(void);
struct hostent *gethostbyname(const char *);
struct hostent *gethostbyaddr(const void *, socklen_t, int);
void sethostent(int);
void endhostent(void);
struct servent *getservent(void);
struct servent *getservbyname(const char *, const char *);
struct servent *getservbyport(int, const char *);
void setservent(int);
void endservent(void);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_ENT_H_ */
| 1,984 | 73 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getservbyname.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/dns/servicestxt.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
struct servent *getservbyname(const char *name, const char *proto) {
static struct servent *ptr0, se0;
static char s_name[DNS_NAME_MAX + 1];
static char localproto[DNS_NAME_MAX + 1];
int p;
if (!ptr0) {
se0.s_name = s_name;
if (!(se0.s_aliases = calloc(1, sizeof(char *)))) return NULL;
se0.s_port = 0;
se0.s_proto = localproto;
ptr0 = &se0;
}
if (proto) {
if (!memccpy(localproto, proto, '\0', DNS_NAME_MAX)) return NULL;
} else
strcpy(localproto, "");
p = LookupServicesByName(name, ptr0->s_proto, DNS_NAME_MAX, ptr0->s_name,
DNS_NAME_MAX, NULL);
if (p == -1) return NULL;
ptr0->s_port = htons(p);
return ptr0;
}
| 3,323 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getprotobynumber.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/dns/prototxt.h"
#include "libc/mem/mem.h"
struct protoent *getprotobynumber(int proto) {
static struct protoent *ptr1, pe1;
static char p_name[DNS_NAME_MAX + 1];
if (!ptr1) {
pe1.p_name = p_name;
if (!(pe1.p_aliases = calloc(1, sizeof(char *)))) return NULL;
pe1.p_proto = -1;
ptr1 = &pe1;
}
if (LookupProtoByNumber(proto, ptr1->p_name, DNS_NAME_MAX, NULL) == -1)
return NULL;
ptr1->p_proto = proto;
return ptr1;
}
| 3,010 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/h_errno.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/dns/dns.h"
/**
* Error number global for gethostbyname*(), gethostbyaddr*(), etc.
*/
int h_errno;
| 1,952 | 25 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/resolvedns.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/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/dnsheader.h"
#include "libc/dns/dnsquestion.h"
#include "libc/dns/resolvconf.h"
#include "libc/intrin/bits.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
#define kMsgMax 512
/**
* Queries Domain Name System for address associated with name.
*
* @param resolvconf can be GetResolvConf()
* @param af can be AF_INET, AF_UNSPEC
* @param name can be a local or fully-qualified hostname
* @param addr should point to a struct sockaddr_in; if this function
* succeeds, its sin_family and sin_addr fields will be modified
* @param addrsize is the byte size of addr
* @return number of matches found, or -1 w/ errno
* @error EAFNOSUPPORT. ENETDOWN, ENAMETOOLONG, EBADMSG
*/
int ResolveDns(const struct ResolvConf *resolvconf, int af, const char *name,
struct sockaddr *addr, uint32_t addrsize) {
int32_t ttl;
int rc, fd, n;
struct DnsQuestion q;
struct DnsHeader h, h2;
struct sockaddr_in *a4;
uint8_t *p, *pe, msg[512];
uint16_t rtype, rclass, rdlength;
if (addrsize < kMinSockaddr4Size) return einval();
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
if (!resolvconf->nameservers.i) return 0;
bzero(&h, sizeof(h));
rc = ebadmsg();
h.id = _rand64();
h.bf1 = 1; /* recursion desired */
h.qdcount = 1;
q.qname = name;
q.qtype = DNS_TYPE_A;
q.qclass = DNS_CLASS_IN;
bzero(msg, sizeof(msg));
SerializeDnsHeader(msg, &h);
if ((n = SerializeDnsQuestion(msg + 12, 500, &q)) == -1) return -1;
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) return -1;
if (sendto(fd, msg, 12 + n, 0, (struct sockaddr *)resolvconf->nameservers.p,
sizeof(*resolvconf->nameservers.p)) == 12 + n &&
(n = read(fd, msg, 512)) >= 12) {
DeserializeDnsHeader(&h2, msg);
if (h2.id == h.id) {
rc = 0;
p = msg + 12;
pe = msg + n;
while (p < pe && h2.qdcount--) {
p += strnlen((char *)p, pe - p) + 1 + 4;
}
while (p < pe && h2.ancount--) {
if ((p[0] & 0xc0) == 0xc0) { /* name pointer */
p += 2;
} else {
p += strnlen((char *)p, pe - p) + 1;
}
if (p + 10 <= pe) {
rtype = READ16BE(p);
rclass = READ16BE(p + 2);
ttl = READ32BE(p + 4);
rdlength = READ16BE(p + 8);
if (p + 10 + rdlength <= pe && rdlength == 4 &&
rclass == DNS_CLASS_IN && rtype == DNS_TYPE_A) {
rc = 1;
a4 = (struct sockaddr_in *)addr;
a4->sin_family = AF_INET;
memcpy(&a4->sin_addr.s_addr, p + 10, 4);
break;
}
p += 10 + rdlength;
}
}
}
}
close(fd);
return rc;
}
| 4,953 | 115 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/dnsheader.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dnsheader.h"
#include "libc/intrin/bits.h"
#include "libc/sysv/errfuns.h"
/**
* Serializes DNS message h to wire.
*
* @return number of bytes written (always 12) or -1 w/ errno
* @see pascalifydnsname()
*/
void SerializeDnsHeader(uint8_t p[restrict 12], const struct DnsHeader *h) {
p[0x0] = h->id >> 8;
p[0x1] = h->id;
p[0x2] = h->bf1;
p[0x3] = h->bf2;
p[0x4] = h->qdcount >> 8;
p[0x5] = h->qdcount;
p[0x6] = h->ancount >> 8;
p[0x7] = h->ancount;
p[0x8] = h->nscount >> 8;
p[0x9] = h->nscount;
p[0xa] = h->arcount >> 8;
p[0xb] = h->arcount;
}
/**
* Serializes DNS message h to wire.
*
* @return number of bytes read (always 12) or -1 w/ errno
*/
void DeserializeDnsHeader(struct DnsHeader *h, const uint8_t p[restrict 12]) {
h->id = READ16BE(p);
h->bf1 = p[2];
h->bf2 = p[3];
h->qdcount = READ16BE(p + 4);
h->ancount = READ16BE(p + 6);
h->nscount = READ16BE(p + 8);
h->arcount = READ16BE(p + 10);
}
| 2,804 | 58 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/consts.h | #ifndef COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#define COSMOPOLITAN_LIBC_DNS_CONSTS_H_
#include "libc/sock/sock.h"
#define DNS_TYPE_A 1
#define DNS_TYPE_NS 2
#define DNS_TYPE_CNAME 5
#define DNS_TYPE_SOA 6
#define DNS_TYPE_PTR 12
#define DNS_TYPE_MX 15
#define DNS_TYPE_TXT 16
#define DNS_CLASS_IN 1
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define kMinSockaddr4Size \
(offsetof(struct sockaddr_in, sin_addr) + sizeof(struct in_addr))
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_CONSTS_H_ */
| 540 | 22 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/rfc0247.txt |
Network Working Group Peggy Karp
Request for Comments: #247 MITRE
NIC 7688 12 October 1971
Categories: Policy, Telnet
Related: #226, 236, 239, 233, 237
Obsoletes: #226
Proferred Set of Standard Host Names
In RFC #226, BBN's TENEX list of Host names was set up as a strawman
set of standard Host names. Comments received since then (an RFC
actually generated comments!!!) have influenced me to propose the
following general rules for forming Host names.
The Host names will be 8 characters in length. The general form is
<site> '-' <machine>
<site> will be at most 4 characters, formed as follows:
(a) Use the keyword in the site name, if not more than
four characters, e.g., NASA Ames, Case Western
Reserve. ---- ----
(b) Use the standard acronym, if not more than four
characters, e.g., UCLA, RADC, NBS.
(c) If a standard abbreviation exists, use it, e.g., Ill.
(d) If none of the above apply, use the first four letters
in the site name, e.g., Burr, Mitr, Harv.
(e) If none of the above is acceptable to the site, the
technical liaison should select the site mnemonic.
<machine> will be at most 4 characters of the form <mfg. #>
<designator>.
Examples of mfg. # are:
IBM 360 2 digit model number
IBM 370 3 digit model number
PDP 1 - 2 digit model number
Burroughs 4 digits
CDC 4 digits
etc.
[Page 1]
RFC #247
<designator> will be used when more than one machine of the same
type is located at a site (e.g., 2 PDP-10s at MIT, at SRI, and
at BBN).
Limiting <machine> to 4 characters does not permit distinctions
to be made between machines with 4 digit mfg. #s. I expect
the situation will be handled in an ad hoc manner by the NIC if
it arises.
TIPs are identified as 'TIP' rather than by '316'. If a Host
is not to be permanently addressable, the machine is identified
as 'TEST'.
A list of Host names, formed according to these rules, is
attached. Alternate Host names should be provided, as
suggested by Jon Postel (RFC #236). RFC's 206, 233, and
236 present lists with 4-character alternate names. The
Technical Liaison should select the alternate name for his
site and communicate the selection to the NIC.
The preceding rules and the attached list of Host names are
subject to the approval of the NWG. Hereafter, the list will
be generated and maintained by the NIC in cooperation with
the Technical Liaison at each site, as suggested in RFC #237.
Comments should be addressed to Dick Watson.
[ This RFC was put into machine readable form for entry ]
[ into the online RFC archives by BBN Corp. under the ]
[ direction of Alex McKenzie. 12/96 ]
[Page 2]
RFC #247
Attachment 1
NETWORK ADDRESS STANDARD NAME
--------------- -------------
1 UCLA-7
65 UCLA-91
2 SRI-10NI
66 SRI-10AI
3 UCSB-75
4 UTAH-10
5 BBN-516
69 BBN-10A
133 BBN-10B
6 MIT-645
70 MIT-10DM
134 MIT-10AI
7 RAND-65
71 RAND-10
8 SDC-75
9 HARV-10
73 HARV-1
137 HARV-11
10 LL-67
74 LL-TX2
138 LL-TSP
11 SAIL-10
12 ILL-11
76 ILL-6500
13 CASE-10
14 CMU-10
15 BURR-6500
79 BURR-TEST
16 AMES-67
144 AMES-TIP
145 MITR-TIP
18 RADC-645
146 RADC-TIP
19 NBS-11
147 NBS-TIP
148 ETAC-TIP
21 TINK-418
22 MCCL-418
23 USC-44
151 USC-TIP
152 GWC-TIP
25 NCAR-7600
153 NCAR-TIP
158 BBNX-TEST
[Page 3]
RFC #247
Attachment 2
An Implementation Scheme
If the standard Host names are formed according to the proposed
rules, the following implementation scheme, suggested by Steve
Crocker, can be used.
Map <site> into an 8-bit number, S and
map <machine> into an 8-bit number, M,
where
S + M = Network Address.
S and M can be selected such that specification of <site>
alone could cause a default to the "primary" Host at
the site. Note that this scheme depends on a unique
<site> designator for each IMP.
Some examples:
If the "primary" Host at UCLA is the 91, let
UCLA -> S = X'41'
7 -> M = X'40'
91 -> M = X'00'
then for
UCLA-7, S + M = X'01' = 1 base 10
UCLA-91,S + M = X'41' = 65 base 10
and
UCLA alone = X'41' = 65 base 10
If the primary Host at BBN is TENEX System A, let
BBN -> S = X'45'
516 -> M = X'40'
10A -> M = X'00'
10B -> M = X'C0'
then for
BBN-516, S + M = X'05' = 5 base 10
BBN-10A, S + M = X'45' = 69 base 10
BBN-10B, S + M = X'85' = 133 base 10
and
BBN alone = X'45' = 69 base 10
The primary Host for each IMP would be designated by the
site and such information disseminated by the NIC.
[Page 4]
| 7,122 | 223 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/resolvehoststxt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/consts.h"
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/mem/alg.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/errfuns.h"
/**
* Finds address associated with name in HOSTS.TXT table.
*
* @param ht can be GetHostsTxt()
* @param af can be AF_INET, AF_UNSPEC
* @param name can be a local or fully-qualified hostname
* @param addr should point to a struct sockaddr_in; if this function
* succeeds, its sin_family and sin_addr fields will be modified
* @param addrsize is the byte size of addr
* @param canon be used to return a pointer to the canonical name
* @return number of matches found, or -1 w/ errno
* @error EAFNOSUPPORT
*/
int ResolveHostsTxt(const struct HostsTxt *ht, int af, const char *name,
struct sockaddr *addr, uint32_t addrsize,
const char **canon) {
size_t i;
struct sockaddr_in *addr4;
if (af != AF_INET && af != AF_UNSPEC) return eafnosupport();
for (i = 0; i < ht->entries.i; ++i) {
if (!CompareDnsNames(name, ht->strings.p + ht->entries.p[i].name)) {
if (addr) {
if (addrsize < kMinSockaddr4Size) return einval();
addr4 = (struct sockaddr_in *)addr;
addr4->sin_family = AF_INET;
memcpy(&addr4->sin_addr.s_addr, &ht->entries.p[i].ip[0], 4);
}
if (canon) {
*canon = ht->strings.p + ht->entries.p[i].canon;
}
return 1;
}
}
return 0;
}
| 3,343 | 63 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getntnameservers.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/calls/syscall_support-nt.internal.h"
#include "libc/dns/dns.h"
#include "libc/dns/resolvconf.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/nt/enum/keyaccess.h"
#include "libc/nt/enum/reggetvalueflags.h"
#include "libc/nt/registry.h"
#include "libc/nt/runtime.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
/**
* Extracts DNS nameserver IPs from Windows Registry.
*
* @param resolv points to a ResolvConf object, which should be zero
* initialized by the caller; or if it already contains items,
* this function will append
* @return number of nameservers appended, or -1 w/ errno
*/
textwindows int GetNtNameServers(struct ResolvConf *resolv) {
int rc;
char value8[128];
int64_t hkInterfaces;
char *state, *addr, *tmp;
struct sockaddr_in nameserver;
char16_t value[128], uuid[64];
uint32_t i, keycount, valuebytes, uuidlen;
keycount = 0;
hkInterfaces = kNtInvalidHandleValue;
if (!RegOpenKeyEx(
kNtHkeyLocalMachine,
u"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces",
0, kNtKeyRead, &hkInterfaces) &&
!RegQueryInfoKey(hkInterfaces, 0, 0, 0, &keycount, 0, 0, 0, 0, 0, 0, 0)) {
nameserver.sin_family = AF_INET;
nameserver.sin_port = htons(DNS_PORT);
rc = 0;
for (i = 0; i < keycount; ++i) {
uuidlen = sizeof(uuid);
if (!RegEnumKeyEx(hkInterfaces, i, uuid, &uuidlen, 0, 0, 0, 0) &&
((!RegGetValue(hkInterfaces, uuid, u"DhcpIpAddress",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)) ||
(!RegGetValue(hkInterfaces, uuid, u"IpAddress",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t))) &&
((!RegGetValue(hkInterfaces, uuid, u"DhcpNameServer",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)) ||
(!RegGetValue(hkInterfaces, uuid, u"NameServer",
kNtRrfRtRegSz | kNtRrfRtRegMultiSz, NULL, value,
((valuebytes = sizeof(value)), &valuebytes)) &&
valuebytes > 2 * sizeof(char16_t)))) {
tprecode16to8(value8, sizeof(value8), value);
tmp = value8;
while ((addr = strtok_r(tmp, ", ", &state))) {
if (inet_pton(AF_INET, addr, &nameserver.sin_addr.s_addr) == 1) {
if (append(&resolv->nameservers, &nameserver) != -1) ++rc;
}
tmp = NULL;
}
}
}
} else {
rc = __winerr();
}
RegCloseKey(hkInterfaces);
return rc;
}
| 4,821 | 94 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/parsehoststxt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/errno.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
/**
* Parses HOSTS.TXT contents.
*
* Hostnames were invented by Peggy Karp; her format looks like this:
*
* # this is a comment
* # IP CANON [ALT...]
* 203.0.113.1 lol.example. lol
* 203.0.113.2 cat.example. cat
*
* @param htp points to a HostsTxt object, which should be zero
* initialized by the caller; or if it already contains items,
* this function will append
* @param f is the file content; see fopen() and fmemopen()
* @return 0 on success, or -1 w/ errno
* @see hoststxtsort() which is the logical next step
*/
int ParseHostsTxt(struct HostsTxt *ht, FILE *f) {
char *line;
size_t linesize;
struct HostsTxtEntry entry;
char *addr, *name, *tok, *comment;
line = NULL;
linesize = 0;
while ((getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
if ((addr = strtok_r(line, " \t\r\n\v", &tok)) &&
inet_pton(AF_INET, addr, entry.ip) == 1) {
entry.canon = ht->strings.i;
while ((name = strtok_r(NULL, " \t\r\n\v", &tok))) {
entry.name = ht->strings.i;
concat(&ht->strings, name, strnlen(name, DNS_NAME_MAX) + 1);
append(&ht->entries, &entry);
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
return 0;
}
| 3,425 | 72 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/herror.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/stdio/stdio.h"
/**
* Prints `h_errno` description to stderr.
* @see perror()
*/
void herror(const char *s) {
fprintf(stderr, "%s%s%s\n", s ? s : "", s ? ": " : "", hstrerror(h_errno));
}
| 2,750 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getservbyport.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/dns/servicestxt.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
struct servent *getservbyport(int port, const char *proto) {
static struct servent *ptr1, se1;
static char s_name[DNS_NAME_MAX + 1];
static char localproto[DNS_NAME_MAX + 1];
if (!ptr1) {
se1.s_name = s_name;
if (!(se1.s_aliases = calloc(1, sizeof(char *)))) return NULL;
se1.s_port = 0;
se1.s_proto = localproto;
ptr1 = &se1;
}
if (proto) {
if (!memccpy(localproto, proto, '\0', DNS_NAME_MAX)) return NULL;
} else
strcpy(localproto, "");
if (LookupServicesByPort(ntohs(port), ptr1->s_proto, DNS_NAME_MAX,
ptr1->s_name, DNS_NAME_MAX, NULL) == -1) {
return NULL;
}
ptr1->s_port = port;
return ptr1;
}
| 3,310 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getaddrinfo.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/dns/dns.h"
#include "libc/dns/hoststxt.h"
#include "libc/dns/resolvconf.h"
#include "libc/dns/servicestxt.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/inaddr.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/errfuns.h"
/**
* Resolves address for internet name.
*
* @param name is either an ip string or a utf-8 hostname
* @param service is the port number as a string
* @param hints may be passed to specialize behavior (optional)
* @param res receives a pointer that must be freed with freeaddrinfo(),
* and won't be modified if non-zero is returned
* @return 0 on success or EAI_xxx value
* @threadsafe
*/
int getaddrinfo(const char *name, const char *service,
const struct addrinfo *hints, struct addrinfo **res) {
int rc, port;
const char *canon;
size_t protolen;
struct addrinfo *ai;
char proto[32];
port = 0;
if (!name && !service) return EAI_NONAME;
if (!name && (hints->ai_flags & AI_CANONNAME)) return EAI_BADFLAGS;
if (service && (port = parseport(service)) == -1) {
if (hints->ai_socktype == SOCK_STREAM)
strcpy(proto, "tcp");
else if (hints->ai_socktype == SOCK_DGRAM)
strcpy(proto, "udp");
else /* ai_socktype == 0 */
strcpy(proto, "");
if ((port = LookupServicesByName(service, proto, sizeof(proto), NULL, 0,
NULL)) == -1) {
return EAI_NONAME;
}
}
if (!(ai = newaddrinfo(port))) return EAI_MEMORY;
if (service) ai->ai_addr4->sin_port = htons(port);
if (hints) {
ai->ai_socktype = hints->ai_socktype;
ai->ai_protocol = hints->ai_protocol;
}
if (!name) {
ai->ai_addr4->sin_addr.s_addr =
(hints && (hints->ai_flags & AI_PASSIVE) == AI_PASSIVE)
? INADDR_ANY
: INADDR_LOOPBACK;
*res = ai;
return 0;
}
if (inet_pton(AF_INET, name, &ai->ai_addr4->sin_addr.s_addr) == 1) {
*res = ai;
return 0;
} else if (hints && (hints->ai_flags & AI_NUMERICHOST) == AI_NUMERICHOST) {
freeaddrinfo(ai);
return EAI_NONAME;
} else if (ResolveHostsTxt(GetHostsTxt(), AF_INET, name, ai->ai_addr,
sizeof(ai->ai_addr4), &canon) > 0) {
memcpy(ai->ai_canonname, canon, min(strlen(canon), DNS_NAME_MAX) + 1);
*res = ai;
return 0;
} else {
rc = ResolveDns(GetResolvConf(), AF_INET, name, ai->ai_addr,
sizeof(ai->ai_addr4));
if (rc > 0) {
*res = ai;
return 0;
}
freeaddrinfo(ai);
if (rc == 0) {
return EAI_NONAME;
} else {
return EAI_SYSTEM;
}
}
}
| 4,647 | 108 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getntservicestxtpath.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/servicestxt.h"
#include "libc/nt/systeminfo.h"
#include "libc/str/str.h"
textwindows char *GetNtServicesTxtPath(char *pathbuf, uint32_t size) {
const char *const kWinHostsPath = "\\drivers\\etc\\services";
uint32_t len = GetSystemDirectoryA(&pathbuf[0], size);
if (len && len + strlen(kWinHostsPath) + 1 < size) {
if (pathbuf[len] == '\\') pathbuf[len--] = '\0';
memcpy(&pathbuf[len], kWinHostsPath, strlen(kWinHostsPath) + 1);
return &pathbuf[0];
} else {
return NULL;
}
}
| 3,036 | 42 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/gai_strerror.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
/**
* Turns getaddrinfo() return code into string.
*/
const char *gai_strerror(int code) {
switch (code) {
case EAI_ADDRFAMILY:
return "ADDRFAMILY";
case EAI_AGAIN:
return "AGAIN";
case EAI_ALLDONE:
return "ALLDONE";
case EAI_BADFLAGS:
return "BADFLAGS";
case EAI_CANCELED:
return "CANCELED";
case EAI_FAIL:
return "FAIL";
case EAI_FAMILY:
return "FAMILY";
case EAI_IDN_ENCODE:
return "ENCODE";
case EAI_INPROGRESS:
return "INPROGRESS";
case EAI_INTR:
return "INTR";
case EAI_MEMORY:
return "MEMORY";
case EAI_NODATA:
return "NODATA";
case EAI_NONAME:
return "NONAME";
case EAI_NOTCANCELED:
return "NOTCANCELED";
case EAI_OVERFLOW:
return "OVERFLOW";
case EAI_SERVICE:
return "SERVICE";
case EAI_SOCKTYPE:
return "SOCKTYPE";
case EAI_SUCCESS:
return "SUCCESS";
case EAI_SYSTEM:
return "SYSTEM";
default:
return "???";
}
}
| 2,891 | 68 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/hoststxt.h | #ifndef COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_
#define COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_
#include "libc/sock/struct/sockaddr.h"
#include "libc/stdio/stdio.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct HostsTxtEntry {
uint8_t ip[4]; /* inet_ntop(AF_INET, he->ip, buf, size) */
uint32_t name; /* &ht->strings.p[he->name] */
uint32_t canon; /* &ht->strings.p[he->canon] */
};
struct HostsTxtEntries {
size_t i, n;
struct HostsTxtEntry *p;
};
struct HostsTxtStrings {
size_t i, n;
char *p;
};
struct HostsTxt {
struct HostsTxtEntries entries;
struct HostsTxtStrings strings;
};
const struct HostsTxt *GetHostsTxt(void) returnsnonnull;
void FreeHostsTxt(struct HostsTxt **) paramsnonnull();
int ParseHostsTxt(struct HostsTxt *, FILE *) paramsnonnull();
int ResolveHostsTxt(const struct HostsTxt *, int, const char *,
struct sockaddr *, uint32_t, const char **)
paramsnonnull((1, 3));
int ResolveHostsReverse(const struct HostsTxt *, int, const uint8_t *, char *,
size_t) paramsnonnull((1, 3));
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_HOSTSTXT_H_ */
| 1,196 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/lookupservicesbyname.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/dns/servicestxt.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
/**
* Opens and searches /etc/services to find port for a given name.
*
* @param servname is a NULL-terminated string
* @param servproto is a NULL-terminated string (eg "tcp", "udp")
* (if servproto is an empty string,
* if is filled with the first matching
* protocol)
* @param servprotolen the size of servproto
* @param buf is a buffer to store the official name of the service
* (if NULL, the official name is not stored)
* @param bufsize is the size of buf
* @param filepath is the location of services file
* (if NULL, uses /etc/services)
* @return -1 on error, or positive port number
* @note aliases are read from file for comparison, but not returned.
* @see LookupServicesByPort
* @threadsafe
*/
int LookupServicesByName(const char *servname, char *servproto,
size_t servprotolen, char *buf, size_t bufsize,
const char *filepath) {
FILE *f;
char *line;
const char *path;
size_t linesize;
int found, result;
char pathbuf[PATH_MAX];
char *name, *port, *proto, *alias, *comment, *tok;
if (!(path = filepath)) {
path = "/etc/services";
if (IsWindows()) {
path =
firstnonnull(GetNtServicesTxtPath(pathbuf, ARRAYLEN(pathbuf)), path);
}
}
if (servprotolen == 0 || !(f = fopen(path, "r"))) {
return -1;
}
line = NULL;
linesize = 0;
found = 0;
result = -1;
if (buf && bufsize != 0) strcpy(buf, "");
while (found == 0 && (getline(&line, &linesize, f)) != -1) {
if ((comment = strchr(line, '#'))) *comment = '\0';
name = strtok_r(line, " \t\r\n\v", &tok);
port = strtok_r(NULL, "/ \t\r\n\v", &tok);
proto = strtok_r(NULL, " \t\r\n\v", &tok);
if (name && port && proto) {
alias = name;
while (alias && strcasecmp(alias, servname) != 0)
alias = strtok_r(NULL, " \t\r\n\v", &tok);
if (alias) /* alias matched with servname */
{
if (!servproto[0] || strncasecmp(proto, servproto, servprotolen) == 0) {
if (!servproto[0] && !memccpy(servproto, proto, '\0', servprotolen)) {
strcpy(servproto, "");
break;
}
if (buf && bufsize != 0 && !memccpy(buf, name, '\0', bufsize)) {
strcpy(buf, "");
break;
}
result = atoi(port);
found = 1;
}
}
}
}
free(line);
if (ferror(f)) {
errno = ferror(f);
return -1;
}
fclose(f);
if (!found) return -1;
return result;
}
| 5,287 | 115 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/serializednsquestion.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/dns.h"
#include "libc/dns/dnsquestion.h"
#include "libc/sysv/errfuns.h"
/**
* Serializes DNS question record to wire.
*
* @return number of bytes written
* @see pascalifydnsname()
*/
int SerializeDnsQuestion(uint8_t *buf, size_t size,
const struct DnsQuestion *dq) {
int wrote;
if ((wrote = PascalifyDnsName(buf, size, dq->qname)) == -1) return -1;
if (wrote + 1 + 4 > size) return enospc();
buf[wrote + 1] = dq->qtype >> 8;
buf[wrote + 2] = dq->qtype;
buf[wrote + 3] = dq->qclass >> 8;
buf[wrote + 4] = dq->qclass;
return wrote + 5;
}
| 2,438 | 40 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/prototxt.h | #ifndef COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_
#define COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int LookupProtoByNumber(const int, char *, size_t, const char *)
paramsnonnull((2));
int LookupProtoByName(const char *, char *, size_t, const char *)
paramsnonnull((1, 2));
char *GetNtProtocolsTxtPath(char *, uint32_t);
/* TODO: implement like struct HostsTxt? */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_DNS_PROTOTXT_H_ */
| 592 | 19 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/getprotobyname.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â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, â
â EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF â
â MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. â
â IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR â
â OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, â
â ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR â
â OTHER DEALINGS IN THE SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dns/ent.h"
#include "libc/dns/prototxt.h"
#include "libc/mem/mem.h"
struct protoent *getprotobyname(const char *name) {
static struct protoent *ptr0, pe0;
static char p_name[DNS_NAME_MAX + 1];
if (!ptr0) {
pe0.p_name = p_name;
if (!(pe0.p_aliases = calloc(1, sizeof(char *)))) return NULL;
pe0.p_proto = -1;
ptr0 = &pe0;
}
ptr0->p_proto = LookupProtoByName(name, ptr0->p_name, DNS_NAME_MAX, NULL);
if (ptr0->p_proto == -1) return NULL;
return ptr0;
}
| 3,016 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/rfc1035.txt | Network Working Group P. Mockapetris
Request for Comments: 1035 ISI
November 1987
Obsoletes: RFCs 882, 883, 973
DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION
1. STATUS OF THIS MEMO
This RFC describes the details of the domain system and protocol, and
assumes that the reader is familiar with the concepts discussed in a
companion RFC, "Domain Names - Concepts and Facilities" [RFC-1034].
The domain system is a mixture of functions and data types which are an
official protocol and functions and data types which are still
experimental. Since the domain system is intentionally extensible, new
data types and experimental behavior should always be expected in parts
of the system beyond the official protocol. The official protocol parts
include standard queries, responses and the Internet class RR data
formats (e.g., host addresses). Since the previous RFC set, several
definitions have changed, so some previous definitions are obsolete.
Experimental or obsolete features are clearly marked in these RFCs, and
such information should be used with caution.
The reader is especially cautioned not to depend on the values which
appear in examples to be current or complete, since their purpose is
primarily pedagogical. Distribution of this memo is unlimited.
Table of Contents
1. STATUS OF THIS MEMO 1
2. INTRODUCTION 3
2.1. Overview 3
2.2. Common configurations 4
2.3. Conventions 7
2.3.1. Preferred name syntax 7
2.3.2. Data Transmission Order 8
2.3.3. Character Case 9
2.3.4. Size limits 10
3. DOMAIN NAME SPACE AND RR DEFINITIONS 10
3.1. Name space definitions 10
3.2. RR definitions 11
3.2.1. Format 11
3.2.2. TYPE values 12
3.2.3. QTYPE values 12
3.2.4. CLASS values 13
Mockapetris [Page 1]
RFC 1035 Domain Implementation and Specification November 1987
3.2.5. QCLASS values 13
3.3. Standard RRs 13
3.3.1. CNAME RDATA format 14
3.3.2. HINFO RDATA format 14
3.3.3. MB RDATA format (EXPERIMENTAL) 14
3.3.4. MD RDATA format (Obsolete) 15
3.3.5. MF RDATA format (Obsolete) 15
3.3.6. MG RDATA format (EXPERIMENTAL) 16
3.3.7. MINFO RDATA format (EXPERIMENTAL) 16
3.3.8. MR RDATA format (EXPERIMENTAL) 17
3.3.9. MX RDATA format 17
3.3.10. NULL RDATA format (EXPERIMENTAL) 17
3.3.11. NS RDATA format 18
3.3.12. PTR RDATA format 18
3.3.13. SOA RDATA format 19
3.3.14. TXT RDATA format 20
3.4. ARPA Internet specific RRs 20
3.4.1. A RDATA format 20
3.4.2. WKS RDATA format 21
3.5. IN-ADDR.ARPA domain 22
3.6. Defining new types, classes, and special namespaces 24
4. MESSAGES 25
4.1. Format 25
4.1.1. Header section format 26
4.1.2. Question section format 28
4.1.3. Resource record format 29
4.1.4. Message compression 30
4.2. Transport 32
4.2.1. UDP usage 32
4.2.2. TCP usage 32
5. MASTER FILES 33
5.1. Format 33
5.2. Use of master files to define zones 35
5.3. Master file example 36
6. NAME SERVER IMPLEMENTATION 37
6.1. Architecture 37
6.1.1. Control 37
6.1.2. Database 37
6.1.3. Time 39
6.2. Standard query processing 39
6.3. Zone refresh and reload processing 39
6.4. Inverse queries (Optional) 40
6.4.1. The contents of inverse queries and responses 40
6.4.2. Inverse query and response example 41
6.4.3. Inverse query processing 42
Mockapetris [Page 2]
RFC 1035 Domain Implementation and Specification November 1987
6.5. Completion queries and responses 42
7. RESOLVER IMPLEMENTATION 43
7.1. Transforming a user request into a query 43
7.2. Sending the queries 44
7.3. Processing responses 46
7.4. Using the cache 47
8. MAIL SUPPORT 47
8.1. Mail exchange binding 48
8.2. Mailbox binding (Experimental) 48
9. REFERENCES and BIBLIOGRAPHY 50
Index 54
2. INTRODUCTION
2.1. Overview
The goal of domain names is to provide a mechanism for naming resources
in such a way that the names are usable in different hosts, networks,
protocol families, internets, and administrative organizations.
From the user's point of view, domain names are useful as arguments to a
local agent, called a resolver, which retrieves information associated
with the domain name. Thus a user might ask for the host address or
mail information associated with a particular domain name. To enable
the user to request a particular type of information, an appropriate
query type is passed to the resolver with the domain name. To the user,
the domain tree is a single information space; the resolver is
responsible for hiding the distribution of data among name servers from
the user.
From the resolver's point of view, the database that makes up the domain
space is distributed among various name servers. Different parts of the
domain space are stored in different name servers, although a particular
data item will be stored redundantly in two or more name servers. The
resolver starts with knowledge of at least one name server. When the
resolver processes a user query it asks a known name server for the
information; in return, the resolver either receives the desired
information or a referral to another name server. Using these
referrals, resolvers learn the identities and contents of other name
servers. Resolvers are responsible for dealing with the distribution of
the domain space and dealing with the effects of name server failure by
consulting redundant databases in other servers.
Name servers manage two kinds of data. The first kind of data held in
sets called zones; each zone is the complete database for a particular
"pruned" subtree of the domain space. This data is called
authoritative. A name server periodically checks to make sure that its
zones are up to date, and if not, obtains a new copy of updated zones
Mockapetris [Page 3]
RFC 1035 Domain Implementation and Specification November 1987
from master files stored locally or in another name server. The second
kind of data is cached data which was acquired by a local resolver.
This data may be incomplete, but improves the performance of the
retrieval process when non-local data is repeatedly accessed. Cached
data is eventually discarded by a timeout mechanism.
This functional structure isolates the problems of user interface,
failure recovery, and distribution in the resolvers and isolates the
database update and refresh problems in the name servers.
2.2. Common configurations
A host can participate in the domain name system in a number of ways,
depending on whether the host runs programs that retrieve information
from the domain system, name servers that answer queries from other
hosts, or various combinations of both functions. The simplest, and
perhaps most typical, configuration is shown below:
Local Host | Foreign
|
+---------+ +----------+ | +--------+
| | user queries | |queries | | |
| User |-------------->| |---------|->|Foreign |
| Program | | Resolver | | | Name |
| |<--------------| |<--------|--| Server |
| | user responses| |responses| | |
+---------+ +----------+ | +--------+
| A |
cache additions | | references |
V | |
+----------+ |
| cache | |
+----------+ |
User programs interact with the domain name space through resolvers; the
format of user queries and user responses is specific to the host and
its operating system. User queries will typically be operating system
calls, and the resolver and its cache will be part of the host operating
system. Less capable hosts may choose to implement the resolver as a
subroutine to be linked in with every program that needs its services.
Resolvers answer user queries with information they acquire via queries
to foreign name servers and the local cache.
Note that the resolver may have to make several queries to several
different foreign name servers to answer a particular user query, and
hence the resolution of a user query may involve several network
accesses and an arbitrary amount of time. The queries to foreign name
servers and the corresponding responses have a standard format described
Mockapetris [Page 4]
RFC 1035 Domain Implementation and Specification November 1987
in this memo, and may be datagrams.
Depending on its capabilities, a name server could be a stand alone
program on a dedicated machine or a process or processes on a large
timeshared host. A simple configuration might be:
Local Host | Foreign
|
+---------+ |
/ /| |
+---------+ | +----------+ | +--------+
| | | | |responses| | |
| | | | Name |---------|->|Foreign |
| Master |-------------->| Server | | |Resolver|
| files | | | |<--------|--| |
| |/ | | queries | +--------+
+---------+ +----------+ |
Here a primary name server acquires information about one or more zones
by reading master files from its local file system, and answers queries
about those zones that arrive from foreign resolvers.
The DNS requires that all zones be redundantly supported by more than
one name server. Designated secondary servers can acquire zones and
check for updates from the primary server using the zone transfer
protocol of the DNS. This configuration is shown below:
Local Host | Foreign
|
+---------+ |
/ /| |
+---------+ | +----------+ | +--------+
| | | | |responses| | |
| | | | Name |---------|->|Foreign |
| Master |-------------->| Server | | |Resolver|
| files | | | |<--------|--| |
| |/ | | queries | +--------+
+---------+ +----------+ |
A |maintenance | +--------+
| +------------|->| |
| queries | |Foreign |
| | | Name |
+------------------|--| Server |
maintenance responses | +--------+
In this configuration, the name server periodically establishes a
virtual circuit to a foreign name server to acquire a copy of a zone or
to check that an existing copy has not changed. The messages sent for
Mockapetris [Page 5]
RFC 1035 Domain Implementation and Specification November 1987
these maintenance activities follow the same form as queries and
responses, but the message sequences are somewhat different.
The information flow in a host that supports all aspects of the domain
name system is shown below:
Local Host | Foreign
|
+---------+ +----------+ | +--------+
| | user queries | |queries | | |
| User |-------------->| |---------|->|Foreign |
| Program | | Resolver | | | Name |
| |<--------------| |<--------|--| Server |
| | user responses| |responses| | |
+---------+ +----------+ | +--------+
| A |
cache additions | | references |
V | |
+----------+ |
| Shared | |
| database | |
+----------+ |
A | |
+---------+ refreshes | | references |
/ /| | V |
+---------+ | +----------+ | +--------+
| | | | |responses| | |
| | | | Name |---------|->|Foreign |
| Master |-------------->| Server | | |Resolver|
| files | | | |<--------|--| |
| |/ | | queries | +--------+
+---------+ +----------+ |
A |maintenance | +--------+
| +------------|->| |
| queries | |Foreign |
| | | Name |
+------------------|--| Server |
maintenance responses | +--------+
The shared database holds domain space data for the local name server
and resolver. The contents of the shared database will typically be a
mixture of authoritative data maintained by the periodic refresh
operations of the name server and cached data from previous resolver
requests. The structure of the domain data and the necessity for
synchronization between name servers and resolvers imply the general
characteristics of this database, but the actual format is up to the
local implementor.
Mockapetris [Page 6]
RFC 1035 Domain Implementation and Specification November 1987
Information flow can also be tailored so that a group of hosts act
together to optimize activities. Sometimes this is done to offload less
capable hosts so that they do not have to implement a full resolver.
This can be appropriate for PCs or hosts which want to minimize the
amount of new network code which is required. This scheme can also
allow a group of hosts can share a small number of caches rather than
maintaining a large number of separate caches, on the premise that the
centralized caches will have a higher hit ratio. In either case,
resolvers are replaced with stub resolvers which act as front ends to
resolvers located in a recursive server in one or more name servers
known to perform that service:
Local Hosts | Foreign
|
+---------+ |
| | responses |
| Stub |<--------------------+ |
| Resolver| | |
| |----------------+ | |
+---------+ recursive | | |
queries | | |
V | |
+---------+ recursive +----------+ | +--------+
| | queries | |queries | | |
| Stub |-------------->| Recursive|---------|->|Foreign |
| Resolver| | Server | | | Name |
| |<--------------| |<--------|--| Server |
+---------+ responses | |responses| | |
+----------+ | +--------+
| Central | |
| cache | |
+----------+ |
In any case, note that domain components are always replicated for
reliability whenever possible.
2.3. Conventions
The domain system has several conventions dealing with low-level, but
fundamental, issues. While the implementor is free to violate these
conventions WITHIN HIS OWN SYSTEM, he must observe these conventions in
ALL behavior observed from other hosts.
2.3.1. Preferred name syntax
The DNS specifications attempt to be as general as possible in the rules
for constructing domain names. The idea is that the name of any
existing object can be expressed as a domain name with minimal changes.
Mockapetris [Page 7]
RFC 1035 Domain Implementation and Specification November 1987
However, when assigning a domain name for an object, the prudent user
will select a name which satisfies both the rules of the domain system
and any existing rules for the object, whether these rules are published
or implied by existing programs.
For example, when naming a mail domain, the user should satisfy both the
rules of this memo and those in RFC-822. When creating a new host name,
the old rules for HOSTS.TXT should be followed. This avoids problems
when old software is converted to use domain names.
The following syntax will result in fewer problems with many
applications that use domain names (e.g., mail, TELNET).
<domain> ::= <subdomain> | " "
<subdomain> ::= <label> | <subdomain> "." <label>
<label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52 alphabetic characters A through Z in
upper case and a through z in lower case
<digit> ::= any one of the ten digits 0 through 9
Note that while upper and lower case letters are allowed in domain
names, no significance is attached to the case. That is, two names with
the same spelling but different case are to be treated as if identical.
The labels must follow the rules for ARPANET host names. They must
start with a letter, end with a letter or digit, and have as interior
characters only letters, digits, and hyphen. There are also some
restrictions on the length. Labels must be 63 characters or less.
For example, the following strings identify hosts in the Internet:
A.ISI.EDU XX.LCS.MIT.EDU SRI-NIC.ARPA
2.3.2. Data Transmission Order
The order of transmission of the header and data described in this
document is resolved to the octet level. Whenever a diagram shows a
Mockapetris [Page 8]
RFC 1035 Domain Implementation and Specification November 1987
group of octets, the order of transmission of those octets is the normal
order in which they are read in English. For example, in the following
diagram, the octets are transmitted in the order they are numbered.
0 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 1 | 2 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 3 | 4 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 5 | 6 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Whenever an octet represents a numeric quantity, the left most bit in
the diagram is the high order or most significant bit. That is, the bit
labeled 0 is the most significant bit. For example, the following
diagram represents the value 170 (decimal).
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|1 0 1 0 1 0 1 0|
+-+-+-+-+-+-+-+-+
Similarly, whenever a multi-octet field represents a numeric quantity
the left most bit of the whole field is the most significant bit. When
a multi-octet quantity is transmitted the most significant octet is
transmitted first.
2.3.3. Character Case
For all parts of the DNS that are part of the official protocol, all
comparisons between character strings (e.g., labels, domain names, etc.)
are done in a case-insensitive manner. At present, this rule is in
force throughout the domain system without exception. However, future
additions beyond current usage may need to use the full binary octet
capabilities in names, so attempts to store domain names in 7-bit ASCII
or use of special bytes to terminate labels, etc., should be avoided.
When data enters the domain system, its original case should be
preserved whenever possible. In certain circumstances this cannot be
done. For example, if two RRs are stored in a database, one at x.y and
one at X.Y, they are actually stored at the same place in the database,
and hence only one casing would be preserved. The basic rule is that
case can be discarded only when data is used to define structure in a
database, and two names are identical when compared in a case
insensitive manner.
Mockapetris [Page 9]
RFC 1035 Domain Implementation and Specification November 1987
Loss of case sensitive data must be minimized. Thus while data for x.y
and X.Y may both be stored under a single location x.y or X.Y, data for
a.x and B.X would never be stored under A.x, A.X, b.x, or b.X. In
general, this preserves the case of the first label of a domain name,
but forces standardization of interior node labels.
Systems administrators who enter data into the domain database should
take care to represent the data they supply to the domain system in a
case-consistent manner if their system is case-sensitive. The data
distribution system in the domain system will ensure that consistent
representations are preserved.
2.3.4. Size limits
Various objects and parameters in the DNS have size limits. They are
listed below. Some could be easily changed, others are more
fundamental.
labels 63 octets or less
names 255 octets or less
TTL positive values of a signed 32 bit number.
UDP messages 512 octets or less
3. DOMAIN NAME SPACE AND RR DEFINITIONS
3.1. Name space definitions
Domain names in messages are expressed in terms of a sequence of labels.
Each label is represented as a one octet length field followed by that
number of octets. Since every domain name ends with the null label of
the root, a domain name is terminated by a length byte of zero. The
high order two bits of every length octet must be zero, and the
remaining six bits of the length field limit the label to 63 octets or
less.
To simplify implementations, the total length of a domain name (i.e.,
label octets and label length octets) is restricted to 255 octets or
less.
Although labels can contain any 8 bit values in octets that make up a
label, it is strongly recommended that labels follow the preferred
syntax described elsewhere in this memo, which is compatible with
existing host naming conventions. Name servers and resolvers must
compare labels in a case-insensitive manner (i.e., A=a), assuming ASCII
with zero parity. Non-alphabetic codes must match exactly.
Mockapetris [Page 10]
RFC 1035 Domain Implementation and Specification November 1987
3.2. RR definitions
3.2.1. Format
All RRs have the same top level format shown below:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
/ NAME /
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| CLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TTL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RDLENGTH |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/ RDATA /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
NAME an owner name, i.e., the name of the node to which this
resource record pertains.
TYPE two octets containing one of the RR TYPE codes.
CLASS two octets containing one of the RR CLASS codes.
TTL a 32 bit signed integer that specifies the time interval
that the resource record may be cached before the source
of the information should again be consulted. Zero
values are interpreted to mean that the RR can only be
used for the transaction in progress, and should not be
cached. For example, SOA records are always distributed
with a zero TTL to prohibit caching. Zero values can
also be used for extremely volatile data.
RDLENGTH an unsigned 16 bit integer that specifies the length in
octets of the RDATA field.
Mockapetris [Page 11]
RFC 1035 Domain Implementation and Specification November 1987
RDATA a variable length string of octets that describes the
resource. The format of this information varies
according to the TYPE and CLASS of the resource record.
3.2.2. TYPE values
TYPE fields are used in resource records. Note that these types are a
subset of QTYPEs.
TYPE value and meaning
A 1 a host address
NS 2 an authoritative name server
MD 3 a mail destination (Obsolete - use MX)
MF 4 a mail forwarder (Obsolete - use MX)
CNAME 5 the canonical name for an alias
SOA 6 marks the start of a zone of authority
MB 7 a mailbox domain name (EXPERIMENTAL)
MG 8 a mail group member (EXPERIMENTAL)
MR 9 a mail rename domain name (EXPERIMENTAL)
NULL 10 a null RR (EXPERIMENTAL)
WKS 11 a well known service description
PTR 12 a domain name pointer
HINFO 13 host information
MINFO 14 mailbox or mail list information
MX 15 mail exchange
TXT 16 text strings
3.2.3. QTYPE values
QTYPE fields appear in the question part of a query. QTYPES are a
superset of TYPEs, hence all TYPEs are valid QTYPEs. In addition, the
following QTYPEs are defined:
Mockapetris [Page 12]
RFC 1035 Domain Implementation and Specification November 1987
AXFR 252 A request for a transfer of an entire zone
MAILB 253 A request for mailbox-related records (MB, MG or MR)
MAILA 254 A request for mail agent RRs (Obsolete - see MX)
* 255 A request for all records
3.2.4. CLASS values
CLASS fields appear in resource records. The following CLASS mnemonics
and values are defined:
IN 1 the Internet
CS 2 the CSNET class (Obsolete - used only for examples in
some obsolete RFCs)
CH 3 the CHAOS class
HS 4 Hesiod [Dyer 87]
3.2.5. QCLASS values
QCLASS fields appear in the question section of a query. QCLASS values
are a superset of CLASS values; every CLASS is a valid QCLASS. In
addition to CLASS values, the following QCLASSes are defined:
* 255 any class
3.3. Standard RRs
The following RR definitions are expected to occur, at least
potentially, in all classes. In particular, NS, SOA, CNAME, and PTR
will be used in all classes, and have the same format in all classes.
Because their RDATA format is known, all domain names in the RDATA
section of these RRs may be compressed.
<domain-name> is a domain name represented as a series of labels, and
terminated by a label with zero length. <character-string> is a single
length octet followed by that number of characters. <character-string>
is treated as binary information, and can be up to 256 characters in
length (including the length octet).
Mockapetris [Page 13]
RFC 1035 Domain Implementation and Specification November 1987
3.3.1. CNAME RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ CNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
CNAME A <domain-name> which specifies the canonical or primary
name for the owner. The owner name is an alias.
CNAME RRs cause no additional section processing, but name servers may
choose to restart the query at the canonical name in certain cases. See
the description of name server logic in [RFC-1034] for details.
3.3.2. HINFO RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ CPU /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ OS /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
CPU A <character-string> which specifies the CPU type.
OS A <character-string> which specifies the operating
system type.
Standard values for CPU and OS can be found in [RFC-1010].
HINFO records are used to acquire general information about a host. The
main use is for protocols such as FTP that can use special procedures
when talking between machines or operating systems of the same type.
3.3.3. MB RDATA format (EXPERIMENTAL)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MADNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MADNAME A <domain-name> which specifies a host which has the
specified mailbox.
Mockapetris [Page 14]
RFC 1035 Domain Implementation and Specification November 1987
MB records cause additional section processing which looks up an A type
RRs corresponding to MADNAME.
3.3.4. MD RDATA format (Obsolete)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MADNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MADNAME A <domain-name> which specifies a host which has a mail
agent for the domain which should be able to deliver
mail for the domain.
MD records cause additional section processing which looks up an A type
record corresponding to MADNAME.
MD is obsolete. See the definition of MX and [RFC-974] for details of
the new scheme. The recommended policy for dealing with MD RRs found in
a master file is to reject them, or to convert them to MX RRs with a
preference of 0.
3.3.5. MF RDATA format (Obsolete)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MADNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MADNAME A <domain-name> which specifies a host which has a mail
agent for the domain which will accept mail for
forwarding to the domain.
MF records cause additional section processing which looks up an A type
record corresponding to MADNAME.
MF is obsolete. See the definition of MX and [RFC-974] for details ofw
the new scheme. The recommended policy for dealing with MD RRs found in
a master file is to reject them, or to convert them to MX RRs with a
preference of 10.
Mockapetris [Page 15]
RFC 1035 Domain Implementation and Specification November 1987
3.3.6. MG RDATA format (EXPERIMENTAL)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MGMNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MGMNAME A <domain-name> which specifies a mailbox which is a
member of the mail group specified by the domain name.
MG records cause no additional section processing.
3.3.7. MINFO RDATA format (EXPERIMENTAL)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ RMAILBX /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ EMAILBX /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
RMAILBX A <domain-name> which specifies a mailbox which is
responsible for the mailing list or mailbox. If this
domain name names the root, the owner of the MINFO RR is
responsible for itself. Note that many existing mailing
lists use a mailbox X-request for the RMAILBX field of
mailing list X, e.g., Msgroup-request for Msgroup. This
field provides a more general mechanism.
EMAILBX A <domain-name> which specifies a mailbox which is to
receive error messages related to the mailing list or
mailbox specified by the owner of the MINFO RR (similar
to the ERRORS-TO: field which has been proposed). If
this domain name names the root, errors should be
returned to the sender of the message.
MINFO records cause no additional section processing. Although these
records can be associated with a simple mailbox, they are usually used
with a mailing list.
Mockapetris [Page 16]
RFC 1035 Domain Implementation and Specification November 1987
3.3.8. MR RDATA format (EXPERIMENTAL)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ NEWNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
NEWNAME A <domain-name> which specifies a mailbox which is the
proper rename of the specified mailbox.
MR records cause no additional section processing. The main use for MR
is as a forwarding entry for a user who has moved to a different
mailbox.
3.3.9. MX RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| PREFERENCE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ EXCHANGE /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
PREFERENCE A 16 bit integer which specifies the preference given to
this RR among others at the same owner. Lower values
are preferred.
EXCHANGE A <domain-name> which specifies a host willing to act as
a mail exchange for the owner name.
MX records cause type A additional section processing for the host
specified by EXCHANGE. The use of MX RRs is explained in detail in
[RFC-974].
3.3.10. NULL RDATA format (EXPERIMENTAL)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ <anything> /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Anything at all may be in the RDATA field so long as it is 65535 octets
or less.
Mockapetris [Page 17]
RFC 1035 Domain Implementation and Specification November 1987
NULL records cause no additional section processing. NULL RRs are not
allowed in master files. NULLs are used as placeholders in some
experimental extensions of the DNS.
3.3.11. NS RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ NSDNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
NSDNAME A <domain-name> which specifies a host which should be
authoritative for the specified class and domain.
NS records cause both the usual additional section processing to locate
a type A record, and, when used in a referral, a special search of the
zone in which they reside for glue information.
The NS RR states that the named host should be expected to have a zone
starting at owner name of the specified class. Note that the class may
not indicate the protocol family which should be used to communicate
with the host, although it is typically a strong hint. For example,
hosts which are name servers for either Internet (IN) or Hesiod (HS)
class information are normally queried using IN class protocols.
3.3.12. PTR RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ PTRDNAME /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
PTRDNAME A <domain-name> which points to some location in the
domain name space.
PTR records cause no additional section processing. These RRs are used
in special domains to point to some other location in the domain space.
These records are simple data, and don't imply any special processing
similar to that performed by CNAME, which identifies aliases. See the
description of the IN-ADDR.ARPA domain for an example.
Mockapetris [Page 18]
RFC 1035 Domain Implementation and Specification November 1987
3.3.13. SOA RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ MNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ RNAME /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| SERIAL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| REFRESH |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RETRY |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| EXPIRE |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| MINIMUM |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
MNAME The <domain-name> of the name server that was the
original or primary source of data for this zone.
RNAME A <domain-name> which specifies the mailbox of the
person responsible for this zone.
SERIAL The unsigned 32 bit version number of the original copy
of the zone. Zone transfers preserve this value. This
value wraps and should be compared using sequence space
arithmetic.
REFRESH A 32 bit time interval before the zone should be
refreshed.
RETRY A 32 bit time interval that should elapse before a
failed refresh should be retried.
EXPIRE A 32 bit time value that specifies the upper limit on
the time interval that can elapse before the zone is no
longer authoritative.
Mockapetris [Page 19]
RFC 1035 Domain Implementation and Specification November 1987
MINIMUM The unsigned 32 bit minimum TTL field that should be
exported with any RR from this zone.
SOA records cause no additional section processing.
All times are in units of seconds.
Most of these fields are pertinent only for name server maintenance
operations. However, MINIMUM is used in all query operations that
retrieve RRs from a zone. Whenever a RR is sent in a response to a
query, the TTL field is set to the maximum of the TTL field from the RR
and the MINIMUM field in the appropriate SOA. Thus MINIMUM is a lower
bound on the TTL field for all RRs in a zone. Note that this use of
MINIMUM should occur when the RRs are copied into the response and not
when the zone is loaded from a master file or via a zone transfer. The
reason for this provison is to allow future dynamic update facilities to
change the SOA RR with known semantics.
3.3.14. TXT RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ TXT-DATA /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
TXT-DATA One or more <character-string>s.
TXT RRs are used to hold descriptive text. The semantics of the text
depends on the domain where it is found.
3.4. Internet specific RRs
3.4.1. A RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ADDRESS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
ADDRESS A 32 bit Internet address.
Hosts that have multiple Internet addresses will have multiple A
records.
Mockapetris [Page 20]
RFC 1035 Domain Implementation and Specification November 1987
A records cause no additional section processing. The RDATA section of
an A line in a master file is an Internet address expressed as four
decimal numbers separated by dots without any imbedded spaces (e.g.,
"10.2.0.52" or "192.0.5.6").
3.4.2. WKS RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ADDRESS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| PROTOCOL | |
+--+--+--+--+--+--+--+--+ |
| |
/ <BIT MAP> /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
ADDRESS An 32 bit Internet address
PROTOCOL An 8 bit IP protocol number
<BIT MAP> A variable length bit map. The bit map must be a
multiple of 8 bits long.
The WKS record is used to describe the well known services supported by
a particular protocol on a particular internet address. The PROTOCOL
field specifies an IP protocol number, and the bit map has one bit per
port of the specified protocol. The first bit corresponds to port 0,
the second to port 1, etc. If the bit map does not include a bit for a
protocol of interest, that bit is assumed zero. The appropriate values
and mnemonics for ports and protocols are specified in [RFC-1010].
For example, if PROTOCOL=TCP (6), the 26th bit corresponds to TCP port
25 (SMTP). If this bit is set, a SMTP server should be listening on TCP
port 25; if zero, SMTP service is not supported on the specified
address.
The purpose of WKS RRs is to provide availability information for
servers for TCP and UDP. If a server supports both TCP and UDP, or has
multiple Internet addresses, then multiple WKS RRs are used.
WKS RRs cause no additional section processing.
In master files, both ports and protocols are expressed using mnemonics
or decimal numbers.
Mockapetris [Page 21]
RFC 1035 Domain Implementation and Specification November 1987
3.5. IN-ADDR.ARPA domain
The Internet uses a special domain to support gateway location and
Internet address to host mapping. Other classes may employ a similar
strategy in other domains. The intent of this domain is to provide a
guaranteed method to perform host address to host name mapping, and to
facilitate queries to locate all gateways on a particular network in the
Internet.
Note that both of these services are similar to functions that could be
performed by inverse queries; the difference is that this part of the
domain name space is structured according to address, and hence can
guarantee that the appropriate data can be located without an exhaustive
search of the domain space.
The domain begins at IN-ADDR.ARPA and has a substructure which follows
the Internet addressing structure.
Domain names in the IN-ADDR.ARPA domain are defined to have up to four
labels in addition to the IN-ADDR.ARPA suffix. Each label represents
one octet of an Internet address, and is expressed as a character string
for a decimal value in the range 0-255 (with leading zeros omitted
except in the case of a zero octet which is represented by a single
zero).
Host addresses are represented by domain names that have all four labels
specified. Thus data for Internet address 10.2.0.52 is located at
domain name 52.0.2.10.IN-ADDR.ARPA. The reversal, though awkward to
read, allows zones to be delegated which are exactly one network of
address space. For example, 10.IN-ADDR.ARPA can be a zone containing
data for the ARPANET, while 26.IN-ADDR.ARPA can be a separate zone for
MILNET. Address nodes are used to hold pointers to primary host names
in the normal domain space.
Network numbers correspond to some non-terminal nodes at various depths
in the IN-ADDR.ARPA domain, since Internet network numbers are either 1,
2, or 3 octets. Network nodes are used to hold pointers to the primary
host names of gateways attached to that network. Since a gateway is, by
definition, on more than one network, it will typically have two or more
network nodes which point at it. Gateways will also have host level
pointers at their fully qualified addresses.
Both the gateway pointers at network nodes and the normal host pointers
at full address nodes use the PTR RR to point back to the primary domain
names of the corresponding hosts.
For example, the IN-ADDR.ARPA domain will contain information about the
ISI gateway between net 10 and 26, an MIT gateway from net 10 to MIT's
Mockapetris [Page 22]
RFC 1035 Domain Implementation and Specification November 1987
net 18, and hosts A.ISI.EDU and MULTICS.MIT.EDU. Assuming that ISI
gateway has addresses 10.2.0.22 and 26.0.0.103, and a name MILNET-
GW.ISI.EDU, and the MIT gateway has addresses 10.0.0.77 and 18.10.0.4
and a name GW.LCS.MIT.EDU, the domain database would contain:
10.IN-ADDR.ARPA. PTR MILNET-GW.ISI.EDU.
10.IN-ADDR.ARPA. PTR GW.LCS.MIT.EDU.
18.IN-ADDR.ARPA. PTR GW.LCS.MIT.EDU.
26.IN-ADDR.ARPA. PTR MILNET-GW.ISI.EDU.
22.0.2.10.IN-ADDR.ARPA. PTR MILNET-GW.ISI.EDU.
103.0.0.26.IN-ADDR.ARPA. PTR MILNET-GW.ISI.EDU.
77.0.0.10.IN-ADDR.ARPA. PTR GW.LCS.MIT.EDU.
4.0.10.18.IN-ADDR.ARPA. PTR GW.LCS.MIT.EDU.
103.0.3.26.IN-ADDR.ARPA. PTR A.ISI.EDU.
6.0.0.10.IN-ADDR.ARPA. PTR MULTICS.MIT.EDU.
Thus a program which wanted to locate gateways on net 10 would originate
a query of the form QTYPE=PTR, QCLASS=IN, QNAME=10.IN-ADDR.ARPA. It
would receive two RRs in response:
10.IN-ADDR.ARPA. PTR MILNET-GW.ISI.EDU.
10.IN-ADDR.ARPA. PTR GW.LCS.MIT.EDU.
The program could then originate QTYPE=A, QCLASS=IN queries for MILNET-
GW.ISI.EDU. and GW.LCS.MIT.EDU. to discover the Internet addresses of
these gateways.
A resolver which wanted to find the host name corresponding to Internet
host address 10.0.0.6 would pursue a query of the form QTYPE=PTR,
QCLASS=IN, QNAME=6.0.0.10.IN-ADDR.ARPA, and would receive:
6.0.0.10.IN-ADDR.ARPA. PTR MULTICS.MIT.EDU.
Several cautions apply to the use of these services:
- Since the IN-ADDR.ARPA special domain and the normal domain
for a particular host or gateway will be in different zones,
the possibility exists that that the data may be inconsistent.
- Gateways will often have two names in separate domains, only
one of which can be primary.
- Systems that use the domain database to initialize their
routing tables must start with enough gateway information to
guarantee that they can access the appropriate name server.
- The gateway data only reflects the existence of a gateway in a
manner equivalent to the current HOSTS.TXT file. It doesn't
replace the dynamic availability information from GGP or EGP.
Mockapetris [Page 23]
RFC 1035 Domain Implementation and Specification November 1987
3.6. Defining new types, classes, and special namespaces
The previously defined types and classes are the ones in use as of the
date of this memo. New definitions should be expected. This section
makes some recommendations to designers considering additions to the
existing facilities. The mailing list [email protected] is the
forum where general discussion of design issues takes place.
In general, a new type is appropriate when new information is to be
added to the database about an existing object, or we need new data
formats for some totally new object. Designers should attempt to define
types and their RDATA formats that are generally applicable to all
classes, and which avoid duplication of information. New classes are
appropriate when the DNS is to be used for a new protocol, etc which
requires new class-specific data formats, or when a copy of the existing
name space is desired, but a separate management domain is necessary.
New types and classes need mnemonics for master files; the format of the
master files requires that the mnemonics for type and class be disjoint.
TYPE and CLASS values must be a proper subset of QTYPEs and QCLASSes
respectively.
The present system uses multiple RRs to represent multiple values of a
type rather than storing multiple values in the RDATA section of a
single RR. This is less efficient for most applications, but does keep
RRs shorter. The multiple RRs assumption is incorporated in some
experimental work on dynamic update methods.
The present system attempts to minimize the duplication of data in the
database in order to insure consistency. Thus, in order to find the
address of the host for a mail exchange, you map the mail domain name to
a host name, then the host name to addresses, rather than a direct
mapping to host address. This approach is preferred because it avoids
the opportunity for inconsistency.
In defining a new type of data, multiple RR types should not be used to
create an ordering between entries or express different formats for
equivalent bindings, instead this information should be carried in the
body of the RR and a single type used. This policy avoids problems with
caching multiple types and defining QTYPEs to match multiple types.
For example, the original form of mail exchange binding used two RR
types one to represent a "closer" exchange (MD) and one to represent a
"less close" exchange (MF). The difficulty is that the presence of one
RR type in a cache doesn't convey any information about the other
because the query which acquired the cached information might have used
a QTYPE of MF, MD, or MAILA (which matched both). The redesigned
Mockapetris [Page 24]
RFC 1035 Domain Implementation and Specification November 1987
service used a single type (MX) with a "preference" value in the RDATA
section which can order different RRs. However, if any MX RRs are found
in the cache, then all should be there.
4. MESSAGES
4.1. Format
All communications inside of the domain protocol are carried in a single
format called a message. The top level format of message is divided
into 5 sections (some of which are empty in certain cases) shown below:
+---------------------+
| Header |
+---------------------+
| Question | the question for the name server
+---------------------+
| Answer | RRs answering the question
+---------------------+
| Authority | RRs pointing toward an authority
+---------------------+
| Additional | RRs holding additional information
+---------------------+
The header section is always present. The header includes fields that
specify which of the remaining sections are present, and also specify
whether the message is a query or a response, a standard query or some
other opcode, etc.
The names of the sections after the header are derived from their use in
standard queries. The question section contains fields that describe a
question to a name server. These fields are a query type (QTYPE), a
query class (QCLASS), and a query domain name (QNAME). The last three
sections have the same format: a possibly empty list of concatenated
resource records (RRs). The answer section contains RRs that answer the
question; the authority section contains RRs that point toward an
authoritative name server; the additional records section contains RRs
which relate to the query, but are not strictly answers for the
question.
Mockapetris [Page 25]
RFC 1035 Domain Implementation and Specification November 1987
4.1.1. Header section format
The header contains the following fields:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
ID A 16 bit identifier assigned by the program that
generates any kind of query. This identifier is copied
the corresponding reply and can be used by the requester
to match up replies to outstanding queries.
QR A one bit field that specifies whether this message is a
query (0), or a response (1).
OPCODE A four bit field that specifies kind of query in this
message. This value is set by the originator of a query
and copied into the response. The values are:
0 a standard query (QUERY)
1 an inverse query (IQUERY)
2 a server status request (STATUS)
3-15 reserved for future use
AA Authoritative Answer - this bit is valid in responses,
and specifies that the responding name server is an
authority for the domain name in question section.
Note that the contents of the answer section may have
multiple owner names because of aliases. The AA bit
Mockapetris [Page 26]
RFC 1035 Domain Implementation and Specification November 1987
corresponds to the name which matches the query name, or
the first owner name in the answer section.
TC TrunCation - specifies that this message was truncated
due to length greater than that permitted on the
transmission channel.
RD Recursion Desired - this bit may be set in a query and
is copied into the response. If RD is set, it directs
the name server to pursue the query recursively.
Recursive query support is optional.
RA Recursion Available - this be is set or cleared in a
response, and denotes whether recursive query support is
available in the name server.
Z Reserved for future use. Must be zero in all queries
and responses.
RCODE Response code - this 4 bit field is set as part of
responses. The values have the following
interpretation:
0 No error condition
1 Format error - The name server was
unable to interpret the query.
2 Server failure - The name server was
unable to process this query due to a
problem with the name server.
3 Name Error - Meaningful only for
responses from an authoritative name
server, this code signifies that the
domain name referenced in the query does
not exist.
4 Not Implemented - The name server does
not support the requested kind of query.
5 Refused - The name server refuses to
perform the specified operation for
policy reasons. For example, a name
server may not wish to provide the
information to the particular requester,
or a name server may not wish to perform
a particular operation (e.g., zone
Mockapetris [Page 27]
RFC 1035 Domain Implementation and Specification November 1987
transfer) for particular data.
6-15 Reserved for future use.
QDCOUNT an unsigned 16 bit integer specifying the number of
entries in the question section.
ANCOUNT an unsigned 16 bit integer specifying the number of
resource records in the answer section.
NSCOUNT an unsigned 16 bit integer specifying the number of name
server resource records in the authority records
section.
ARCOUNT an unsigned 16 bit integer specifying the number of
resource records in the additional records section.
4.1.2. Question section format
The question section is used to carry the "question" in most queries,
i.e., the parameters that define what is being asked. The section
contains QDCOUNT (usually 1) entries, each of the following format:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ QNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QTYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QCLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
QNAME a domain name represented as a sequence of labels, where
each label consists of a length octet followed by that
number of octets. The domain name terminates with the
zero length octet for the null label of the root. Note
that this field may be an odd number of octets; no
padding is used.
QTYPE a two octet code which specifies the type of the query.
The values for this field include all codes valid for a
TYPE field, together with some more general codes which
can match more than one type of RR.
Mockapetris [Page 28]
RFC 1035 Domain Implementation and Specification November 1987
QCLASS a two octet code that specifies the class of the query.
For example, the QCLASS field is IN for the Internet.
4.1.3. Resource record format
The answer, authority, and additional sections all share the same
format: a variable number of resource records, where the number of
records is specified in the corresponding count field in the header.
Each resource record has the following format:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
/ NAME /
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| CLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TTL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RDLENGTH |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/ RDATA /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
NAME a domain name to which this resource record pertains.
TYPE two octets containing one of the RR type codes. This
field specifies the meaning of the data in the RDATA
field.
CLASS two octets which specify the class of the data in the
RDATA field.
TTL a 32 bit unsigned integer that specifies the time
interval (in seconds) that the resource record may be
cached before it should be discarded. Zero values are
interpreted to mean that the RR can only be used for the
transaction in progress, and should not be cached.
Mockapetris [Page 29]
RFC 1035 Domain Implementation and Specification November 1987
RDLENGTH an unsigned 16 bit integer that specifies the length in
octets of the RDATA field.
RDATA a variable length string of octets that describes the
resource. The format of this information varies
according to the TYPE and CLASS of the resource record.
For example, the if the TYPE is A and the CLASS is IN,
the RDATA field is a 4 octet ARPA Internet address.
4.1.4. Message compression
In order to reduce the size of messages, the domain system utilizes a
compression scheme which eliminates the repetition of domain names in a
message. In this scheme, an entire domain name or a list of labels at
the end of a domain name is replaced with a pointer to a prior occurance
of the same name.
The pointer takes the form of a two octet sequence:
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| 1 1| OFFSET |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
The first two bits are ones. This allows a pointer to be distinguished
from a label, since the label must begin with two zero bits because
labels are restricted to 63 octets or less. (The 10 and 01 combinations
are reserved for future use.) The OFFSET field specifies an offset from
the start of the message (i.e., the first octet of the ID field in the
domain header). A zero offset specifies the first byte of the ID field,
etc.
The compression scheme allows a domain name in a message to be
represented as either:
- a sequence of labels ending in a zero octet
- a pointer
- a sequence of labels ending with a pointer
Pointers can only be used for occurances of a domain name where the
format is not class specific. If this were not the case, a name server
or resolver would be required to know the format of all RRs it handled.
As yet, there are no such cases, but they may occur in future RDATA
formats.
If a domain name is contained in a part of the message subject to a
length field (such as the RDATA section of an RR), and compression is
Mockapetris [Page 30]
RFC 1035 Domain Implementation and Specification November 1987
used, the length of the compressed name is used in the length
calculation, rather than the length of the expanded name.
Programs are free to avoid using pointers in messages they generate,
although this will reduce datagram capacity, and may cause truncation.
However all programs are required to understand arriving messages that
contain pointers.
For example, a datagram might need to use the domain names F.ISI.ARPA,
FOO.F.ISI.ARPA, ARPA, and the root. Ignoring the other fields of the
message, these domain names might be represented as:
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
20 | 1 | F |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
22 | 3 | I |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
24 | S | I |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
26 | 4 | A |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
28 | R | P |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
30 | A | 0 |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
40 | 3 | F |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
42 | O | O |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
44 | 1 1| 20 |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
64 | 1 1| 26 |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
92 | 0 | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
The domain name for F.ISI.ARPA is shown at offset 20. The domain name
FOO.F.ISI.ARPA is shown at offset 40; this definition uses a pointer to
concatenate a label for FOO to the previously defined F.ISI.ARPA. The
domain name ARPA is defined at offset 64 using a pointer to the ARPA
component of the name F.ISI.ARPA at 20; note that this pointer relies on
ARPA being the last label in the string at 20. The root domain name is
Mockapetris [Page 31]
RFC 1035 Domain Implementation and Specification November 1987
defined by a single octet of zeros at 92; the root domain name has no
labels.
4.2. Transport
The DNS assumes that messages will be transmitted as datagrams or in a
byte stream carried by a virtual circuit. While virtual circuits can be
used for any DNS activity, datagrams are preferred for queries due to
their lower overhead and better performance. Zone refresh activities
must use virtual circuits because of the need for reliable transfer.
The Internet supports name server access using TCP [RFC-793] on server
port 53 (decimal) as well as datagram access using UDP [RFC-768] on UDP
port 53 (decimal).
4.2.1. UDP usage
Messages sent using UDP user server port 53 (decimal).
Messages carried by UDP are restricted to 512 bytes (not counting the IP
or UDP headers). Longer messages are truncated and the TC bit is set in
the header.
UDP is not acceptable for zone transfers, but is the recommended method
for standard queries in the Internet. Queries sent using UDP may be
lost, and hence a retransmission strategy is required. Queries or their
responses may be reordered by the network, or by processing in name
servers, so resolvers should not depend on them being returned in order.
The optimal UDP retransmission policy will vary with performance of the
Internet and the needs of the client, but the following are recommended:
- The client should try other servers and server addresses
before repeating a query to a specific address of a server.
- The retransmission interval should be based on prior
statistics if possible. Too aggressive retransmission can
easily slow responses for the community at large. Depending
on how well connected the client is to its expected servers,
the minimum retransmission interval should be 2-5 seconds.
More suggestions on server selection and retransmission policy can be
found in the resolver section of this memo.
4.2.2. TCP usage
Messages sent over TCP connections use server port 53 (decimal). The
message is prefixed with a two byte length field which gives the message
Mockapetris [Page 32]
RFC 1035 Domain Implementation and Specification November 1987
length, excluding the two byte length field. This length field allows
the low-level processing to assemble a complete message before beginning
to parse it.
Several connection management policies are recommended:
- The server should not block other activities waiting for TCP
data.
- The server should support multiple connections.
- The server should assume that the client will initiate
connection closing, and should delay closing its end of the
connection until all outstanding client requests have been
satisfied.
- If the server needs to close a dormant connection to reclaim
resources, it should wait until the connection has been idle
for a period on the order of two minutes. In particular, the
server should allow the SOA and AXFR request sequence (which
begins a refresh operation) to be made on a single connection.
Since the server would be unable to answer queries anyway, a
unilateral close or reset may be used instead of a graceful
close.
5. MASTER FILES
Master files are text files that contain RRs in text form. Since the
contents of a zone can be expressed in the form of a list of RRs a
master file is most often used to define a zone, though it can be used
to list a cache's contents. Hence, this section first discusses the
format of RRs in a master file, and then the special considerations when
a master file is used to create a zone in some name server.
5.1. Format
The format of these files is a sequence of entries. Entries are
predominantly line-oriented, though parentheses can be used to continue
a list of items across a line boundary, and text literals can contain
CRLF within the text. Any combination of tabs and spaces act as a
delimiter between the separate items that make up an entry. The end of
any line in the master file can end with a comment. The comment starts
with a ";" (semicolon).
The following entries are defined:
<blank>[<comment>]
Mockapetris [Page 33]
RFC 1035 Domain Implementation and Specification November 1987
$ORIGIN <domain-name> [<comment>]
$INCLUDE <file-name> [<domain-name>] [<comment>]
<domain-name><rr> [<comment>]
<blank><rr> [<comment>]
Blank lines, with or without comments, are allowed anywhere in the file.
Two control entries are defined: $ORIGIN and $INCLUDE. $ORIGIN is
followed by a domain name, and resets the current origin for relative
domain names to the stated name. $INCLUDE inserts the named file into
the current file, and may optionally specify a domain name that sets the
relative domain name origin for the included file. $INCLUDE may also
have a comment. Note that a $INCLUDE entry never changes the relative
origin of the parent file, regardless of changes to the relative origin
made within the included file.
The last two forms represent RRs. If an entry for an RR begins with a
blank, then the RR is assumed to be owned by the last stated owner. If
an RR entry begins with a <domain-name>, then the owner name is reset.
<rr> contents take one of the following forms:
[<TTL>] [<class>] <type> <RDATA>
[<class>] [<TTL>] <type> <RDATA>
The RR begins with optional TTL and class fields, followed by a type and
RDATA field appropriate to the type and class. Class and type use the
standard mnemonics, TTL is a decimal integer. Omitted class and TTL
values are default to the last explicitly stated values. Since type and
class mnemonics are disjoint, the parse is unique. (Note that this
order is different from the order used in examples and the order used in
the actual RRs; the given order allows easier parsing and defaulting.)
<domain-name>s make up a large share of the data in the master file.
The labels in the domain name are expressed as character strings and
separated by dots. Quoting conventions allow arbitrary characters to be
stored in domain names. Domain names that end in a dot are called
absolute, and are taken as complete. Domain names which do not end in a
dot are called relative; the actual domain name is the concatenation of
the relative part with an origin specified in a $ORIGIN, $INCLUDE, or as
an argument to the master file loading routine. A relative name is an
error when no origin is available.
Mockapetris [Page 34]
RFC 1035 Domain Implementation and Specification November 1987
<character-string> is expressed in one or two ways: as a contiguous set
of characters without interior spaces, or as a string beginning with a "
and ending with a ". Inside a " delimited string any character can
occur, except for a " itself, which must be quoted using \ (back slash).
Because these files are text files several special encodings are
necessary to allow arbitrary data to be loaded. In particular:
of the root.
@ A free standing @ is used to denote the current origin.
\X where X is any character other than a digit (0-9), is
used to quote that character so that its special meaning
does not apply. For example, "\." can be used to place
a dot character in a label.
\DDD where each D is a digit is the octet corresponding to
the decimal number described by DDD. The resulting
octet is assumed to be text and is not checked for
special meaning.
( ) Parentheses are used to group data that crosses a line
boundary. In effect, line terminations are not
recognized within parentheses.
; Semicolon is used to start a comment; the remainder of
the line is ignored.
5.2. Use of master files to define zones
When a master file is used to load a zone, the operation should be
suppressed if any errors are encountered in the master file. The
rationale for this is that a single error can have widespread
consequences. For example, suppose that the RRs defining a delegation
have syntax errors; then the server will return authoritative name
errors for all names in the subzone (except in the case where the
subzone is also present on the server).
Several other validity checks that should be performed in addition to
insuring that the file is syntactically correct:
1. All RRs in the file should have the same class.
2. Exactly one SOA RR should be present at the top of the zone.
3. If delegations are present and glue information is required,
it should be present.
Mockapetris [Page 35]
RFC 1035 Domain Implementation and Specification November 1987
4. Information present outside of the authoritative nodes in the
zone should be glue information, rather than the result of an
origin or similar error.
5.3. Master file example
The following is an example file which might be used to define the
ISI.EDU zone.and is loaded with an origin of ISI.EDU:
@ IN SOA VENERA Action\.domains (
20 ; SERIAL
7200 ; REFRESH
600 ; RETRY
3600000; EXPIRE
60) ; MINIMUM
NS A.ISI.EDU.
NS VENERA
NS VAXA
MX 10 VENERA
MX 20 VAXA
A A 26.3.0.103
VENERA A 10.1.0.52
A 128.9.0.32
VAXA A 10.2.0.27
A 128.9.0.33
$INCLUDE <SUBSYS>ISI-MAILBOXES.TXT
Where the file <SUBSYS>ISI-MAILBOXES.TXT is:
MOE MB A.ISI.EDU.
LARRY MB A.ISI.EDU.
CURLEY MB A.ISI.EDU.
STOOGES MG MOE
MG LARRY
MG CURLEY
Note the use of the \ character in the SOA RR to specify the responsible
person mailbox "[email protected]".
Mockapetris [Page 36]
RFC 1035 Domain Implementation and Specification November 1987
6. NAME SERVER IMPLEMENTATION
6.1. Architecture
The optimal structure for the name server will depend on the host
operating system and whether the name server is integrated with resolver
operations, either by supporting recursive service, or by sharing its
database with a resolver. This section discusses implementation
considerations for a name server which shares a database with a
resolver, but most of these concerns are present in any name server.
6.1.1. Control
A name server must employ multiple concurrent activities, whether they
are implemented as separate tasks in the host's OS or multiplexing
inside a single name server program. It is simply not acceptable for a
name server to block the service of UDP requests while it waits for TCP
data for refreshing or query activities. Similarly, a name server
should not attempt to provide recursive service without processing such
requests in parallel, though it may choose to serialize requests from a
single client, or to regard identical requests from the same client as
duplicates. A name server should not substantially delay requests while
it reloads a zone from master files or while it incorporates a newly
refreshed zone into its database.
6.1.2. Database
While name server implementations are free to use any internal data
structures they choose, the suggested structure consists of three major
parts:
- A "catalog" data structure which lists the zones available to
this server, and a "pointer" to the zone data structure. The
main purpose of this structure is to find the nearest ancestor
zone, if any, for arriving standard queries.
- Separate data structures for each of the zones held by the
name server.
- A data structure for cached data. (or perhaps separate caches
for different classes)
All of these data structures can be implemented an identical tree
structure format, with different data chained off the nodes in different
parts: in the catalog the data is pointers to zones, while in the zone
and cache data structures, the data will be RRs. In designing the tree
framework the designer should recognize that query processing will need
to traverse the tree using case-insensitive label comparisons; and that
Mockapetris [Page 37]
RFC 1035 Domain Implementation and Specification November 1987
in real data, a few nodes have a very high branching factor (100-1000 or
more), but the vast majority have a very low branching factor (0-1).
One way to solve the case problem is to store the labels for each node
in two pieces: a standardized-case representation of the label where all
ASCII characters are in a single case, together with a bit mask that
denotes which characters are actually of a different case. The
branching factor diversity can be handled using a simple linked list for
a node until the branching factor exceeds some threshold, and
transitioning to a hash structure after the threshold is exceeded. In
any case, hash structures used to store tree sections must insure that
hash functions and procedures preserve the casing conventions of the
DNS.
The use of separate structures for the different parts of the database
is motivated by several factors:
- The catalog structure can be an almost static structure that
need change only when the system administrator changes the
zones supported by the server. This structure can also be
used to store parameters used to control refreshing
activities.
- The individual data structures for zones allow a zone to be
replaced simply by changing a pointer in the catalog. Zone
refresh operations can build a new structure and, when
complete, splice it into the database via a simple pointer
replacement. It is very important that when a zone is
refreshed, queries should not use old and new data
simultaneously.
- With the proper search procedures, authoritative data in zones
will always "hide", and hence take precedence over, cached
data.
- Errors in zone definitions that cause overlapping zones, etc.,
may cause erroneous responses to queries, but problem
determination is simplified, and the contents of one "bad"
zone can't corrupt another.
- Since the cache is most frequently updated, it is most
vulnerable to corruption during system restarts. It can also
become full of expired RR data. In either case, it can easily
be discarded without disturbing zone data.
A major aspect of database design is selecting a structure which allows
the name server to deal with crashes of the name server's host. State
information which a name server should save across system crashes
Mockapetris [Page 38]
RFC 1035 Domain Implementation and Specification November 1987
includes the catalog structure (including the state of refreshing for
each zone) and the zone data itself.
6.1.3. Time
Both the TTL data for RRs and the timing data for refreshing activities
depends on 32 bit timers in units of seconds. Inside the database,
refresh timers and TTLs for cached data conceptually "count down", while
data in the zone stays with constant TTLs.
A recommended implementation strategy is to store time in two ways: as
a relative increment and as an absolute time. One way to do this is to
use positive 32 bit numbers for one type and negative numbers for the
other. The RRs in zones use relative times; the refresh timers and
cache data use absolute times. Absolute numbers are taken with respect
to some known origin and converted to relative values when placed in the
response to a query. When an absolute TTL is negative after conversion
to relative, then the data is expired and should be ignored.
6.2. Standard query processing
The major algorithm for standard query processing is presented in
[RFC-1034].
When processing queries with QCLASS=*, or some other QCLASS which
matches multiple classes, the response should never be authoritative
unless the server can guarantee that the response covers all classes.
When composing a response, RRs which are to be inserted in the
additional section, but duplicate RRs in the answer or authority
sections, may be omitted from the additional section.
When a response is so long that truncation is required, the truncation
should start at the end of the response and work forward in the
datagram. Thus if there is any data for the authority section, the
answer section is guaranteed to be unique.
The MINIMUM value in the SOA should be used to set a floor on the TTL of
data distributed from a zone. This floor function should be done when
the data is copied into a response. This will allow future dynamic
update protocols to change the SOA MINIMUM field without ambiguous
semantics.
6.3. Zone refresh and reload processing
In spite of a server's best efforts, it may be unable to load zone data
from a master file due to syntax errors, etc., or be unable to refresh a
zone within the its expiration parameter. In this case, the name server
Mockapetris [Page 39]
RFC 1035 Domain Implementation and Specification November 1987
should answer queries as if it were not supposed to possess the zone.
If a master is sending a zone out via AXFR, and a new version is created
during the transfer, the master should continue to send the old version
if possible. In any case, it should never send part of one version and
part of another. If completion is not possible, the master should reset
the connection on which the zone transfer is taking place.
6.4. Inverse queries (Optional)
Inverse queries are an optional part of the DNS. Name servers are not
required to support any form of inverse queries. If a name server
receives an inverse query that it does not support, it returns an error
response with the "Not Implemented" error set in the header. While
inverse query support is optional, all name servers must be at least
able to return the error response.
6.4.1. The contents of inverse queries and responses Inverse
queries reverse the mappings performed by standard query operations;
while a standard query maps a domain name to a resource, an inverse
query maps a resource to a domain name. For example, a standard query
might bind a domain name to a host address; the corresponding inverse
query binds the host address to a domain name.
Inverse queries take the form of a single RR in the answer section of
the message, with an empty question section. The owner name of the
query RR and its TTL are not significant. The response carries
questions in the question section which identify all names possessing
the query RR WHICH THE NAME SERVER KNOWS. Since no name server knows
about all of the domain name space, the response can never be assumed to
be complete. Thus inverse queries are primarily useful for database
management and debugging activities. Inverse queries are NOT an
acceptable method of mapping host addresses to host names; use the IN-
ADDR.ARPA domain instead.
Where possible, name servers should provide case-insensitive comparisons
for inverse queries. Thus an inverse query asking for an MX RR of
"Venera.isi.edu" should get the same response as a query for
"VENERA.ISI.EDU"; an inverse query for HINFO RR "IBM-PC UNIX" should
produce the same result as an inverse query for "IBM-pc unix". However,
this cannot be guaranteed because name servers may possess RRs that
contain character strings but the name server does not know that the
data is character.
When a name server processes an inverse query, it either returns:
1. zero, one, or multiple domain names for the specified
resource as QNAMEs in the question section
Mockapetris [Page 40]
RFC 1035 Domain Implementation and Specification November 1987
2. an error code indicating that the name server doesn't support
inverse mapping of the specified resource type.
When the response to an inverse query contains one or more QNAMEs, the
owner name and TTL of the RR in the answer section which defines the
inverse query is modified to exactly match an RR found at the first
QNAME.
RRs returned in the inverse queries cannot be cached using the same
mechanism as is used for the replies to standard queries. One reason
for this is that a name might have multiple RRs of the same type, and
only one would appear. For example, an inverse query for a single
address of a multiply homed host might create the impression that only
one address existed.
6.4.2. Inverse query and response example The overall structure
of an inverse query for retrieving the domain name that corresponds to
Internet address 10.1.0.52 is shown below:
+-----------------------------------------+
Header | OPCODE=IQUERY, ID=997 |
+-----------------------------------------+
Question | <empty> |
+-----------------------------------------+
Answer | <anyname> A IN 10.1.0.52 |
+-----------------------------------------+
Authority | <empty> |
+-----------------------------------------+
Additional | <empty> |
+-----------------------------------------+
This query asks for a question whose answer is the Internet style
address 10.1.0.52. Since the owner name is not known, any domain name
can be used as a placeholder (and is ignored). A single octet of zero,
signifying the root, is usually used because it minimizes the length of
the message. The TTL of the RR is not significant. The response to
this query might be:
Mockapetris [Page 41]
RFC 1035 Domain Implementation and Specification November 1987
+-----------------------------------------+
Header | OPCODE=RESPONSE, ID=997 |
+-----------------------------------------+
Question |QTYPE=A, QCLASS=IN, QNAME=VENERA.ISI.EDU |
+-----------------------------------------+
Answer | VENERA.ISI.EDU A IN 10.1.0.52 |
+-----------------------------------------+
Authority | <empty> |
+-----------------------------------------+
Additional | <empty> |
+-----------------------------------------+
Note that the QTYPE in a response to an inverse query is the same as the
TYPE field in the answer section of the inverse query. Responses to
inverse queries may contain multiple questions when the inverse is not
unique. If the question section in the response is not empty, then the
RR in the answer section is modified to correspond to be an exact copy
of an RR at the first QNAME.
6.4.3. Inverse query processing
Name servers that support inverse queries can support these operations
through exhaustive searches of their databases, but this becomes
impractical as the size of the database increases. An alternative
approach is to invert the database according to the search key.
For name servers that support multiple zones and a large amount of data,
the recommended approach is separate inversions for each zone. When a
particular zone is changed during a refresh, only its inversions need to
be redone.
Support for transfer of this type of inversion may be included in future
versions of the domain system, but is not supported in this version.
6.5. Completion queries and responses
The optional completion services described in RFC-882 and RFC-883 have
been deleted. Redesigned services may become available in the future.
Mockapetris [Page 42]
RFC 1035 Domain Implementation and Specification November 1987
7. RESOLVER IMPLEMENTATION
The top levels of the recommended resolver algorithm are discussed in
[RFC-1034]. This section discusses implementation details assuming the
database structure suggested in the name server implementation section
of this memo.
7.1. Transforming a user request into a query
The first step a resolver takes is to transform the client's request,
stated in a format suitable to the local OS, into a search specification
for RRs at a specific name which match a specific QTYPE and QCLASS.
Where possible, the QTYPE and QCLASS should correspond to a single type
and a single class, because this makes the use of cached data much
simpler. The reason for this is that the presence of data of one type
in a cache doesn't confirm the existence or non-existence of data of
other types, hence the only way to be sure is to consult an
authoritative source. If QCLASS=* is used, then authoritative answers
won't be available.
Since a resolver must be able to multiplex multiple requests if it is to
perform its function efficiently, each pending request is usually
represented in some block of state information. This state block will
typically contain:
- A timestamp indicating the time the request began.
The timestamp is used to decide whether RRs in the database
can be used or are out of date. This timestamp uses the
absolute time format previously discussed for RR storage in
zones and caches. Note that when an RRs TTL indicates a
relative time, the RR must be timely, since it is part of a
zone. When the RR has an absolute time, it is part of a
cache, and the TTL of the RR is compared against the timestamp
for the start of the request.
Note that using the timestamp is superior to using a current
time, since it allows RRs with TTLs of zero to be entered in
the cache in the usual manner, but still used by the current
request, even after intervals of many seconds due to system
load, query retransmission timeouts, etc.
- Some sort of parameters to limit the amount of work which will
be performed for this request.
The amount of work which a resolver will do in response to a
client request must be limited to guard against errors in the
database, such as circular CNAME references, and operational
problems, such as network partition which prevents the
Mockapetris [Page 43]
RFC 1035 Domain Implementation and Specification November 1987
resolver from accessing the name servers it needs. While
local limits on the number of times a resolver will retransmit
a particular query to a particular name server address are
essential, the resolver should have a global per-request
counter to limit work on a single request. The counter should
be set to some initial value and decremented whenever the
resolver performs any action (retransmission timeout,
retransmission, etc.) If the counter passes zero, the request
is terminated with a temporary error.
Note that if the resolver structure allows one request to
start others in parallel, such as when the need to access a
name server for one request causes a parallel resolve for the
name server's addresses, the spawned request should be started
with a lower counter. This prevents circular references in
the database from starting a chain reaction of resolver
activity.
- The SLIST data structure discussed in [RFC-1034].
This structure keeps track of the state of a request if it
must wait for answers from foreign name servers.
7.2. Sending the queries
As described in [RFC-1034], the basic task of the resolver is to
formulate a query which will answer the client's request and direct that
query to name servers which can provide the information. The resolver
will usually only have very strong hints about which servers to ask, in
the form of NS RRs, and may have to revise the query, in response to
CNAMEs, or revise the set of name servers the resolver is asking, in
response to delegation responses which point the resolver to name
servers closer to the desired information. In addition to the
information requested by the client, the resolver may have to call upon
its own services to determine the address of name servers it wishes to
contact.
In any case, the model used in this memo assumes that the resolver is
multiplexing attention between multiple requests, some from the client,
and some internally generated. Each request is represented by some
state information, and the desired behavior is that the resolver
transmit queries to name servers in a way that maximizes the probability
that the request is answered, minimizes the time that the request takes,
and avoids excessive transmissions. The key algorithm uses the state
information of the request to select the next name server address to
query, and also computes a timeout which will cause the next action
should a response not arrive. The next action will usually be a
transmission to some other server, but may be a temporary error to the
Mockapetris [Page 44]
RFC 1035 Domain Implementation and Specification November 1987
client.
The resolver always starts with a list of server names to query (SLIST).
This list will be all NS RRs which correspond to the nearest ancestor
zone that the resolver knows about. To avoid startup problems, the
resolver should have a set of default servers which it will ask should
it have no current NS RRs which are appropriate. The resolver then adds
to SLIST all of the known addresses for the name servers, and may start
parallel requests to acquire the addresses of the servers when the
resolver has the name, but no addresses, for the name servers.
To complete initialization of SLIST, the resolver attaches whatever
history information it has to the each address in SLIST. This will
usually consist of some sort of weighted averages for the response time
of the address, and the batting average of the address (i.e., how often
the address responded at all to the request). Note that this
information should be kept on a per address basis, rather than on a per
name server basis, because the response time and batting average of a
particular server may vary considerably from address to address. Note
also that this information is actually specific to a resolver address /
server address pair, so a resolver with multiple addresses may wish to
keep separate histories for each of its addresses. Part of this step
must deal with addresses which have no such history; in this case an
expected round trip time of 5-10 seconds should be the worst case, with
lower estimates for the same local network, etc.
Note that whenever a delegation is followed, the resolver algorithm
reinitializes SLIST.
The information establishes a partial ranking of the available name
server addresses. Each time an address is chosen and the state should
be altered to prevent its selection again until all other addresses have
been tried. The timeout for each transmission should be 50-100% greater
than the average predicted value to allow for variance in response.
Some fine points:
- The resolver may encounter a situation where no addresses are
available for any of the name servers named in SLIST, and
where the servers in the list are precisely those which would
normally be used to look up their own addresses. This
situation typically occurs when the glue address RRs have a
smaller TTL than the NS RRs marking delegation, or when the
resolver caches the result of a NS search. The resolver
should detect this condition and restart the search at the
next ancestor zone, or alternatively at the root.
Mockapetris [Page 45]
RFC 1035 Domain Implementation and Specification November 1987
- If a resolver gets a server error or other bizarre response
from a name server, it should remove it from SLIST, and may
wish to schedule an immediate transmission to the next
candidate server address.
7.3. Processing responses
The first step in processing arriving response datagrams is to parse the
response. This procedure should include:
- Check the header for reasonableness. Discard datagrams which
are queries when responses are expected.
- Parse the sections of the message, and insure that all RRs are
correctly formatted.
- As an optional step, check the TTLs of arriving data looking
for RRs with excessively long TTLs. If a RR has an
excessively long TTL, say greater than 1 week, either discard
the whole response, or limit all TTLs in the response to 1
week.
The next step is to match the response to a current resolver request.
The recommended strategy is to do a preliminary matching using the ID
field in the domain header, and then to verify that the question section
corresponds to the information currently desired. This requires that
the transmission algorithm devote several bits of the domain ID field to
a request identifier of some sort. This step has several fine points:
- Some name servers send their responses from different
addresses than the one used to receive the query. That is, a
resolver cannot rely that a response will come from the same
address which it sent the corresponding query to. This name
server bug is typically encountered in UNIX systems.
- If the resolver retransmits a particular request to a name
server it should be able to use a response from any of the
transmissions. However, if it is using the response to sample
the round trip time to access the name server, it must be able
to determine which transmission matches the response (and keep
transmission times for each outgoing message), or only
calculate round trip times based on initial transmissions.
- A name server will occasionally not have a current copy of a
zone which it should have according to some NS RRs. The
resolver should simply remove the name server from the current
SLIST, and continue.
Mockapetris [Page 46]
RFC 1035 Domain Implementation and Specification November 1987
7.4. Using the cache
In general, we expect a resolver to cache all data which it receives in
responses since it may be useful in answering future client requests.
However, there are several types of data which should not be cached:
- When several RRs of the same type are available for a
particular owner name, the resolver should either cache them
all or none at all. When a response is truncated, and a
resolver doesn't know whether it has a complete set, it should
not cache a possibly partial set of RRs.
- Cached data should never be used in preference to
authoritative data, so if caching would cause this to happen
the data should not be cached.
- The results of an inverse query should not be cached.
- The results of standard queries where the QNAME contains "*"
labels if the data might be used to construct wildcards. The
reason is that the cache does not necessarily contain existing
RRs or zone boundary information which is necessary to
restrict the application of the wildcard RRs.
- RR data in responses of dubious reliability. When a resolver
receives unsolicited responses or RR data other than that
requested, it should discard it without caching it. The basic
implication is that all sanity checks on a packet should be
performed before any of it is cached.
In a similar vein, when a resolver has a set of RRs for some name in a
response, and wants to cache the RRs, it should check its cache for
already existing RRs. Depending on the circumstances, either the data
in the response or the cache is preferred, but the two should never be
combined. If the data in the response is from authoritative data in the
answer section, it is always preferred.
8. MAIL SUPPORT
The domain system defines a standard for mapping mailboxes into domain
names, and two methods for using the mailbox information to derive mail
routing information. The first method is called mail exchange binding
and the other method is mailbox binding. The mailbox encoding standard
and mail exchange binding are part of the DNS official protocol, and are
the recommended method for mail routing in the Internet. Mailbox
binding is an experimental feature which is still under development and
subject to change.
Mockapetris [Page 47]
RFC 1035 Domain Implementation and Specification November 1987
The mailbox encoding standard assumes a mailbox name of the form
"<local-part>@<mail-domain>". While the syntax allowed in each of these
sections varies substantially between the various mail internets, the
preferred syntax for the ARPA Internet is given in [RFC-822].
The DNS encodes the <local-part> as a single label, and encodes the
<mail-domain> as a domain name. The single label from the <local-part>
is prefaced to the domain name from <mail-domain> to form the domain
name corresponding to the mailbox. Thus the mailbox HOSTMASTER@SRI-
NIC.ARPA is mapped into the domain name HOSTMASTER.SRI-NIC.ARPA. If the
<local-part> contains dots or other special characters, its
representation in a master file will require the use of backslash
quoting to ensure that the domain name is properly encoded. For
example, the mailbox [email protected] would be represented as
Action\.domains.ISI.EDU.
8.1. Mail exchange binding
Mail exchange binding uses the <mail-domain> part of a mailbox
specification to determine where mail should be sent. The <local-part>
is not even consulted. [RFC-974] specifies this method in detail, and
should be consulted before attempting to use mail exchange support.
One of the advantages of this method is that it decouples mail
destination naming from the hosts used to support mail service, at the
cost of another layer of indirection in the lookup function. However,
the addition layer should eliminate the need for complicated "%", "!",
etc encodings in <local-part>.
The essence of the method is that the <mail-domain> is used as a domain
name to locate type MX RRs which list hosts willing to accept mail for
<mail-domain>, together with preference values which rank the hosts
according to an order specified by the administrators for <mail-domain>.
In this memo, the <mail-domain> ISI.EDU is used in examples, together
with the hosts VENERA.ISI.EDU and VAXA.ISI.EDU as mail exchanges for
ISI.EDU. If a mailer had a message for [email protected], it would
route it by looking up MX RRs for ISI.EDU. The MX RRs at ISI.EDU name
VENERA.ISI.EDU and VAXA.ISI.EDU, and type A queries can find the host
addresses.
8.2. Mailbox binding (Experimental)
In mailbox binding, the mailer uses the entire mail destination
specification to construct a domain name. The encoded domain name for
the mailbox is used as the QNAME field in a QTYPE=MAILB query.
Several outcomes are possible for this query:
Mockapetris [Page 48]
RFC 1035 Domain Implementation and Specification November 1987
1. The query can return a name error indicating that the mailbox
does not exist as a domain name.
In the long term, this would indicate that the specified
mailbox doesn't exist. However, until the use of mailbox
binding is universal, this error condition should be
interpreted to mean that the organization identified by the
global part does not support mailbox binding. The
appropriate procedure is to revert to exchange binding at
this point.
2. The query can return a Mail Rename (MR) RR.
The MR RR carries new mailbox specification in its RDATA
field. The mailer should replace the old mailbox with the
new one and retry the operation.
3. The query can return a MB RR.
The MB RR carries a domain name for a host in its RDATA
field. The mailer should deliver the message to that host
via whatever protocol is applicable, e.g., b,SMTP.
4. The query can return one or more Mail Group (MG) RRs.
This condition means that the mailbox was actually a mailing
list or mail group, rather than a single mailbox. Each MG RR
has a RDATA field that identifies a mailbox that is a member
of the group. The mailer should deliver a copy of the
message to each member.
5. The query can return a MB RR as well as one or more MG RRs.
This condition means the the mailbox was actually a mailing
list. The mailer can either deliver the message to the host
specified by the MB RR, which will in turn do the delivery to
all members, or the mailer can use the MG RRs to do the
expansion itself.
In any of these cases, the response may include a Mail Information
(MINFO) RR. This RR is usually associated with a mail group, but is
legal with a MB. The MINFO RR identifies two mailboxes. One of these
identifies a responsible person for the original mailbox name. This
mailbox should be used for requests to be added to a mail group, etc.
The second mailbox name in the MINFO RR identifies a mailbox that should
receive error messages for mail failures. This is particularly
appropriate for mailing lists when errors in member names should be
reported to a person other than the one who sends a message to the list.
Mockapetris [Page 49]
RFC 1035 Domain Implementation and Specification November 1987
New fields may be added to this RR in the future.
9. REFERENCES and BIBLIOGRAPHY
[Dyer 87] S. Dyer, F. Hsu, "Hesiod", Project Athena
Technical Plan - Name Service, April 1987, version 1.9.
Describes the fundamentals of the Hesiod name service.
[IEN-116] J. Postel, "Internet Name Server", IEN-116,
USC/Information Sciences Institute, August 1979.
A name service obsoleted by the Domain Name System, but
still in use.
[Quarterman 86] J. Quarterman, and J. Hoskins, "Notable Computer Networks",
Communications of the ACM, October 1986, volume 29, number
10.
[RFC-742] K. Harrenstien, "NAME/FINGER", RFC-742, Network
Information Center, SRI International, December 1977.
[RFC-768] J. Postel, "User Datagram Protocol", RFC-768,
USC/Information Sciences Institute, August 1980.
[RFC-793] J. Postel, "Transmission Control Protocol", RFC-793,
USC/Information Sciences Institute, September 1981.
[RFC-799] D. Mills, "Internet Name Domains", RFC-799, COMSAT,
September 1981.
Suggests introduction of a hierarchy in place of a flat
name space for the Internet.
[RFC-805] J. Postel, "Computer Mail Meeting Notes", RFC-805,
USC/Information Sciences Institute, February 1982.
[RFC-810] E. Feinler, K. Harrenstien, Z. Su, and V. White, "DOD
Internet Host Table Specification", RFC-810, Network
Information Center, SRI International, March 1982.
Obsolete. See RFC-952.
[RFC-811] K. Harrenstien, V. White, and E. Feinler, "Hostnames
Server", RFC-811, Network Information Center, SRI
International, March 1982.
Mockapetris [Page 50]
RFC 1035 Domain Implementation and Specification November 1987
Obsolete. See RFC-953.
[RFC-812] K. Harrenstien, and V. White, "NICNAME/WHOIS", RFC-812,
Network Information Center, SRI International, March
1982.
[RFC-819] Z. Su, and J. Postel, "The Domain Naming Convention for
Internet User Applications", RFC-819, Network
Information Center, SRI International, August 1982.
Early thoughts on the design of the domain system.
Current implementation is completely different.
[RFC-821] J. Postel, "Simple Mail Transfer Protocol", RFC-821,
USC/Information Sciences Institute, August 1980.
[RFC-830] Z. Su, "A Distributed System for Internet Name Service",
RFC-830, Network Information Center, SRI International,
October 1982.
Early thoughts on the design of the domain system.
Current implementation is completely different.
[RFC-882] P. Mockapetris, "Domain names - Concepts and
Facilities," RFC-882, USC/Information Sciences
Institute, November 1983.
Superceeded by this memo.
[RFC-883] P. Mockapetris, "Domain names - Implementation and
Specification," RFC-883, USC/Information Sciences
Institute, November 1983.
Superceeded by this memo.
[RFC-920] J. Postel and J. Reynolds, "Domain Requirements",
RFC-920, USC/Information Sciences Institute,
October 1984.
Explains the naming scheme for top level domains.
[RFC-952] K. Harrenstien, M. Stahl, E. Feinler, "DoD Internet Host
Table Specification", RFC-952, SRI, October 1985.
Specifies the format of HOSTS.TXT, the host/address
table replaced by the DNS.
Mockapetris [Page 51]
RFC 1035 Domain Implementation and Specification November 1987
[RFC-953] K. Harrenstien, M. Stahl, E. Feinler, "HOSTNAME Server",
RFC-953, SRI, October 1985.
This RFC contains the official specification of the
hostname server protocol, which is obsoleted by the DNS.
This TCP based protocol accesses information stored in
the RFC-952 format, and is used to obtain copies of the
host table.
[RFC-973] P. Mockapetris, "Domain System Changes and
Observations", RFC-973, USC/Information Sciences
Institute, January 1986.
Describes changes to RFC-882 and RFC-883 and reasons for
them.
[RFC-974] C. Partridge, "Mail routing and the domain system",
RFC-974, CSNET CIC BBN Labs, January 1986.
Describes the transition from HOSTS.TXT based mail
addressing to the more powerful MX system used with the
domain system.
[RFC-1001] NetBIOS Working Group, "Protocol standard for a NetBIOS
service on a TCP/UDP transport: Concepts and Methods",
RFC-1001, March 1987.
This RFC and RFC-1002 are a preliminary design for
NETBIOS on top of TCP/IP which proposes to base NetBIOS
name service on top of the DNS.
[RFC-1002] NetBIOS Working Group, "Protocol standard for a NetBIOS
service on a TCP/UDP transport: Detailed
Specifications", RFC-1002, March 1987.
[RFC-1010] J. Reynolds, and J. Postel, "Assigned Numbers", RFC-1010,
USC/Information Sciences Institute, May 1987.
Contains socket numbers and mnemonics for host names,
operating systems, etc.
[RFC-1031] W. Lazear, "MILNET Name Domain Transition", RFC-1031,
November 1987.
Describes a plan for converting the MILNET to the DNS.
[RFC-1032] M. Stahl, "Establishing a Domain - Guidelines for
Administrators", RFC-1032, November 1987.
Mockapetris [Page 52]
RFC 1035 Domain Implementation and Specification November 1987
Describes the registration policies used by the NIC to
administer the top level domains and delegate subzones.
[RFC-1033] M. Lottor, "Domain Administrators Operations Guide",
RFC-1033, November 1987.
A cookbook for domain administrators.
[Solomon 82] M. Solomon, L. Landweber, and D. Neuhengen, "The CSNET
Name Server", Computer Networks, vol 6, nr 3, July 1982.
Describes a name service for CSNET which is independent
from the DNS and DNS use in the CSNET.
Mockapetris [Page 53]
RFC 1035 Domain Implementation and Specification November 1987
Index
* 13
; 33, 35
<character-string> 35
<domain-name> 34
@ 35
\ 35
A 12
Byte order 8
CH 13
Character case 9
CLASS 11
CNAME 12
Completion 42
CS 13
Hesiod 13
HINFO 12
HS 13
IN 13
IN-ADDR.ARPA domain 22
Inverse queries 40
Mailbox names 47
MB 12
MD 12
MF 12
MG 12
MINFO 12
MINIMUM 20
MR 12
MX 12
NS 12
NULL 12
Port numbers 32
Primary server 5
PTR 12, 18
Mockapetris [Page 54]
RFC 1035 Domain Implementation and Specification November 1987
QCLASS 13
QTYPE 12
RDATA 12
RDLENGTH 11
Secondary server 5
SOA 12
Stub resolvers 7
TCP 32
TXT 12
TYPE 11
UDP 32
WKS 12
Mockapetris [Page 55]
| 122,549 | 3,078 | jart/cosmopolitan | false |
cosmopolitan/libc/dns/hstrerror.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/dns/ent.h"
/**
* Turns `h_errno` value into string.
*/
const char *hstrerror(int err) {
switch (err) {
case HOST_NOT_FOUND:
return "HOST_NOT_FOUND";
case TRY_AGAIN:
return "TRY_AGAIN";
case NO_RECOVERY:
return "NO_RECOVERY";
case NO_DATA:
return "NO_DATA";
default:
return "UNKNOWN";
}
}
| 2,196 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/crt/crt.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 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/macros.internal.h"
#include "libc/notice.inc"
#include "libc/runtime/internal.h"
.section .start,"ax",@progbits
// System Five userspace program entrypoint.
//
// @param rsp is [n,argvâ..argvâââ,0,envpâ..,0,auxvâ..,0,..]
// @note FreeBSD is special (see freebsd/lib/csu/amd64/...)
// @note NetBSD will only zero the call-clobbered registers
// @note ape.S and ape-loader both set RCX to XNU on Darwin
// @noreturn
_start:
#ifdef __x86_64__
#if SupportsXnu()
// Hack for detecting M1 Rosetta environment.
// https://github.com/jart/cosmopolitan/issues/429#issuecomment-1166704377
cmp $-1,%ebx
jne 0f
cmp $+1,%edx
jne 0f
mov $_HOSTXNU,%cl
xor %edi,%edi
0:
#endif
#if SupportsFreebsd()
// detect free besiyata dishmaya
test %rdi,%rdi
cmovnz %rdi,%rsp
jz 0f
movb $_HOSTFREEBSD,%cl
0:
#endif
// set operating system when already detected
mov %cl,__hostos(%rip)
// get startup timestamp as early as possible
// its used by --strace flag and kprintf() %T
rdtsc
ezlea kStartTsc,bx
mov %eax,(%rbx)
mov %edx,4(%rbx)
// translates arguments from old stack abi
mov (%rsp),%ebx // argc
lea 8(%rsp),%rsi // argv
lea 16(%rsp,%rbx,8),%rdx // envp
mov %rsp,__oldstack(%rip)
// setup a stack frame
// align stack to GetStackSize() so GetStackAddr() is fast
.weak ape_stack_memsz
mov $ape_stack_memsz,%r8d
mov $ape_stack_align,%r9d
cmp $_HOSTMETAL,%cl
cmove %r9d,%r8d
neg %r8
and %r8,%rsp
xor %ebp,%ebp
// bofram 9f
// make win32 imps noop
.weak ape_idata_iat
.weak ape_idata_iatend
ezlea _missingno,ax
ezlea ape_idata_iat,di
ezlea ape_idata_iatend,cx
sub %rdi,%rcx
shr $3,%ecx
rep stosq
// scan through environment varis
// find start of auxiliary values
xor %eax,%eax
or $-1,%ecx
mov %rdx,%rdi
repnz scasq
mov %rdi,%rcx // auxv
#if SupportsXnu()
// xnu doesn't have auxiliary values
testb IsXnu()
jz 1f // polyfill xnu auxv
push $0 // auxv[1][1]=0
push $0 // auxv[1][0]=0
mov %rsp,%rcx // auxv
#endif
// enter cosmopolitan runtime
1: mov %ebx,%edi
call cosmo
9: .unreachable
////////////////////////////////////////////////////////////////////////////////
#elif defined(__aarch64__)
// save original stack pointer
// this is the first argument to cosmo() below
mov x0,sp
// align stack to GetStackSize() so GetStackAddr() is fast
mov x1,sp
.weak ape_stack_memsz
ldr x2,=ape_stack_memsz
neg x2,x2
and x1,x2,x1
mov sp,x1
// setup backtraces
mov x29,#0
// second arg shall be struct Syslib passed by ape-m1.c
// used to talk to apple's authoritarian libraries
// should be set to zero on other platforms
mov x1,x15
// switch to c code
bl cosmo
.unreachable
////////////////////////////////////////////////////////////////////////////////
#else
#error "architecture unsupported"
#endif /* __x86_64__ */
.endfn _start,weak,hidden
| 4,687 | 148 | jart/cosmopolitan | false |
cosmopolitan/libc/crt/crt.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ââââââââââââââââââââââââ
#
# SYNOPSIS
#
# Cosmopolitan C Runtime.
#
# OVERVIEW
#
# This is a special object library defining the Cosmopolitan SysV
# userspace runtime entrypoint, i.e. _start(). The $(CRT) argument
# should come first in the link order when building ELF binaries;
# becauseo it's the lowest level function; it wraps main(); and it
# decides which runtime support libraries get schlepped into builds.
#
# Please note that, when building an αcϵαlly pδrÏαblε εxεcµÏαblε,
# lower-level entrypoints exist and as such, $(CRT) will generally
# come second in link-order after $(APE).
PKGS += CRT
CRT_ARTIFACTS += CRT
CRT = o/$(MODE)/libc/crt/crt.o
CRT_FILES = libc/crt/crt.S
CRT_SRCS = libc/crt/crt.S
CRT_OBJS = o/$(MODE)/libc/crt/crt.o
$(CRT_OBJS): $(BUILD_FILES) libc/crt/crt.mk
# these assembly files are safe to build on aarch64
o/$(MODE)/libc/crt/crt.o: libc/crt/crt.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
.PHONY: o/$(MODE)/libc/crt
o/$(MODE)/libc/crt: $(CRT)
| 1,214 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_setcanceltype.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/errno.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
/**
* Sets cancellation strategy.
*
* @param type may be one of:
* - `PTHREAD_CANCEL_DEFERRED` (default)
* - `PTHREAD_CANCEL_ASYNCHRONOUS`
* @param oldtype optionally receives old value
* @return 0 on success, or errno on error
* @raise ENOTSUP on Windows if asynchronous
* @raise EINVAL if `type` has bad value
* @see pthread_cancel() for docs
*/
errno_t pthread_setcanceltype(int type, int *oldtype) {
struct PosixThread *pt;
switch (type) {
case PTHREAD_CANCEL_ASYNCHRONOUS:
if (IsWindows()) {
return ENOTSUP;
}
// fallthrough
case PTHREAD_CANCEL_DEFERRED:
pt = (struct PosixThread *)__get_tls()->tib_pthread;
if (oldtype) {
if (pt->flags & PT_ASYNC) {
*oldtype = PTHREAD_CANCEL_ASYNCHRONOUS;
} else {
*oldtype = PTHREAD_CANCEL_DEFERRED;
}
}
if (type == PTHREAD_CANCEL_DEFERRED) {
pt->flags &= ~PT_ASYNC;
} else {
pt->flags |= PT_ASYNC;
}
return 0;
default:
return EINVAL;
}
}
| 3,041 | 64 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cond_signal.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/thread/thread.h"
#include "third_party/nsync/cv.h"
/**
* Wakes at least one thread waiting on condition, e.g.
*
* pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
* pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
* // ...
* pthread_mutex_lock(&lock);
* pthread_cond_signal(&cond, &lock);
* pthread_mutex_unlock(&lock);
*
* This function has no effect if there aren't any threads currently
* waiting on the condition.
*
* @return 0 on success, or errno on error
* @see pthread_cond_broadcast
* @see pthread_cond_wait
*/
errno_t pthread_cond_signal(pthread_cond_t *cond) {
nsync_cv_signal((nsync_cv *)cond);
return 0;
}
| 2,515 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_getguardsize.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/thread/thread.h"
/**
* Returns size of unmapped pages at bottom of stack.
*
* @param guardsize will be set to guard size in bytes
* @return 0 on success, or errno on error
*/
errno_t pthread_attr_getguardsize(const pthread_attr_t *attr,
size_t *guardsize) {
*guardsize = attr->__guardsize;
return 0;
}
| 2,197 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_getaffinity_np.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/sched-sysv.internal.h"
#include "libc/calls/struct/cpuset.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
/**
* Gets CPU affinity for thread.
*
* @param size is bytes in bitset, which should be `sizeof(cpu_set_t)`
* @return 0 on success, or errno on error
* @raise EINVAL if `size` or `bitset` is invalid
* @raise ENOSYS if not Linux, FreeBSD, or NetBSD
* @raise ESRCH if thread isn't alive
*/
errno_t pthread_getaffinity_np(pthread_t thread, size_t size,
cpu_set_t *bitset) {
int e, rc, tid;
if (!(rc = pthread_getunique_np(thread, &tid))) {
e = errno;
if (size != sizeof(cpu_set_t)) {
rc = einval();
} else if (IsWindows() || IsMetal() || IsOpenbsd()) {
rc = enosys();
} else if (IsFreebsd()) {
if (!sys_sched_getaffinity_freebsd(CPU_LEVEL_WHICH, CPU_WHICH_TID, tid,
32, bitset)) {
rc = 32;
} else {
rc = -1;
}
} else if (IsNetbsd()) {
if (!sys_sched_getaffinity_netbsd(tid, 0, 32, bitset)) {
rc = 32;
} else {
rc = -1;
}
} else {
rc = sys_sched_getaffinity(tid, size, bitset);
}
if (rc > 0) {
if (rc < size) {
bzero((char *)bitset + rc, size - rc);
}
rc = 0;
}
}
STRACE("pthread_getaffinity_np(%d, %'zu, %p) â %s", tid, size, bitset,
DescribeErrno(rc));
return rc;
}
| 3,504 | 77 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_getunique_np.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/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
/**
* Returns system thread id of POSIX thread.
*
* @return 0 on success, or errno on error
*/
errno_t pthread_getunique_np(pthread_t thread, pthread_id_np_t *out_tid) {
int tid;
struct PosixThread *pt;
for (pt = (struct PosixThread *)thread;;) {
tid = atomic_load_explicit(&pt->ptid, memory_order_acquire);
if (!tid) {
pthread_yield();
} else {
*out_tid = tid;
return 0;
}
}
}
| 2,395 | 42 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/thread.h | #ifndef COSMOPOLITAN_LIBC_THREAD_THREAD_H_
#define COSMOPOLITAN_LIBC_THREAD_THREAD_H_
#define PTHREAD_KEYS_MAX 128
#define PTHREAD_STACK_MIN FRAMESIZE
#define PTHREAD_DESTRUCTOR_ITERATIONS 4
#define PTHREAD_BARRIER_SERIAL_THREAD 31337
#define PTHREAD_MUTEX_DEFAULT 0
#define PTHREAD_MUTEX_NORMAL 0
#define PTHREAD_MUTEX_RECURSIVE 1
#define PTHREAD_MUTEX_ERRORCHECK 2
#define PTHREAD_MUTEX_STALLED 0
#define PTHREAD_MUTEX_ROBUST 1
#define PTHREAD_PROCESS_PRIVATE 0
#define PTHREAD_PROCESS_SHARED 1
#define PTHREAD_CREATE_JOINABLE 0
#define PTHREAD_CREATE_DETACHED 1
#define PTHREAD_INHERIT_SCHED 0
#define PTHREAD_EXPLICIT_SCHED 1
#define PTHREAD_CANCELED ((void *)-1)
#define PTHREAD_CANCEL_ENABLE 0
#define PTHREAD_CANCEL_DISABLE 1
#define PTHREAD_CANCEL_MASKED 2
#define PTHREAD_CANCEL_DEFERRED 0
#define PTHREAD_CANCEL_ASYNCHRONOUS 1
#define PTHREAD_SCOPE_SYSTEM 0
#define PTHREAD_SCOPE_PROCESS 1
#define PTHREAD_ATTR_NO_SIGMASK_NP -1
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define PTHREAD_ONCE_INIT _PTHREAD_INIT
#define PTHREAD_COND_INITIALIZER _PTHREAD_INIT
#define PTHREAD_RWLOCK_INITIALIZER _PTHREAD_INIT
#define PTHREAD_MUTEX_INITIALIZER _PTHREAD_INIT
#define _PTHREAD_INIT \
{ 0 }
typedef uintptr_t pthread_t;
typedef int pthread_id_np_t;
typedef char pthread_condattr_t;
typedef char pthread_rwlockattr_t;
typedef char pthread_barrierattr_t;
typedef unsigned pthread_key_t;
typedef void (*pthread_key_dtor)(void *);
typedef struct pthread_once_s {
_Atomic(uint32_t) _lock;
} pthread_once_t;
typedef struct pthread_spinlock_s {
_Atomic(int) _lock;
} pthread_spinlock_t;
typedef struct pthread_mutex_s {
_Atomic(int32_t) _lock;
unsigned _type : 2;
unsigned _pshared : 1;
unsigned _depth : 6;
unsigned _owner : 23;
long _pid;
} pthread_mutex_t;
typedef struct pthread_mutexattr_s {
char _type;
char _pshared;
} pthread_mutexattr_t;
typedef struct pthread_cond_s {
void *_nsync[2];
} pthread_cond_t;
typedef struct pthread_rwlock_s {
void *_nsync[2];
char _iswrite;
} pthread_rwlock_t;
typedef struct pthread_barrier_s {
void *_nsync;
} pthread_barrier_t;
typedef struct pthread_attr_s {
char __detachstate;
char __inheritsched;
char __havesigmask;
int __schedparam;
int __schedpolicy;
int __contentionscope;
unsigned __guardsize;
unsigned __stacksize;
uint32_t __sigmask[4];
char *__stackaddr;
} pthread_attr_t;
struct _pthread_cleanup_buffer {
void (*__routine)(void *);
void *__arg;
int __canceltype;
struct _pthread_cleanup_buffer *__prev;
};
/* clang-format off */
int pthread_atfork(void (*)(void), void (*)(void), void (*)(void));
int pthread_attr_destroy(pthread_attr_t *) paramsnonnull();
int pthread_attr_getdetachstate(const pthread_attr_t *, int *) paramsnonnull();
int pthread_attr_getguardsize(const pthread_attr_t *, size_t *) paramsnonnull();
int pthread_attr_getinheritsched(const pthread_attr_t *, int *) paramsnonnull();
int pthread_attr_getschedpolicy(const pthread_attr_t *, int *) paramsnonnull();
int pthread_attr_getscope(const pthread_attr_t *, int *) paramsnonnull();
int pthread_attr_getstack(const pthread_attr_t *, void **, size_t *) paramsnonnull();
int pthread_attr_getstacksize(const pthread_attr_t *, size_t *) paramsnonnull();
int pthread_attr_init(pthread_attr_t *) paramsnonnull();
int pthread_attr_setdetachstate(pthread_attr_t *, int) paramsnonnull();
int pthread_attr_setguardsize(pthread_attr_t *, size_t) paramsnonnull();
int pthread_attr_setinheritsched(pthread_attr_t *, int) paramsnonnull();
int pthread_attr_setschedpolicy(pthread_attr_t *, int) paramsnonnull();
int pthread_attr_setscope(pthread_attr_t *, int) paramsnonnull();
int pthread_attr_setstack(pthread_attr_t *, void *, size_t) paramsnonnull((1));
int pthread_attr_setstacksize(pthread_attr_t *, size_t) paramsnonnull();
int pthread_barrier_destroy(pthread_barrier_t *) paramsnonnull();
int pthread_barrier_init(pthread_barrier_t *, const pthread_barrierattr_t *, unsigned) paramsnonnull((1));
int pthread_barrier_wait(pthread_barrier_t *) paramsnonnull();
int pthread_barrierattr_destroy(pthread_barrierattr_t *) paramsnonnull();
int pthread_barrierattr_getpshared(const pthread_barrierattr_t *, int *) paramsnonnull();
int pthread_barrierattr_init(pthread_barrierattr_t *) paramsnonnull();
int pthread_barrierattr_setpshared(pthread_barrierattr_t *, int) paramsnonnull();
int pthread_cancel(pthread_t);
int pthread_cond_broadcast(pthread_cond_t *) paramsnonnull();
int pthread_cond_destroy(pthread_cond_t *) paramsnonnull();
int pthread_cond_init(pthread_cond_t *, const pthread_condattr_t *) paramsnonnull((1));
int pthread_cond_signal(pthread_cond_t *) paramsnonnull();
int pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *) paramsnonnull();
int pthread_condattr_destroy(pthread_condattr_t *) paramsnonnull();
int pthread_condattr_getpshared(const pthread_condattr_t *, int *) paramsnonnull();
int pthread_condattr_init(pthread_condattr_t *) paramsnonnull();
int pthread_condattr_setpshared(pthread_condattr_t *, int) paramsnonnull();
int pthread_create(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *) paramsnonnull((1, 3));
int pthread_detach(pthread_t);
int pthread_equal(pthread_t, pthread_t);
int pthread_getattr_np(pthread_t, pthread_attr_t *) paramsnonnull();
int pthread_getname_np(pthread_t, char *, size_t) paramsnonnull();
int pthread_getunique_np(pthread_t, pthread_id_np_t *) paramsnonnull();
int pthread_join(pthread_t, void **);
int pthread_key_create(pthread_key_t *, pthread_key_dtor) paramsnonnull((1));
int pthread_key_delete(pthread_key_t);
int pthread_kill(pthread_t, int);
int pthread_mutex_consistent(pthread_mutex_t *) paramsnonnull();
int pthread_mutex_destroy(pthread_mutex_t *) paramsnonnull();
int pthread_mutex_init(pthread_mutex_t *, const pthread_mutexattr_t *) paramsnonnull((1));
int pthread_mutex_lock(pthread_mutex_t *) paramsnonnull();
int pthread_mutex_trylock(pthread_mutex_t *) paramsnonnull();
int pthread_mutex_unlock(pthread_mutex_t *) paramsnonnull();
int pthread_mutexattr_destroy(pthread_mutexattr_t *) paramsnonnull();
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *, int *) paramsnonnull();
int pthread_mutexattr_gettype(const pthread_mutexattr_t *, int *) paramsnonnull();
int pthread_mutexattr_init(pthread_mutexattr_t *) paramsnonnull();
int pthread_mutexattr_setpshared(pthread_mutexattr_t *, int) paramsnonnull();
int pthread_mutexattr_settype(pthread_mutexattr_t *, int) paramsnonnull();
int pthread_once(pthread_once_t *, void (*)(void)) paramsnonnull();
int pthread_orphan_np(void);
int pthread_print_np(int, const char *, ...);
int pthread_rwlock_destroy(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlock_init(pthread_rwlock_t *, const pthread_rwlockattr_t *) paramsnonnull((1));
int pthread_rwlock_rdlock(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlock_tryrdlock(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlock_trywrlock(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlock_unlock(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlock_wrlock(pthread_rwlock_t *) paramsnonnull();
int pthread_rwlockattr_destroy(pthread_rwlockattr_t *) paramsnonnull();
int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *, int *) paramsnonnull();
int pthread_rwlockattr_init(pthread_rwlockattr_t *) paramsnonnull();
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *, int) paramsnonnull();
int pthread_setcancelstate(int, int *);
int pthread_setcanceltype(int, int *);
int pthread_setname_np(pthread_t, const char *) paramsnonnull();
int pthread_setschedprio(pthread_t, int);
int pthread_setspecific(pthread_key_t, const void *);
int pthread_spin_destroy(pthread_spinlock_t *) paramsnonnull();
int pthread_spin_init(pthread_spinlock_t *, int) paramsnonnull();
int pthread_spin_lock(pthread_spinlock_t *) paramsnonnull();
int pthread_spin_trylock(pthread_spinlock_t *) paramsnonnull();
int pthread_spin_unlock(pthread_spinlock_t *) paramsnonnull();
int pthread_testcancel_np(void);
int pthread_tryjoin_np(pthread_t, void **);
int pthread_yield(void);
pthread_id_np_t pthread_getthreadid_np(void);
pthread_t pthread_self(void) pureconst;
void *pthread_getspecific(pthread_key_t);
void pthread_cleanup_pop(struct _pthread_cleanup_buffer *, int) paramsnonnull();
void pthread_cleanup_push(struct _pthread_cleanup_buffer *, void (*)(void *), void *) paramsnonnull((1));
void pthread_decimate_np(void);
void pthread_exit(void *) wontreturn;
void pthread_testcancel(void);
/* clang-format on */
#define pthread_cleanup_push(routine, arg) \
{ \
struct _pthread_cleanup_buffer _buffer; \
pthread_cleanup_push(&_buffer, (routine), (arg));
#define pthread_cleanup_pop(execute) \
pthread_cleanup_pop(&_buffer, (execute)); \
}
#if (__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 407 && \
!defined(__STRICT_ANSI__) && !defined(MODE_DBG)
extern const errno_t EBUSY;
#define pthread_spin_lock(pSpin) \
({ \
pthread_spinlock_t *_s = pSpin; \
while (__atomic_test_and_set(&_s->_lock, __ATOMIC_ACQUIRE)) donothing; \
0; \
})
#define pthread_spin_unlock(pSpin) \
({ \
pthread_spinlock_t *_s = pSpin; \
__atomic_store_n(&_s->_lock, 0, __ATOMIC_RELEASE); \
0; \
})
#define pthread_spin_trylock(pSpin) \
({ \
pthread_spinlock_t *_s = pSpin; \
__atomic_test_and_set(&_s->_lock, __ATOMIC_ACQUIRE) ? EBUSY : 0; \
})
#define pthread_spin_init(pSpin, multiprocess) \
(__atomic_store_n(&(pSpin)->_lock, 0, __ATOMIC_RELAXED), 0)
#define pthread_spin_destroy(pSpin) \
(__atomic_store_n(&(pSpin)->_lock, -1, __ATOMIC_RELAXED), 0)
#endif /* GCC 4.7+ */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_THREAD_THREAD_H_ */
| 10,335 | 247 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cond_destroy.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/thread/thread.h"
/**
* Destroys condition.
*
* @return 0 on success, or error number on failure
* @raise EINVAL if threads are still waiting on condition
*/
errno_t pthread_cond_destroy(pthread_cond_t *cond) {
memset(cond, -1, sizeof(*cond));
return 0;
}
| 2,142 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_post.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/limits.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/semaphore.h"
#include "third_party/nsync/futex.internal.h"
/**
* Unlocks semaphore.
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if `sem` isn't valid
*/
int sem_post(sem_t *sem) {
int rc, old, wakeups;
old = atomic_fetch_add_explicit(&sem->sem_value, 1, memory_order_acq_rel);
_unassert(old > INT_MIN);
if (old >= 0) {
wakeups = nsync_futex_wake_(&sem->sem_value, 1, true);
_npassert(wakeups >= 0);
rc = 0;
} else {
wakeups = 0;
rc = einval();
}
return rc;
}
| 2,536 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_self.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/assert.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
/**
* Returns current POSIX thread.
* @asyncsignalsafe
*/
pthread_t pthread_self(void) {
pthread_t t;
t = __get_tls()->tib_pthread;
_unassert(t);
return t;
}
| 2,092 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cond_init.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/thread/thread.h"
/**
* Initializes condition.
*
* @param attr may be null
* @return 0 on success, or error number on failure
*/
errno_t pthread_cond_init(pthread_cond_t *cond,
const pthread_condattr_t *attr) {
*cond = (pthread_cond_t){0};
return 0;
}
| 2,138 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_mutexattr_gettype.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/thread/thread.h"
/**
* Gets mutex type.
*
* @param type will be set to one of these on success
* - `PTHREAD_MUTEX_NORMAL`
* - `PTHREAD_MUTEX_RECURSIVE`
* - `PTHREAD_MUTEX_ERRORCHECK`
* @return 0 on success, or error on failure
*/
errno_t pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type) {
*type = attr->_type;
return 0;
}
| 2,219 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_reschedule.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/sched-sysv.internal.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
errno_t _pthread_reschedule(struct PosixThread *pt) {
int e, rc, tid;
int policy = pt->attr.__schedpolicy;
struct sched_param param = {pt->attr.__schedparam};
if (!(rc = pthread_getunique_np((pthread_t)pt, &tid))) {
e = errno;
if (IsNetbsd()) {
rc = sys_sched_setparam_netbsd(0, tid, policy, ¶m);
} else if (IsLinux()) {
rc = sys_sched_setscheduler(tid, policy, ¶m);
} else if (IsFreebsd()) {
rc = _pthread_setschedparam_freebsd(tid, policy, ¶m);
} else {
rc = enosys();
}
if (rc == -1) {
rc = errno;
errno = e;
}
}
return rc;
}
| 2,700 | 49 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_mutexattr_destroy.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/thread/thread.h"
/**
* Destroys mutex attr.
* @return 0 on success, or error number on failure
*/
errno_t pthread_mutexattr_destroy(pthread_mutexattr_t *attr) {
memset(attr, -1, sizeof(*attr));
return 0;
}
| 2,091 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_equal.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/thread/thread.h"
/**
* Compares thread ids;
*
* @return nonzero if equal, otherwise zero
*/
int pthread_equal(pthread_t t1, pthread_t t2) {
return t1 == t2;
}
| 2,017 | 29 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cancel.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/calls/ucontext.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
#ifdef __x86_64__
int systemfive_cancel(void);
extern const char systemfive_cancellable[];
extern const char systemfive_cancellable_end[];
int _pthread_cancel_sys(void) {
struct PosixThread *pt;
pt = (struct PosixThread *)__get_tls()->tib_pthread;
if (!(pt->flags & (PT_NOCANCEL | PT_MASKED)) || (pt->flags & PT_ASYNC)) {
pthread_exit(PTHREAD_CANCELED);
}
pt->flags |= PT_NOCANCEL | PT_OPENBSD_KLUDGE;
return ecanceled();
}
static void OnSigThr(int sig, siginfo_t *si, void *ctx) {
ucontext_t *uc = ctx;
struct CosmoTib *t = __get_tls();
struct PosixThread *pt = (struct PosixThread *)t->tib_pthread;
if (pt && !(pt->flags & PT_NOCANCEL) &&
atomic_load_explicit(&pt->cancelled, memory_order_acquire)) {
sigaddset(&uc->uc_sigmask, sig);
if (systemfive_cancellable <= (char *)uc->uc_mcontext.rip &&
(char *)uc->uc_mcontext.rip < systemfive_cancellable_end) {
uc->uc_mcontext.rip = (intptr_t)systemfive_cancel;
} else if (pt->flags & PT_ASYNC) {
pthread_exit(PTHREAD_CANCELED);
} else {
__tkill(atomic_load_explicit(&t->tib_tid, memory_order_relaxed), sig, t);
}
}
}
static void ListenForSigThr(void) {
struct sigaction sa;
sa.sa_sigaction = OnSigThr;
sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
memset(&sa.sa_mask, -1, sizeof(sa.sa_mask));
_npassert(!sigaction(SIGTHR, &sa, 0));
}
/**
* Cancels thread.
*
* When a thread is cancelled, it'll interrupt blocking i/o calls,
* invoke any cleanup handlers that were pushed on the thread's stack
* before the cancellation occurred, in addition to destructing pthread
* keys, before finally, the thread shall abruptly exit.
*
* By default, pthread_cancel() can only take effect when a thread
* reaches a cancellation point. Such functions are documented with
* `@cancellationpoint`. They check the cancellation state before the
* underlying system call is issued. If the system call is issued and
* blocks, then pthread_cancel() will interrupt the operation in which
* case the syscall wrapper will check the cancelled state a second
* time, only if the raw system call returned EINTR.
*
* The following system calls are implemented as cancellation points.
*
* - `accept4`
* - `accept`
* - `clock_nanosleep`
* - `connect`
* - `copy_file_range`
* - `creat`
* - `epoll_wait`
* - `fcntl(F_OFD_SETLKW)`
* - `fcntl(F_SETLKW)`
* - `fdatasync`
* - `flock`
* - `fstatfs`
* - `fsync`
* - `ftruncate`
* - `getrandom`
* - `msync`
* - `nanosleep`
* - `open`
* - `openat`
* - `pause`
* - `poll`
* - `ppoll`
* - `pread`
* - `preadv`
* - `pselect`
* - `pwrite`
* - `pwritev`
* - `read`
* - `readv`
* - `recvfrom`
* - `recvmsg`
* - `select`
* - `sendmsg`
* - `sendto`
* - `sigsuspend`
* - `sigtimedwait`
* - `sigwaitinfo`
* - `statfs`
* - `tcdrain`
* - `truncate`
* - `wait3`
* - `wait4`
* - `wait`
* - `waitpid`
* - `write`
* - `writev`
*
* The following library calls are implemented as cancellation points.
*
* - `fopen`
* - `gzopen`, `gzread`, `gzwrite`, etc.
* - `lockf(F_LOCK)`
* - `nsync_cv_wait_with_deadline`
* - `nsync_cv_wait`
* - `opendir`
* - `pclose`
* - `popen`
* - `fwrite`, `printf`, `fprintf`, `putc`, etc.
* - `pthread_cond_timedwait`
* - `pthread_cond_wait`
* - `pthread_join`
* - `sem_timedwait`
* - `sem_wait`
* - `sleep`
* - `timespec_sleep_until`
* - `tmpfd`
* - `tmpfile`
* - `usleep`
*
* Other userspace libraries provided by Cosmopolitan Libc that call the
* cancellation points above will block cancellations while running. The
* following are examples of functions that *aren't* cancellation points
*
* - `INFOF()`, `WARNF()`, etc.
* - `getentropy`
* - `gmtime_r`
* - `kprintf`
* - `localtime_r`
* - `nsync_mu_lock`
* - `nsync_mu_unlock`
* - `openpty`
* - `pthread_getname_np`
* - `pthread_mutex_lock`
* - `pthread_mutex_unlock`
* - `pthread_setname_np`
* - `sem_open`
* - `system`
* - `timespec_sleep`
* - `touch`
*
* The way to block cancellations temporarily is:
*
* int cs;
* pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
* // ...
* pthread_setcancelstate(cs, 0);
*
* In order to support cancellations all your code needs to be rewritten
* so that when resources such as file descriptors are managed they must
* have a cleanup crew pushed to the stack. For example even malloc() is
* technically unsafe w.r.t. leaks without doing something like this:
*
* void *p = malloc(123);
* pthread_cleanup_push(free, p);
* read(0, p, 123);
* pthread_cleanup_pop(1);
*
* Consider using Cosmopolitan Libc's garbage collector since it will be
* executed when a thread exits due to a cancellation.
*
* void *p = _gc(malloc(123));
* read(0, p, 123);
*
* It's possible to put a thread in asynchronous cancellation mode using
*
* pthread_setcancelstate(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
* for (;;) donothing;
*
* In which case a thread may be cancelled at any assembly opcode. This
* is useful for immediately halting threads that consume cpu and don't
* use any system calls. It shouldn't be used on threads that will call
* cancellation points since in that case asynchronous mode could cause
* resource leaks to happen, in such a way that can't be worked around.
*
* If none of the above options seem savory to you, then a third way is
* offered for doing cancellations. Cosmopolitan Libc supports the Musl
* Libc `PTHREAD_CANCEL_MASKED` non-POSIX extension. Any thread may pass
* this setting to pthread_setcancelstate(), in which case threads won't
* be abruptly destroyed upon cancellation and have their stack unwound;
* instead, cancellation points will simply raise an `ECANCELED` error,
* which can be more safely and intuitively handled for many use cases.
* For example:
*
* pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0);
* void *p = malloc(123);
* int rc = read(0, p, 123);
* free(p);
* if (rc == ECANCELED) {
* pthread_exit(0);
* }
*
* Shows how the masked cancellations paradigm can be safely used. Note
* that it's so important that cancellation point error return codes be
* checked. Code such as the following:
*
* pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0);
* void *p = malloc(123);
* write(2, "log\n", 4); // XXX: fails to check result
* int rc = read(0, p, 123);
* free(p);
* if (rc == ECANCELED) {
* pthread_exit(0); // XXX: not run if write() was cancelled
* }
*
* Isn't safe to use in masked mode. That's because if a cancellation
* occurs during the write() operation then cancellations are blocked
* while running read(). Masked mode doesn't have second chances. You
* must rigorously check the results of each cancellation point call.
*
* @return 0 on success, or errno on error
* @raise ESRCH if thread isn't alive
*/
errno_t pthread_cancel(pthread_t thread) {
int e, rc, tid;
static bool once;
struct PosixThread *pt;
if (!once) ListenForSigThr(), once = true;
pt = (struct PosixThread *)thread;
switch (atomic_load_explicit(&pt->status, memory_order_acquire)) {
case kPosixThreadZombie:
case kPosixThreadTerminated:
return ESRCH;
default:
break;
}
atomic_store_explicit(&pt->cancelled, 1, memory_order_release);
if (thread == __get_tls()->tib_pthread) {
if (!(pt->flags & (PT_NOCANCEL | PT_MASKED)) && (pt->flags & PT_ASYNC)) {
pthread_exit(PTHREAD_CANCELED);
}
return 0;
}
if (!(rc = pthread_getunique_np(thread, &tid))) {
if (!IsWindows()) {
e = errno;
if (!__tkill(tid, SIGTHR, pt->tib)) {
rc = 0;
} else {
rc = errno;
errno = e;
}
} else {
rc = 0;
}
}
return rc;
}
#endif /* __x86_64__ */
/**
* Creates cancellation point in calling thread.
*
* This function can be used to force `PTHREAD_CANCEL_DEFERRED` threads
* to cancel without needing to invoke an interruptible system call. If
* the calling thread is in the `PTHREAD_CANCEL_DISABLE` then this will
* do nothing. If the calling thread hasn't yet been cancelled, this'll
* do nothing. In `PTHREAD_CANCEL_MASKED` mode, this also does nothing.
*
* @see pthread_testcancel_np()
*/
void pthread_testcancel(void) {
struct PosixThread *pt;
if (!__tls_enabled) return;
if (!(pt = (struct PosixThread *)__get_tls()->tib_pthread)) return;
if (pt->flags & PT_NOCANCEL) return;
if ((!(pt->flags & PT_MASKED) || (pt->flags & PT_ASYNC)) &&
atomic_load_explicit(&pt->cancelled, memory_order_acquire)) {
pthread_exit(PTHREAD_CANCELED);
}
}
/**
* Creates cancellation point in calling thread.
*
* This function can be used to force `PTHREAD_CANCEL_DEFERRED` threads
* to cancel without needing to invoke an interruptible system call. If
* the calling thread is in the `PTHREAD_CANCEL_DISABLE` then this will
* do nothing. If the calling thread hasn't yet been cancelled, this'll
* do nothing. If the calling thread uses `PTHREAD_CANCEL_MASKED`, then
* this function returns `ECANCELED` if a cancellation occurred, rather
* than the normal behavior which is to destroy and cleanup the thread.
* Any `ECANCELED` result must not be ignored, because the thread shall
* have cancellations disabled once it occurs.
*
* @return 0 if not cancelled or cancellation is blocked or `ECANCELED`
* in masked mode when the calling thread has been cancelled
*/
errno_t pthread_testcancel_np(void) {
int rc;
struct PosixThread *pt;
if (!__tls_enabled) return 0;
if (!(pt = (struct PosixThread *)__get_tls()->tib_pthread)) return 0;
if (pt->flags & PT_NOCANCEL) return 0;
if (!atomic_load_explicit(&pt->cancelled, memory_order_acquire)) return 0;
if (!(pt->flags & PT_MASKED) || (pt->flags & PT_ASYNC)) {
pthread_exit(PTHREAD_CANCELED);
} else {
pt->flags |= PT_NOCANCEL;
return ECANCELED;
}
}
| 12,389 | 351 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_setaffinity_np.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/sched-sysv.internal.h"
#include "libc/calls/struct/cpuset.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/enum/threadaccess.h"
#include "libc/nt/runtime.h"
#include "libc/nt/thread.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
static dontinline textwindows int sys_pthread_setaffinity_nt(
int tid, uint64_t size, const cpu_set_t *bitset) {
int rc;
int64_t h;
h = OpenThread(kNtThreadSetInformation | kNtThreadQueryInformation, false,
tid);
if (!h) return __winerr();
rc = SetThreadAffinityMask(h, bitset->__bits[0]) ? 0 : __winerr();
CloseHandle(h);
return rc;
}
/**
* Asks kernel to only schedule thread on particular CPUs.
*
* @param size is bytes in bitset, which should be `sizeof(cpu_set_t)`
* @return 0 on success, or errno on error
* @raise EINVAL if `size` or `bitset` is invalid
* @raise ENOSYS if not Linux, FreeBSD, NetBSD, or Windows
* @see sched_setaffinity() for processes
*/
errno_t pthread_setaffinity_np(pthread_t thread, size_t size,
const cpu_set_t *bitset) {
int e, rc, tid;
if (!(rc = pthread_getunique_np(thread, &tid))) {
e = errno;
if (size != sizeof(cpu_set_t)) {
rc = einval();
} else if (IsWindows()) {
rc = sys_pthread_setaffinity_nt(tid, size, bitset);
} else if (IsFreebsd()) {
rc = sys_sched_setaffinity_freebsd(CPU_LEVEL_WHICH, CPU_WHICH_TID, tid,
32, bitset);
} else if (IsNetbsd()) {
rc = sys_sched_setaffinity_netbsd(tid, 0, 32, bitset);
} else {
rc = sys_sched_setaffinity(tid, size, bitset);
}
if (rc == -1) {
rc = errno;
errno = e;
}
}
STRACE("pthread_setaffinity_np(%d, %'zu, %p) â %s", tid, size, bitset,
DescribeErrno(rc));
return rc;
}
| 3,877 | 80 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_rwlock_rdlock.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/thread/thread.h"
#include "third_party/nsync/mu.h"
/**
* Acquires read lock on read-write lock.
*
* @return 0 on success, or errno on error
*/
errno_t pthread_rwlock_rdlock(pthread_rwlock_t *rwlock) {
nsync_mu_rlock((nsync_mu *)rwlock);
return 0;
}
| 2,109 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_init.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/intrin/atomic.h"
#include "libc/limits.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/semaphore.h"
#include "third_party/nsync/mu_semaphore.h"
/**
* Initializes unnamed semaphore.
*
* Calling sem_init() on an already initialized semaphore is undefined.
*
* @param sem should make its way to sem_destroy() if this succeeds
* @param pshared if semaphore may be shared between processes, provided
* `sem` is backed by `mmap(MAP_ANONYMOUS | MAP_SHARED)` memory
* @param value is initial count of semaphore
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if `value` exceeds `SEM_VALUE_MAX`
*/
int sem_init(sem_t *sem, int pshared, unsigned value) {
if (value > SEM_VALUE_MAX) return einval();
sem->sem_magic = SEM_MAGIC_UNNAMED;
atomic_store_explicit(&sem->sem_value, value, memory_order_relaxed);
sem->sem_pshared = !!pshared;
sem->sem_pid = getpid();
sem->sem_waiters = 0;
return 0;
}
| 2,831 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_print_np.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/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#include "third_party/nsync/dll.h"
#define N 2048
#define M 15
#define append(f, ...) o += f(buf + o, N - o, __VA_ARGS__)
static const char *DescribeStatus(enum PosixThreadStatus status) {
switch (status) {
case kPosixThreadJoinable:
return "JOINAB";
case kPosixThreadDetached:
return "DETACH";
case kPosixThreadTerminated:
return "TERMIN";
case kPosixThreadZombie:
return "ZOMBIE";
default:
unreachable;
}
}
static const char *DescribeFlags(char buf[M], struct PosixThread *pt) {
char *p = buf;
if (pt->cancelled) *p++ = '*';
if (pt->flags & PT_EXITING) *p++ = 'X';
if (pt->flags & PT_STATIC) *p++ = 'S';
if (pt->flags & PT_OWNSTACK) *p++ = 'O';
if (pt->flags & PT_ASYNC) *p++ = 'A';
if (pt->flags & PT_MASKED) *p++ = 'M';
if (pt->flags & PT_OPENBSD_KLUDGE) *p++ = 'K';
if (pt->flags & PT_INCANCEL) *p++ = '?';
if (pt->flags & PT_NOCANCEL) *p++ = '!';
*p = 0;
return buf;
}
int pthread_print_np(int fd, const char *fmt, ...) {
va_list va;
int rc, o = 0;
nsync_dll_element_ *e;
struct PosixThread *pt;
char buf[N], flagbuf[M];
pthread_spin_lock(&_pthread_lock);
if (fmt) {
va_start(va, fmt);
append(kvsnprintf, fmt, va);
va_end(va);
append(ksnprintf, "\n");
}
append(ksnprintf, "%6s %6s %6s %6s %s\n", "ptid", "tid", "status", "flags",
"start");
for (e = nsync_dll_first_(_pthread_list); e;
e = nsync_dll_next_(_pthread_list, e)) {
pt = (struct PosixThread *)e->container;
append(ksnprintf, "%-6d %-6d %6s %6s %t\n", pt->ptid, pt->tib->tib_tid,
DescribeStatus(pt->status), DescribeFlags(flagbuf, pt), pt->start);
}
pthread_spin_unlock(&_pthread_lock);
BLOCK_CANCELLATIONS;
strace_enabled(-1);
rc = write(fd, buf, strlen(buf));
strace_enabled(+1);
ALLOW_CANCELLATIONS;
return rc;
}
| 3,933 | 92 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_setschedparam.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/errno.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread2.h"
/**
* Changes scheduling of thread, e.g.
*
* struct sched_param p = {sched_get_priority_min(SCHED_OTHER)};
* pthread_setschedparam(thread, SCHED_OTHER, &p);
*
* @param policy may be one of:
* - `SCHED_OTHER` the default policy
* - `SCHED_FIFO` for real-time scheduling (usually needs root)
* - `SCHED_RR` for round-robin scheduling (usually needs root)
* - `SCHED_IDLE` for lowest effort (Linux and FreeBSD only)
* - `SCHED_BATCH` for "batch" style execution of processes if
* supported (Linux), otherwise it's treated as `SCHED_OTHER`
* @raise ENOSYS on XNU, Windows, OpenBSD
* @raise EPERM if not authorized to use scheduler in question (e.g.
* trying to use a real-time scheduler as non-root on Linux) or
* possibly because pledge() was used and isn't allowing this
* @see sched_get_priority_min()
* @see sched_get_priority_max()
* @see sched_setscheduler()
*/
errno_t pthread_setschedparam(pthread_t thread, int policy,
const struct sched_param *param) {
struct PosixThread *pt = (struct PosixThread *)thread;
pt->attr.__schedpolicy = policy;
pt->attr.__schedparam = param->sched_priority;
return _pthread_reschedule(pt);
}
| 3,168 | 51 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cond_broadcast.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/thread/thread.h"
#include "third_party/nsync/cv.h"
/**
* Wakes all threads waiting on condition, e.g.
*
* pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
* pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
* // ...
* pthread_mutex_lock(&lock);
* pthread_cond_broadcast(&cond);
* pthread_mutex_unlock(&lock);
*
* This function has no effect if there aren't any threads currently
* waiting on the condition.
*
* @return 0 on success, or errno on error
* @see pthread_cond_signal
* @see pthread_cond_wait
*/
errno_t pthread_cond_broadcast(pthread_cond_t *cond) {
nsync_cv_broadcast((nsync_cv *)cond);
return 0;
}
| 2,506 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/tls2.h | #ifndef COSMOPOLITAN_LIBC_THREAD_TLS2_H_
#define COSMOPOLITAN_LIBC_THREAD_TLS2_H_
#include "libc/dce.h"
#include "libc/thread/tls.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#if defined(__GNUC__) && defined(__x86_64__) && !defined(__STRICT_ANSI__)
/**
* Returns location of thread information block.
*
* This should be favored over __get_tls() for .privileged code that
* can't be self-modified by __enable_tls().
*/
static noasan inline struct CosmoTib *__get_tls_privileged(void) {
char *tib, *lin = (char *)0x30;
if (IsLinux() || IsFreebsd() || IsNetbsd() || IsOpenbsd() || IsMetal()) {
asm("mov\t%%fs:(%1),%0" : "=a"(tib) : "r"(lin) : "memory");
} else {
asm("mov\t%%gs:(%1),%0" : "=a"(tib) : "r"(lin) : "memory");
if (IsWindows()) {
tib = *(char **)(tib + 0x1480 + __tls_index * 8);
}
}
return (struct CosmoTib *)tib;
}
static noasan inline struct CosmoTib *__get_tls_win32(void) {
char *tib, *lin = (char *)0x30;
asm("mov\t%%gs:(%1),%0" : "=a"(tib) : "r"(lin) : "memory");
tib = *(char **)(tib + 0x1480 + __tls_index * 8);
return (struct CosmoTib *)tib;
}
static noasan inline void __set_tls_win32(void *tls) {
asm("mov\t%1,%%gs:%0" : "=m"(*((long *)0x1480 + __tls_index)) : "r"(tls));
}
#elif defined(__aarch64__)
#define __get_tls_privileged() __get_tls()
#define __get_tls_win32() ((struct CosmoTib *)0)
#define __set_tls_win32(tls) (void)0
#endif /* GNU x86-64 */
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_THREAD_TLS2_H_ */
| 1,564 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_mutexattr_init.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/thread/thread.h"
/**
* Initializes mutex attr.
* @return 0 on success, or error number on failure
*/
errno_t pthread_mutexattr_init(pthread_mutexattr_t *attr) {
*attr = (pthread_mutexattr_t){0};
return 0;
}
| 2,066 | 29 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/wait0.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/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
#include "libc/thread/wait0.internal.h"
#include "third_party/nsync/futex.internal.h"
/**
* Blocks until memory location becomes zero.
*
* This is intended to be used on the child thread id, which is updated
* by the clone() system call when a thread terminates. We need this in
* order to know when it's safe to free a thread's stack. This function
* uses futexes on Linux, FreeBSD, OpenBSD, and Windows. On other
* platforms this uses polling with exponential backoff.
*
* @return 0 on success, or errno on error
* @raise ECANCELED if calling thread was cancelled in masked mode
* @raise EBUSY if `abstime` was specified and deadline expired
* @cancellationpoint
*/
errno_t _wait0(const atomic_int *ctid, struct timespec *abstime) {
int x, e, rc = 0;
// "The behavior is undefined if the value specified by the thread
// argument to pthread_join() refers to the calling thread."
// ââQuoth POSIX.1-2017
_unassert(ctid != &__get_tls()->tib_tid);
// "If the thread calling pthread_join() is canceled, then the target
// thread shall not be detached." ââQuoth POSIX.1-2017
if (!(rc = pthread_testcancel_np())) {
BEGIN_CANCELLATION_POINT;
while ((x = atomic_load_explicit(ctid, memory_order_acquire))) {
e = nsync_futex_wait_(ctid, x, !IsWindows(), abstime);
if (e == -ECANCELED) {
rc = ECANCELED;
break;
} else if (e == -ETIMEDOUT) {
rc = EBUSY;
break;
}
}
END_CANCELLATION_POINT;
}
return rc;
}
| 3,621 | 68 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_getschedpolicy.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/thread/thread.h"
/**
* Gets thread scheduler policy attribute
*/
errno_t pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy) {
*policy = attr->__schedpolicy;
return 0;
}
| 2,045 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_condattr_setpshared.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/errno.h"
#include "libc/thread/thread.h"
/**
* Sets condition process sharing.
*
* @param pshared can be one of
* - `PTHREAD_PROCESS_PRIVATE` (default)
* - `PTHREAD_PROCESS_SHARED` (unsupported)
* @return 0 on success, or error on failure
* @raises EINVAL if `pshared` is invalid
*/
errno_t pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared) {
switch (pshared) {
case PTHREAD_PROCESS_PRIVATE:
*attr = pshared;
return 0;
default:
return EINVAL;
}
}
| 2,362 | 40 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_cond_wait.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/thread/thread.h"
#include "libc/thread/thread2.h"
/**
* Waits for condition, e.g.
*
* pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
* pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
* // ...
* pthread_mutex_lock(&lock);
* pthread_cond_wait(&cond, &lock);
* pthread_mutex_unlock(&lock);
*
* @param mutex needs to be held by thread when calling this function
* @return 0 on success, or errno on error
* @raise ECANCELED if calling thread was cancelled in masked mode
* @raise EPERM if `mutex` is `PTHREAD_MUTEX_ERRORCHECK` and the lock
* isn't owned by the current thread
* @see pthread_cond_timedwait
* @see pthread_cond_broadcast
* @see pthread_cond_signal
* @cancellationpoint
*/
errno_t pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) {
return pthread_cond_timedwait(cond, mutex, 0);
}
| 2,709 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_barrierattr_init.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/thread/thread.h"
/**
* Initializes barrier attributes.
*
* @return 0 on success, or error on failure
*/
errno_t pthread_barrierattr_init(pthread_barrierattr_t *attr) {
*attr = 0;
return 0;
}
| 2,051 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_trywait.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/limits.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/semaphore.h"
/**
* Locks semaphore only if it's currently not locked.
*
* @return 0 on success, or -1 w/ errno
* @raise EAGAIN if semaphore is locked
* @raise EDEADLK if deadlock was detected
* @raise EINVAL if `sem` is invalid
*/
int sem_trywait(sem_t *sem) {
int v;
v = atomic_load_explicit(&sem->sem_value, memory_order_relaxed);
do {
_unassert(v > INT_MIN);
if (!v) return eagain();
if (v < 0) return einval();
} while (!atomic_compare_exchange_weak_explicit(
&sem->sem_value, &v, v - 1, memory_order_acquire, memory_order_relaxed));
return 0;
}
| 2,611 | 46 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_getsigmask_np.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/thread/thread2.h"
/**
* Gets signal mask on thread attributes object.
*
* @param attr is the thread attributes object
* @param sigmask will receive the output signal mask on success, or
* null if a simple presence check is desired
* @return 0 on success, errno on error, or `PTHREAD_ATTR_NO_SIGMASK_NP`
* if there wasn't any signal mask present in `attr`
*/
errno_t pthread_attr_getsigmask_np(const pthread_attr_t *attr,
sigset_t *sigmask) {
_Static_assert(sizeof(attr->__sigmask) == sizeof(*sigmask), "");
if (!attr->__havesigmask) return PTHREAD_ATTR_NO_SIGMASK_NP;
if (sigmask) memcpy(sigmask, attr->__sigmask, sizeof(*sigmask));
return 0;
}
| 2,582 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_join.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/thread/thread2.h"
/**
* Waits for thread to terminate.
*
* Multiple threads joining the same thread is undefined behavior. If a
* deferred or masked cancellation happens to the calling thread either
* before or during the waiting process then the target thread will not
* be joined. Calling pthread_join() on a non-joinable thread, e.g. one
* that's been detached, is undefined behavior. If a thread attempts to
* join itself, then the behavior is undefined.
*
* @param value_ptr if non-null will receive pthread_exit() argument
* if the thread called pthread_exit(), or `PTHREAD_CANCELED` if
* pthread_cancel() destroyed the thread instead
* @return 0 on success, or errno on error
* @raise ECANCELED if calling thread was cancelled in masked mode
* @cancellationpoint
* @returnserrno
* @threadsafe
*/
errno_t pthread_join(pthread_t thread, void **value_ptr) {
return pthread_timedjoin_np(thread, value_ptr, 0);
}
| 2,795 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_getname_np.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/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/asmflag.h"
#include "libc/intrin/atomic.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/pr.h"
#include "libc/thread/posixthread.internal.h"
static errno_t pthread_getname_impl(pthread_t thread, char *name, size_t size) {
int e, fd, rc, tid, len;
if ((rc = pthread_getunique_np(thread, &tid))) return rc;
if (!size) return 0;
bzero(name, size);
e = errno;
if (IsLinux()) {
// TASK_COMM_LEN is 16 on Linux so we're just being paranoid.
char buf[256] = {0};
if (tid == gettid()) {
if (prctl(PR_GET_NAME, buf) == -1) {
rc = errno;
errno = e;
return rc;
}
} else {
char path[128], *p = path;
p = stpcpy(p, "/proc/self/task/");
p = FormatUint32(p, tid);
p = stpcpy(p, "/comm");
if ((fd = sys_openat(AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0)) == -1) {
rc = errno;
errno = e;
return rc;
}
rc = sys_read(fd, buf, sizeof(buf) - 1);
rc |= sys_close(fd);
if (rc == -1) {
rc = errno;
errno = e;
return rc;
}
_chomp(buf);
}
if ((len = strlen(buf))) {
memcpy(name, buf, MIN(len, size - 1));
}
if (len > size - 1) {
return ERANGE;
}
return 0;
} else if (IsNetbsd()) {
char cf;
int ax, dx;
// NetBSD doesn't document the subtleties of its nul-terminator
// behavior, so like Linux we shall take the paranoid approach.
asm volatile(CFLAG_ASM("syscall")
: CFLAG_CONSTRAINT(cf), "=a"(ax), "=d"(dx)
: "1"(324 /* _lwp_getname */), "D"(tid), "S"(name),
"d"(size - 1)
: "rcx", "r8", "r9", "r10", "r11", "memory");
if (!cf) {
// if size + our nul + kernel's nul is the buffer size, then we
// can't say with absolute confidence truncation didn't happen.
if (strlen(name) + 1 + 1 <= size) {
return 0;
} else {
return ERANGE;
}
} else {
return ax;
}
} else {
return ENOSYS;
}
}
/**
* Gets name of thread registered with system, e.g.
*
* char name[64];
* pthread_getname_np(thread, name, sizeof(name));
*
* If the thread doesn't have a name, then empty string is returned.
* This implementation guarantees `buf` is always modified, even on
* error, and will always be nul-terminated. If `size` is 0 then this
* function returns 0. Your `buf` is also chomped to remove newlines.
*
* @return 0 on success, or errno on error
* @raise ERANGE if `size` wasn't large enough, in which case your
* result will still be returned truncated if possible
* @raise ENOSYS on MacOS, Windows, FreeBSD, and OpenBSD
*/
errno_t pthread_getname_np(pthread_t thread, char *name, size_t size) {
errno_t rc;
BLOCK_CANCELLATIONS;
rc = pthread_getname_impl(thread, name, size);
ALLOW_CANCELLATIONS;
return rc;
}
| 5,038 | 128 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_mutexattr_getpshared.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/thread/thread.h"
/**
* Gets mutex process sharing.
*
* @param pshared is set to one of the following
* - `PTHREAD_PROCESS_PRIVATE` (default)
* - `PTHREAD_PROCESS_SHARED`
* @return 0 on success, or error on failure
*/
errno_t pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr,
int *pshared) {
*pshared = attr->_pshared;
return 0;
}
| 2,250 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_getstacksize.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/runtime/stack.h"
#include "libc/thread/thread.h"
/**
* Returns size of thread stack.
*
* This defaults to GetStackSize().
*
* @param x will be set to stack size in bytes
* @return 0 on success, or errno on error
* @see pthread_attr_setstacksize()
*/
errno_t pthread_attr_getstacksize(const pthread_attr_t *a, size_t *x) {
if (a->__stacksize) {
*x = a->__stacksize;
} else {
*x = GetStackSize();
}
return 0;
}
| 2,285 | 39 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/semaphore.h | #ifndef COSMOPOLITAN_LIBC_CALLS_SEMAPHORE_H_
#define COSMOPOLITAN_LIBC_CALLS_SEMAPHORE_H_
#include "libc/calls/struct/timespec.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define SEM_FAILED ((sem_t *)0)
#define SEM_MAGIC_NAMED 0xDEADBEEFu
#define SEM_MAGIC_UNNAMED 0xFEEDABEEu
typedef struct {
union {
struct {
_Atomic(int) sem_value;
_Atomic(int) sem_waiters;
_Atomic(int) sem_prefs; /* named only */
unsigned sem_magic;
int64_t sem_dev; /* named only */
int64_t sem_ino; /* named only */
int sem_pid; /* unnamed only */
bool sem_lazydelete; /* named only */
bool sem_pshared;
};
void *sem_space[32];
};
} sem_t;
int sem_init(sem_t *, int, unsigned);
int sem_destroy(sem_t *);
int sem_post(sem_t *);
int sem_wait(sem_t *);
int sem_trywait(sem_t *);
int sem_timedwait(sem_t *, const struct timespec *);
int sem_getvalue(sem_t *, int *);
sem_t *sem_open(const char *, int, ...);
int sem_close(sem_t *);
int sem_unlink(const char *);
const char *sem_path_np(const char *, char *, size_t);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_SEMAPHORE_H_ */
| 1,222 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_barrier_destroy.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/thread/thread.h"
#include "third_party/nsync/counter.h"
/**
* Destroys barrier.
*
* @return 0 on success, or error on failure
* @raise EINVAL if threads are still inside the barrier
*/
errno_t pthread_barrier_destroy(pthread_barrier_t *barrier) {
if (barrier->_nsync) {
nsync_counter_free(barrier->_nsync);
barrier->_nsync = 0;
}
return 0;
}
| 2,239 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/spawn.h | #ifndef COSMOPOLITAN_LIBC_THREAD_SPAWN_H_
#define COSMOPOLITAN_LIBC_THREAD_SPAWN_H_
#include "libc/thread/tls.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct spawn {
int ptid;
char *stk;
char *tls;
struct CosmoTib *tib;
};
int _spawn(int (*)(void *, int), void *, struct spawn *) _Hide;
int _join(struct spawn *) _Hide;
char *_mktls(struct CosmoTib **) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_THREAD_SPAWN_H_ */
| 507 | 21 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_setschedparam_freebsd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/sched_param.h"
#include "libc/sysv/consts/sched.h"
#include "libc/thread/freebsd.internal.h"
#include "libc/thread/posixthread.internal.h"
#define RTP_SET_FREEBSD 1
#define PRI_REALTIME_FREEBSD 2
#define RTP_PRIO_MAX_FREEBSD 31
#define PRI_FIFO_BIT_FREEBSD 8
#define PRI_FIFO_FREEBSD (PRI_REALTIME_FREEBSD | PRI_FIFO_BIT_FREEBSD)
#define PRI_TIMESHARE_FREEBSD 3
int sys_rtprio_thread(int fun, int tid, struct rtprio *inout_rtp);
int _pthread_setschedparam_freebsd(int tid, int policy,
const struct sched_param *param) {
struct rtprio rtp;
if (policy == SCHED_RR) {
rtp.type = PRI_REALTIME_FREEBSD;
rtp.prio = RTP_PRIO_MAX_FREEBSD - param->sched_priority;
} else if (policy == SCHED_FIFO) {
rtp.type = PRI_FIFO_FREEBSD;
rtp.prio = RTP_PRIO_MAX_FREEBSD - param->sched_priority;
} else {
rtp.type = PRI_TIMESHARE_FREEBSD;
rtp.prio = 0;
}
return sys_rtprio_thread(RTP_SET_FREEBSD, tid, &rtp);
}
| 2,843 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setschedparam.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/sched_param.h"
#include "libc/errno.h"
#include "libc/thread/thread2.h"
/**
* Sets thread scheduler parameter attribute, e.g.
*
* pthread_t id;
* pthread_attr_t attr;
* pthread_attr_init(&attr);
* struct sched_param pri = {sched_get_priority_min(SCHED_OTHER)};
* pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
* pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
* pthread_attr_setschedparam(&attr, &pri);
* pthread_create(&id, &attr, func, 0);
* pthread_attr_destroy(&attr);
* pthread_join(id, 0);
*
* @param param specifies priority on scheduling policies that need it
* @see pthread_attr_setschedpolicy()
* @see sched_get_priority_min()
* @see sched_get_priority_max()
* @see sched_setparam()
*/
errno_t pthread_attr_setschedparam(pthread_attr_t *attr,
const struct sched_param *param) {
attr->__schedparam = param->sched_priority;
return 0;
}
| 2,822 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_rwlock_destroy.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/thread/thread.h"
/**
* Destroys read-write lock.
*
* @return 0 on success, or error number on failure
* @raise EINVAL if any threads still hold the lock
*/
errno_t pthread_rwlock_destroy(pthread_rwlock_t *rwlock) {
memset(rwlock, -1, sizeof(*rwlock));
return 0;
}
| 2,151 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_timedwait.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/assert.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timespec.internal.h"
#include "libc/errno.h"
#include "libc/intrin/atomic.h"
#include "libc/limits.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/semaphore.h"
#include "libc/thread/thread.h"
#include "third_party/nsync/futex.internal.h"
static void sem_delay(int n) {
volatile int i;
for (i = 0; i != 1 << n; i++) donothing;
}
static void sem_timedwait_cleanup(void *arg) {
sem_t *sem = arg;
_unassert(atomic_fetch_add_explicit(&sem->sem_waiters, -1,
memory_order_acq_rel) > 0);
}
/**
* Locks semaphore w/ deadline.
*
* @param abstime is absolute deadline or null to wait forever
* @return 0 on success, or -1 w/ errno
* @raise ECANCELED if calling thread was cancelled in masked mode
* @raise EINTR if signal was delivered instead
* @raise EDEADLK if deadlock was detected
* @raise ETIMEDOUT if deadline expired
* @raise EINVAL if `sem` is invalid
* @cancellationpoint
*/
int sem_timedwait(sem_t *sem, const struct timespec *abstime) {
int e, i, v, rc;
struct timespec ts;
e = errno;
for (i = 0; i < 7; ++i) {
rc = sem_trywait(sem);
if (!rc) {
return rc;
} else if (errno == EAGAIN) {
errno = e;
sem_delay(i);
} else {
return rc;
}
}
BEGIN_CANCELLATION_POINT;
_unassert(atomic_fetch_add_explicit(&sem->sem_waiters, +1,
memory_order_acq_rel) >= 0);
pthread_cleanup_push(sem_timedwait_cleanup, sem);
do {
if (!(v = atomic_load_explicit(&sem->sem_value, memory_order_relaxed))) {
rc = nsync_futex_wait_(&sem->sem_value, v, true, abstime);
if (rc == -EINTR || rc == -ECANCELED) {
errno = -rc;
rc = -1;
} else if (rc == -EAGAIN || rc == -EWOULDBLOCK) {
rc = 0;
} else if (rc == -ETIMEDOUT) {
_npassert(abstime);
if (timespec_cmp(*abstime, timespec_real()) <= 0) {
rc = etimedout();
} else {
rc = 0;
}
} else {
_npassert(!rc);
rc = 0;
}
} else if (v > 0) {
rc = 0;
} else {
_unassert(v > INT_MIN);
rc = einval();
}
} while (!rc && (!v || !atomic_compare_exchange_weak_explicit(
&sem->sem_value, &v, v - 1, memory_order_acquire,
memory_order_relaxed)));
pthread_cleanup_pop(1);
END_CANCELLATION_POINT;
return rc;
}
| 4,376 | 110 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_barrierattr_setpshared.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/errno.h"
#include "libc/thread/thread.h"
/**
* Sets barrier process sharing.
*
* @param pshared can be one of
* - `PTHREAD_PROCESS_PRIVATE` (default)
* - `PTHREAD_PROCESS_SHARED` (unsupported)
* @return 0 on success, or error on failure
* @raises EINVAL if `pshared` is invalid
*/
errno_t pthread_barrierattr_setpshared(pthread_barrierattr_t *attr,
int pshared) {
switch (pshared) {
case PTHREAD_PROCESS_PRIVATE:
*attr = pshared;
return 0;
default:
return EINVAL;
}
}
| 2,405 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_getthreadid_np.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/thread/thread.h"
/**
* Returns thread id of current POSIX thread.
*/
pthread_id_np_t pthread_getthreadid_np(void) {
return gettid();
}
| 2,021 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_orphan_np.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/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
/**
* Returns true if calling thread is the only thread.
*/
int pthread_orphan_np(void) {
bool res;
pthread_spin_lock(&_pthread_lock);
res = _pthread_list == _pthread_list->prev &&
_pthread_list == _pthread_list->next;
pthread_spin_unlock(&_pthread_lock);
return res;
}
| 2,205 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/xnu.internal.h | #ifndef COSMOPOLITAN_LIBC_THREAD_XNU_INTERNAL_H_
#define COSMOPOLITAN_LIBC_THREAD_XNU_INTERNAL_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*
* XNU thread system calls.
* See darwin-libpthread/kern/kern_support.c
*/
errno_t sys_clone_xnu(void *func, void *func_arg, void *stack, void *pthread,
uint32_t flags);
int sys_bsdthread_register(
void (*threadstart)(void *pthread, int machport, void *(*func)(void *),
void *arg, intptr_t *, unsigned),
void (*wqthread)(void *pthread, void *machport, void *, void *, int),
uint32_t flags, void *stack_addr_hint, void *targetconc_ptr,
uint32_t dispatchqueue_offset, uint32_t tsd_offset);
int bsdthread_terminate(void *stackaddr, size_t freesize, uint32_t port,
uint32_t sem);
int __pthread_kill(uint32_t port, int sig);
int bsdthread_ctl(void *cmd, void *arg1, void *arg2, void *arg3);
uint64_t thread_selfid(void);
uint64_t thread_selfusage(void);
int thread_selfcounts(int type, void *buf, uint64_t nbytes);
int thread_fast_set_cthread_self(void *tls);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_THREAD_XNU_INTERNAL_H_ */
| 1,229 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_getvalue.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/intrin/atomic.h"
#include "libc/thread/semaphore.h"
/**
* Returns semaphore value.
*
* @param sem was created by sem_init()
* @param sval receives output value
* @return 0 on success, or -1 w/ errno
*/
int sem_getvalue(sem_t *sem, int *sval) {
*sval = atomic_load_explicit(&sem->sem_value, memory_order_relaxed);
return 0;
}
| 2,242 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setdetachstate.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/errno.h"
#include "libc/thread/thread.h"
/**
* Sets thread detachable attribute, e.g.
*
* pthread_attr_t attr;
* pthread_attr_init(&attr);
* pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
* pthread_create(0, &attr, func, 0);
* pthread_attr_destroy(&attr);
*
* @param detachstate can be one of
* - `PTHREAD_CREATE_JOINABLE` (default)
* - `PTHREAD_CREATE_DETACHED`
* @return 0 on success, or error on failure
* @raises EINVAL if `detachstate` is invalid
*/
errno_t pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate) {
switch (detachstate) {
case PTHREAD_CREATE_JOINABLE:
case PTHREAD_CREATE_DETACHED:
attr->__detachstate = detachstate;
return 0;
default:
return EINVAL;
}
}
| 2,630 | 47 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setstacksize.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/errno.h"
#include "libc/thread/thread.h"
/**
* Defines minimum stack size for thread.
*
* @param stacksize contains stack size in bytes
* @return 0 on success, or errno on error
* @raise EINVAL if `stacksize` is less than `PTHREAD_STACK_MIN`
*/
errno_t pthread_attr_setstacksize(pthread_attr_t *a, size_t stacksize) {
if (stacksize < PTHREAD_STACK_MIN) return EINVAL;
a->__stacksize = stacksize;
return 0;
}
| 2,272 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_barrier_wait.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/thread/thread.h"
#include "third_party/nsync/counter.h"
/**
* Waits for all threads to arrive at barrier.
*
* When the barrier is broken, the state becomes reset to what it was
* when pthread_barrier_init() was called, so that the barrior may be
* used again in the same way. The last thread to arrive shall be the
* last to leave and it returns a magic value.
*
* @return 0 on success, `PTHREAD_BARRIER_SERIAL_THREAD` to one lucky
* thread which was the last arrival, or an errno on error
*/
errno_t pthread_barrier_wait(pthread_barrier_t *barrier) {
if (nsync_counter_add(barrier->_nsync, -1)) {
nsync_counter_wait(barrier->_nsync, nsync_time_no_deadline);
return 0;
} else {
return PTHREAD_BARRIER_SERIAL_THREAD;
}
}
| 2,604 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/freebsd.internal.h | #ifndef COSMOPOLITAN_LIBC_THREAD_FREEBSD_INTERNAL_H_
#define COSMOPOLITAN_LIBC_THREAD_FREEBSD_INTERNAL_H_
#include "libc/calls/struct/timespec.h"
#include "libc/errno.h"
#include "libc/intrin/asmflag.h"
/**
* @fileoverview FreeBSD Threading
*
* @note even though FreeBSD uses a 64-bit type for thread IDs the
* maximum legal range is PID_MAX + 2 (100001) through INT_MAX
*/
#define THR_SUSPENDED 1
#define THR_SYSTEM_SCOPE 2
#define UMTX_OP_WAIT 2
#define UMTX_OP_WAIT_UINT 11
#define UMTX_OP_WAIT_UINT_PRIVATE 15
#define UMTX_OP_WAKE 3
#define UMTX_OP_WAKE_PRIVATE 16
#define UMTX_ABSTIME 1
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct rtprio {
uint16_t type; /* scheduling class */
uint16_t prio;
};
struct thr_param {
void (*start_func)(void *);
void *arg;
char *stack_base;
uint64_t stack_size;
char *tls_base;
uint64_t tls_size;
int64_t *child_tid;
int64_t *parent_tid;
int32_t flags;
struct rtprio *rtp;
};
struct _umtx_time {
struct timespec _timeout;
uint32_t _flags;
uint32_t _clockid;
};
int sys_umtx_timedwait_uint(_Atomic(int) *, int, bool, const struct timespec *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_THREAD_FREEBSD_INTERNAL_H_ */
| 1,329 | 56 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setinheritsched.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/assert.h"
#include "libc/errno.h"
#include "libc/thread/thread.h"
/**
* Sets thread scheduler inheritance attribute, e.g.
*
* pthread_t id;
* pthread_attr_t attr;
* pthread_attr_init(&attr);
* struct sched_param pri = {sched_get_priority_min(SCHED_OTHER)};
* pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
* pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
* pthread_attr_setschedparam(&attr, &pri);
* pthread_create(&id, &attr, func, 0);
* pthread_attr_destroy(&attr);
* pthread_join(id, 0);
*
* @param inheritsched may be one of:
* - `PTHREAD_INHERIT_SCHED` the default
* - `PTHREAD_EXPLICIT_SCHED` to enable rescheduling
* @return 0 on success, or errno on error
* @raise EINVAL on bad value
*/
errno_t pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched) {
switch (inheritsched) {
case PTHREAD_INHERIT_SCHED:
case PTHREAD_EXPLICIT_SCHED:
attr->__inheritsched = inheritsched;
return 0;
default:
return EINVAL;
}
}
| 2,900 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_ungarbage.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/nexgen32e/gc.internal.h"
#include "libc/thread/tls.h"
void _pthread_ungarbage(void) {
int i;
struct Garbages *g;
struct CosmoTib *tib;
tib = __get_tls();
while ((g = tib->tib_garbages)) {
tib->tib_garbages = 0;
while (g->i--) {
((void (*)(intptr_t))g->p[g->i].fn)(g->p[g->i].arg);
}
free(g->p);
free(g);
}
}
| 2,224 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setschedpolicy.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/thread/thread.h"
/**
* Sets thread scheduler policy attribute, e.g.
*
* pthread_t id;
* pthread_attr_t attr;
* pthread_attr_init(&attr);
* struct sched_param pri = {sched_get_priority_min(SCHED_OTHER)};
* pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
* pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
* pthread_attr_setschedparam(&attr, &pri);
* pthread_create(&id, &attr, func, 0);
* pthread_attr_destroy(&attr);
* pthread_join(id, 0);
*
* @param policy may be one of:
* - `SCHED_OTHER` the default policy
* - `SCHED_FIFO` for real-time scheduling (usually needs root)
* - `SCHED_RR` for round-robin scheduling (usually needs root)
* - `SCHED_IDLE` for lowest effort (Linux and FreeBSD only)
* - `SCHED_BATCH` for "batch" style execution of processes if
* supported (Linux), otherwise it's treated as `SCHED_OTHER`
* @see sched_setscheduler()
*/
errno_t pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy) {
attr->__schedpolicy = policy;
return 0;
}
| 2,921 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_mutexattr_settype.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/errno.h"
#include "libc/thread/thread.h"
/**
* Sets mutex type.
*
* @param type can be one of
* - `PTHREAD_MUTEX_NORMAL`
* - `PTHREAD_MUTEX_DEFAULT`
* - `PTHREAD_MUTEX_RECURSIVE`
* - `PTHREAD_MUTEX_ERRORCHECK`
* @return 0 on success, or error on failure
* @raises EINVAL if `type` is invalid
*/
errno_t pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type) {
switch (type) {
case PTHREAD_MUTEX_NORMAL:
case PTHREAD_MUTEX_RECURSIVE:
case PTHREAD_MUTEX_ERRORCHECK:
attr->_type = type;
return 0;
default:
return EINVAL;
}
}
| 2,446 | 44 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_setschedprio.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/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
/**
* Sets scheduler parameter on thread.
*/
errno_t pthread_setschedprio(pthread_t thread, int prio) {
struct PosixThread *pt = (struct PosixThread *)thread;
pt->attr.__schedparam = prio;
return _pthread_reschedule(pt);
}
| 2,146 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/sem_path_np.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/str/blake2.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/thread.h"
/**
* Returns filesystem pathname of named semaphore.
*
* @param name is `name` of semaphore which should begin with slash
* @param buf is temporary storage with at least `size` bytes
* @param size is size of `buf` in bytes
* @return pointer to file system path
* @raise ENAMETOOLONG if constructed path would exceed `size`
*/
const char *sem_path_np(const char *name, char *buf, size_t size) {
char *p;
unsigned n;
const char *path, *a;
uint8_t digest[BLAKE2B256_DIGEST_LENGTH];
a = "/tmp/", n = 5;
if (IsLinux() && isdirectory("/dev/shm")) {
a = "/dev/shm/", n = 9;
}
if (n + BLAKE2B256_DIGEST_LENGTH * 2 + 4 < size) {
BLAKE2B256(name, strlen(name), digest);
p = mempcpy(buf, a, n);
p = hexpcpy(p, digest, BLAKE2B256_DIGEST_LENGTH);
p = mempcpy(p, ".sem", 5);
path = buf;
} else {
enametoolong();
path = 0;
}
return path;
}
| 2,922 | 57 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_attr_setguardsize.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/thread/thread.h"
/**
* Sets size of unmapped pages at bottom of stack.
*
* @param guardsize contains guard size in bytes
* @return 0 on success, or errno on error
*/
errno_t pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize) {
attr->__guardsize = guardsize;
return 0;
}
| 2,146 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/thread/pthread_barrierattr_getpshared.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/thread/thread.h"
/**
* Gets barrier process sharing.
*
* @param pshared is set to one of the following
* - `PTHREAD_PROCESS_PRIVATE` (default)
* - `PTHREAD_PROCESS_SHARED` (unsupported)
* @return 0 on success, or error on failure
*/
errno_t pthread_barrierattr_getpshared(const pthread_barrierattr_t *attr,
int *pshared) {
*pshared = *attr;
return 0;
}
| 2,263 | 34 | jart/cosmopolitan | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.