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