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