2.94 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.1\",\"href\":\"%s/nodeinfo_2_1\"},"
 289            "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\",\"href\":\"%s/nodeinfo_2_0\"}"
 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) - 1, 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 (body == NULL) {
 604        if (status == HTTP_STATUS_FORBIDDEN)
 605            body = xs_str_new("<h1>403 Forbidden (" USER_AGENT ")</h1>");
 606
 607        if (status == HTTP_STATUS_NOT_FOUND)
 608            body = xs_str_new("<h1>404 Not Found (" USER_AGENT ")</h1>");
 609
 610        if (status == HTTP_STATUS_GONE)
 611            body = xs_str_new("<h1>410 Gone (" USER_AGENT ")</h1>");
 612
 613        if (status == HTTP_STATUS_BAD_REQUEST)
 614            body = xs_str_new("<h1>400 Bad Request (" USER_AGENT ")</h1>");
 615    }
 616
 617    if (status == HTTP_STATUS_SEE_OTHER)
 618        headers = xs_dict_append(headers, "location", body);
 619
 620    if (status == HTTP_STATUS_FOUND)
 621        headers = xs_dict_append(headers, "location", xs_fmt("%s%s", p, q_path));
 622
 623    if (status == HTTP_STATUS_UNAUTHORIZED && body) {
 624        xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
 625                                body, xs_dict_get(srv_config, "host"));
 626
 627        headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
 628        headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
 629    }
 630
 631    if (ctype == NULL)
 632        ctype = "text/html; charset=utf-8";
 633
 634    headers = xs_dict_append(headers, "content-type", ctype);
 635    headers = xs_dict_append(headers, "x-creator",    USER_AGENT);
 636
 637    if (!xs_is_null(etag))
 638        headers = xs_dict_append(headers, "etag", etag);
 639    if (!xs_is_null(last_modified))
 640        headers = xs_dict_append(headers, "last-modified", last_modified);
 641    if (!xs_is_null(link))
 642        headers = xs_dict_append(headers, "Link", link);
 643
 644    /* if there are any additional headers, add them */
 645    const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
 646    if (xs_type(more_headers) == XSTYPE_DICT) {
 647        const char *k, *v;
 648        int c = 0;
 649        while (xs_dict_next(more_headers, &k, &v, &c))
 650            headers = xs_dict_set(headers, k, v);
 651    }
 652
 653    if (b_size == 0 && body != NULL)
 654        b_size = strlen(body);
 655
 656    /* if it was a HEAD, no body will be sent */
 657    if (strcmp(method, "HEAD") == 0)
 658        body = xs_free(body);
 659
 660    headers = xs_dict_append(headers, "access-control-allow-origin", "*");
 661    headers = xs_dict_append(headers, "access-control-allow-headers", "*");
 662    headers = xs_dict_append(headers, "access-control-expose-headers", "Link");
 663
 664    /* disable any form of fucking JavaScript */
 665    headers = xs_dict_append(headers, "Content-Security-Policy", "script-src ;");
 666
 667    if (p_state->use_fcgi)
 668        xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
 669    else
 670        xs_httpd_response(f, status, xs_http_status_text(status), headers, body, b_size);
 671
 672    fclose(f);
 673
 674    srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
 675
 676    /* JSON validation check */
 677    if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
 678        xs *j = xs_json_loads(body);
 679
 680        if (j == NULL) {
 681            srv_log(xs_fmt("bad JSON"));
 682            srv_archive_error("bad_json", "bad JSON", req, body);
 683        }
 684    }
 685
 686    xs_free(body);
 687}
 688
 689
 690void job_post(const xs_val *job, int urgent)
 691/* posts a job for the threads to process it */
 692{
 693    if (job != NULL) {
 694        /* lock the mutex */
 695        pthread_mutex_lock(&job_mutex);
 696
 697        job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
 698        *i = (job_fifo_item){ NULL, xs_dup(job) };
 699
 700        if (job_fifo_first == NULL)
 701            job_fifo_first = job_fifo_last = i;
 702        else
 703        if (urgent) {
 704            /* prepend */
 705            i->next = job_fifo_first;
 706            job_fifo_first = i;
 707        }
 708        else {
 709            /* append */
 710            job_fifo_last->next = i;
 711            job_fifo_last = i;
 712        }
 713
 714        p_state->job_fifo_size++;
 715
 716        if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
 717            p_state->peak_job_fifo_size = p_state->job_fifo_size;
 718
 719        /* unlock the mutex */
 720        pthread_mutex_unlock(&job_mutex);
 721
 722        /* ask for someone to attend it */
 723        sem_post(job_sem);
 724    }
 725}
 726
 727
 728void job_wait(xs_val **job)
 729/* waits for an available job */
 730{
 731    *job = NULL;
 732
 733    if (sem_wait(job_sem) == 0) {
 734        /* lock the mutex */
 735        pthread_mutex_lock(&job_mutex);
 736
 737        /* dequeue */
 738        job_fifo_item *i = job_fifo_first;
 739
 740        if (i != NULL) {
 741            job_fifo_first = i->next;
 742
 743            if (job_fifo_first == NULL)
 744                job_fifo_last = NULL;
 745
 746            *job = i->job;
 747            xs_free(i);
 748
 749            p_state->job_fifo_size--;
 750        }
 751
 752        /* unlock the mutex */
 753        pthread_mutex_unlock(&job_mutex);
 754    }
 755}
 756
 757
 758static void *job_thread(void *arg)
 759/* job thread */
 760{
 761    int pid = (int)(uintptr_t)arg;
 762
 763    srv_debug(1, xs_fmt("job thread %d started", pid));
 764
 765    for (;;) {
 766        xs *job = NULL;
 767
 768        p_state->th_state[pid] = THST_WAIT;
 769
 770        job_wait(&job);
 771
 772        if (job == NULL) /* corrupted message? */
 773            continue;
 774
 775        if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
 776            break;
 777        else
 778        if (xs_type(job) == XSTYPE_DATA) {
 779            /* it's a socket */
 780            FILE *f = NULL;
 781
 782            p_state->th_state[pid] = THST_IN;
 783
 784            xs_data_get(&f, job);
 785
 786            if (f != NULL)
 787                httpd_connection(f);
 788        }
 789        else {
 790            /* it's a q_item */
 791            p_state->th_state[pid] = THST_QUEUE;
 792
 793            process_queue_item(job);
 794        }
 795    }
 796
 797    p_state->th_state[pid] = THST_STOP;
 798
 799    srv_debug(1, xs_fmt("job thread %d stopped", pid));
 800
 801    return NULL;
 802}
 803
 804/* background thread sleep control */
 805static pthread_mutex_t sleep_mutex;
 806static pthread_cond_t  sleep_cond;
 807
 808static void *background_thread(void *arg)
 809/* background thread (queue management and other things) */
 810{
 811    time_t t, purge_time, rss_time;
 812
 813    (void)arg;
 814
 815    t = time(NULL);
 816
 817    /* first purge time */
 818    purge_time = t + 10 * 60;
 819
 820    /* first RSS polling time */
 821    rss_time = t + 15 * 60;
 822
 823    srv_log(xs_fmt("background thread started"));
 824
 825    enqueue_fsck();
 826
 827    while (p_state->srv_running) {
 828        int cnt = 0;
 829
 830        p_state->th_state[0] = THST_QUEUE;
 831
 832        {
 833            xs *list = user_list();
 834            const char *uid;
 835
 836            /* process queues for all users */
 837            xs_list_foreach(list, uid) {
 838                snac user;
 839
 840                if (user_open(&user, uid)) {
 841                    cnt += process_user_queue(&user);
 842                    user_free(&user);
 843                }
 844            }
 845        }
 846
 847        /* global queue */
 848        cnt += process_queue();
 849
 850        t = time(NULL);
 851
 852        /* time to purge? */
 853        if (t > purge_time) {
 854            /* next purge time is tomorrow */
 855            purge_time = t + 24 * 60 * 60;
 856
 857            xs *q_item = xs_dict_new();
 858            q_item = xs_dict_append(q_item, "type", "purge");
 859            job_post(q_item, 0);
 860        }
 861
 862        /* time to poll the RSS? */
 863        if (t > rss_time) {
 864            /* next RSS poll time */
 865            int hours = xs_number_get(xs_dict_get_def(srv_config, "rss_hashtag_poll_hours", "4"));
 866
 867            /* don't hammer servers too much */
 868            if (hours < 1)
 869                hours = 1;
 870
 871            rss_time = t + 60 * 60 * hours;
 872
 873            xs *q_item = xs_dict_new();
 874            q_item = xs_dict_append(q_item, "type", "rss_hashtag_poll");
 875            job_post(q_item, 0);
 876        }
 877
 878        if (cnt == 0) {
 879            /* sleep 3 seconds */
 880
 881            p_state->th_state[0] = THST_WAIT;
 882
 883#ifdef USE_POLL_FOR_SLEEP
 884            poll(NULL, 0, 3 * 1000);
 885#else
 886            struct timespec ts;
 887
 888            clock_gettime(CLOCK_REALTIME, &ts);
 889            ts.tv_sec += 3;
 890
 891            pthread_mutex_lock(&sleep_mutex);
 892            while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
 893            pthread_mutex_unlock(&sleep_mutex);
 894#endif
 895        }
 896    }
 897
 898    p_state->th_state[0] = THST_STOP;
 899
 900    srv_log(xs_fmt("background thread stopped"));
 901
 902    return NULL;
 903}
 904
 905
 906void term_handler(int s)
 907{
 908    (void)s;
 909
 910    longjmp(on_break, 1);
 911}
 912
 913
 914srv_state *srv_state_op(xs_str **fname, int op)
 915/* opens or deletes the shared memory object */
 916{
 917    int fd;
 918    srv_state *ss = NULL;
 919
 920    if (*fname == NULL)
 921        *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
 922
 923    switch (op) {
 924    case 0: /* open for writing */
 925
 926#ifdef WITHOUT_SHM
 927
 928        errno = ENOTSUP;
 929
 930#else
 931
 932        if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
 933            ftruncate(fd, sizeof(*ss));
 934
 935            if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
 936                 MAP_SHARED, fd, 0)) == MAP_FAILED)
 937                ss = NULL;
 938
 939            close(fd);
 940        }
 941
 942#endif
 943
 944        if (ss == NULL) {
 945            /* shared memory error: just create a plain structure */
 946            srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
 947            ss = malloc(sizeof(*ss));
 948        }
 949
 950        /* init structure */
 951        *ss = (srv_state){0};
 952        ss->s_size = sizeof(*ss);
 953
 954        break;
 955
 956    case 1: /* open for reading */
 957
 958#ifdef WITHOUT_SHM
 959
 960        errno = ENOTSUP;
 961
 962#else
 963
 964        if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
 965            if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
 966                ss = NULL;
 967
 968            close(fd);
 969        }
 970
 971#endif
 972
 973        if (ss == NULL) {
 974            /* shared memory error */
 975            srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
 976        }
 977        else
 978        if (ss->s_size != sizeof(*ss)) {
 979            srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
 980                ss->s_size, sizeof(*ss)));
 981
 982            munmap(ss, sizeof(*ss));
 983
 984            ss = NULL;
 985        }
 986
 987        break;
 988
 989    case 2: /* unlink */
 990
 991#ifndef WITHOUT_SHM
 992
 993        if (*fname)
 994            shm_unlink(*fname);
 995
 996#endif
 997
 998        break;
 999    }
1000
1001    return ss;
1002}
1003
1004
1005void httpd(void)
1006/* starts the server */
1007{
1008    const char *address = NULL;
1009    const char *port = NULL;
1010    xs *full_address = NULL;
1011    int rs;
1012    pthread_t threads[MAX_THREADS] = {0};
1013    int n;
1014    xs *sem_name = NULL;
1015    xs *shm_name = NULL;
1016    sem_t anon_job_sem;
1017    xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
1018    int pidfd;
1019
1020    {
1021        /* do some pidfile locking acrobatics */
1022        if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
1023            srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
1024            return;
1025        }
1026
1027        if (lockf(pidfd, F_TLOCK, 1) == -1) {
1028            srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
1029            close(pidfd);
1030            return;
1031        }
1032
1033        ftruncate(pidfd, 0);
1034
1035        xs *s = xs_fmt("%d\n", (int)getpid());
1036        write(pidfd, s, strlen(s));
1037    }
1038
1039    address = xs_dict_get(srv_config, "address");
1040
1041    if (*address == '/') {
1042        rs = xs_unix_socket_server(address, NULL);
1043        full_address = xs_fmt("unix:%s", address);
1044    }
1045    else {
1046        port = xs_number_str(xs_dict_get(srv_config, "port"));
1047        full_address = xs_fmt("%s:%s", address, port);
1048
1049        rs = xs_socket_server(address, port);
1050    }
1051
1052    if (rs == -1) {
1053        srv_log(xs_fmt("cannot bind socket to %s", full_address));
1054        return;
1055    }
1056
1057    /* setup the server stat structure */
1058    p_state = srv_state_op(&shm_name, 0);
1059
1060    p_state->srv_start_time = time(NULL);
1061
1062    p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
1063
1064    p_state->srv_running = 1;
1065
1066    signal(SIGPIPE, SIG_IGN);
1067    signal(SIGTERM, term_handler);
1068    signal(SIGINT,  term_handler);
1069
1070    srv_log(xs_fmt(USER_AGENT " httpd%s start %s", p_state->use_fcgi ? " (FastCGI)" : "",
1071                    full_address));
1072
1073    /* show the number of usable file descriptors */
1074    struct rlimit r;
1075    getrlimit(RLIMIT_NOFILE, &r);
1076    srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
1077                        (int) r.rlim_cur, (int) r.rlim_max));
1078
1079    /* initialize the job control engine */
1080    pthread_mutex_init(&job_mutex, NULL);
1081    sem_name = xs_fmt("/job_%d", getpid());
1082    job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
1083
1084    if (job_sem == NULL) {
1085        /* error opening a named semaphore; try with an anonymous one */
1086        if (sem_init(&anon_job_sem, 0, 0) != -1)
1087            job_sem = &anon_job_sem;
1088    }
1089
1090    if (job_sem == NULL) {
1091        srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
1092        return;
1093    }
1094
1095    /* initialize sleep control */
1096    pthread_mutex_init(&sleep_mutex, NULL);
1097    pthread_cond_init(&sleep_cond, NULL);
1098
1099    p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
1100
1101#ifdef _SC_NPROCESSORS_ONLN
1102    if (p_state->n_threads == 0) {
1103        /* get number of CPUs on the machine */
1104        p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
1105    }
1106#endif
1107
1108    if (p_state->n_threads < 4)
1109        p_state->n_threads = 4;
1110
1111    if (p_state->n_threads > MAX_THREADS)
1112        p_state->n_threads = MAX_THREADS;
1113
1114    srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
1115
1116    /* thread #0 is the background thread */
1117    pthread_create(&threads[0], NULL, background_thread, NULL);
1118
1119    /* the rest of threads are for job processing */
1120    char *ptr = (char *) 0x1;
1121    for (n = 1; n < p_state->n_threads; n++)
1122        pthread_create(&threads[n], NULL, job_thread, ptr++);
1123
1124    if (setjmp(on_break) == 0) {
1125        for (;;) {
1126            int cs = xs_socket_accept(rs);
1127
1128            if (cs != -1) {
1129                FILE *f = fdopen(cs, "r+");
1130                xs *job = xs_data_new(&f, sizeof(FILE *));
1131                job_post(job, 1);
1132            } else {
1133                srv_log(xs_fmt("error: xs_socket_accept failed: %s", strerror(errno)));
1134                break;
1135            }
1136        }
1137    }
1138
1139    p_state->srv_running = 0;
1140
1141    /* send as many exit jobs as working threads */
1142    for (n = 1; n < p_state->n_threads; n++)
1143        job_post(xs_stock(XSTYPE_FALSE), 0);
1144
1145    /* wait for all the threads to exit */
1146    for (n = 0; n < p_state->n_threads; n++)
1147        pthread_join(threads[n], NULL);
1148
1149    sem_close(job_sem);
1150    sem_unlink(sem_name);
1151
1152    srv_state_op(&shm_name, 2);
1153
1154    xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
1155
1156    srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
1157                p_state->use_fcgi ? " (FastCGI)" : "",
1158                full_address, uptime));
1159
1160    unlink(pidfile);
1161}