1
0

httpd.c 32 KB

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