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