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