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