httpd.c 33 KB

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