2.72
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 /* is it the server root? */
215 if (*q_path == '\0' || strcmp(q_path, "/") == 0) {
216 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
217 const char *t = NULL;
218
219 if (xs_type(q_vars) == XSTYPE_DICT && (t = xs_dict_get(q_vars, "t"))) {
220 /** search by tag **/
221 int skip = 0;
222 int show = xs_number_get(xs_dict_get_def(srv_config, "def_timeline_entries",
223 xs_dict_get_def(srv_config, "max_timeline_entries", "50")));
224 const char *v;
225
226 if ((v = xs_dict_get(q_vars, "skip")) != NULL)
227 skip = atoi(v);
228 if ((v = xs_dict_get(q_vars, "show")) != NULL)
229 show = atoi(v);
230
231 xs *tl = tag_search(t, skip, show + 1);
232 int more = 0;
233 if (xs_list_len(tl) >= show + 1) {
234 /* drop the last one */
235 tl = xs_list_del(tl, -1);
236 more = 1;
237 }
238
239 const char *accept = xs_dict_get(req, "accept");
240 if (!xs_is_null(accept) && strcmp(accept, "application/rss+xml") == 0) {
241 xs *link = xs_fmt("%s/?t=%s", srv_baseurl, t);
242
243 *body = timeline_to_rss(NULL, tl, link, link, link);
244 *ctype = "application/rss+xml; charset=utf-8";
245 }
246 else {
247 xs *page = xs_fmt("?t=%s", t);
248 xs *title = xs_fmt(L("Search results for tag #%s"), t);
249 *body = html_timeline(NULL, tl, 0, skip, show, more, title, page, 0, NULL);
250 }
251 }
252 else
253 if (xs_type(xs_dict_get(srv_config, "show_instance_timeline")) == XSTYPE_TRUE) {
254 /** instance timeline **/
255 xs *tl = timeline_instance_list(0, 30);
256 *body = html_timeline(NULL, tl, 0, 0, 0, 0,
257 L("Recent posts by users in this instance"), NULL, 0, NULL);
258 }
259 else
260 *body = greeting_html();
261
262 if (*body)
263 status = HTTP_STATUS_OK;
264 }
265 else
266 if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
267 status = HTTP_STATUS_OK;
268 *body = xs_base64_dec(default_avatar_base64(), b_size);
269 *ctype = "image/png";
270 }
271 else
272 if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
273 status = HTTP_STATUS_OK;
274 *ctype = "application/json; charset=utf-8";
275 *body = xs_fmt("{\"links\":["
276 "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
277 "\"href\":\"%s/nodeinfo_2_0\"}]}",
278 srv_baseurl);
279 }
280 else
281 if (strcmp(q_path, "/.well-known/host-meta") == 0) {
282 status = HTTP_STATUS_OK;
283 *ctype = "application/xrd+xml";
284 *body = xs_fmt("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
285 "<XRD>"
286 "<Link rel=\"lrdd\" type=\"application/xrd+xml\" template=\"https://%s/.well-known/webfinger?resource={uri}\"/>"
287 "</XRD>", xs_dict_get(srv_config, "host"));
288 }
289 else
290 if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
291 status = HTTP_STATUS_OK;
292 *ctype = "application/json; charset=utf-8";
293 *body = nodeinfo_2_0();
294 }
295 else
296 if (strcmp(q_path, "/robots.txt") == 0) {
297 status = HTTP_STATUS_OK;
298 *ctype = "text/plain";
299 *body = xs_str_new("User-agent: *\n"
300 "Disallow: /\n");
301 }
302 else
303 if (strcmp(q_path, "/style.css") == 0) {
304 FILE *f;
305 xs *css_fn = xs_fmt("%s/style.css", srv_basedir);
306
307 if ((f = fopen(css_fn, "r")) != NULL) {
308 *body = xs_readall(f);
309 fclose(f);
310
311 status = HTTP_STATUS_OK;
312 *ctype = "text/css";
313 }
314 }
315 else
316 if (strcmp(q_path, "/share") == 0) {
317 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
318 const char *url = xs_dict_get(q_vars, "url");
319 const char *text = xs_dict_get(q_vars, "text");
320 xs *s = NULL;
321
322 if (xs_type(text) == XSTYPE_STRING) {
323 if (xs_type(url) == XSTYPE_STRING)
324 s = xs_fmt("%s:\n\n%s\n", text, url);
325 else
326 s = xs_fmt("%s\n", text);
327 }
328 else
329 if (xs_type(url) == XSTYPE_STRING)
330 s = xs_fmt("%s\n", url);
331 else
332 s = xs_str_new(NULL);
333
334 status = HTTP_STATUS_OK;
335 *ctype = "text/html; charset=utf-8";
336 *body = xs_fmt(share_page,
337 xs_dict_get(srv_config, "host"),
338 srv_baseurl,
339 xs_dict_get(srv_config, "host"),
340 srv_baseurl,
341 s,
342 USER_AGENT
343 );
344 }
345 else
346 if (strcmp(q_path, "/authorize_interaction") == 0) {
347 const xs_dict *q_vars = xs_dict_get(req, "q_vars");
348 const char *uri = xs_dict_get(q_vars, "uri");
349
350 if (xs_is_string(uri)) {
351 status = HTTP_STATUS_OK;
352 *ctype = "text/html; charset=utf-8";
353 *body = xs_fmt(authorize_interaction_page,
354 xs_dict_get(srv_config, "host"),
355 srv_baseurl,
356 xs_dict_get(srv_config, "host"),
357 srv_baseurl,
358 uri,
359 uri,
360 USER_AGENT
361 );
362 }
363 }
364
365 if (status != 0)
366 srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
367
368 return status;
369}
370
371
372void httpd_connection(FILE *f)
373/* the connection processor */
374{
375 xs *req;
376 const char *method;
377 int status = 0;
378 xs_str *body = NULL;
379 int b_size = 0;
380 char *ctype = NULL;
381 xs *headers = xs_dict_new();
382 xs *q_path = NULL;
383 xs *payload = NULL;
384 xs *etag = NULL;
385 xs *last_modified = NULL;
386 xs *link = NULL;
387 int p_size = 0;
388 const char *p;
389 int fcgi_id;
390
391 if (p_state->use_fcgi)
392 req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
393 else
394 req = xs_httpd_request(f, &payload, &p_size);
395
396 if (req == NULL) {
397 /* probably because a timeout */
398 fclose(f);
399 return;
400 }
401
402 if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
403 /* missing needed headers; discard */
404 fclose(f);
405 return;
406 }
407
408 q_path = xs_dup(p);
409
410 /* crop the q_path from leading / and the prefix */
411 if (xs_endswith(q_path, "/"))
412 q_path = xs_crop_i(q_path, 0, -1);
413
414 p = xs_dict_get(srv_config, "prefix");
415 if (xs_startswith(q_path, p))
416 q_path = xs_crop_i(q_path, strlen(p), 0);
417
418 if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
419 /* cascade through */
420 if (status == 0)
421 status = server_get_handler(req, q_path, &body, &b_size, &ctype);
422
423 if (status == 0)
424 status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
425
426 if (status == 0)
427 status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
428
429#ifndef NO_MASTODON_API
430 if (status == 0)
431 status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
432
433 if (status == 0)
434 status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype, &link);
435#endif /* NO_MASTODON_API */
436
437 if (status == 0)
438 status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag, &last_modified);
439 }
440 else
441 if (strcmp(method, "POST") == 0) {
442
443#ifndef NO_MASTODON_API
444 if (status == 0)
445 status = oauth_post_handler(req, q_path,
446 payload, p_size, &body, &b_size, &ctype);
447
448 if (status == 0)
449 status = mastoapi_post_handler(req, q_path,
450 payload, p_size, &body, &b_size, &ctype);
451#endif
452
453 if (status == 0)
454 status = activitypub_post_handler(req, q_path,
455 payload, p_size, &body, &b_size, &ctype);
456
457 if (status == 0)
458 status = html_post_handler(req, q_path,
459 payload, p_size, &body, &b_size, &ctype);
460 }
461 else
462 if (strcmp(method, "PUT") == 0) {
463
464#ifndef NO_MASTODON_API
465 if (status == 0)
466 status = mastoapi_put_handler(req, q_path,
467 payload, p_size, &body, &b_size, &ctype);
468#endif
469
470 }
471 else
472 if (strcmp(method, "PATCH") == 0) {
473
474#ifndef NO_MASTODON_API
475 if (status == 0)
476 status = mastoapi_patch_handler(req, q_path,
477 payload, p_size, &body, &b_size, &ctype);
478#endif
479
480 }
481 else
482 if (strcmp(method, "OPTIONS") == 0) {
483 const char *methods = "OPTIONS, GET, HEAD, POST, PUT, DELETE";
484 headers = xs_dict_append(headers, "allow", methods);
485 headers = xs_dict_append(headers, "access-control-allow-methods", methods);
486 status = HTTP_STATUS_OK;
487 }
488 else
489 if (strcmp(method, "DELETE") == 0) {
490#ifndef NO_MASTODON_API
491 if (status == 0)
492 status = mastoapi_delete_handler(req, q_path,
493 payload, p_size, &body, &b_size, &ctype);
494#endif
495 }
496
497 /* unattended? it's an error */
498 if (status == 0) {
499 srv_archive_error("unattended_method", "unattended method", req, payload);
500 srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
501 status = HTTP_STATUS_NOT_FOUND;
502 }
503
504 if (status == HTTP_STATUS_FORBIDDEN)
505 body = xs_str_new("<h1>403 Forbidden (" USER_AGENT ")</h1>");
506
507 if (status == HTTP_STATUS_NOT_FOUND)
508 body = xs_str_new("<h1>404 Not Found (" USER_AGENT ")</h1>");
509
510 if (status == HTTP_STATUS_BAD_REQUEST && body != NULL)
511 body = xs_str_new("<h1>400 Bad Request (" USER_AGENT ")</h1>");
512
513 if (status == HTTP_STATUS_SEE_OTHER)
514 headers = xs_dict_append(headers, "location", body);
515
516 if (status == HTTP_STATUS_UNAUTHORIZED && body) {
517 xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
518 body, xs_dict_get(srv_config, "host"));
519
520 headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
521 headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
522 }
523
524 if (ctype == NULL)
525 ctype = "text/html; charset=utf-8";
526
527 headers = xs_dict_append(headers, "content-type", ctype);
528 headers = xs_dict_append(headers, "x-creator", USER_AGENT);
529
530 if (!xs_is_null(etag))
531 headers = xs_dict_append(headers, "etag", etag);
532 if (!xs_is_null(last_modified))
533 headers = xs_dict_append(headers, "last-modified", last_modified);
534 if (!xs_is_null(link))
535 headers = xs_dict_append(headers, "Link", link);
536
537 /* if there are any additional headers, add them */
538 const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
539 if (xs_type(more_headers) == XSTYPE_DICT) {
540 const char *k, *v;
541 int c = 0;
542 while (xs_dict_next(more_headers, &k, &v, &c))
543 headers = xs_dict_set(headers, k, v);
544 }
545
546 if (b_size == 0 && body != NULL)
547 b_size = strlen(body);
548
549 /* if it was a HEAD, no body will be sent */
550 if (strcmp(method, "HEAD") == 0)
551 body = xs_free(body);
552
553 headers = xs_dict_append(headers, "access-control-allow-origin", "*");
554 headers = xs_dict_append(headers, "access-control-allow-headers", "*");
555
556 if (p_state->use_fcgi)
557 xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
558 else
559 xs_httpd_response(f, status, http_status_text(status), headers, body, b_size);
560
561 fclose(f);
562
563 srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
564
565 /* JSON validation check */
566 if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
567 xs *j = xs_json_loads(body);
568
569 if (j == NULL) {
570 srv_log(xs_fmt("bad JSON"));
571 srv_archive_error("bad_json", "bad JSON", req, body);
572 }
573 }
574
575 xs_free(body);
576}
577
578
579void job_post(const xs_val *job, int urgent)
580/* posts a job for the threads to process it */
581{
582 if (job != NULL) {
583 /* lock the mutex */
584 pthread_mutex_lock(&job_mutex);
585
586 job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
587 *i = (job_fifo_item){ NULL, xs_dup(job) };
588
589 if (job_fifo_first == NULL)
590 job_fifo_first = job_fifo_last = i;
591 else
592 if (urgent) {
593 /* prepend */
594 i->next = job_fifo_first;
595 job_fifo_first = i;
596 }
597 else {
598 /* append */
599 job_fifo_last->next = i;
600 job_fifo_last = i;
601 }
602
603 p_state->job_fifo_size++;
604
605 if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
606 p_state->peak_job_fifo_size = p_state->job_fifo_size;
607
608 /* unlock the mutex */
609 pthread_mutex_unlock(&job_mutex);
610
611 /* ask for someone to attend it */
612 sem_post(job_sem);
613 }
614}
615
616
617void job_wait(xs_val **job)
618/* waits for an available job */
619{
620 *job = NULL;
621
622 if (sem_wait(job_sem) == 0) {
623 /* lock the mutex */
624 pthread_mutex_lock(&job_mutex);
625
626 /* dequeue */
627 job_fifo_item *i = job_fifo_first;
628
629 if (i != NULL) {
630 job_fifo_first = i->next;
631
632 if (job_fifo_first == NULL)
633 job_fifo_last = NULL;
634
635 *job = i->job;
636 xs_free(i);
637
638 p_state->job_fifo_size--;
639 }
640
641 /* unlock the mutex */
642 pthread_mutex_unlock(&job_mutex);
643 }
644}
645
646
647static void *job_thread(void *arg)
648/* job thread */
649{
650 int pid = (int)(uintptr_t)arg;
651
652 srv_debug(1, xs_fmt("job thread %d started", pid));
653
654 for (;;) {
655 xs *job = NULL;
656
657 p_state->th_state[pid] = THST_WAIT;
658
659 job_wait(&job);
660
661 if (job == NULL) /* corrupted message? */
662 continue;
663
664 if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
665 break;
666 else
667 if (xs_type(job) == XSTYPE_DATA) {
668 /* it's a socket */
669 FILE *f = NULL;
670
671 p_state->th_state[pid] = THST_IN;
672
673 xs_data_get(&f, job);
674
675 if (f != NULL)
676 httpd_connection(f);
677 }
678 else {
679 /* it's a q_item */
680 p_state->th_state[pid] = THST_QUEUE;
681
682 process_queue_item(job);
683 }
684 }
685
686 p_state->th_state[pid] = THST_STOP;
687
688 srv_debug(1, xs_fmt("job thread %d stopped", pid));
689
690 return NULL;
691}
692
693/* background thread sleep control */
694static pthread_mutex_t sleep_mutex;
695static pthread_cond_t sleep_cond;
696
697static void *background_thread(void *arg)
698/* background thread (queue management and other things) */
699{
700 time_t purge_time;
701
702 (void)arg;
703
704 /* first purge time */
705 purge_time = time(NULL) + 10 * 60;
706
707 srv_log(xs_fmt("background thread started"));
708
709 while (p_state->srv_running) {
710 time_t t;
711 int cnt = 0;
712
713 p_state->th_state[0] = THST_QUEUE;
714
715 {
716 xs *list = user_list();
717 char *p;
718 const char *uid;
719
720 /* process queues for all users */
721 p = list;
722 while (xs_list_iter(&p, &uid)) {
723 snac snac;
724
725 if (user_open(&snac, uid)) {
726 cnt += process_user_queue(&snac);
727 user_free(&snac);
728 }
729 }
730 }
731
732 /* global queue */
733 cnt += process_queue();
734
735 /* time to purge? */
736 if ((t = time(NULL)) > purge_time) {
737 /* next purge time is tomorrow */
738 purge_time = t + 24 * 60 * 60;
739
740 xs *q_item = xs_dict_new();
741 q_item = xs_dict_append(q_item, "type", "purge");
742 job_post(q_item, 0);
743 }
744
745 if (cnt == 0) {
746 /* sleep 3 seconds */
747
748 p_state->th_state[0] = THST_WAIT;
749
750#ifdef USE_POLL_FOR_SLEEP
751 poll(NULL, 0, 3 * 1000);
752#else
753 struct timespec ts;
754
755 clock_gettime(CLOCK_REALTIME, &ts);
756 ts.tv_sec += 3;
757
758 pthread_mutex_lock(&sleep_mutex);
759 while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
760 pthread_mutex_unlock(&sleep_mutex);
761#endif
762 }
763 }
764
765 p_state->th_state[0] = THST_STOP;
766
767 srv_log(xs_fmt("background thread stopped"));
768
769 return NULL;
770}
771
772
773void term_handler(int s)
774{
775 (void)s;
776
777 longjmp(on_break, 1);
778}
779
780
781srv_state *srv_state_op(xs_str **fname, int op)
782/* opens or deletes the shared memory object */
783{
784 int fd;
785 srv_state *ss = NULL;
786
787 if (*fname == NULL)
788 *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
789
790 switch (op) {
791 case 0: /* open for writing */
792
793#ifdef WITHOUT_SHM
794
795 errno = ENOTSUP;
796
797#else
798
799 if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
800 ftruncate(fd, sizeof(*ss));
801
802 if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
803 MAP_SHARED, fd, 0)) == MAP_FAILED)
804 ss = NULL;
805
806 close(fd);
807 }
808
809#endif
810
811 if (ss == NULL) {
812 /* shared memory error: just create a plain structure */
813 srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
814 ss = malloc(sizeof(*ss));
815 }
816
817 /* init structure */
818 *ss = (srv_state){0};
819 ss->s_size = sizeof(*ss);
820
821 break;
822
823 case 1: /* open for reading */
824
825#ifdef WITHOUT_SHM
826
827 errno = ENOTSUP;
828
829#else
830
831 if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
832 if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
833 ss = NULL;
834
835 close(fd);
836 }
837
838#endif
839
840 if (ss == NULL) {
841 /* shared memory error */
842 srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
843 }
844 else
845 if (ss->s_size != sizeof(*ss)) {
846 srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
847 ss->s_size, sizeof(*ss)));
848
849 munmap(ss, sizeof(*ss));
850
851 ss = NULL;
852 }
853
854 break;
855
856 case 2: /* unlink */
857
858#ifndef WITHOUT_SHM
859
860 if (*fname)
861 shm_unlink(*fname);
862
863#endif
864
865 break;
866 }
867
868 return ss;
869}
870
871
872void httpd(void)
873/* starts the server */
874{
875 const char *address = NULL;
876 const char *port = NULL;
877 xs *full_address = NULL;
878 int rs;
879 pthread_t threads[MAX_THREADS] = {0};
880 int n;
881 xs *sem_name = NULL;
882 xs *shm_name = NULL;
883 sem_t anon_job_sem;
884 xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
885 int pidfd;
886
887 {
888 /* do some pidfile locking acrobatics */
889 if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
890 srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
891 return;
892 }
893
894 if (lockf(pidfd, F_TLOCK, 1) == -1) {
895 srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
896 close(pidfd);
897 return;
898 }
899
900 ftruncate(pidfd, 0);
901
902 xs *s = xs_fmt("%d\n", (int)getpid());
903 write(pidfd, s, strlen(s));
904 }
905
906 address = xs_dict_get(srv_config, "address");
907
908 if (*address == '/') {
909 rs = xs_unix_socket_server(address, NULL);
910 full_address = xs_fmt("unix:%s", address);
911 }
912 else {
913 port = xs_number_str(xs_dict_get(srv_config, "port"));
914 full_address = xs_fmt("%s:%s", address, port);
915
916 rs = xs_socket_server(address, port);
917 }
918
919 if (rs == -1) {
920 srv_log(xs_fmt("cannot bind socket to %s", full_address));
921 return;
922 }
923
924 /* setup the server stat structure */
925 p_state = srv_state_op(&shm_name, 0);
926
927 p_state->srv_start_time = time(NULL);
928
929 p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
930
931 p_state->srv_running = 1;
932
933 signal(SIGPIPE, SIG_IGN);
934 signal(SIGTERM, term_handler);
935 signal(SIGINT, term_handler);
936
937 srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
938 full_address, USER_AGENT));
939
940 /* show the number of usable file descriptors */
941 struct rlimit r;
942 getrlimit(RLIMIT_NOFILE, &r);
943 srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
944 (int) r.rlim_cur, (int) r.rlim_max));
945
946 /* initialize the job control engine */
947 pthread_mutex_init(&job_mutex, NULL);
948 sem_name = xs_fmt("/job_%d", getpid());
949 job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
950
951 if (job_sem == NULL) {
952 /* error opening a named semaphore; try with an anonymous one */
953 if (sem_init(&anon_job_sem, 0, 0) != -1)
954 job_sem = &anon_job_sem;
955 }
956
957 if (job_sem == NULL) {
958 srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
959 return;
960 }
961
962 /* initialize sleep control */
963 pthread_mutex_init(&sleep_mutex, NULL);
964 pthread_cond_init(&sleep_cond, NULL);
965
966 p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
967
968#ifdef _SC_NPROCESSORS_ONLN
969 if (p_state->n_threads == 0) {
970 /* get number of CPUs on the machine */
971 p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
972 }
973#endif
974
975 if (p_state->n_threads < 4)
976 p_state->n_threads = 4;
977
978 if (p_state->n_threads > MAX_THREADS)
979 p_state->n_threads = MAX_THREADS;
980
981 srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
982
983 /* thread #0 is the background thread */
984 pthread_create(&threads[0], NULL, background_thread, NULL);
985
986 /* the rest of threads are for job processing */
987 char *ptr = (char *) 0x1;
988 for (n = 1; n < p_state->n_threads; n++)
989 pthread_create(&threads[n], NULL, job_thread, ptr++);
990
991 if (setjmp(on_break) == 0) {
992 for (;;) {
993 int cs = xs_socket_accept(rs);
994
995 if (cs != -1) {
996 FILE *f = fdopen(cs, "r+");
997 xs *job = xs_data_new(&f, sizeof(FILE *));
998 job_post(job, 1);
999 }
1000 else
1001 break;
1002 }
1003 }
1004
1005 p_state->srv_running = 0;
1006
1007 /* send as many exit jobs as working threads */
1008 for (n = 1; n < p_state->n_threads; n++)
1009 job_post(xs_stock(XSTYPE_FALSE), 0);
1010
1011 /* wait for all the threads to exit */
1012 for (n = 0; n < p_state->n_threads; n++)
1013 pthread_join(threads[n], NULL);
1014
1015 sem_close(job_sem);
1016 sem_unlink(sem_name);
1017
1018 srv_state_op(&shm_name, 2);
1019
1020 xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
1021
1022 srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
1023 p_state->use_fcgi ? " (FastCGI)" : "",
1024 full_address, uptime));
1025
1026 unlink(pidfile);
1027}