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