httpd.c 32 KB

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