repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
zap | github_2023 | zigzap | c | on_repl_message | static void on_repl_message(fio_msg_s *msg) {
fio_write((intptr_t)msg->udata1, msg->msg.data, msg->msg.len);
} | /* Forward REPL messages to the socket - pub/sub callback */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-client.c#L119-L121 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | main | int main(int argc, char const *argv[]) {
/* Setup CLI arguments */
fio_cli_start(argc, argv, 1, 2, "use:\n\tclient <args> hostname port\n",
FIO_CLI_BOOL("-tls use TLS to establish a secure connection."),
FIO_CLI_STRING("-tls-alpn set the ALPN extension for TLS."),
FIO_CLI_STRING("-trust comma separated list of PEM "
"certification files for TLS verification."),
FIO_CLI_INT("-v -verbousity sets the verbosity level 0..5 (5 "
"== debug, 0 == quite)."));
/* set logging level */
FIO_LOG_LEVEL = FIO_LOG_LEVEL_ERROR;
if (fio_cli_get("-v") && fio_cli_get_i("-v") >= 0)
FIO_LOG_LEVEL = fio_cli_get_i("-v");
/* Manage TLS */
fio_tls_s *tls = NULL;
if (fio_cli_get_bool("-tls")) {
tls = fio_tls_new(NULL, NULL, NULL, NULL);
if (fio_cli_get("-trust")) {
const char *trust = fio_cli_get("-trust");
size_t len = strlen(trust);
const char *end = memchr(trust, ',', len);
while (end) {
/* copy partial string to attach NUL char at end of file name */
fio_str_s tmp = FIO_STR_INIT;
fio_str_info_s t = fio_str_write(&tmp, trust, end - trust);
fio_tls_trust(tls, t.data);
fio_str_free(&tmp);
len -= (end - trust) + 1;
trust = end + 1;
end = memchr(trust, ',', len);
}
fio_tls_trust(tls, trust);
}
if (fio_cli_get("-tls-alpn")) {
fio_tls_alpn_add(tls, fio_cli_get("-tls-alpn"), NULL, NULL, NULL);
}
}
/* Attach REPL */
repl_attach();
/* Log connection attempt */
if (fio_cli_unnamed_count() == 1 || fio_cli_unnamed(1)[0] == 0 ||
(fio_cli_unnamed(1)[0] == '0' || fio_cli_unnamed(1)[1] == 0)) {
FIO_LOG_INFO("Attempting to connect to Unix socket at: %s\n",
fio_cli_unnamed(0));
} else {
FIO_LOG_INFO("Attempting to connect to TCP/IP socket at: %s:%s\n",
fio_cli_unnamed(0), fio_cli_unnamed(1));
}
intptr_t uuid =
fio_connect(.address = fio_cli_unnamed(0), .port = fio_cli_unnamed(1),
.on_connect = on_connect, .on_fail = on_fail, .udata = tls);
if (uuid == -1 && fio_cli_get_bool("-v"))
FIO_LOG_ERROR("Connection can't be established");
else
fio_start(.threads = 1);
fio_tls_destroy(tls);
fio_cli_end();
} | /* *****************************************************************************
Main
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-client.c#L154-L216 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | echo_on_data | static void echo_on_data(intptr_t uuid, fio_protocol_s *prt) {
// echo buffer
char buffer[1024] = {'E', 'c', 'h', 'o', ':', ' '};
ssize_t len;
// Read to the buffer, starting after the "Echo: "
while ((len = fio_read(uuid, buffer + 6, 1018)) > 0) {
fprintf(stderr, "Read: %.*s", (int)len, buffer + 6);
// Write back the message
fio_write(uuid, buffer, len + 6);
// Handle goodbye
if ((buffer[6] | 32) == 'b' && (buffer[7] | 32) == 'y' &&
(buffer[8] | 32) == 'e') {
fio_write(uuid, "Goodbye.\n", 9);
fio_close(uuid);
return;
}
}
(void)prt; // we can ignore the unused argument
} | /* *****************************************************************************
Echo connection callbacks
***************************************************************************** */
// A callback to be called whenever data is available on the socket | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-echo.c#L30-L48 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | echo_ping | static void echo_ping(intptr_t uuid, fio_protocol_s *prt) {
fio_write(uuid, "Server: Are you there?\n", 23);
(void)prt; // we can ignore the unused argument
} | // A callback called whenever a timeout is reach | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-echo.c#L51-L54 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | echo_on_shutdown | static uint8_t echo_on_shutdown(intptr_t uuid, fio_protocol_s *prt) {
fio_write(uuid, "Echo server shutting down\nGoodbye.\n", 35);
return 0;
(void)prt; // we can ignore the unused argument
} | // A callback called if the server is shutting down...
// ... while the connection is still open | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-echo.c#L58-L62 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | echo_on_open | static void echo_on_open(intptr_t uuid, void *udata) {
// Protocol objects MUST be dynamically allocated when multi-threading.
fio_protocol_s *echo_proto = malloc(sizeof(*echo_proto));
*echo_proto = (fio_protocol_s){.on_data = echo_on_data,
.on_shutdown = echo_on_shutdown,
.on_close = echo_on_close,
.ping = echo_ping};
fprintf(stderr, "New Connection %p received from %s\n", (void *)echo_proto,
fio_peer_addr(uuid).data);
fio_attach(uuid, echo_proto);
fio_write2(uuid, .data.buffer = "Echo Service: Welcome\n", .length = 22,
.after.dealloc = FIO_DEALLOC_NOOP);
fio_timeout_set(uuid, 5);
(void)udata; // ignore this
} | /* *****************************************************************************
The main echo protocol creation callback
***************************************************************************** */
// A callback called for new connections | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-echo.c#L75-L89 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | main | int main(int argc, char const *argv[]) {
/* Setup CLI arguments */
fio_cli_start(argc, argv, 0, 0, "this example accepts the following options:",
FIO_CLI_INT("-t -thread number of threads to run."),
FIO_CLI_INT("-w -workers number of workers to run."),
"-b, -address the address to bind to.",
FIO_CLI_INT("-p,-port the port to bind to."),
FIO_CLI_BOOL("-v -log enable logging."));
/* Setup default values */
fio_cli_set_default("-p", "3000");
fio_cli_set_default("-t", "1");
fio_cli_set_default("-w", "1");
/* Listen for connections */
if (fio_listen(.port = fio_cli_get("-p"), .on_open = echo_on_open) == -1) {
perror("No listening socket available on port 3000");
exit(-1);
}
/* Run the server and hang until a stop signal is received */
fio_start(.threads = fio_cli_get_i("-t"), .workers = fio_cli_get_i("-w"));
} | /* *****************************************************************************
The main function (listens to the `echo` connections and handles CLI)
***************************************************************************** */
// The main function starts listening to echo connections | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-echo.c#L96-L117 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | on_http_request | int on_http_request(light_http_s *http) {
/* handle a request for `http->path` */
if (1) {
/* a simple, hardcoded HTTP/1.1 response */
static char HTTP_RESPONSE[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 13\r\n"
"Connection: keep-alive\r\n"
"Content-Type: text/plain\r\n"
"\r\n"
"Hello Wolrld!";
fio_write2(http->uuid, .data.buffer = HTTP_RESPONSE,
.length = sizeof(HTTP_RESPONSE) - 1,
.after.dealloc = FIO_DEALLOC_NOOP);
} else {
/* an allocated, dynamic, HTTP/1.1 response */
light_http_send_response(
http->uuid, 200, (fio_str_info_s){.len = 2, .data = "OK"}, 1,
(fio_str_info_s[][2]){{{.len = 12, .data = "Content-Type"},
{.len = 10, .data = "text/plain"}}},
(fio_str_info_s){.len = 13, .data = "Hello Wolrld!"});
}
return 0;
} | /* *****************************************************************************
The HTTP/1.1 Request Handler - change this to whateve you feel like.
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L85-L107 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | main | int main(int argc, char const *argv[]) {
/* A simple CLI interface. */
fio_cli_start(argc, argv, 0, 0,
"Custom HTTP example for the facil.io framework.",
FIO_CLI_INT("-port -p Port to bind to. Default: 3000"),
FIO_CLI_INT("-workers -w Number of workers (processes)."),
FIO_CLI_INT("-threads -t Number of threads."));
/* Default to port 3000. */
fio_cli_set_default("-p", "3000");
/* Default to single thread. */
fio_cli_set_default("-t", "1");
/* try to listen on port 3000. */
if (fio_listen(.port = fio_cli_get("-p"), .address = NULL,
.on_open = light_http_on_open, .udata = NULL) == -1)
perror("FATAL ERROR: Couldn't open listening socket"), exit(errno);
/* run facil with 1 working thread - this blocks until we're done. */
fio_start(.threads = fio_cli_get_i("-t"), .workers = fio_cli_get_i("-w"));
/* clean up */
fio_cli_end();
return 0;
} | /* our main function / starting point */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L117-L137 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_request | int light_http1_on_request(http1_parser_s *parser) {
int ret = on_http_request(parser2pr(parser));
fio_str_free(&parser2pr(parser)->body);
parser2pr(parser)->reset = 1;
return ret;
} | /* *****************************************************************************
The HTTP/1.1 Parsing Callbacks - we need to implememnt everything for the parser
***************************************************************************** */
/** called when a request was received. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L144-L149 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_response | int light_http1_on_response(http1_parser_s *parser) {
return -1;
(void)parser;
} | /** called when a response was received, this is for HTTP clients (error). */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L152-L155 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_method | int light_http1_on_method(http1_parser_s *parser, char *method,
size_t method_len) {
parser2pr(parser)->method = method;
return 0;
(void)method_len;
} | /** called when a request method is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L158-L163 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_status | int light_http1_on_status(http1_parser_s *parser, size_t status,
char *status_str, size_t len) {
return -1;
(void)parser;
(void)status;
(void)status_str;
(void)len;
} | /** called when a response status is parsed. the status_str is the string
* without the prefixed numerical status indicator.*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L167-L174 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_path | int light_http1_on_path(http1_parser_s *parser, char *path, size_t path_len) {
parser2pr(parser)->path = path;
return 0;
(void)path_len;
} | /** called when a request path (excluding query) is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L176-L180 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_query | int light_http1_on_query(http1_parser_s *parser, char *query,
size_t query_len) {
parser2pr(parser)->query = query;
return 0;
(void)query_len;
} | /** called when a request path (excluding query) is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L182-L187 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_http_version | int light_http1_on_http_version(http1_parser_s *parser, char *version,
size_t len) {
parser2pr(parser)->http_version = version;
return 0;
(void)len;
} | /** called when a the HTTP/1.x version is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L189-L194 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_header | int light_http1_on_header(http1_parser_s *parser, char *name, size_t name_len,
char *data, size_t data_len) {
if (parser2pr(parser)->header_count >= MAX_HTTP_HEADER_COUNT)
return -1;
parser2pr(parser)->headers[parser2pr(parser)->header_count] = name;
parser2pr(parser)->values[parser2pr(parser)->header_count] = data;
++parser2pr(parser)->header_count;
return 0;
(void)name_len;
(void)data_len;
} | /** called when a header is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L196-L206 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_body_chunk | int light_http1_on_body_chunk(http1_parser_s *parser, char *data,
size_t data_len) {
if (parser->state.content_length >= MAX_HTTP_BODY_MAX)
return -1;
if (fio_str_write(&parser2pr(parser)->body, data, data_len).len >=
MAX_HTTP_BODY_MAX)
return -1;
return 0;
} | /** called when a body chunk is parsed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L209-L217 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http1_on_error | int light_http1_on_error(http1_parser_s *parser) {
/* close the connection */
fio_close(parser2pr(parser)->uuid);
return 0;
} | /** called when a protocol error occurred. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L220-L224 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http_on_open | void light_http_on_open(intptr_t uuid, void *udata) {
/*
* we should allocate a protocol object for this connection.
*
* since protocol objects are stateful (the parsing, internal locks, etc'), we
* need a different protocol object per connection.
*
* NOTE: the extra length in the memory will be the R/W buffer.
*/
light_http_s *p =
malloc(sizeof(*p) + MAX_HTTP_HEADER_LENGTH + MIN_HTTP_READFILE);
*p = (light_http_s){
.protocol.on_data = light_http_on_data, /* setting the data callback */
.protocol.on_close = light_http_on_close, /* setting the close callback */
.uuid = uuid,
.body = FIO_STR_INIT,
};
/* timeouts are important. timeouts are in seconds. */
fio_timeout_set(uuid, 5);
/*
* this is a very IMPORTANT function call,
* it attaches the protocol to the socket.
*/
fio_attach(uuid, &p->protocol);
/* the `udata` wasn't used, but it's good for dynamic settings and such */
(void)udata;
} | /* this will be called when a connection is opened. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L235-L261 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http_on_data | void light_http_on_data(intptr_t uuid, fio_protocol_s *pr) {
/* We will read some / all of the data */
light_http_s *h = (light_http_s *)pr;
ssize_t tmp =
fio_read(uuid, (char *)(h + 1) + h->buf_writer,
(MAX_HTTP_HEADER_LENGTH + MIN_HTTP_READFILE) - h->buf_writer);
if (tmp <= 0) {
/* reading failed, we're done. */
return;
}
h->buf_writer += tmp;
/* feed the parser until it's done consuminng data. */
do {
tmp = http1_fio_parser(.parser = &h->parser,
.buffer = (char *)(h + 1) + h->buf_reader,
.length = h->buf_writer - h->buf_reader,
.on_request = light_http1_on_request,
.on_response = light_http1_on_response,
.on_method = light_http1_on_method,
.on_status = light_http1_on_status,
.on_path = light_http1_on_path,
.on_query = light_http1_on_query,
.on_http_version = light_http1_on_http_version,
.on_header = light_http1_on_header,
.on_body_chunk = light_http1_on_body_chunk,
.on_error = light_http1_on_error);
if (fio_str_len(&h->body)) {
/* when reading to a body, the data is copied */
/* keep the reading position at buf_reader. */
h->buf_writer -= tmp;
if (h->buf_writer != h->buf_reader) {
/* some data wasn't processed, move it to the writer's position*/
memmove((char *)(h + 1) + h->buf_reader,
(char *)(h + 1) + h->buf_reader + tmp,
h->buf_writer - h->buf_reader);
}
} else {
/* since we didn't copy the data, we need to move the reader forward */
h->buf_reader += tmp;
if (h->reset) {
h->header_count = 0;
/* a request just finished, move the reader back to 0... */
/* and test for HTTP pipelinig. */
h->buf_writer -= h->buf_reader;
if (h->buf_writer) {
memmove((char *)(h + 1), (char *)(h + 1) + h->buf_reader,
h->buf_writer);
}
h->buf_reader = 0;
}
}
} while ((size_t)tmp);
} | /* this will be called when the connection has incoming data. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L264-L316 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http_on_close | void light_http_on_close(intptr_t uuid, fio_protocol_s *pr) {
/* in case we lost connection midway */
fio_str_free(&((light_http_s *)pr)->body);
/* free our protocol data and resources */
free(pr);
(void)uuid;
} | /* this will be called when the connection is closed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L319-L325 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | light_http_send_response | void light_http_send_response(intptr_t uuid, int status,
fio_str_info_s status_str, size_t header_count,
fio_str_info_s headers[][2],
fio_str_info_s body) {
static size_t date_len = 0; /* TODO: implement a date header when missing */
size_t total_len = 9 + 4 + 15 + 20 /* max content length */ + 2 +
status_str.len + 2 + date_len + 7 + 2 + body.len;
for (size_t i = 0; i < header_count; ++i) {
total_len += headers[i][0].len + 1 + headers[i][1].len + 2;
}
if (status < 100 || status > 999)
status = 500;
fio_str_s *response = fio_str_new2();
fio_str_capa_assert(response, total_len);
fio_str_write(response, "HTTP/1.1 ", 9);
fio_str_write_i(response, status);
fio_str_write(response, status_str.data, status_str.len);
fio_str_write(response, "\r\nContent-Length:", 17);
fio_str_write_i(response, body.len);
fio_str_write(response, "\r\n", 2);
// memcpy(pos, "Date:", 5);
// pos += 5;
// pos += http_time2str(pos, facil_last_tick().tv_sec);
// *pos++ = '\r';
// *pos++ = '\n';
for (size_t i = 0; i < header_count; ++i) {
fio_str_write(response, headers[i][0].data, headers[i][0].len);
fio_str_write(response, ":", 1);
fio_str_write(response, headers[i][1].data, headers[i][1].len);
fio_str_write(response, "\r\n", 2);
}
fio_str_write(response, "\r\n", 2);
if (body.len && body.data)
fio_str_write(response, body.data, body.len);
fio_str_send_free2(uuid, response);
} | /* *****************************************************************************
Fast HTTP response handling
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/raw-http.c#L331-L369 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | main | int main(int argc, char const *argv[]) {
/* initialize the CLI helper and options */
cli_init(argc, argv);
/* sertup routes */
route_add("/json", on_request_json);
route_add("/plaintext", on_request_plain_text);
/* Server name and header */
HTTP_HEADER_SERVER = fiobj_str_new("server", 6);
HTTP_VALUE_SERVER = fiobj_str_new("facil.io " FIO_VERSION_STRING,
strlen("facil.io " FIO_VERSION_STRING));
/* JSON values to be serialized */
JSON_KEY = fiobj_str_new("message", 7);
JSON_VALUE = fiobj_str_new("Hello, World!", 13);
/* Test for static file service */
const char *public_folder = fio_cli_get("-www");
if (public_folder) {
fprintf(stderr, "* serving static files from:%s\n", public_folder);
}
/* listen to HTTP connections */
http_listen(fio_cli_get("-port"), fio_cli_get("-address"),
.on_request = route_perform, .public_folder = public_folder,
.log = fio_cli_get_bool("-log"));
/* Start the facil.io reactor */
fio_start(.threads = fio_cli_get_i("-t"), .workers = fio_cli_get_i("-w"));
/* perform cleanup */
cleanup();
return 0;
} | /* *****************************************************************************
The main function
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L54-L87 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | on_request_json | static void on_request_json(http_s *h) {
http_set_header(h, HTTP_HEADER_CONTENT_TYPE, http_mimetype_find("json", 4));
FIOBJ json;
/* create a new Hash to be serialized for every request */
FIOBJ hash = fiobj_hash_new2(1);
fiobj_hash_set(hash, JSON_KEY, fiobj_dup(JSON_VALUE));
json = fiobj_obj2json(hash, 0);
fiobj_free(hash);
fio_str_info_s tmp = fiobj_obj2cstr(json);
http_send_body(h, tmp.data, tmp.len);
fiobj_free(json);
} | /* *****************************************************************************
Request handlers
***************************************************************************** */
/* handles JSON requests */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L94-L105 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | on_request_plain_text | static void on_request_plain_text(http_s *h) {
http_set_header(h, HTTP_HEADER_CONTENT_TYPE, http_mimetype_find("txt", 3));
http_send_body(h, "Hello, World!", 13);
} | /* handles plain text requests (Hello World) */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L108-L111 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | cli_init | static void cli_init(int argc, char const *argv[]) {
fio_cli_start(argc, argv, 0, 0,
"This is a facil.io framework benchmark application.\n"
"\nFor details about the benchmarks visit:\n"
"http://frameworkbenchmarks.readthedocs.io/en/latest/\n"
"\nThe following arguments are supported:",
FIO_CLI_PRINT_HEADER("Concurrency:"),
FIO_CLI_INT("-threads -t The number of threads to use. "
"System dependent default."),
FIO_CLI_INT("-workers -w The number of processes to use. "
"System dependent default."),
FIO_CLI_PRINT_HEADER("Address Binding:"),
FIO_CLI_INT("-port -p The port number to listen to "
"(set to 0 for Unix Sockets."),
FIO_CLI_STRING("-address -b The address to bind to."),
FIO_CLI_PRINT_HEADER("HTTP Settings:"),
FIO_CLI_STRING("-public -www A public folder for serve an HTTP "
"static file service."),
FIO_CLI_BOOL("-log -v Turns logging on (logs to terminal)."),
FIO_CLI_PRINT_HEADER("Misc:"),
FIO_CLI_STRING("-database -db The database adrress (URL)."));
/* setup default port */
if (!fio_cli_get("-p")) {
fio_cli_set("-p", "8080");
fio_cli_set("-port", "8080");
}
/* setup database address */
if (!fio_cli_get("-db")) {
char *database = getenv("DBHOST");
if (!database)
database = "localhost";
fio_cli_set("-db", database);
fio_cli_set("-database", database);
}
} | /* *****************************************************************************
CLI
***************************************************************************** */
/* initialize CLI helper and manage it's default options */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L118-L154 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | route_add | static void route_add(char *path, void (*handler)(http_s *)) {
/* add handler to the hash map */
fio_str_s tmp = FIO_STR_INIT_STATIC(path);
/* fio hash maps support up to 96 full collisions, we can use len as hash */
fio_router_insert(&routes, fio_str_len(&tmp), tmp, handler, NULL);
} | /* adds a route to our simple router */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L174-L179 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | route_perform | static void route_perform(http_s *h) {
/* add required Serevr header */
http_set_header(h, HTTP_HEADER_SERVER, fiobj_dup(HTTP_VALUE_SERVER));
/* collect path from hash map */
fio_str_info_s tmp_i = fiobj_obj2cstr(h->path);
fio_str_s tmp = FIO_STR_INIT_EXISTING(tmp_i.data, tmp_i.len, 0);
fio_router_handler_fn handler = fio_router_find(&routes, tmp_i.len, tmp);
/* forward request or send error */
if (handler) {
handler(h);
return;
}
http_send_error(h, 404);
} | /* routes a request to the correct handler */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L182-L195 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | route_clear | static void route_clear(void) { fio_router_free(&routes); } | /* cleanup for our router */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L198-L198 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | cleanup | static void cleanup(void) {
fio_cli_end();
fiobj_free(HTTP_HEADER_SERVER);
fiobj_free(HTTP_VALUE_SERVER);
fiobj_free(JSON_KEY);
fiobj_free(JSON_VALUE);
route_clear();
} | /* *****************************************************************************
Cleanup
***************************************************************************** */
/* cleanup any leftovers */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/framework_benchmark.c#L205-L213 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | on_open_shootout_websocket | static void on_open_shootout_websocket(ws_s *ws) {
fio_atomic_add(&sub_count, 2);
websocket_subscribe(ws, .channel = CHANNEL_TEXT, .force_text = 1,
.on_unsubscribe = on_websocket_unsubscribe);
websocket_subscribe(ws, .channel = CHANNEL_BINARY, .force_binary = 1,
.on_unsubscribe = on_websocket_unsubscribe);
} | /* *****************************************************************************
WebSocket event callbacks
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L61-L67 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | answer_http_request | static void answer_http_request(http_s *request) {
http_set_header(request, HTTP_HEADER_CONTENT_TYPE,
http_mimetype_find("txt", 3));
http_send_body(request, "This is a Websocket-Shootout example!", 37);
} | /* *****************************************************************************
HTTP events
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L100-L104 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | logger_subscribe | static void logger_subscribe(const fio_pubsub_engine_s *eng,
fio_str_info_s channel, fio_match_fn match) {
FIO_LOG_INFO("(%d) Channel subscription created: %s", getpid(), channel.data);
(void)eng;
(void)match;
} | /* *****************************************************************************
Pub/Sub logging (for debugging)
***************************************************************************** */
/** Should subscribe channel. Failures are ignored. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L120-L125 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | logger_unsubscribe | static void logger_unsubscribe(const fio_pubsub_engine_s *eng,
fio_str_info_s channel, fio_match_fn match) {
FIO_LOG_INFO("(%d) Channel subscription destroyed: %s", getpid(),
channel.data);
fflush(stderr);
(void)eng;
(void)match;
} | /** Should unsubscribe channel. Failures are ignored. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L127-L134 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | logger_publish | static void logger_publish(const fio_pubsub_engine_s *eng,
fio_str_info_s channel, fio_str_info_s msg,
uint8_t is_json) {
(void)eng;
(void)channel;
(void)msg;
(void)is_json;
} | /** Should publish a message through the engine. Failures are ignored. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L136-L143 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | redis_cleanup | static void redis_cleanup(void *e_) {
redis_engine_destroy(e_);
FIO_LOG_DEBUG("Cleaned up redis engine object.");
FIO_PUBSUB_DEFAULT = FIO_PUBSUB_CLUSTER;
} | /* *****************************************************************************
Redis cleanup helpers
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L155-L159 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | main | int main(int argc, char const *argv[]) {
const char *port = "3000";
const char *public_folder = NULL;
uint32_t threads = 0;
uint32_t workers = 0;
uint8_t print_log = 0;
/* **** Command line arguments **** */
fio_cli_start(
argc, argv, 0, 0,
"This is a facil.io example application.\n"
"\nThis example conforms to the "
"Websocket Shootout requirements at:\n"
"https://github.com/hashrocket/websocket-shootout\n"
"\nThe following arguments are supported:",
FIO_CLI_PRINT_HEADER("Concurrency"),
FIO_CLI_INT("-threads -t The number of threads to use. "
"System dependent default."),
FIO_CLI_INT("-workers -w The number of processes to use. "
"System dependent default."),
FIO_CLI_PRINT_HEADER("Connectivity"),
FIO_CLI_INT("-port -p The port number to listen to."),
FIO_CLI_PRINT_HEADER("HTTP settings"),
"-public -www A public folder for serve an HTTP static file service.",
FIO_CLI_BOOL("-log -v Turns logging on."), FIO_CLI_PRINT_HEADER("Misc"),
"-redis -r add a Redis pub/sub round-trip.",
FIO_CLI_BOOL("-debug Turns debug notifications on."));
if (fio_cli_get_bool("-debug"))
FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
if (fio_cli_get("-p"))
port = fio_cli_get("-p");
if (fio_cli_get("-www")) {
public_folder = fio_cli_get("-www");
fprintf(stderr, "* serving static files from:%s\n", public_folder);
}
if (fio_cli_get_i("-t"))
threads = fio_cli_get_i("-t");
if (fio_cli_get_i("-w"))
workers = fio_cli_get_i("-w");
print_log = fio_cli_get_i("-v");
redis_initialize();
fio_cli_end();
/* **** actual code **** */
if (http_listen(port, NULL, .on_request = answer_http_request,
.on_upgrade = answer_http_upgrade, .log = print_log,
.public_folder = public_folder) == -1) {
perror("Couldn't initiate Websocket Shootout service");
exit(1);
}
/* patch for dealing with the High Sierra `fork` limitations */
PATCH_ENV();
if (FIO_LOG_LEVEL == FIO_LOG_LEVEL_DEBUG) {
fio_pubsub_attach(&PUBSUB_LOGGIN_ENGINE);
fio_state_callback_add(FIO_CALL_ON_SHUTDOWN, print_subscription_balance,
"on shutdown");
fio_state_callback_add(FIO_CALL_ON_FINISH, print_subscription_balance,
"on finish");
fio_state_callback_add(FIO_CALL_AT_EXIT, print_subscription_balance,
"at exit");
}
fio_start(.threads = threads, .workers = workers);
} | /* *****************************************************************************
The main function
***************************************************************************** */
/*
Read available command line details using "-?".
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/benchmarks/websocket_shootout.c#L186-L255 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | on_http_request | static void on_http_request(http_s *h) {
/* set a response and send it (finnish vs. destroy). */
http_send_body(h, "Hello World!", 12);
} | /* TODO: edit this function to handle HTTP data and answer Websocket requests.*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/boiler_plate/src/http_service.c#L5-L8 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | initialize_http_service | void initialize_http_service(void) {
/* listen for inncoming connections */
if (http_listen(fio_cli_get("-p"), fio_cli_get("-b"),
.on_request = on_http_request,
.max_body_size = fio_cli_get_i("-maxbd") * 1024 * 1024,
.ws_max_msg_size = fio_cli_get_i("-max-msg") * 1024,
.public_folder = fio_cli_get("-public"),
.log = fio_cli_get_bool("-log"),
.timeout = fio_cli_get_i("-keep-alive"),
.ws_timeout = fio_cli_get_i("-ping")) == -1) {
/* listen failed ?*/
perror("ERROR: facil couldn't initialize HTTP service (already running?)");
exit(1);
}
} | /* starts a listeninng socket for HTTP connections. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/examples/boiler_plate/src/http_service.c#L11-L25 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_capa | size_t fio_capa(void) {
if (fio_data)
return fio_data->capa;
return 0;
} | /**
* Returns the maximum number of open files facil.io can handle per worker
* process.
*
* Total OS limits might apply as well but aren't shown.
*
* The value of 0 indicates either that the facil.io library wasn't initialized
* yet or that it's resources were released.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L256-L260 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_packet_free | static inline void fio_packet_free(fio_packet_s *packet) {
packet->dealloc(packet->data.buffer);
fio_free(packet);
} | /* *****************************************************************************
Packet allocation (for socket's user-buffer)
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L266-L269 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_max_fd_min | static void fio_max_fd_min(uint32_t fd) {
if (fio_data->max_protocol_fd > fd)
return;
fio_lock(&fio_data->lock);
if (fio_data->max_protocol_fd < fd)
fio_data->max_protocol_fd = fd;
fio_unlock(&fio_data->lock);
} | /* *****************************************************************************
Core Connection Data Clearing
***************************************************************************** */
/* set the minimal max_protocol_fd */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L281-L288 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_max_fd_shrink | static void fio_max_fd_shrink(void) {
fio_lock(&fio_data->lock);
uint32_t fd = fio_data->max_protocol_fd;
while (fd && fd_data(fd).protocol == NULL)
--fd;
fio_data->max_protocol_fd = fd;
fio_unlock(&fio_data->lock);
} | /* set the minimal max_protocol_fd */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L291-L298 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_clear_fd | static inline int fio_clear_fd(intptr_t fd, uint8_t is_open) {
fio_packet_s *packet;
fio_protocol_s *protocol;
fio_rw_hook_s *rw_hooks;
void *rw_udata;
fio_uuid_links_s links;
fio_lock(&(fd_data(fd).sock_lock));
links = fd_data(fd).links;
packet = fd_data(fd).packet;
protocol = fd_data(fd).protocol;
rw_hooks = fd_data(fd).rw_hooks;
rw_udata = fd_data(fd).rw_udata;
fd_data(fd) = (fio_fd_data_s){
.open = is_open,
.sock_lock = fd_data(fd).sock_lock,
.protocol_lock = fd_data(fd).protocol_lock,
.rw_hooks = (fio_rw_hook_s *)&FIO_DEFAULT_RW_HOOKS,
.counter = fd_data(fd).counter + 1,
.packet_last = &fd_data(fd).packet,
};
fio_unlock(&(fd_data(fd).sock_lock));
if (rw_hooks && rw_hooks->cleanup)
rw_hooks->cleanup(rw_udata);
while (packet) {
fio_packet_s *tmp = packet;
packet = packet->next;
fio_packet_free(tmp);
}
if (fio_uuid_links_count(&links)) {
FIO_SET_FOR_LOOP(&links, pos) {
if (pos->hash)
pos->obj((void *)pos->hash);
}
}
fio_uuid_links_free(&links);
if (protocol && protocol->on_close) {
fio_defer(deferred_on_close, (void *)fd2uuid(fd), protocol);
}
if (is_open)
fio_max_fd_min(fd);
return 0;
} | /* resets connection data, marking it as either open or closed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L301-L342 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | protocol_unlock | inline static void protocol_unlock(fio_protocol_s *pr,
enum fio_protocol_lock_e type) {
fio_unlock(&prt_meta(pr).locks[type]);
} | /** See `fio_protocol_try_lock` for details. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L381-L384 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_protocol_unlock | void fio_protocol_unlock(fio_protocol_s *pr, enum fio_protocol_lock_e type) {
protocol_unlock(pr, type);
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L403-L405 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_fd2uuid | intptr_t fio_fd2uuid(int fd) {
if (fd < 0 || (size_t)fd >= fio_data->capa)
return -1;
if (!fd_data(fd).open) {
fio_lock(&fd_data(fd).protocol_lock);
fio_clear_fd(fd, 1);
fio_unlock(&fd_data(fd).protocol_lock);
}
return fd2uuid(fd);
} | /* *****************************************************************************
UUID validation and state
***************************************************************************** */
/* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L412-L421 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_is_valid | int fio_is_valid(intptr_t uuid) { return uuid_is_valid(uuid); } | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L424-L424 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_is_closed | int fio_is_closed(intptr_t uuid) {
return !uuid_is_valid(uuid) || !uuid_data(uuid).open || uuid_data(uuid).close;
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L427-L429 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_is_running | int16_t fio_is_running(void) { return fio_data && fio_data->active; } | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L437-L437 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_last_tick | struct timespec fio_last_tick(void) {
return fio_data->last_cycle;
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L440-L442 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_touch | void fio_touch(intptr_t uuid) {
if (uuid_is_valid(uuid))
touchfd(fio_uuid2fd(uuid));
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L447-L450 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_peer_addr | fio_str_info_s fio_peer_addr(intptr_t uuid) {
if (fio_is_closed(uuid) || !uuid_data(uuid).addr_len)
return (fio_str_info_s){.data = NULL, .len = 0, .capa = 0};
return (fio_str_info_s){.data = (char *)uuid_data(uuid).addr,
.len = uuid_data(uuid).addr_len,
.capa = 0};
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L453-L459 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_local_addr | size_t fio_local_addr(char *dest, size_t limit) {
if (gethostname(dest, limit))
return 0;
struct addrinfo hints, *info;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_CANONNAME; // get cannonical name
if (getaddrinfo(dest, "http", &hints, &info) != 0)
return 0;
for (struct addrinfo *pos = info; pos; pos = pos->ai_next) {
if (pos->ai_canonname) {
size_t len = strlen(pos->ai_canonname);
if (len >= limit)
len = limit - 1;
memcpy(dest, pos->ai_canonname, len);
dest[len] = 0;
freeaddrinfo(info);
return len;
}
}
freeaddrinfo(info);
return 0;
} | /**
* Writes the local machine address (qualified host name) to the buffer.
*
* Returns the amount of data written (excluding the NUL byte).
*
* `limit` is the maximum number of bytes in the buffer, including the NUL byte.
*
* If the returned value == limit - 1, the result might have been truncated.
*
* If 0 is returned, an erro might have occured (see `errno`) and the contents
* of `dest` is undefined.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L473-L500 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_uuid_link | void fio_uuid_link(intptr_t uuid, void *obj, void (*on_close)(void *obj)) {
if (!uuid_is_valid(uuid))
goto invalid;
fio_lock(&uuid_data(uuid).sock_lock);
if (!uuid_is_valid(uuid))
goto locked_invalid;
fio_uuid_links_overwrite(&uuid_data(uuid).links, (uintptr_t)obj, on_close,
NULL);
fio_unlock(&uuid_data(uuid).sock_lock);
return;
locked_invalid:
fio_unlock(&uuid_data(uuid).sock_lock);
invalid:
errno = EBADF;
on_close(obj);
} | /* *****************************************************************************
UUID attachments (linking objects to the UUID's lifetime)
***************************************************************************** */
/* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L507-L522 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_uuid_unlink | int fio_uuid_unlink(intptr_t uuid, void *obj) {
if (!uuid_is_valid(uuid))
goto invalid;
fio_lock(&uuid_data(uuid).sock_lock);
if (!uuid_is_valid(uuid))
goto locked_invalid;
/* default object comparison is always true */
int ret =
fio_uuid_links_remove(&uuid_data(uuid).links, (uintptr_t)obj, NULL, NULL);
if (ret)
errno = ENOTCONN;
fio_unlock(&uuid_data(uuid).sock_lock);
return ret;
locked_invalid:
fio_unlock(&uuid_data(uuid).sock_lock);
invalid:
errno = EBADF;
return -1;
} | /* public API. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L525-L543 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_thread_suspend | FIO_FUNC void fio_thread_suspend(void) {
fio_lock(&fio_thread_lock);
fio_ls_embd_push(&fio_thread_queue, &fio_thread_data.node);
fio_unlock(&fio_thread_lock);
struct pollfd list = {
.events = (POLLPRI | POLLIN),
.fd = fio_thread_data.fd_wait,
};
if (poll(&list, 1, 5000) > 0) {
/* thread was removed from the list through signal */
uint64_t data;
int r = read(fio_thread_data.fd_wait, &data, sizeof(data));
(void)r;
} else {
/* remove self from list */
fio_lock(&fio_thread_lock);
fio_ls_embd_remove(&fio_thread_data.node);
fio_unlock(&fio_thread_lock);
}
} | /* suspend thread execution (might be resumed unexpectedly) */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L700-L719 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_thread_signal | FIO_FUNC void fio_thread_signal(void) {
fio_thread_queue_s *t;
int fd = -2;
fio_lock(&fio_thread_lock);
t = (fio_thread_queue_s *)fio_ls_embd_shift(&fio_thread_queue);
if (t)
fd = t->fd_signal;
fio_unlock(&fio_thread_lock);
if (fd >= 0) {
uint64_t data = 1;
int r = write(fd, (void *)&data, sizeof(data));
(void)r;
} else if (fd == -1) {
/* hardly the best way, but there's a thread sleeping on air */
kill(getpid(), SIGCONT);
}
} | /* wake up a single thread */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L722-L738 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_thread_broadcast | FIO_FUNC void fio_thread_broadcast(void) {
while (fio_ls_embd_any(&fio_thread_queue)) {
fio_thread_signal();
}
} | /* wake up all threads */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L741-L745 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_thread_wait | static void fio_defer_thread_wait(void) {
#if FIO_ENGINE_POLL
fio_poll();
return;
#endif
if (FIO_DEFER_THROTTLE_POLL) {
fio_thread_suspend();
} else {
/* keeps threads active (concurrent), but reduces performance */
static __thread size_t static_throttle = 262143UL;
fio_throttle_thread(static_throttle);
if (fio_defer_has_queue())
static_throttle = 1;
else if (static_throttle < FIO_DEFER_THROTTLE_LIMIT)
static_throttle = (static_throttle << 1);
}
} | /**
* A thread entering this function should wait for new evennts.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L751-L767 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_clear_tasks_for_queue | static inline void fio_defer_clear_tasks_for_queue(fio_task_queue_s *queue) {
fio_lock(&queue->lock);
while (queue->reader) {
fio_defer_queue_block_s *tmp = queue->reader;
queue->reader = queue->reader->next;
if (tmp != &queue->static_queue) {
COUNT_DEALLOC;
free(tmp);
}
}
queue->static_queue = (fio_defer_queue_block_s){.next = NULL};
queue->reader = queue->writer = &queue->static_queue;
fio_unlock(&queue->lock);
} | /* same as fio_defer_clear_queue , just inlined */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L988-L1001 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_perform_single_task_for_queue | static inline int
fio_defer_perform_single_task_for_queue(fio_task_queue_s *queue) {
fio_defer_task_s task = fio_defer_pop_task(queue);
if (!task.func)
return -1;
task.func(task.arg1, task.arg2);
return 0;
} | /**
* Performs a single task from the queue, returning -1 if the queue was empty.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1006-L1013 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer | int fio_defer(void (*func)(void *, void *), void *arg1, void *arg2) {
/* must have a task to defer */
if (!func)
goto call_error;
fio_defer_push_task(func, arg1, arg2);
return 0;
call_error:
return -1;
} | /* *****************************************************************************
External Task API
***************************************************************************** */
/** Defer an execution of a function for later. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1034-L1043 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_perform | void fio_defer_perform(void) {
#if FIO_USE_URGENT_QUEUE
while (fio_defer_perform_single_task_for_queue(&task_queue_urgent) == 0 ||
fio_defer_perform_single_task_for_queue(&task_queue_normal) == 0)
;
#else
while (fio_defer_perform_single_task_for_queue(&task_queue_normal) == 0)
;
#endif
// for (;;) {
// #if FIO_USE_URGENT_QUEUE
// fio_defer_task_s task = fio_defer_pop_task(&task_queue_urgent);
// if (!task.func)
// task = fio_defer_pop_task(&task_queue_normal);
// #else
// fio_defer_task_s task = fio_defer_pop_task(&task_queue_normal);
// #endif
// if (!task.func)
// return;
// task.func(task.arg1, task.arg2);
// }
} | /** Performs all deferred functions until the queue had been depleted. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1046-L1067 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_has_queue | int fio_defer_has_queue(void) {
#if FIO_USE_URGENT_QUEUE
return task_queue_urgent.reader != task_queue_urgent.writer ||
task_queue_urgent.reader->write != task_queue_urgent.reader->read ||
task_queue_normal.reader != task_queue_normal.writer ||
task_queue_normal.reader->write != task_queue_normal.reader->read;
#else
return task_queue_normal.reader != task_queue_normal.writer ||
task_queue_normal.reader->write != task_queue_normal.reader->read;
#endif
} | /** Returns true if there are deferred functions waiting for execution. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1070-L1080 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_clear_queue | void fio_defer_clear_queue(void) { fio_defer_clear_tasks(); } | /** Clears the queue. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1083-L1083 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_defer_thread_pool_join | static void fio_defer_thread_pool_join(fio_defer_thread_pool_s *pool) {
for (size_t i = 0; i < pool->thread_count; ++i) {
fio_thread_join(pool->threads[i]);
}
free(pool);
} | /* joins a thread pool */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1105-L1110 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_mark_time | static inline void fio_mark_time(void) {
clock_gettime(CLOCK_REALTIME, &fio_data->last_cycle);
} | /** Marks the current time as facil.io's cycle time */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1174-L1176 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_calc_due | static struct timespec fio_timer_calc_due(size_t interval) {
struct timespec now = fio_last_tick();
if (interval >= 1000) {
unsigned long long secs = interval / 1000;
now.tv_sec += secs;
interval -= secs * 1000;
}
now.tv_nsec += (interval * 1000000UL);
if (now.tv_nsec >= 1000000000L) {
now.tv_nsec -= 1000000000L;
now.tv_sec += 1;
}
return now;
} | /** Calculates the due time for a task, given it's interval */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1179-L1192 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_calc_first_interval | static size_t fio_timer_calc_first_interval(void) {
if (fio_defer_has_queue())
return 0;
if (fio_ls_embd_is_empty(&fio_timers)) {
return FIO_POLL_TICK;
}
struct timespec now = fio_last_tick();
struct timespec due =
FIO_LS_EMBD_OBJ(fio_timer_s, node, fio_timers.next)->due;
if (due.tv_sec < now.tv_sec ||
(due.tv_sec == now.tv_sec && due.tv_nsec <= now.tv_nsec))
return 0;
size_t interval = 1000L * (due.tv_sec - now.tv_sec);
if (due.tv_nsec >= now.tv_nsec) {
interval += (due.tv_nsec - now.tv_nsec) / 1000000L;
} else {
interval -= (now.tv_nsec - due.tv_nsec) / 1000000L;
}
if (interval > FIO_POLL_TICK)
interval = FIO_POLL_TICK;
return interval;
} | /** Returns the number of miliseconds until the next event, up to FIO_POLL_TICK
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1196-L1217 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_compare | static int fio_timer_compare(struct timespec a, struct timespec b) {
if (a.tv_sec == b.tv_sec) {
if (a.tv_nsec < b.tv_nsec)
return 1;
if (a.tv_nsec > b.tv_nsec)
return -1;
return 0;
}
if (a.tv_sec < b.tv_sec)
return 1;
return -1;
} | /* simple a<=>b if "a" is bigger a negative result is returned, eq == 0. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1220-L1231 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_add_order | static void fio_timer_add_order(fio_timer_s *timer) {
timer->due = fio_timer_calc_due(timer->interval);
// fio_ls_embd_s *pos = &fio_timers;
fio_lock(&fio_timer_lock);
FIO_LS_EMBD_FOR(&fio_timers, node) {
fio_timer_s *t2 = FIO_LS_EMBD_OBJ(fio_timer_s, node, node);
if (fio_timer_compare(timer->due, t2->due) >= 0) {
fio_ls_embd_push(node, &timer->node);
goto finish;
}
}
fio_ls_embd_push(&fio_timers, &timer->node);
finish:
fio_unlock(&fio_timer_lock);
} | /** Places a timer in an ordered linked list. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1234-L1248 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_perform_single | static void fio_timer_perform_single(void *timer_, void *ignr) {
fio_timer_s *timer = timer_;
timer->task(timer->arg);
if (!timer->repetitions || fio_atomic_sub(&timer->repetitions, 1))
goto reschedule;
if (timer->on_finish)
timer->on_finish(timer->arg);
free(timer);
return;
(void)ignr;
reschedule:
fio_timer_add_order(timer);
} | /** Performs a timer task and re-adds it to the queue (or cleans it up) */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1251-L1263 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_timer_schedule | static void fio_timer_schedule(void) {
struct timespec now = fio_last_tick();
fio_lock(&fio_timer_lock);
while (fio_ls_embd_any(&fio_timers) &&
fio_timer_compare(
FIO_LS_EMBD_OBJ(fio_timer_s, node, fio_timers.next)->due, now) >=
0) {
fio_ls_embd_s *tmp = fio_ls_embd_remove(fio_timers.next);
fio_defer(fio_timer_perform_single, FIO_LS_EMBD_OBJ(fio_timer_s, node, tmp),
NULL);
}
fio_unlock(&fio_timer_lock);
} | /** schedules all timers that are due to be performed. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1266-L1278 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_run_every | int fio_run_every(size_t milliseconds, size_t repetitions, void (*task)(void *),
void *arg, void (*on_finish)(void *)) {
if (!task || (milliseconds == 0 && !repetitions))
return -1;
fio_timer_s *timer = malloc(sizeof(*timer));
FIO_ASSERT_ALLOC(timer);
fio_mark_time();
*timer = (fio_timer_s){
.due = fio_timer_calc_due(milliseconds),
.interval = milliseconds,
.repetitions = repetitions,
.task = task,
.arg = arg,
.on_finish = on_finish,
};
fio_timer_add_order(timer);
return 0;
} | /**
* Creates a timer to run a task at the specified interval.
*
* The task will repeat `repetitions` times. If `repetitions` is set to 0, task
* will repeat forever.
*
* Returns -1 on error.
*
* The `on_finish` handler is always called (even on error).
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1302-L1319 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | reap_child_handler | static void reap_child_handler(int sig) {
(void)(sig);
int old_errno = errno;
while (waitpid(-1, NULL, WNOHANG) > 0)
;
errno = old_errno;
if (fio_old_sig_chld.sa_handler != SIG_IGN &&
fio_old_sig_chld.sa_handler != SIG_DFL)
fio_old_sig_chld.sa_handler(sig);
} | /*
* Zombie Reaping
* With thanks to Dr Graham D Shaw.
* http://www.microhowto.info/howto/reap_zombie_processes_using_a_sigchld_handler.html
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1365-L1374 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_reap_children | void fio_reap_children(void) {
struct sigaction sa;
if (fio_old_sig_chld.sa_handler)
return;
sa.sa_handler = reap_child_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, &fio_old_sig_chld) == -1) {
perror("Child reaping initialization failed");
kill(0, SIGINT);
exit(errno);
}
} | /* initializes zombie reaping for the process */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1377-L1389 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | sig_int_handler | static void sig_int_handler(int sig) {
struct sigaction *old = NULL;
switch (sig) {
#if !FIO_DISABLE_HOT_RESTART
case SIGUSR1:
fio_signal_children_flag = 1;
old = &fio_old_sig_usr1;
break;
#endif
/* fallthrough */
case SIGINT:
if (!old)
old = &fio_old_sig_int;
/* fallthrough */
case SIGTERM:
if (!old)
old = &fio_old_sig_term;
fio_stop();
break;
case SIGPIPE:
if (!old)
old = &fio_old_sig_pipe;
/* fallthrough */
default:
break;
}
/* propagate signale handling to previous existing handler (if any) */
if (old && old->sa_handler != SIG_IGN && old->sa_handler != SIG_DFL)
old->sa_handler(sig);
} | /* handles the SIGUSR1, SIGINT and SIGTERM signals. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1392-L1421 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_signal_handler_setup | static void fio_signal_handler_setup(void) {
/* setup signal handling */
struct sigaction act;
if (fio_trylock(&fio_signal_set_flag))
return;
memset(&act, 0, sizeof(act));
act.sa_handler = sig_int_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGINT, &act, &fio_old_sig_int)) {
perror("couldn't set signal handler");
return;
};
if (sigaction(SIGTERM, &act, &fio_old_sig_term)) {
perror("couldn't set signal handler");
return;
};
#if !FIO_DISABLE_HOT_RESTART
if (sigaction(SIGUSR1, &act, &fio_old_sig_usr1)) {
perror("couldn't set signal handler");
return;
};
#endif
act.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &act, &fio_old_sig_pipe)) {
perror("couldn't set signal handler");
return;
};
} | /* setup handling for the SIGUSR1, SIGPIPE, SIGINT and SIGTERM signals. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1424-L1457 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_is_worker | int fio_is_worker(void) { return fio_data->is_worker; } | /**
* Returns 1 if the current process is a worker process or a single process.
*
* Otherwise returns 0.
*
* NOTE: When cluster mode is off, the root process is also the worker process.
* This means that single process instances don't automatically respawn
* after critical errors.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1489-L1489 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_is_master | int fio_is_master(void) {
return fio_data->is_worker == 0 || fio_data->workers == 1;
} | /**
* Returns 1 if the current process is the master (root) process.
*
* Otherwise returns 0.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1496-L1498 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_parent_pid | pid_t fio_parent_pid(void) { return fio_data->parent; } | /** returns facil.io's parent (root) process pid. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1501-L1501 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_expected_concurrency | void fio_expected_concurrency(int16_t *threads, int16_t *processes) {
if (!threads || !processes)
return;
if (!*threads && !*processes) {
/* both options set to 0 - default to cores*cores matrix */
ssize_t cpu_count = fio_detect_cpu_cores();
#if FIO_CPU_CORES_LIMIT
if (cpu_count > FIO_CPU_CORES_LIMIT) {
static int print_cores_warning = 1;
if (print_cores_warning) {
FIO_LOG_WARNING(
"Detected %zu cores. Capping auto-detection of cores to %zu.\n"
" Avoid this message by setting threads / workers manually.\n"
" To increase auto-detection limit, recompile with:\n"
" -DFIO_CPU_CORES_LIMIT=%zu",
(size_t)cpu_count, (size_t)FIO_CPU_CORES_LIMIT, (size_t)cpu_count);
print_cores_warning = 0;
}
cpu_count = FIO_CPU_CORES_LIMIT;
}
#endif
*threads = *processes = (int16_t)cpu_count;
if (cpu_count > 3) {
/* leave a core available for the kernel */
--(*processes);
}
} else if (*threads < 0 || *processes < 0) {
/* Set any option that is less than 0 be equal to cores/value */
/* Set any option equal to 0 be equal to the other option in value */
ssize_t cpu_count = fio_detect_cpu_cores();
size_t thread_cpu_adjust = (*threads <= 0 ? 1 : 0);
size_t worker_cpu_adjust = (*processes <= 0 ? 1 : 0);
if (cpu_count > 0) {
int16_t tmp = 0;
if (*threads < 0)
tmp = (int16_t)(cpu_count / (*threads * -1));
else if (*threads == 0) {
tmp = -1 * *processes;
thread_cpu_adjust = 0;
} else
tmp = *threads;
if (*processes < 0)
*processes = (int16_t)(cpu_count / (*processes * -1));
else if (*processes == 0) {
*processes = -1 * *threads;
worker_cpu_adjust = 0;
}
*threads = tmp;
tmp = *processes;
if (worker_cpu_adjust && (*processes * *threads) >= cpu_count &&
cpu_count > 3) {
/* leave a resources available for the kernel */
--*processes;
}
if (thread_cpu_adjust && (*threads * tmp) >= cpu_count && cpu_count > 3) {
/* leave a resources available for the kernel */
--*threads;
}
}
}
/* make sure we have at least one process and at least one thread */
if (*processes <= 0)
*processes = 1;
if (*threads <= 0)
*threads = 1;
} | /**
* Returns the number of expected threads / processes to be used by facil.io.
*
* The pointers should start with valid values that match the expected threads /
* processes values passed to `fio_run`.
*
* The data in the pointers will be overwritten with the result.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1525-L1592 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_poll | static size_t fio_poll(void) {
/* shrink fd poll range */
size_t end = fio_data->capa; // max_protocol_fd might break TLS
size_t start = 0;
struct pollfd *list = NULL;
fio_lock(&fio_data->lock);
while (start < end && fio_data->poll[start].fd == -1)
++start;
while (start < end && fio_data->poll[end - 1].fd == -1)
--end;
if (start != end) {
/* copy poll list for multi-threaded poll */
list = fio_malloc(sizeof(struct pollfd) * end);
memcpy(list + start, fio_data->poll + start,
(sizeof(struct pollfd)) * (end - start));
}
fio_unlock(&fio_data->lock);
int timeout = fio_timer_calc_first_interval();
size_t count = 0;
if (start == end) {
fio_throttle_thread((timeout * 1000000UL));
} else if (poll(list + start, end - start, timeout) == -1) {
goto finish;
}
for (size_t i = start; i < end; ++i) {
if (list[i].revents) {
touchfd(i);
++count;
if (list[i].revents & FIO_POLL_WRITE_EVENTS) {
// FIO_LOG_DEBUG("Poll Write %zu => %p", i, (void *)fd2uuid(i));
fio_poll_remove_write(i);
fio_defer_push_urgent(deferred_on_ready, (void *)fd2uuid(i), NULL);
}
if (list[i].revents & FIO_POLL_READ_EVENTS) {
// FIO_LOG_DEBUG("Poll Read %zu => %p", i, (void *)fd2uuid(i));
fio_poll_remove_read(i);
fio_defer_push_task(deferred_on_data, (void *)fd2uuid(i), NULL);
}
if (list[i].revents & (POLLHUP | POLLERR)) {
// FIO_LOG_DEBUG("Poll Hangup %zu => %p", i, (void *)fd2uuid(i));
fio_poll_remove_fd(i);
fio_force_close_in_poll(fd2uuid(i));
}
if (list[i].revents & POLLNVAL) {
// FIO_LOG_DEBUG("Poll Invalid %zu => %p", i, (void *)fd2uuid(i));
fio_poll_remove_fd(i);
fio_lock(&fd_data(i).protocol_lock);
fio_clear_fd(i, 0);
fio_unlock(&fd_data(i).protocol_lock);
}
}
}
finish:
fio_free(list);
return count;
} | /** returns non-zero if events were scheduled, 0 if idle */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L1983-L2040 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | mock_on_ev | static void mock_on_ev(intptr_t uuid, fio_protocol_s *protocol) {
(void)uuid;
(void)protocol;
} | /* FIO_ENGINE_POLL */
/* *****************************************************************************
Section Start Marker
IO Callbacks / Event Handling
***************************************************************************** */
/* *****************************************************************************
Mock Protocol Callbacks and Service Funcions
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2077-L2080 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | deferred_on_close | static void deferred_on_close(void *uuid_, void *pr_) {
fio_protocol_s *pr = pr_;
if (pr->rsv)
goto postpone;
pr->on_close((intptr_t)uuid_, pr);
return;
postpone:
fio_defer_push_task(deferred_on_close, uuid_, pr_);
} | /* *****************************************************************************
Deferred event handlers - these tasks safely forward the events to the Protocol
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2123-L2131 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_force_event | void fio_force_event(intptr_t uuid, enum fio_io_event ev) {
if (!uuid_is_valid(uuid))
return;
switch (ev) {
case FIO_EVENT_ON_DATA:
fio_trylock(&uuid_data(uuid).scheduled);
fio_defer_push_task(deferred_on_data, (void *)uuid, (void *)1);
break;
case FIO_EVENT_ON_TIMEOUT:
fio_defer_push_task(deferred_ping, (void *)uuid, NULL);
break;
case FIO_EVENT_ON_READY:
fio_defer_push_urgent(deferred_on_ready, (void *)uuid, NULL);
break;
}
} | /* *****************************************************************************
Forcing / Suspending IO events
***************************************************************************** */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2258-L2273 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_set_non_block | int fio_set_non_block(int fd) {
/* If they have O_NONBLOCK, use the Posix way to do it */
#if defined(O_NONBLOCK)
/* Fixme: O_NONBLOCK is defined but broken on SunOS 4.1.x and AIX 3.2.5. */
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
flags = 0;
#ifdef O_CLOEXEC
return fcntl(fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
#else
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
#endif
#elif defined(FIONBIO)
/* Otherwise, use the old way of doing it */
static int flags = 1;
return ioctl(fd, FIONBIO, &flags);
#else
#error No functions / argumnet macros for non-blocking sockets.
#endif
} | /* *****************************************************************************
Section Start Marker
IO Socket Layer
Read / Write / Accept / Connect / etc'
***************************************************************************** */
/* *****************************************************************************
Internal socket initialization functions
***************************************************************************** */
/**
Sets a socket to non blocking state.
This function is called automatically for the new socket, when using
`fio_accept` or `fio_connect`.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2322-L2341 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_accept | intptr_t fio_accept(intptr_t srv_uuid) {
struct sockaddr_in6 addrinfo[2]; /* grab a slice of stack (aligned) */
socklen_t addrlen = sizeof(addrinfo);
int client;
#ifdef SOCK_NONBLOCK
client = accept4(fio_uuid2fd(srv_uuid), (struct sockaddr *)addrinfo, &addrlen,
SOCK_NONBLOCK | SOCK_CLOEXEC);
if (client <= 0)
return -1;
#else
client = accept(fio_uuid2fd(srv_uuid), (struct sockaddr *)addrinfo, &addrlen);
if (client <= 0)
return -1;
if (fio_set_non_block(client) == -1) {
close(client);
return -1;
}
#endif
// avoid the TCP delay algorithm.
{
int optval = 1;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));
}
// handle socket buffers.
{
int optval = 0;
socklen_t size = (socklen_t)sizeof(optval);
if (!getsockopt(client, SOL_SOCKET, SO_SNDBUF, &optval, &size) &&
optval <= 131072) {
optval = 131072;
setsockopt(client, SOL_SOCKET, SO_SNDBUF, &optval, sizeof(optval));
optval = 131072;
setsockopt(client, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval));
}
}
fio_lock(&fd_data(client).protocol_lock);
fio_clear_fd(client, 1);
fio_unlock(&fd_data(client).protocol_lock);
/* copy peer address */
if (((struct sockaddr *)addrinfo)->sa_family == AF_UNIX) {
fd_data(client).addr_len = uuid_data(srv_uuid).addr_len;
if (uuid_data(srv_uuid).addr_len) {
memcpy(fd_data(client).addr, uuid_data(srv_uuid).addr,
uuid_data(srv_uuid).addr_len + 1);
}
} else {
fio_tcp_addr_cpy(client, ((struct sockaddr *)addrinfo)->sa_family,
(struct sockaddr *)addrinfo);
}
return fd2uuid(client);
} | /**
* `fio_accept` accepts a new socket connection from a server socket - see the
* server flag on `fio_socket`.
*
* NOTE: this function does NOT attach the socket to the IO reactor -see
* `fio_attach`.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2365-L2417 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_unix_socket | static intptr_t fio_unix_socket(const char *address, uint8_t server) {
/* Unix socket */
struct sockaddr_un addr = {0};
size_t addr_len = strlen(address);
if (addr_len >= sizeof(addr.sun_path)) {
FIO_LOG_ERROR("(fio_unix_socket) address too long (%zu bytes > %zu bytes).",
addr_len, sizeof(addr.sun_path) - 1);
errno = ENAMETOOLONG;
return -1;
}
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, address, addr_len + 1); /* copy the NUL byte. */
#if defined(__APPLE__)
addr.sun_len = addr_len;
#endif
// get the file descriptor
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
return -1;
}
if (fio_set_non_block(fd) == -1) {
close(fd);
return -1;
}
if (server) {
unlink(addr.sun_path);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
// perror("couldn't bind unix socket");
close(fd);
return -1;
}
if (listen(fd, SOMAXCONN) < 0) {
// perror("couldn't start listening to unix socket");
close(fd);
return -1;
}
/* chmod for foriegn connections */
fchmod(fd, 0777);
} else {
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1 &&
errno != EINPROGRESS) {
close(fd);
return -1;
}
}
fio_lock(&fd_data(fd).protocol_lock);
fio_clear_fd(fd, 1);
fio_unlock(&fd_data(fd).protocol_lock);
if (addr_len < sizeof(fd_data(fd).addr)) {
memcpy(fd_data(fd).addr, address, addr_len + 1); /* copy the NUL byte. */
fd_data(fd).addr_len = addr_len;
}
return fd2uuid(fd);
} | /* Creates a Unix socket - returning it's uuid (or -1) */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2420-L2473 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_tcp_socket | static intptr_t fio_tcp_socket(const char *address, const char *port,
uint8_t server) {
/* TCP/IP socket */
// setup the address
struct addrinfo hints = {0};
struct addrinfo *addrinfo; // will point to the results
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
if (getaddrinfo(address, port, &hints, &addrinfo)) {
// perror("addr err");
return -1;
}
// get the file descriptor
int fd =
socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
if (fd <= 0) {
freeaddrinfo(addrinfo);
return -1;
}
// make sure the socket is non-blocking
if (fio_set_non_block(fd) < 0) {
freeaddrinfo(addrinfo);
close(fd);
return -1;
}
if (server) {
{
// avoid the "address taken"
int optval = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
}
// bind the address to the socket
int bound = 0;
for (struct addrinfo *i = addrinfo; i != NULL; i = i->ai_next) {
if (!bind(fd, i->ai_addr, i->ai_addrlen))
bound = 1;
}
if (!bound) {
// perror("bind err");
freeaddrinfo(addrinfo);
close(fd);
return -1;
}
#ifdef TCP_FASTOPEN
{
// support TCP Fast Open when available
int optval = 128;
setsockopt(fd, addrinfo->ai_protocol, TCP_FASTOPEN, &optval,
sizeof(optval));
}
#endif
if (listen(fd, SOMAXCONN) < 0) {
freeaddrinfo(addrinfo);
close(fd);
return -1;
}
} else {
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
errno = 0;
for (struct addrinfo *i = addrinfo; i; i = i->ai_next) {
if (connect(fd, i->ai_addr, i->ai_addrlen) == 0 || errno == EINPROGRESS)
goto socket_okay;
}
freeaddrinfo(addrinfo);
close(fd);
return -1;
}
socket_okay:
fio_lock(&fd_data(fd).protocol_lock);
fio_clear_fd(fd, 1);
fio_unlock(&fd_data(fd).protocol_lock);
fio_tcp_addr_cpy(fd, addrinfo->ai_family, (void *)addrinfo);
freeaddrinfo(addrinfo);
return fd2uuid(fd);
} | /* Creates a TCP/IP socket - returning it's uuid (or -1) */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2476-L2553 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_socket | intptr_t fio_socket(const char *address, const char *port, uint8_t server) {
intptr_t uuid;
if (port) {
char *pos = (char *)port;
int64_t n = fio_atol(&pos);
/* make sure port is only numerical */
if (*pos) {
FIO_LOG_ERROR("(fio_socket) port %s is not a number.", port);
errno = EINVAL;
return -1;
}
/* a negative port number will revert to a Unix socket. */
if (n <= 0) {
if (n < -1)
FIO_LOG_WARNING("(fio_socket) negative port number %s is ignored.",
port);
port = NULL;
}
}
if (!address && !port) {
FIO_LOG_ERROR("(fio_socket) both address and port are missing or invalid.");
errno = EINVAL;
return -1;
}
if (!port) {
do {
errno = 0;
uuid = fio_unix_socket(address, server);
} while (errno == EINTR);
} else {
do {
errno = 0;
uuid = fio_tcp_socket(address, port, server);
} while (errno == EINTR);
}
return uuid;
} | /* PUBLIC API: opens a server or client socket */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2556-L2592 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_read | ssize_t fio_read(intptr_t uuid, void *buffer, size_t count) {
if (!uuid_is_valid(uuid) || !uuid_data(uuid).open) {
errno = EBADF;
return -1;
}
if (count == 0)
return 0;
fio_lock(&uuid_data(uuid).sock_lock);
ssize_t (*rw_read)(intptr_t, void *, void *, size_t) =
uuid_data(uuid).rw_hooks->read;
void *udata = uuid_data(uuid).rw_udata;
fio_unlock(&uuid_data(uuid).sock_lock);
int old_errno = errno;
ssize_t ret;
retry_int:
ret = rw_read(uuid, udata, buffer, count);
if (ret > 0) {
fio_touch(uuid);
return ret;
}
if (ret < 0 && errno == EINTR)
goto retry_int;
if (ret < 0 &&
(errno == EWOULDBLOCK || errno == EAGAIN || errno == ENOTCONN)) {
errno = old_errno;
return 0;
}
fio_force_close(uuid);
return -1;
} | /* *****************************************************************************
Socket / Connection Functions
***************************************************************************** */
/**
* Returns the information available about the socket's peer address.
*
* If no information is available, the struct will be initialized with zero
* (`addr == NULL`).
* The information is only available when the socket was accepted using
* `fio_accept` or opened using `fio_connect`.
*/
/**
* `fio_read` attempts to read up to count bytes from the socket into the
* buffer starting at `buffer`.
*
* `fio_read`'s return values are wildly different then the native return
* values and they aim at making far simpler sense.
*
* `fio_read` returns the number of bytes read (0 is a valid return value which
* simply means that no bytes were read from the buffer).
*
* On a fatal connection error that leads to the connection being closed (or if
* the connection is already closed), `fio_read` returns -1.
*
* The value 0 is the valid value indicating no data was read.
*
* Data might be available in the kernel's buffer while it is not available to
* be read using `fio_read` (i.e., when using a transport layer, such as TLS).
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2766-L2795 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_write2_fn | ssize_t fio_write2_fn(intptr_t uuid, fio_write_args_s options) {
if (!uuid_is_valid(uuid))
goto error;
/* create packet */
fio_packet_s *packet = fio_packet_alloc();
*packet = (fio_packet_s){
.length = options.length,
.offset = options.offset,
.data.buffer = (void *)options.data.buffer,
};
if (options.is_fd) {
packet->write_func = (uuid_data(uuid).rw_hooks == &FIO_DEFAULT_RW_HOOKS)
? fio_sock_sendfile_from_fd
: fio_sock_write_from_fd;
packet->dealloc =
(options.after.dealloc ? options.after.dealloc
: (void (*)(void *))fio_sock_perform_close_fd);
} else {
packet->write_func = fio_sock_write_buffer;
packet->dealloc = (options.after.dealloc ? options.after.dealloc : free);
}
/* add packet to outgoing list */
uint8_t was_empty = 1;
fio_lock(&uuid_data(uuid).sock_lock);
if (!uuid_is_valid(uuid)) {
goto locked_error;
}
if (uuid_data(uuid).packet)
was_empty = 0;
if (options.urgent == 0) {
*uuid_data(uuid).packet_last = packet;
uuid_data(uuid).packet_last = &packet->next;
} else {
fio_packet_s **pos = &uuid_data(uuid).packet;
if (*pos)
pos = &(*pos)->next;
packet->next = *pos;
*pos = packet;
if (!packet->next) {
uuid_data(uuid).packet_last = &packet->next;
}
}
fio_atomic_add(&uuid_data(uuid).packet_count, 1);
fio_unlock(&uuid_data(uuid).sock_lock);
if (was_empty) {
touchfd(fio_uuid2fd(uuid));
deferred_on_ready((void *)uuid, (void *)1);
}
return 0;
locked_error:
fio_unlock(&uuid_data(uuid).sock_lock);
fio_packet_free(packet);
errno = EBADF;
return -1;
error:
if (options.after.dealloc) {
options.after.dealloc((void *)options.data.buffer);
}
errno = EBADF;
return -1;
} | /**
* `fio_write2_fn` is the actual function behind the macro `fio_write2`.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2800-L2862 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | FIO_DEALLOC_NOOP | void FIO_DEALLOC_NOOP(void *arg) { (void)arg; } | /** A noop function for fio_write2 in cases not deallocation is required. */ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2865-L2865 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_pending | size_t fio_pending(intptr_t uuid) {
if (!uuid_is_valid(uuid))
return 0;
return uuid_data(uuid).packet_count;
} | /**
* Returns the number of `fio_write` calls that are waiting in the socket's
* queue and haven't been processed.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2871-L2875 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_close | void fio_close(intptr_t uuid) {
if (!uuid_is_valid(uuid)) {
errno = EBADF;
return;
}
if (uuid_data(uuid).packet || uuid_data(uuid).sock_lock) {
uuid_data(uuid).close = 1;
fio_poll_add_write(fio_uuid2fd(uuid));
return;
}
fio_force_close(uuid);
} | /**
* `fio_close` marks the connection for disconnection once all the data was
* sent. The actual disconnection will be managed by the `fio_flush` function.
*
* `fio_flash` will be automatically scheduled.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2883-L2894 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_force_close | void fio_force_close(intptr_t uuid) {
if (!uuid_is_valid(uuid)) {
errno = EBADF;
return;
}
// FIO_LOG_DEBUG("fio_force_close called for uuid %p", (void *)uuid);
/* make sure the close marker is set */
if (!uuid_data(uuid).close)
uuid_data(uuid).close = 1;
/* clear away any packets in case we want to cut the connection short. */
fio_packet_s *packet = NULL;
fio_lock(&uuid_data(uuid).sock_lock);
packet = uuid_data(uuid).packet;
uuid_data(uuid).packet = NULL;
uuid_data(uuid).packet_last = &uuid_data(uuid).packet;
uuid_data(uuid).sent = 0;
fio_unlock(&uuid_data(uuid).sock_lock);
while (packet) {
fio_packet_s *tmp = packet;
packet = packet->next;
fio_packet_free(tmp);
}
/* check for rw-hooks termination packet */
if (uuid_data(uuid).open && (uuid_data(uuid).close & 1) &&
uuid_data(uuid).rw_hooks->before_close(uuid, uuid_data(uuid).rw_udata)) {
uuid_data(uuid).close = 2; /* don't repeat the before_close callback */
fio_touch(uuid);
fio_poll_add_write(fio_uuid2fd(uuid));
return;
}
fio_lock(&uuid_data(uuid).protocol_lock);
fio_clear_fd(fio_uuid2fd(uuid), 0);
fio_unlock(&uuid_data(uuid).protocol_lock);
close(fio_uuid2fd(uuid));
#if FIO_ENGINE_POLL
fio_poll_remove_fd(fio_uuid2fd(uuid));
#endif
if (fio_data->connection_count)
fio_atomic_sub(&fio_data->connection_count, 1);
} | /**
* `fio_force_close` closes the connection immediately, without adhering to any
* protocol restrictions and without sending any remaining data in the
* connection buffer.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2901-L2940 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
zap | github_2023 | zigzap | c | fio_flush | ssize_t fio_flush(intptr_t uuid) {
if (!uuid_is_valid(uuid))
goto invalid;
errno = 0;
ssize_t flushed = 0;
int tmp;
/* start critical section */
if (fio_trylock(&uuid_data(uuid).sock_lock))
goto would_block;
if (!uuid_data(uuid).packet)
goto flush_rw_hook;
const fio_packet_s *old_packet = uuid_data(uuid).packet;
const size_t old_sent = uuid_data(uuid).sent;
tmp = uuid_data(uuid).packet->write_func(fio_uuid2fd(uuid),
uuid_data(uuid).packet);
if (tmp <= 0) {
goto test_errno;
}
if (uuid_data(uuid).packet_count >= FIO_SLOWLORIS_LIMIT &&
uuid_data(uuid).packet == old_packet &&
uuid_data(uuid).sent >= old_sent &&
(uuid_data(uuid).sent - old_sent) < 32768) {
/* Slowloris attack assumed */
goto attacked;
}
/* end critical section */
fio_unlock(&uuid_data(uuid).sock_lock);
/* test for fio_close marker */
if (!uuid_data(uuid).packet && uuid_data(uuid).close)
goto closed;
/* return state */
return uuid_data(uuid).open && uuid_data(uuid).packet != NULL;
would_block:
errno = EWOULDBLOCK;
return -1;
closed:
fio_force_close(uuid);
return -1;
flush_rw_hook:
flushed = uuid_data(uuid).rw_hooks->flush(uuid, uuid_data(uuid).rw_udata);
fio_unlock(&uuid_data(uuid).sock_lock);
if (!flushed)
return 0;
if (flushed < 0) {
goto test_errno;
}
touchfd(fio_uuid2fd(uuid));
return 1;
test_errno:
fio_unlock(&uuid_data(uuid).sock_lock);
switch (errno) {
case EWOULDBLOCK: /* fallthrough */
#if EWOULDBLOCK != EAGAIN
case EAGAIN: /* fallthrough */
#endif
case ENOTCONN: /* fallthrough */
case EINPROGRESS: /* fallthrough */
case ENOSPC: /* fallthrough */
case EADDRNOTAVAIL: /* fallthrough */
case EINTR:
return 1;
case EFAULT:
FIO_LOG_ERROR("fio_flush EFAULT - possible memory address error sent to "
"Unix socket.");
/* fallthrough */
case EPIPE: /* fallthrough */
case EIO: /* fallthrough */
case EINVAL: /* fallthrough */
case EBADF:
uuid_data(uuid).close = 1;
fio_force_close(uuid);
return -1;
}
fprintf(stderr, "UUID error: %p (%d)\n", (void *)uuid, errno);
perror("No errno handler");
return 0;
invalid:
/* bad UUID */
errno = EBADF;
return -1;
attacked:
/* don't close, just detach from facil.io and mark uuid as invalid */
FIO_LOG_WARNING("(facil.io) possible Slowloris attack from %.*s",
(int)fio_peer_addr(uuid).len, fio_peer_addr(uuid).data);
fio_unlock(&uuid_data(uuid).sock_lock);
fio_clear_fd(fio_uuid2fd(uuid), 0);
return -1;
} | /**
* `fio_flush` attempts to write any remaining data in the internal buffer to
* the underlying file descriptor and closes the underlying file descriptor once
* if it's marked for closure (and all the data was sent).
*
* Return values: 1 will be returned if data remains in the buffer. 0
* will be returned if the buffer was fully drained. -1 will be returned on an
* error or when the connection is closed.
*/ | https://github.com/zigzap/zap/blob/675c65b509d48c21a8d1fa4c5ec53fc407643a3b/facil.io/lib/facil/fio.c#L2951-L3051 | 675c65b509d48c21a8d1fa4c5ec53fc407643a3b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.