httpd.c 32 KB

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