2022-05-16 21:33:19 +00:00
|
|
|
#if 0
|
|
|
|
/*─────────────────────────────────────────────────────────────────╗
|
|
|
|
│ To the extent possible under law, Justine Tunney has waived │
|
|
|
|
│ all copyright and related or neighboring rights to this file, │
|
|
|
|
│ as it is written in the following disclaimers: │
|
|
|
|
│ • http://unlicense.org/ │
|
|
|
|
│ • http://creativecommons.org/publicdomain/zero/1.0/ │
|
|
|
|
╚─────────────────────────────────────────────────────────────────*/
|
|
|
|
#endif
|
2023-11-09 03:06:35 +00:00
|
|
|
#ifndef _COSMO_SOURCE
|
2023-10-12 03:26:28 +00:00
|
|
|
#define _COSMO_SOURCE
|
2023-11-09 03:06:35 +00:00
|
|
|
#endif
|
2023-10-12 03:26:28 +00:00
|
|
|
#include <assert.h>
|
|
|
|
#include <cosmo.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <netinet/in.h>
|
|
|
|
#include <netinet/tcp.h>
|
|
|
|
#include <pthread.h>
|
|
|
|
#include <signal.h>
|
|
|
|
#include <stdatomic.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/auxv.h>
|
|
|
|
#include <sys/socket.h>
|
|
|
|
#include <time.h>
|
2024-06-23 17:08:48 +00:00
|
|
|
#include "libc/mem/leaks.h"
|
2024-07-04 17:52:16 +00:00
|
|
|
#include "libc/runtime/runtime.h"
|
2022-05-14 14:44:02 +00:00
|
|
|
|
|
|
|
/**
|
2023-10-12 04:38:27 +00:00
|
|
|
* @fileoverview greenbean lightweight threaded web server
|
2022-05-14 14:44:02 +00:00
|
|
|
*/
|
|
|
|
|
2022-05-16 20:20:08 +00:00
|
|
|
#define PORT 8080
|
2023-10-12 03:26:28 +00:00
|
|
|
#define KEEPALIVE 5000
|
2023-09-07 10:24:46 +00:00
|
|
|
#define LOGGING 1
|
2022-05-14 14:44:02 +00:00
|
|
|
|
|
|
|
#define STANDARD_RESPONSE_HEADERS \
|
|
|
|
"Server: greenbean/1.o\r\n" \
|
|
|
|
"Referrer-Policy: origin\r\n" \
|
|
|
|
"Cache-Control: private; max-age=0\r\n"
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
int server;
|
2023-10-16 06:42:09 +00:00
|
|
|
int threads;
|
2023-09-07 10:24:46 +00:00
|
|
|
atomic_int a_termsig;
|
|
|
|
atomic_int a_workers;
|
|
|
|
atomic_int a_messages;
|
|
|
|
atomic_int a_connections;
|
|
|
|
pthread_cond_t statuscond;
|
|
|
|
pthread_mutex_t statuslock;
|
|
|
|
const char *volatile status = "";
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
#if LOGGING
|
|
|
|
// prints persistent status line
|
|
|
|
// \r moves cursor back to beginning of line
|
|
|
|
// \e[K clears text from cursor to end of line
|
|
|
|
#define LOG(FMT, ...) kprintf("\r\e[K" FMT "\n", ##__VA_ARGS__)
|
|
|
|
#else
|
|
|
|
#define LOG(FMT, ...) (void)0
|
|
|
|
#endif
|
|
|
|
|
|
|
|
// updates the status line if it's convenient to do so
|
2023-09-07 10:24:46 +00:00
|
|
|
void SomethingHappened(void) {
|
|
|
|
unassert(!pthread_cond_signal(&statuscond));
|
|
|
|
}
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// performs a guaranteed update of the main thread status line
|
2023-09-07 10:24:46 +00:00
|
|
|
void SomethingImportantHappened(void) {
|
|
|
|
unassert(!pthread_mutex_lock(&statuslock));
|
|
|
|
unassert(!pthread_cond_signal(&statuscond));
|
|
|
|
unassert(!pthread_mutex_unlock(&statuslock));
|
|
|
|
}
|
2022-05-15 16:14:48 +00:00
|
|
|
|
2023-10-16 06:42:09 +00:00
|
|
|
wontreturn void ExplainPrlimit(void) {
|
|
|
|
kprintf("error: you need more resources; try running:\n"
|
|
|
|
"sudo prlimit --pid=$$ --nofile=%d\n"
|
|
|
|
"sudo prlimit --pid=$$ --nproc=%d\n",
|
|
|
|
threads * 2, threads * 2);
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
2022-09-09 18:30:33 +00:00
|
|
|
void *Worker(void *id) {
|
2023-10-12 03:26:28 +00:00
|
|
|
pthread_setname_np(pthread_self(), "Worker");
|
2022-05-14 14:44:02 +00:00
|
|
|
|
|
|
|
// connection loop
|
2023-09-07 10:24:46 +00:00
|
|
|
while (!a_termsig) {
|
2023-10-12 03:26:28 +00:00
|
|
|
int client;
|
|
|
|
uint32_t clientsize;
|
|
|
|
int inmsglen, outmsglen;
|
2022-05-14 14:44:02 +00:00
|
|
|
struct sockaddr_in clientaddr;
|
2023-10-16 06:42:09 +00:00
|
|
|
char buf[1000], *p, *q;
|
2022-05-14 14:44:02 +00:00
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// musl libc and cosmopolitan libc support a posix thread extension
|
2023-10-11 18:45:31 +00:00
|
|
|
// that makes thread cancelation work much better. your io routines
|
2023-10-12 03:26:28 +00:00
|
|
|
// will just raise ECANCELED, so you can check for cancelation with
|
2023-09-07 10:24:46 +00:00
|
|
|
// normal logic rather than needing to push and pop cleanup handler
|
|
|
|
// functions onto the stack, or worse dealing with async interrupts
|
|
|
|
unassert(!pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0));
|
2022-05-16 20:20:08 +00:00
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
// wait for client connection
|
2023-10-12 03:26:28 +00:00
|
|
|
clientsize = sizeof(clientaddr);
|
|
|
|
client = accept(server, (struct sockaddr *)&clientaddr, &clientsize);
|
2022-05-14 14:44:02 +00:00
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// turn cancel off, so we don't need to check write() for ecanceled
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0));
|
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
if (client == -1) {
|
2023-10-12 03:26:28 +00:00
|
|
|
// accept() errors are generally ephemeral or recoverable
|
|
|
|
// it'd potentially be a good idea to exponential backoff here
|
|
|
|
if (errno == ECANCELED)
|
|
|
|
continue; // pthread_cancel() was called
|
2023-10-16 06:42:09 +00:00
|
|
|
if (errno == EMFILE)
|
|
|
|
ExplainPrlimit();
|
2023-10-12 03:26:28 +00:00
|
|
|
LOG("accept() returned %m");
|
|
|
|
SomethingHappened();
|
2022-05-14 14:44:02 +00:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// this causes read() and write() to raise eagain after some time
|
|
|
|
struct timeval timeo = {KEEPALIVE / 1000, KEEPALIVE % 1000};
|
|
|
|
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
|
|
|
|
setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo));
|
|
|
|
|
|
|
|
// log the incoming http message
|
|
|
|
unsigned clientip = ntohl(clientaddr.sin_addr.s_addr);
|
2023-09-07 10:24:46 +00:00
|
|
|
++a_connections;
|
2023-10-12 03:26:28 +00:00
|
|
|
LOG("%6H accepted connection from %hhu.%hhu.%hhu.%hhu:%hu", clientip >> 24,
|
|
|
|
clientip >> 16, clientip >> 8, clientip, ntohs(clientaddr.sin_port));
|
2023-09-07 10:24:46 +00:00
|
|
|
SomethingHappened();
|
2023-10-12 03:26:28 +00:00
|
|
|
(void)clientip;
|
2022-05-16 20:20:08 +00:00
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
// message loop
|
2023-09-07 10:24:46 +00:00
|
|
|
ssize_t got, sent;
|
|
|
|
struct HttpMessage msg;
|
2022-05-14 14:44:02 +00:00
|
|
|
do {
|
2023-10-12 03:26:28 +00:00
|
|
|
|
|
|
|
// wait for next http message (non-fragmented required)
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0));
|
2023-10-16 06:42:09 +00:00
|
|
|
got = read(client, buf, sizeof(buf));
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0));
|
2023-10-12 03:26:28 +00:00
|
|
|
if (got <= 0) {
|
|
|
|
if (!got) {
|
|
|
|
LOG("%6H client disconnected");
|
|
|
|
} else if (errno == EAGAIN) {
|
|
|
|
LOG("%6H client timed out");
|
|
|
|
} else if (errno == ECANCELED) {
|
|
|
|
LOG("%6H disconnecting client due to shutdown");
|
|
|
|
} else {
|
|
|
|
LOG("%6H read() returned %m");
|
|
|
|
}
|
|
|
|
SomethingHappened();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
// check that client message wasn't fragmented into more reads
|
2023-10-12 03:26:28 +00:00
|
|
|
InitHttpMessage(&msg, kHttpRequest);
|
2024-06-04 12:41:53 +00:00
|
|
|
if ((inmsglen = ParseHttpMessage(&msg, buf, got, sizeof(buf))) <= 0) {
|
2023-10-12 03:26:28 +00:00
|
|
|
if (!inmsglen) {
|
|
|
|
LOG("%6H client sent fragmented message");
|
|
|
|
} else {
|
|
|
|
LOG("%6H client sent bad message");
|
|
|
|
}
|
|
|
|
SomethingHappened();
|
|
|
|
break;
|
|
|
|
}
|
2022-05-14 14:44:02 +00:00
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// update server status with details of new message
|
|
|
|
++a_messages;
|
|
|
|
LOG("%6H received message from %hhu.%hhu.%hhu.%hhu:%hu for path %#.*s",
|
|
|
|
clientip >> 24, clientip >> 16, clientip >> 8, clientip,
|
2023-10-16 06:42:09 +00:00
|
|
|
ntohs(clientaddr.sin_port), msg.uri.b - msg.uri.a, buf + msg.uri.a);
|
2023-09-07 10:24:46 +00:00
|
|
|
SomethingHappened();
|
2022-05-14 14:44:02 +00:00
|
|
|
|
|
|
|
// display hello world html page for http://127.0.0.1:8080/
|
2023-09-07 10:24:46 +00:00
|
|
|
struct tm tm;
|
|
|
|
int64_t unixts;
|
|
|
|
struct timespec ts;
|
2022-05-14 14:44:02 +00:00
|
|
|
if (msg.method == kHttpGet &&
|
2023-10-16 06:42:09 +00:00
|
|
|
(msg.uri.b - msg.uri.a == 1 && buf[msg.uri.a + 0] == '/')) {
|
2022-05-14 14:44:02 +00:00
|
|
|
q = "<!doctype html>\r\n"
|
|
|
|
"<title>hello world</title>\r\n"
|
|
|
|
"<h1>hello world</h1>\r\n"
|
|
|
|
"<p>this is a fun webpage\r\n"
|
|
|
|
"<p>hosted by greenbean\r\n";
|
2023-10-16 06:42:09 +00:00
|
|
|
p = stpcpy(buf, "HTTP/1.1 200 OK\r\n" STANDARD_RESPONSE_HEADERS
|
|
|
|
"Content-Type: text/html; charset=utf-8\r\n"
|
|
|
|
"Date: ");
|
2022-05-23 17:15:53 +00:00
|
|
|
clock_gettime(0, &ts), unixts = ts.tv_sec;
|
2022-05-14 14:44:02 +00:00
|
|
|
p = FormatHttpDateTime(p, gmtime_r(&unixts, &tm));
|
|
|
|
p = stpcpy(p, "\r\nContent-Length: ");
|
|
|
|
p = FormatInt32(p, strlen(q));
|
|
|
|
p = stpcpy(p, "\r\n\r\n");
|
|
|
|
p = stpcpy(p, q);
|
2023-10-16 06:42:09 +00:00
|
|
|
outmsglen = p - buf;
|
|
|
|
sent = write(client, buf, outmsglen);
|
2022-05-14 14:44:02 +00:00
|
|
|
|
|
|
|
} else {
|
|
|
|
// display 404 not found error page for every thing else
|
|
|
|
q = "<!doctype html>\r\n"
|
|
|
|
"<title>404 not found</title>\r\n"
|
|
|
|
"<h1>404 not found</h1>\r\n";
|
2023-10-16 06:42:09 +00:00
|
|
|
p = stpcpy(buf, "HTTP/1.1 404 Not Found\r\n" STANDARD_RESPONSE_HEADERS
|
|
|
|
"Content-Type: text/html; charset=utf-8\r\n"
|
|
|
|
"Date: ");
|
2022-05-23 17:15:53 +00:00
|
|
|
clock_gettime(0, &ts), unixts = ts.tv_sec;
|
2022-05-14 14:44:02 +00:00
|
|
|
p = FormatHttpDateTime(p, gmtime_r(&unixts, &tm));
|
|
|
|
p = stpcpy(p, "\r\nContent-Length: ");
|
|
|
|
p = FormatInt32(p, strlen(q));
|
|
|
|
p = stpcpy(p, "\r\n\r\n");
|
|
|
|
p = stpcpy(p, q);
|
2023-10-16 06:42:09 +00:00
|
|
|
outmsglen = p - buf;
|
|
|
|
sent = write(client, buf, p - buf);
|
2022-05-14 14:44:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// if the client isn't pipelining and write() wrote the full
|
|
|
|
// amount, then since we sent the content length and checked
|
|
|
|
// that the client didn't attach a payload, we are so synced
|
|
|
|
// thus we can safely process more messages
|
2023-10-12 03:26:28 +00:00
|
|
|
} while (got == inmsglen && //
|
2023-09-07 10:24:46 +00:00
|
|
|
sent == outmsglen && //
|
2022-05-14 14:44:02 +00:00
|
|
|
!msg.headers[kHttpContentLength].a &&
|
|
|
|
!msg.headers[kHttpTransferEncoding].a &&
|
|
|
|
(msg.method == kHttpGet || msg.method == kHttpHead));
|
2023-10-12 03:26:28 +00:00
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
DestroyHttpMessage(&msg);
|
2023-09-07 10:24:46 +00:00
|
|
|
--a_connections;
|
|
|
|
SomethingHappened();
|
2023-10-12 03:26:28 +00:00
|
|
|
close(client);
|
2022-05-14 14:44:02 +00:00
|
|
|
}
|
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
--a_workers;
|
|
|
|
SomethingImportantHappened();
|
|
|
|
return 0;
|
2022-05-14 14:44:02 +00:00
|
|
|
}
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
void PrintEphemeralStatusLine(void) {
|
2022-05-23 17:15:53 +00:00
|
|
|
kprintf("\r\e[K\e[32mgreenbean\e[0m "
|
|
|
|
"workers=%d "
|
|
|
|
"connections=%d "
|
|
|
|
"messages=%d%s ",
|
2023-10-12 03:26:28 +00:00
|
|
|
a_workers, a_connections, a_messages, status);
|
2023-09-07 10:24:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void OnTerm(int sig) {
|
|
|
|
a_termsig = sig;
|
|
|
|
status = " shutting down...";
|
|
|
|
SomethingHappened();
|
2022-05-23 17:15:53 +00:00
|
|
|
}
|
|
|
|
|
2022-05-14 14:44:02 +00:00
|
|
|
int main(int argc, char *argv[]) {
|
2023-09-07 10:24:46 +00:00
|
|
|
int i;
|
2022-05-23 17:15:53 +00:00
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// print cpu registers and backtrace on crash
|
|
|
|
// note that pledge'll makes backtraces worse
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
// you can press ctrl+\ to trigger backtraces
|
2023-10-09 18:56:21 +00:00
|
|
|
// ShowCrashReports();
|
2022-05-23 17:15:53 +00:00
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// listen for ctrl-c, terminal close, and kill
|
|
|
|
struct sigaction sa = {.sa_handler = OnTerm};
|
|
|
|
unassert(!sigaction(SIGINT, &sa, 0));
|
|
|
|
unassert(!sigaction(SIGHUP, &sa, 0));
|
|
|
|
unassert(!sigaction(SIGTERM, &sa, 0));
|
|
|
|
|
|
|
|
// you can pass the number of threads you want as the first command arg
|
2023-10-16 06:42:09 +00:00
|
|
|
threads = argc > 1 ? atoi(argv[1]) : __get_cpu_count();
|
2022-07-10 15:27:50 +00:00
|
|
|
if (!(1 <= threads && threads <= 100000)) {
|
2023-10-12 03:26:28 +00:00
|
|
|
tinyprint(2, "error: invalid number of threads\n", NULL);
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
// create listening socket that'll be shared by threads
|
|
|
|
int yes = 1;
|
|
|
|
struct sockaddr_in addr = {.sin_family = AF_INET, .sin_port = htons(PORT)};
|
|
|
|
server = socket(AF_INET, SOCK_STREAM, 0);
|
|
|
|
if (server == -1) {
|
|
|
|
perror("socket");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
setsockopt(server, SOL_TCP, TCP_FASTOPEN, &yes, sizeof(yes));
|
|
|
|
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
|
|
|
if (bind(server, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
|
|
|
|
perror("bind");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
if (listen(server, SOMAXCONN)) {
|
|
|
|
perror("listen");
|
2022-07-10 11:01:17 +00:00
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// print all the ips that 0.0.0.0 would bind
|
|
|
|
// Cosmo's GetHostIps() API is much easier than ioctl(SIOCGIFCONF)
|
|
|
|
uint32_t *hostips;
|
2024-07-07 22:55:55 +00:00
|
|
|
for (hostips = GetHostIps(), i = 0; hostips[i]; ++i) {
|
2023-10-12 03:26:28 +00:00
|
|
|
kprintf("listening on http://%hhu.%hhu.%hhu.%hhu:%hu\n", hostips[i] >> 24,
|
|
|
|
hostips[i] >> 16, hostips[i] >> 8, hostips[i], PORT);
|
2023-09-07 10:24:46 +00:00
|
|
|
}
|
2024-07-07 22:55:55 +00:00
|
|
|
free(hostips);
|
2023-09-07 10:24:46 +00:00
|
|
|
|
2022-07-25 02:40:32 +00:00
|
|
|
// secure the server
|
2023-09-07 10:24:46 +00:00
|
|
|
//
|
|
|
|
// pledge() and unveil() let us whitelist which system calls and files
|
|
|
|
// the server will be allowed to use. this way if it gets hacked, they
|
|
|
|
// won't be able to do much damage, like compromising the whole server
|
|
|
|
//
|
|
|
|
// pledge violations on openbsd are logged nicely to the system logger
|
|
|
|
// but on linux we need to use a cosmopolitan extension to get details
|
|
|
|
// although doing that slightly weakens the security pledge() provides
|
|
|
|
//
|
|
|
|
// if your operating system doesn't support these security features or
|
|
|
|
// is too old, then pledge() and unveil() don't consider this an error
|
|
|
|
// so it works. if security is critical there's a special call to test
|
|
|
|
// which is npassert(!pledge(0, 0)), and npassert(unveil("", 0) != -1)
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
__pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; // c. greenbean --strace
|
2022-07-25 02:40:32 +00:00
|
|
|
unveil("/dev/null", "rw");
|
|
|
|
unveil(0, 0);
|
|
|
|
pledge("stdio inet", 0);
|
|
|
|
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
// initialize our synchronization data structures, which were written
|
|
|
|
// by mike burrows in a library called *nsync we've tailored for libc
|
|
|
|
unassert(!pthread_cond_init(&statuscond, 0));
|
|
|
|
unassert(!pthread_mutex_init(&statuslock, 0));
|
|
|
|
|
|
|
|
// spawn over 9000 worker threads
|
2023-09-07 10:24:46 +00:00
|
|
|
//
|
|
|
|
// you don't need weird i/o models, or event driven yoyo pattern code
|
|
|
|
// to build a massively scalable server. the secret is to use threads
|
|
|
|
// with tiny stacks. then you can write plain simple imperative code!
|
|
|
|
//
|
|
|
|
// we block signals in our worker threads so we won't need messy code
|
|
|
|
// to spin on eintr. operating systems also deliver signals to random
|
|
|
|
// threads, and we'd have ctrl-c, etc. be handled by the main thread.
|
|
|
|
//
|
|
|
|
// alternatively you can just use signal() instead of sigaction(); it
|
|
|
|
// uses SA_RESTART because all the syscalls the worker currently uses
|
|
|
|
// are documented as @restartable which means no EINTR toil is needed
|
|
|
|
sigset_t block;
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
sigemptyset(&block);
|
|
|
|
sigaddset(&block, SIGINT);
|
|
|
|
sigaddset(&block, SIGHUP);
|
|
|
|
sigaddset(&block, SIGQUIT);
|
2023-09-07 10:24:46 +00:00
|
|
|
pthread_attr_t attr;
|
|
|
|
unassert(!pthread_attr_init(&attr));
|
Make improvements
- Every unit test now passes on Apple Silicon. The final piece of this
puzzle was porting our POSIX threads cancelation support, since that
works differently on ARM64 XNU vs. AMD64. Our semaphore support on
Apple Silicon is also superior now compared to AMD64, thanks to the
grand central dispatch library which lets *NSYNC locks go faster.
- The Cosmopolitan runtime is now more stable, particularly on Windows.
To do this, thread local storage is mandatory at all runtime levels,
and the innermost packages of the C library is no longer being built
using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
process startup phase, and then later on the runtime re-allocates it
either statically or dynamically to support code using _Thread_local.
fork() and execve() now do a better job cooperating with threads. We
can now check how much stack memory is left in the process or thread
when functions like kprintf() / execve() etc. call alloca(), so that
ENOMEM can be raised, reduce a buffer size, or just print a warning.
- POSIX signal emulation is now implemented the same way kernels do it
with pthread_kill() and raise(). Any thread can interrupt any other
thread, regardless of what it's doing. If it's blocked on read/write
then the killer thread will cancel its i/o operation so that EINTR can
be returned in the mark thread immediately. If it's doing a tight CPU
bound operation, then that's also interrupted by the signal delivery.
Signal delivery works now by suspending a thread and pushing context
data structures onto its stack, and redirecting its execution to a
trampoline function, which calls SetThreadContext(GetCurrentThread())
when it's done.
- We're now doing a better job managing locks and handles. On NetBSD we
now close semaphore file descriptors in forked children. Semaphores on
Windows can now be canceled immediately, which means mutexes/condition
variables will now go faster. Apple Silicon semaphores can be canceled
too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
syscalls are now used on XNU when appropriate to ensure pthread_cancel
requests aren't lost. The MbedTLS library has been updated to support
POSIX thread cancelations. See tool/build/runitd.c for an example of
how it can be used for production multi-threaded tls servers. Handles
on Windows now leak less often across processes. All i/o operations on
Windows are now overlapped, which means file pointers can no longer be
inherited across dup() and fork() for the time being.
- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
which means, for example, that posix_spawn() now goes 3x faster. POSIX
spawn is also now more correct. Like Musl, it's now able to report the
failure code of execve() via a pipe although our approach favors using
shared memory to do that on systems that have a true vfork() function.
- We now spawn a thread to deliver SIGALRM to threads when setitimer()
is used. This enables the most precise wakeups the OS makes possible.
- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
it turned out the kernel would actually commit the PT_GNU_STACK size
which caused RSS to be 6mb for every process. Now it's down to ~4kb.
On Apple Silicon, we reduce the mandatory upstream thread size to the
smallest possible size to reduce the memory overhead of Cosmo threads.
The examples directory has a program called greenbean which can spawn
a web server on Linux with 10,000 worker threads and have the memory
usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
thread-local storage is now optional; it won't be allocated until the
pthread_setspecific/getspecific functions are called. On Windows, the
threads that get spawned which are internal to the libc implementation
use reserve rather than commit memory, which shaves a few hundred kb.
- sigaltstack() is now supported on Windows, however it's currently not
able to be used to handle stack overflows, since crash signals are
still generated by WIN32. However the crash handler will still switch
to the alt stack, which is helpful in environments with tiny threads.
- Test binaries are now smaller. Many of the mandatory dependencies of
the test runner have been removed. This ensures many programs can do a
better job only linking the the thing they're testing. This caused the
test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb
- long double is no longer used in the implementation details of libc,
except in the APIs that define it. The old code that used long double
for time (instead of struct timespec) has now been thoroughly removed.
- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
backtraces itself, it'll just print a command you can run on the shell
using our new `cosmoaddr2line` program to view the backtrace.
- Crash report signal handling now works in a much better way. Instead
of terminating the process, it now relies on SA_RESETHAND so that the
default SIG_IGN behavior can terminate the process if necessary.
- Our pledge() functionality has now been fully ported to AARCH64 Linux.
2023-09-19 03:44:45 +00:00
|
|
|
unassert(!pthread_attr_setstacksize(&attr, 65536));
|
2024-07-04 17:52:16 +00:00
|
|
|
unassert(!pthread_attr_setguardsize(&attr, getpagesize()));
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_attr_setsigmask_np(&attr, &block));
|
2023-10-12 03:26:28 +00:00
|
|
|
unassert(!pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0));
|
2024-07-07 22:55:55 +00:00
|
|
|
pthread_t *th = calloc(threads, sizeof(pthread_t));
|
2022-07-10 11:01:17 +00:00
|
|
|
for (i = 0; i < threads; ++i) {
|
2023-09-07 10:24:46 +00:00
|
|
|
int rc;
|
|
|
|
++a_workers;
|
|
|
|
if ((rc = pthread_create(th + i, &attr, Worker, (void *)(intptr_t)i))) {
|
|
|
|
--a_workers;
|
2023-10-12 03:26:28 +00:00
|
|
|
kprintf("pthread_create failed: %s\n", strerror(rc));
|
2023-10-16 06:42:09 +00:00
|
|
|
if (rc == EAGAIN)
|
|
|
|
ExplainPrlimit();
|
2023-09-07 10:24:46 +00:00
|
|
|
if (!i)
|
|
|
|
exit(1);
|
|
|
|
threads = i;
|
|
|
|
break;
|
2022-07-10 11:01:17 +00:00
|
|
|
}
|
2023-09-07 10:24:46 +00:00
|
|
|
if (!(i % 50)) {
|
2023-10-12 03:26:28 +00:00
|
|
|
PrintEphemeralStatusLine();
|
2022-07-10 11:01:17 +00:00
|
|
|
}
|
2022-05-14 14:44:02 +00:00
|
|
|
}
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_attr_destroy(&attr));
|
2022-05-23 17:15:53 +00:00
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// show status line on terminal until terminated
|
|
|
|
struct timespec tick = timespec_real();
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_mutex_lock(&statuslock));
|
|
|
|
while (!a_termsig) {
|
2023-10-12 03:26:28 +00:00
|
|
|
PrintEphemeralStatusLine();
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_cond_wait(&statuscond, &statuslock));
|
2023-10-12 03:26:28 +00:00
|
|
|
// limit status line updates to sixty frames per second
|
|
|
|
do
|
|
|
|
tick = timespec_add(tick, (struct timespec){0, 1e9 / 60});
|
|
|
|
while (timespec_cmp(tick, timespec_real()) < 0);
|
|
|
|
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, 0);
|
2022-05-16 20:20:08 +00:00
|
|
|
}
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_mutex_unlock(&statuslock));
|
2022-05-23 17:15:53 +00:00
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// cancel all the worker threads so they shut down asap
|
|
|
|
// and it'll wait on active clients to gracefully close
|
|
|
|
// you've never seen a production server close so fast!
|
|
|
|
for (i = 0; i < threads; ++i) {
|
|
|
|
pthread_cancel(th[i]);
|
|
|
|
}
|
2022-05-23 17:15:53 +00:00
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// on windows this is the only way accept() can be canceled
|
|
|
|
if (IsWindows())
|
|
|
|
close(server);
|
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// print status in terminal as the shutdown progresses
|
|
|
|
unassert(!pthread_mutex_lock(&statuslock));
|
|
|
|
while (a_workers) {
|
|
|
|
unassert(!pthread_cond_wait(&statuscond, &statuslock));
|
2023-10-12 03:26:28 +00:00
|
|
|
PrintEphemeralStatusLine();
|
2023-09-07 10:24:46 +00:00
|
|
|
}
|
|
|
|
unassert(!pthread_mutex_unlock(&statuslock));
|
|
|
|
|
|
|
|
// wait for final termination and free thread memory
|
2022-07-10 11:01:17 +00:00
|
|
|
for (i = 0; i < threads; ++i) {
|
2023-09-07 10:24:46 +00:00
|
|
|
unassert(!pthread_join(th[i], 0));
|
|
|
|
}
|
2024-07-07 22:55:55 +00:00
|
|
|
free(th);
|
2023-09-07 10:24:46 +00:00
|
|
|
|
2023-10-12 03:26:28 +00:00
|
|
|
// close the server socket
|
|
|
|
if (!IsWindows())
|
|
|
|
close(server);
|
|
|
|
|
2023-09-07 10:24:46 +00:00
|
|
|
// clean up terminal line
|
2023-10-12 03:26:28 +00:00
|
|
|
LOG("thank you for choosing \e[32mgreenbean\e[0m");
|
2023-09-07 10:24:46 +00:00
|
|
|
|
|
|
|
// clean up more resources
|
|
|
|
unassert(!pthread_cond_destroy(&statuscond));
|
2023-10-12 03:26:28 +00:00
|
|
|
unassert(!pthread_mutex_destroy(&statuslock));
|
2023-09-07 10:24:46 +00:00
|
|
|
|
|
|
|
// quality assurance
|
2024-06-23 17:08:48 +00:00
|
|
|
CheckForMemoryLeaks();
|
2022-05-14 14:44:02 +00:00
|
|
|
}
|