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