httpd.c 31 KB

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