httpd.c 31 KB

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