1
0

httpd.c 32 KB

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