2.74
httpd.c
1/* snac - A simple, minimalistic ActivityPub instance */
2/* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
3
4#include "xs.h"
5#include "xs_io.h"
6#include "xs_json.h"
7#include "xs_socket.h"
8#include "xs_unix_socket.h"
9#include "xs_httpd.h"
10#include "xs_mime.h"
11#include "xs_time.h"
12#include "xs_openssl.h"
13#include "xs_fcgi.h"
14#include "xs_html.h"
15
16#include "snac.h"
17
18#include <setjmp.h>
19#include <pthread.h>
20#include <semaphore.h>
21#include <fcntl.h>
22#include <stdint.h>
23
24#include <sys/resource.h> // for getrlimit()
25
26#include <sys/mman.h>
27
28#ifdef USE_POLL_FOR_SLEEP
29#include <poll.h>
30#endif
31
32/** server state **/
33srv_state *p_state = NULL;
34
35
36/** job control **/
37
38/* mutex to access the lists of jobs */
39static pthread_mutex_t job_mutex;
40
41/* semaphore to trigger job processing */
42static sem_t *job_sem;
43
44typedef struct job_fifo_item {
45 struct job_fifo_item *next;
46 xs_val *job;
47} job_fifo_item;
48
49static job_fifo_item *job_fifo_first = NULL;
50static job_fifo_item *job_fifo_last = NULL;
51
52
53/** other global data **/
54
55static jmp_buf on_break;
56
57
58/** code **/
59
60/* nodeinfo 2.0 template */
61const char *nodeinfo_2_0_template = ""
62 "{\"version\":\"2.0\","
63 "\"software\":{\"name\":\"snac\",\"version\":\"" VERSION "\"},"
64 "\"protocols\":[\"activitypub\"],"
65 "\"services\":{\"outbound\":[],\"inbound\":[]},"
66 "\"usage\":{\"users\":{\"total\":%d,\"activeMonth\":%d,\"activeHalfyear\":%d},"
67 "\"localPosts\":%d},"
68 "\"openRegistrations\":false,\"metadata\":{}}";
69
70xs_str *nodeinfo_2_0(void)
71/* builds a nodeinfo json object */
72{
73 int n_utotal = 0;
74 int n_umonth = 0;
75 int n_uhyear = 0;
76 int n_posts = 0;
77 xs *users = user_list();
78 xs_list *p = users;
79 const char *v;
80 double now = (double)time(NULL);
81
82 while (xs_list_iter(&p, &v)) {
83 /* build the full path name to the last usage log */
84 xs *llfn = xs_fmt("%s/user/%s/lastlog.txt", srv_basedir, v);
85 double llsecs = now - mtime(llfn);
86
87 if (llsecs < 60 * 60 * 24 * 30 * 6) {
88 n_uhyear++;
89
90 if (llsecs < 60 * 60 * 24 * 30)
91 n_umonth++;
92 }
93
94 n_utotal++;
95
96 /* build the file to each user public.idx */
97 xs *pidxfn = xs_fmt("%s/user/%s/public.idx", srv_basedir, v);
98 n_posts += index_len(pidxfn);
99 }
100
101 return xs_fmt(nodeinfo_2_0_template, n_utotal, n_umonth, n_uhyear, n_posts);
102}
103
104
105static xs_str *greeting_html(void)
106/* processes and returns greeting.html */
107{
108 /* try to open greeting.html */
109 xs *fn = xs_fmt("%s/greeting.html", srv_basedir);
110 FILE *f;
111 xs_str *s = NULL;
112
113 if ((f = fopen(fn, "r")) != NULL) {
114 s = xs_readall(f);
115 fclose(f);
116
117 /* replace %host% */
118 s = xs_replace_i(s, "%host%", xs_dict_get(srv_config, "host"));
119
120 const char *adm_email = xs_dict_get(srv_config, "admin_email");
121 if (xs_is_null(adm_email) || *adm_email == '\0')
122 adm_email = "the administrator of this instance";
123
124 /* replace %admin_email */
125 s = xs_replace_i(s, "%admin_email%", adm_email);
126
127 /* does it have a %userlist% mark? */
128 if (xs_str_in(s, "%userlist%") != -1) {
129 const char *host = xs_dict_get(srv_config, "host");
130 xs *list = user_list();
131 xs_list *p = list;
132 const xs_str *uid;
133
134 xs_html *ul = xs_html_tag("ul",
135 xs_html_attr("class", "snac-user-list"));
136
137 p = list;
138 while (xs_list_iter(&p, &uid)) {
139 snac user;
140
141 if (strcmp(uid, "relay") && user_open(&user, uid)) {
142 xs_html_add(ul,
143 xs_html_tag("li",
144 xs_html_tag("a",
145 xs_html_attr("href", user.actor),
146 xs_html_text("@"),
147 xs_html_text(uid),
148 xs_html_text("@"),
149 xs_html_text(host),
150 xs_html_text(" ("),
151 xs_html_text(xs_dict_get(user.config, "name")),
152 xs_html_text(")"))));
153
154 user_free(&user);
155 }
156 }
157
158 xs *s1 = xs_html_render(ul);
159 s = xs_replace_i(s, "%userlist%", s1);
160 }
161 }
162
163 return s;
164}
165
166
167const char *share_page = ""
168"<!DOCTYPE html>\n"
169"<html>\n"
170"<head>\n"
171"<title>%s - snac</title>\n"
172"<meta content=\"width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no\" name=\"viewport\">\n"
173"<link rel=\"stylesheet\" type=\"text/css\" href=\"%s/style.css\"/>\n"
174"<style>:root {color-scheme: light dark}</style>\n"
175"</head>\n"
176"<body><h1>%s link share</h1>\n"
177"<form method=\"get\" action=\"%s/share-bridge\">\n"
178"<textarea name=\"content\" rows=\"6\" wrap=\"virtual\" required=\"required\" style=\"width: 50em\">%s</textarea>\n"
179"<p>Login: <input type=\"text\" name=\"login\" autocapitalize=\"off\" required=\"required\"></p>\n"
180"<input type=\"submit\" value=\"OK\">\n"
181"</form><p>%s</p></body></html>\n"
182"";
183
184
185const char *authorize_interaction_page = ""
186"<!DOCTYPE html>\n"
187"<html>\n"
188"<head>\n"
189"<title>%s - snac</title>\n"
190"<meta content=\"width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no\" name=\"viewport\">\n"
191"<link rel=\"stylesheet\" type=\"text/css\" href=\"%s/style.css\"/>\n"
192"<style>:root {color-scheme: light dark}</style>\n"
193"</head>\n"
194"<body><h1>%s authorize interaction</h1>\n"
195"<form method=\"get\" action=\"%s/auth-int-bridge\">\n"
196"<select name=\"action\">\n"
197"<option value=\"Follow\">Follow</option>\n"
198"<option value=\"Boost\">Boost</option>\n"
199"<option value=\"Like\">Like</option>\n"
200"</select> %s\n"
201"<input type=\"hidden\" name=\"id\" value=\"%s\">\n"
202"<p>Login: <input type=\"text\" name=\"login\" autocapitalize=\"off\" required=\"required\"></p>\n"
203"<input type=\"submit\" value=\"OK\">\n"
204"</form><p>%s</p></body></html>\n"
205"";
206
207
208int server_get_handler(xs_dict *req, const char *q_path,
209 char **body, int *b_size, char **ctype)
210/* basic server services */
211{
212 int status = 0;
213
214 const snac *user = NULL;
215
216 /* is it the server root? */
217 if (*q_path == '\0' || strcmp(q_path, "/") == 0) {
218 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
219 const char *t = NULL;
220
221 if (xs_type(q_vars) == XSTYPE_DICT && (t = xs_dict_get(q_vars, "t"))) {
222 /** search by tag **/
223 int skip = 0;
224 int show = xs_number_get(xs_dict_get_def(srv_config, "def_timeline_entries",
225 xs_dict_get_def(srv_config, "max_timeline_entries", "50")));
226 const char *v;
227
228 if ((v = xs_dict_get(q_vars, "skip")) != NULL)
229 skip = atoi(v);
230 if ((v = xs_dict_get(q_vars, "show")) != NULL)
231 show = atoi(v);
232
233 xs *tl = tag_search(t, skip, show + 1);
234 int more = 0;
235 if (xs_list_len(tl) >= show + 1) {
236 /* drop the last one */
237 tl = xs_list_del(tl, -1);
238 more = 1;
239 }
240
241 const char *accept = xs_dict_get(req, "accept");
242 if (!xs_is_null(accept) && strcmp(accept, "application/rss+xml") == 0) {
243 xs *link = xs_fmt("%s/?t=%s", srv_baseurl, t);
244
245 *body = timeline_to_rss(NULL, tl, link, link, link);
246 *ctype = "application/rss+xml; charset=utf-8";
247 }
248 else {
249 xs *page = xs_fmt("?t=%s", t);
250 xs *title = xs_fmt(L("Search results for tag #%s"), t);
251 *body = html_timeline(NULL, tl, 0, skip, show, more, title, page, 0, NULL);
252 }
253 }
254 else
255 if (xs_type(xs_dict_get(srv_config, "show_instance_timeline")) == XSTYPE_TRUE) {
256 /** instance timeline **/
257 xs *tl = timeline_instance_list(0, 30);
258 *body = html_timeline(NULL, tl, 0, 0, 0, 0,
259 L("Recent posts by users in this instance"), NULL, 0, NULL);
260 }
261 else
262 *body = greeting_html();
263
264 if (*body)
265 status = HTTP_STATUS_OK;
266 }
267 else
268 if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
269 status = HTTP_STATUS_OK;
270 *body = xs_base64_dec(default_avatar_base64(), b_size);
271 *ctype = "image/png";
272 }
273 else
274 if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
275 status = HTTP_STATUS_OK;
276 *ctype = "application/json; charset=utf-8";
277 *body = xs_fmt("{\"links\":["
278 "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
279 "\"href\":\"%s/nodeinfo_2_0\"}]}",
280 srv_baseurl);
281 }
282 else
283 if (strcmp(q_path, "/.well-known/host-meta") == 0) {
284 status = HTTP_STATUS_OK;
285 *ctype = "application/xrd+xml";
286 *body = xs_fmt("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
287 "<XRD>"
288 "<Link rel=\"lrdd\" type=\"application/xrd+xml\" template=\"https://%s/.well-known/webfinger?resource={uri}\"/>"
289 "</XRD>", xs_dict_get(srv_config, "host"));
290 }
291 else
292 if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
293 status = HTTP_STATUS_OK;
294 *ctype = "application/json; charset=utf-8";
295 *body = nodeinfo_2_0();
296 }
297 else
298 if (strcmp(q_path, "/robots.txt") == 0) {
299 status = HTTP_STATUS_OK;
300 *ctype = "text/plain";
301 *body = xs_str_new("User-agent: *\n"
302 "Disallow: /\n");
303 }
304 else
305 if (strcmp(q_path, "/style.css") == 0) {
306 FILE *f;
307 xs *css_fn = xs_fmt("%s/style.css", srv_basedir);
308
309 if ((f = fopen(css_fn, "r")) != NULL) {
310 *body = xs_readall(f);
311 fclose(f);
312
313 status = HTTP_STATUS_OK;
314 *ctype = "text/css";
315 }
316 }
317 else
318 if (strcmp(q_path, "/share") == 0) {
319 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
320 const char *url = xs_dict_get(q_vars, "url");
321 const char *text = xs_dict_get(q_vars, "text");
322 xs *s = NULL;
323
324 if (xs_type(text) == XSTYPE_STRING) {
325 if (xs_type(url) == XSTYPE_STRING)
326 s = xs_fmt("%s:\n\n%s\n", text, url);
327 else
328 s = xs_fmt("%s\n", text);
329 }
330 else
331 if (xs_type(url) == XSTYPE_STRING)
332 s = xs_fmt("%s\n", url);
333 else
334 s = xs_str_new(NULL);
335
336 status = HTTP_STATUS_OK;
337 *ctype = "text/html; charset=utf-8";
338 *body = xs_fmt(share_page,
339 xs_dict_get(srv_config, "host"),
340 srv_baseurl,
341 xs_dict_get(srv_config, "host"),
342 srv_baseurl,
343 s,
344 USER_AGENT
345 );
346 }
347 else
348 if (strcmp(q_path, "/authorize_interaction") == 0) {
349 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
350 const char *uri = xs_dict_get(q_vars, "uri");
351
352 if (xs_is_string(uri)) {
353 status = HTTP_STATUS_OK;
354 *ctype = "text/html; charset=utf-8";
355 *body = xs_fmt(authorize_interaction_page,
356 xs_dict_get(srv_config, "host"),
357 srv_baseurl,
358 xs_dict_get(srv_config, "host"),
359 srv_baseurl,
360 uri,
361 uri,
362 USER_AGENT
363 );
364 }
365 }
366
367 if (status != 0)
368 srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
369
370 return status;
371}
372
373
374void httpd_connection(FILE *f)
375/* the connection processor */
376{
377 xs *req;
378 const char *method;
379 int status = 0;
380 xs_str *body = NULL;
381 int b_size = 0;
382 char *ctype = NULL;
383 xs *headers = xs_dict_new();
384 xs *q_path = NULL;
385 xs *payload = NULL;
386 xs *etag = NULL;
387 xs *last_modified = NULL;
388 xs *link = NULL;
389 int p_size = 0;
390 const char *p;
391 int fcgi_id;
392
393 if (p_state->use_fcgi)
394 req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
395 else
396 req = xs_httpd_request(f, &payload, &p_size);
397
398 if (req == NULL) {
399 /* probably because a timeout */
400 fclose(f);
401 return;
402 }
403
404 if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
405 /* missing needed headers; discard */
406 fclose(f);
407 return;
408 }
409
410 q_path = xs_dup(p);
411
412 /* crop the q_path from leading / and the prefix */
413 if (xs_endswith(q_path, "/"))
414 q_path = xs_crop_i(q_path, 0, -1);
415
416 p = xs_dict_get(srv_config, "prefix");
417 if (xs_startswith(q_path, p))
418 q_path = xs_crop_i(q_path, strlen(p), 0);
419
420 if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
421 /* cascade through */
422 if (status == 0)
423 status = server_get_handler(req, q_path, &body, &b_size, &ctype);
424
425 if (status == 0)
426 status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
427
428 if (status == 0)
429 status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
430
431#ifndef NO_MASTODON_API
432 if (status == 0)
433 status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
434
435 if (status == 0)
436 status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype, &link);
437#endif /* NO_MASTODON_API */
438
439 if (status == 0)
440 status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag, &last_modified);
441 }
442 else
443 if (strcmp(method, "POST") == 0) {
444
445#ifndef NO_MASTODON_API
446 if (status == 0)
447 status = oauth_post_handler(req, q_path,
448 payload, p_size, &body, &b_size, &ctype);
449
450 if (status == 0)
451 status = mastoapi_post_handler(req, q_path,
452 payload, p_size, &body, &b_size, &ctype);
453#endif
454
455 if (status == 0)
456 status = activitypub_post_handler(req, q_path,
457 payload, p_size, &body, &b_size, &ctype);
458
459 if (status == 0)
460 status = html_post_handler(req, q_path,
461 payload, p_size, &body, &b_size, &ctype);
462 }
463 else
464 if (strcmp(method, "PUT") == 0) {
465
466#ifndef NO_MASTODON_API
467 if (status == 0)
468 status = mastoapi_put_handler(req, q_path,
469 payload, p_size, &body, &b_size, &ctype);
470#endif
471
472 }
473 else
474 if (strcmp(method, "PATCH") == 0) {
475
476#ifndef NO_MASTODON_API
477 if (status == 0)
478 status = mastoapi_patch_handler(req, q_path,
479 payload, p_size, &body, &b_size, &ctype);
480#endif
481
482 }
483 else
484 if (strcmp(method, "OPTIONS") == 0) {
485 const char *methods = "OPTIONS, GET, HEAD, POST, PUT, DELETE";
486 headers = xs_dict_append(headers, "allow", methods);
487 headers = xs_dict_append(headers, "access-control-allow-methods", methods);
488 status = HTTP_STATUS_OK;
489 }
490 else
491 if (strcmp(method, "DELETE") == 0) {
492#ifndef NO_MASTODON_API
493 if (status == 0)
494 status = mastoapi_delete_handler(req, q_path,
495 payload, p_size, &body, &b_size, &ctype);
496#endif
497 }
498
499 /* unattended? it's an error */
500 if (status == 0) {
501 srv_archive_error("unattended_method", "unattended method", req, payload);
502 srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
503 status = HTTP_STATUS_NOT_FOUND;
504 }
505
506 if (status == HTTP_STATUS_FORBIDDEN)
507 body = xs_str_new("<h1>403 Forbidden (" USER_AGENT ")</h1>");
508
509 if (status == HTTP_STATUS_NOT_FOUND)
510 body = xs_str_new("<h1>404 Not Found (" USER_AGENT ")</h1>");
511
512 if (status == HTTP_STATUS_BAD_REQUEST && body != NULL)
513 body = xs_str_new("<h1>400 Bad Request (" USER_AGENT ")</h1>");
514
515 if (status == HTTP_STATUS_SEE_OTHER)
516 headers = xs_dict_append(headers, "location", body);
517
518 if (status == HTTP_STATUS_UNAUTHORIZED && body) {
519 xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
520 body, xs_dict_get(srv_config, "host"));
521
522 headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
523 headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
524 }
525
526 if (ctype == NULL)
527 ctype = "text/html; charset=utf-8";
528
529 headers = xs_dict_append(headers, "content-type", ctype);
530 headers = xs_dict_append(headers, "x-creator", USER_AGENT);
531
532 if (!xs_is_null(etag))
533 headers = xs_dict_append(headers, "etag", etag);
534 if (!xs_is_null(last_modified))
535 headers = xs_dict_append(headers, "last-modified", last_modified);
536 if (!xs_is_null(link))
537 headers = xs_dict_append(headers, "Link", link);
538
539 /* if there are any additional headers, add them */
540 const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
541 if (xs_type(more_headers) == XSTYPE_DICT) {
542 const char *k, *v;
543 int c = 0;
544 while (xs_dict_next(more_headers, &k, &v, &c))
545 headers = xs_dict_set(headers, k, v);
546 }
547
548 if (b_size == 0 && body != NULL)
549 b_size = strlen(body);
550
551 /* if it was a HEAD, no body will be sent */
552 if (strcmp(method, "HEAD") == 0)
553 body = xs_free(body);
554
555 headers = xs_dict_append(headers, "access-control-allow-origin", "*");
556 headers = xs_dict_append(headers, "access-control-allow-headers", "*");
557
558 /* disable any form of fucking JavaScript */
559 headers = xs_dict_append(headers, "Content-Security-Policy", "script-src ;");
560
561 if (p_state->use_fcgi)
562 xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
563 else
564 xs_httpd_response(f, status, http_status_text(status), headers, body, b_size);
565
566 fclose(f);
567
568 srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
569
570 /* JSON validation check */
571 if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
572 xs *j = xs_json_loads(body);
573
574 if (j == NULL) {
575 srv_log(xs_fmt("bad JSON"));
576 srv_archive_error("bad_json", "bad JSON", req, body);
577 }
578 }
579
580 xs_free(body);
581}
582
583
584void job_post(const xs_val *job, int urgent)
585/* posts a job for the threads to process it */
586{
587 if (job != NULL) {
588 /* lock the mutex */
589 pthread_mutex_lock(&job_mutex);
590
591 job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
592 *i = (job_fifo_item){ NULL, xs_dup(job) };
593
594 if (job_fifo_first == NULL)
595 job_fifo_first = job_fifo_last = i;
596 else
597 if (urgent) {
598 /* prepend */
599 i->next = job_fifo_first;
600 job_fifo_first = i;
601 }
602 else {
603 /* append */
604 job_fifo_last->next = i;
605 job_fifo_last = i;
606 }
607
608 p_state->job_fifo_size++;
609
610 if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
611 p_state->peak_job_fifo_size = p_state->job_fifo_size;
612
613 /* unlock the mutex */
614 pthread_mutex_unlock(&job_mutex);
615
616 /* ask for someone to attend it */
617 sem_post(job_sem);
618 }
619}
620
621
622void job_wait(xs_val **job)
623/* waits for an available job */
624{
625 *job = NULL;
626
627 if (sem_wait(job_sem) == 0) {
628 /* lock the mutex */
629 pthread_mutex_lock(&job_mutex);
630
631 /* dequeue */
632 job_fifo_item *i = job_fifo_first;
633
634 if (i != NULL) {
635 job_fifo_first = i->next;
636
637 if (job_fifo_first == NULL)
638 job_fifo_last = NULL;
639
640 *job = i->job;
641 xs_free(i);
642
643 p_state->job_fifo_size--;
644 }
645
646 /* unlock the mutex */
647 pthread_mutex_unlock(&job_mutex);
648 }
649}
650
651
652static void *job_thread(void *arg)
653/* job thread */
654{
655 int pid = (int)(uintptr_t)arg;
656
657 srv_debug(1, xs_fmt("job thread %d started", pid));
658
659 for (;;) {
660 xs *job = NULL;
661
662 p_state->th_state[pid] = THST_WAIT;
663
664 job_wait(&job);
665
666 if (job == NULL) /* corrupted message? */
667 continue;
668
669 if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
670 break;
671 else
672 if (xs_type(job) == XSTYPE_DATA) {
673 /* it's a socket */
674 FILE *f = NULL;
675
676 p_state->th_state[pid] = THST_IN;
677
678 xs_data_get(&f, job);
679
680 if (f != NULL)
681 httpd_connection(f);
682 }
683 else {
684 /* it's a q_item */
685 p_state->th_state[pid] = THST_QUEUE;
686
687 process_queue_item(job);
688 }
689 }
690
691 p_state->th_state[pid] = THST_STOP;
692
693 srv_debug(1, xs_fmt("job thread %d stopped", pid));
694
695 return NULL;
696}
697
698/* background thread sleep control */
699static pthread_mutex_t sleep_mutex;
700static pthread_cond_t sleep_cond;
701
702static void *background_thread(void *arg)
703/* background thread (queue management and other things) */
704{
705 time_t purge_time;
706
707 (void)arg;
708
709 /* first purge time */
710 purge_time = time(NULL) + 10 * 60;
711
712 srv_log(xs_fmt("background thread started"));
713
714 while (p_state->srv_running) {
715 time_t t;
716 int cnt = 0;
717
718 p_state->th_state[0] = THST_QUEUE;
719
720 {
721 xs *list = user_list();
722 char *p;
723 const char *uid;
724
725 /* process queues for all users */
726 p = list;
727 while (xs_list_iter(&p, &uid)) {
728 snac snac;
729
730 if (user_open(&snac, uid)) {
731 cnt += process_user_queue(&snac);
732 user_free(&snac);
733 }
734 }
735 }
736
737 /* global queue */
738 cnt += process_queue();
739
740 /* time to purge? */
741 if ((t = time(NULL)) > purge_time) {
742 /* next purge time is tomorrow */
743 purge_time = t + 24 * 60 * 60;
744
745 xs *q_item = xs_dict_new();
746 q_item = xs_dict_append(q_item, "type", "purge");
747 job_post(q_item, 0);
748 }
749
750 if (cnt == 0) {
751 /* sleep 3 seconds */
752
753 p_state->th_state[0] = THST_WAIT;
754
755#ifdef USE_POLL_FOR_SLEEP
756 poll(NULL, 0, 3 * 1000);
757#else
758 struct timespec ts;
759
760 clock_gettime(CLOCK_REALTIME, &ts);
761 ts.tv_sec += 3;
762
763 pthread_mutex_lock(&sleep_mutex);
764 while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
765 pthread_mutex_unlock(&sleep_mutex);
766#endif
767 }
768 }
769
770 p_state->th_state[0] = THST_STOP;
771
772 srv_log(xs_fmt("background thread stopped"));
773
774 return NULL;
775}
776
777
778void term_handler(int s)
779{
780 (void)s;
781
782 longjmp(on_break, 1);
783}
784
785
786srv_state *srv_state_op(xs_str **fname, int op)
787/* opens or deletes the shared memory object */
788{
789 int fd;
790 srv_state *ss = NULL;
791
792 if (*fname == NULL)
793 *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
794
795 switch (op) {
796 case 0: /* open for writing */
797
798#ifdef WITHOUT_SHM
799
800 errno = ENOTSUP;
801
802#else
803
804 if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
805 ftruncate(fd, sizeof(*ss));
806
807 if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
808 MAP_SHARED, fd, 0)) == MAP_FAILED)
809 ss = NULL;
810
811 close(fd);
812 }
813
814#endif
815
816 if (ss == NULL) {
817 /* shared memory error: just create a plain structure */
818 srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
819 ss = malloc(sizeof(*ss));
820 }
821
822 /* init structure */
823 *ss = (srv_state){0};
824 ss->s_size = sizeof(*ss);
825
826 break;
827
828 case 1: /* open for reading */
829
830#ifdef WITHOUT_SHM
831
832 errno = ENOTSUP;
833
834#else
835
836 if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
837 if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
838 ss = NULL;
839
840 close(fd);
841 }
842
843#endif
844
845 if (ss == NULL) {
846 /* shared memory error */
847 srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
848 }
849 else
850 if (ss->s_size != sizeof(*ss)) {
851 srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
852 ss->s_size, sizeof(*ss)));
853
854 munmap(ss, sizeof(*ss));
855
856 ss = NULL;
857 }
858
859 break;
860
861 case 2: /* unlink */
862
863#ifndef WITHOUT_SHM
864
865 if (*fname)
866 shm_unlink(*fname);
867
868#endif
869
870 break;
871 }
872
873 return ss;
874}
875
876
877void httpd(void)
878/* starts the server */
879{
880 const char *address = NULL;
881 const char *port = NULL;
882 xs *full_address = NULL;
883 int rs;
884 pthread_t threads[MAX_THREADS] = {0};
885 int n;
886 xs *sem_name = NULL;
887 xs *shm_name = NULL;
888 sem_t anon_job_sem;
889 xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
890 int pidfd;
891
892 {
893 /* do some pidfile locking acrobatics */
894 if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
895 srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
896 return;
897 }
898
899 if (lockf(pidfd, F_TLOCK, 1) == -1) {
900 srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
901 close(pidfd);
902 return;
903 }
904
905 ftruncate(pidfd, 0);
906
907 xs *s = xs_fmt("%d\n", (int)getpid());
908 write(pidfd, s, strlen(s));
909 }
910
911 address = xs_dict_get(srv_config, "address");
912
913 if (*address == '/') {
914 rs = xs_unix_socket_server(address, NULL);
915 full_address = xs_fmt("unix:%s", address);
916 }
917 else {
918 port = xs_number_str(xs_dict_get(srv_config, "port"));
919 full_address = xs_fmt("%s:%s", address, port);
920
921 rs = xs_socket_server(address, port);
922 }
923
924 if (rs == -1) {
925 srv_log(xs_fmt("cannot bind socket to %s", full_address));
926 return;
927 }
928
929 /* setup the server stat structure */
930 p_state = srv_state_op(&shm_name, 0);
931
932 p_state->srv_start_time = time(NULL);
933
934 p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
935
936 p_state->srv_running = 1;
937
938 signal(SIGPIPE, SIG_IGN);
939 signal(SIGTERM, term_handler);
940 signal(SIGINT, term_handler);
941
942 srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
943 full_address, USER_AGENT));
944
945 /* show the number of usable file descriptors */
946 struct rlimit r;
947 getrlimit(RLIMIT_NOFILE, &r);
948 srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
949 (int) r.rlim_cur, (int) r.rlim_max));
950
951 /* initialize the job control engine */
952 pthread_mutex_init(&job_mutex, NULL);
953 sem_name = xs_fmt("/job_%d", getpid());
954 job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
955
956 if (job_sem == NULL) {
957 /* error opening a named semaphore; try with an anonymous one */
958 if (sem_init(&anon_job_sem, 0, 0) != -1)
959 job_sem = &anon_job_sem;
960 }
961
962 if (job_sem == NULL) {
963 srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
964 return;
965 }
966
967 /* initialize sleep control */
968 pthread_mutex_init(&sleep_mutex, NULL);
969 pthread_cond_init(&sleep_cond, NULL);
970
971 p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
972
973#ifdef _SC_NPROCESSORS_ONLN
974 if (p_state->n_threads == 0) {
975 /* get number of CPUs on the machine */
976 p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
977 }
978#endif
979
980 if (p_state->n_threads < 4)
981 p_state->n_threads = 4;
982
983 if (p_state->n_threads > MAX_THREADS)
984 p_state->n_threads = MAX_THREADS;
985
986 srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
987
988 /* thread #0 is the background thread */
989 pthread_create(&threads[0], NULL, background_thread, NULL);
990
991 /* the rest of threads are for job processing */
992 char *ptr = (char *) 0x1;
993 for (n = 1; n < p_state->n_threads; n++)
994 pthread_create(&threads[n], NULL, job_thread, ptr++);
995
996 if (setjmp(on_break) == 0) {
997 for (;;) {
998 int cs = xs_socket_accept(rs);
999
1000 if (cs != -1) {
1001 FILE *f = fdopen(cs, "r+");
1002 xs *job = xs_data_new(&f, sizeof(FILE *));
1003 job_post(job, 1);
1004 }
1005 else
1006 break;
1007 }
1008 }
1009
1010 p_state->srv_running = 0;
1011
1012 /* send as many exit jobs as working threads */
1013 for (n = 1; n < p_state->n_threads; n++)
1014 job_post(xs_stock(XSTYPE_FALSE), 0);
1015
1016 /* wait for all the threads to exit */
1017 for (n = 0; n < p_state->n_threads; n++)
1018 pthread_join(threads[n], NULL);
1019
1020 sem_close(job_sem);
1021 sem_unlink(sem_name);
1022
1023 srv_state_op(&shm_name, 2);
1024
1025 xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
1026
1027 srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
1028 p_state->use_fcgi ? " (FastCGI)" : "",
1029 full_address, uptime));
1030
1031 unlink(pidfile);
1032}