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