httpd.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. /* add users endpoint redirection mimic Mastodon behaviour */
  416. const char *users_endpoint = "/users";
  417. if (xs_startswith(q_path, users_endpoint)) {
  418. q_path = xs_crop_i(q_path, strlen(users_endpoint), 0);
  419. status = HTTP_STATUS_FOUND;
  420. }
  421. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  422. /* cascade through */
  423. if (status == 0)
  424. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  425. if (status == 0)
  426. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  427. if (status == 0)
  428. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  429. #ifndef NO_MASTODON_API
  430. if (status == 0)
  431. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  432. if (status == 0)
  433. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype, &link);
  434. #endif /* NO_MASTODON_API */
  435. if (status == 0)
  436. status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag, &last_modified);
  437. }
  438. else
  439. if (strcmp(method, "POST") == 0) {
  440. if (status == 0)
  441. status = server_post_handler(req, q_path,
  442. payload, p_size, &body, &b_size, &ctype);
  443. #ifndef NO_MASTODON_API
  444. if (status == 0)
  445. status = oauth_post_handler(req, q_path,
  446. payload, p_size, &body, &b_size, &ctype);
  447. if (status == 0)
  448. status = mastoapi_post_handler(req, q_path,
  449. payload, p_size, &body, &b_size, &ctype);
  450. #endif
  451. if (status == 0)
  452. status = activitypub_post_handler(req, q_path,
  453. payload, p_size, &body, &b_size, &ctype);
  454. if (status == 0)
  455. status = html_post_handler(req, q_path,
  456. payload, p_size, &body, &b_size, &ctype);
  457. }
  458. else
  459. if (strcmp(method, "PUT") == 0) {
  460. #ifndef NO_MASTODON_API
  461. if (status == 0)
  462. status = mastoapi_put_handler(req, q_path,
  463. payload, p_size, &body, &b_size, &ctype);
  464. #endif
  465. }
  466. else
  467. if (strcmp(method, "PATCH") == 0) {
  468. #ifndef NO_MASTODON_API
  469. if (status == 0)
  470. status = mastoapi_patch_handler(req, q_path,
  471. payload, p_size, &body, &b_size, &ctype);
  472. #endif
  473. }
  474. else
  475. if (strcmp(method, "OPTIONS") == 0) {
  476. const char *methods = "OPTIONS, GET, HEAD, POST, PUT, DELETE";
  477. headers = xs_dict_append(headers, "allow", methods);
  478. headers = xs_dict_append(headers, "access-control-allow-methods", methods);
  479. status = HTTP_STATUS_OK;
  480. }
  481. else
  482. if (strcmp(method, "DELETE") == 0) {
  483. #ifndef NO_MASTODON_API
  484. if (status == 0)
  485. status = mastoapi_delete_handler(req, q_path,
  486. payload, p_size, &body, &b_size, &ctype);
  487. #endif
  488. }
  489. /* unattended? it's an error */
  490. if (status == 0) {
  491. srv_archive_error("unattended_method", "unattended method", req, payload);
  492. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  493. status = HTTP_STATUS_NOT_FOUND;
  494. }
  495. if (status == HTTP_STATUS_FORBIDDEN)
  496. body = xs_str_new("<h1>403 Forbidden (" USER_AGENT ")</h1>");
  497. if (status == HTTP_STATUS_NOT_FOUND)
  498. body = xs_str_new("<h1>404 Not Found (" USER_AGENT ")</h1>");
  499. if (status == HTTP_STATUS_GONE)
  500. body = xs_str_new("<h1>410 Gone (" USER_AGENT ")</h1>");
  501. if (status == HTTP_STATUS_BAD_REQUEST && body != NULL)
  502. body = xs_str_new("<h1>400 Bad Request (" USER_AGENT ")</h1>");
  503. if (status == HTTP_STATUS_SEE_OTHER)
  504. headers = xs_dict_append(headers, "location", body);
  505. if (status == HTTP_STATUS_FOUND)
  506. headers = xs_dict_append(headers, "location", xs_fmt("%s%s", p, q_path));
  507. if (status == HTTP_STATUS_UNAUTHORIZED && body) {
  508. xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
  509. body, xs_dict_get(srv_config, "host"));
  510. headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
  511. headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
  512. }
  513. if (ctype == NULL)
  514. ctype = "text/html; charset=utf-8";
  515. headers = xs_dict_append(headers, "content-type", ctype);
  516. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  517. if (!xs_is_null(etag))
  518. headers = xs_dict_append(headers, "etag", etag);
  519. if (!xs_is_null(last_modified))
  520. headers = xs_dict_append(headers, "last-modified", last_modified);
  521. if (!xs_is_null(link))
  522. headers = xs_dict_append(headers, "Link", link);
  523. /* if there are any additional headers, add them */
  524. const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
  525. if (xs_type(more_headers) == XSTYPE_DICT) {
  526. const char *k, *v;
  527. int c = 0;
  528. while (xs_dict_next(more_headers, &k, &v, &c))
  529. headers = xs_dict_set(headers, k, v);
  530. }
  531. if (b_size == 0 && body != NULL)
  532. b_size = strlen(body);
  533. /* if it was a HEAD, no body will be sent */
  534. if (strcmp(method, "HEAD") == 0)
  535. body = xs_free(body);
  536. headers = xs_dict_append(headers, "access-control-allow-origin", "*");
  537. headers = xs_dict_append(headers, "access-control-allow-headers", "*");
  538. headers = xs_dict_append(headers, "access-control-expose-headers", "Link");
  539. /* disable any form of fucking JavaScript */
  540. headers = xs_dict_append(headers, "Content-Security-Policy", "script-src ;");
  541. if (p_state->use_fcgi)
  542. xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
  543. else
  544. xs_httpd_response(f, status, xs_http_status_text(status), headers, body, b_size);
  545. fclose(f);
  546. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  547. /* JSON validation check */
  548. if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
  549. xs *j = xs_json_loads(body);
  550. if (j == NULL) {
  551. srv_log(xs_fmt("bad JSON"));
  552. srv_archive_error("bad_json", "bad JSON", req, body);
  553. }
  554. }
  555. xs_free(body);
  556. }
  557. void job_post(const xs_val *job, int urgent)
  558. /* posts a job for the threads to process it */
  559. {
  560. if (job != NULL) {
  561. /* lock the mutex */
  562. pthread_mutex_lock(&job_mutex);
  563. job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
  564. *i = (job_fifo_item){ NULL, xs_dup(job) };
  565. if (job_fifo_first == NULL)
  566. job_fifo_first = job_fifo_last = i;
  567. else
  568. if (urgent) {
  569. /* prepend */
  570. i->next = job_fifo_first;
  571. job_fifo_first = i;
  572. }
  573. else {
  574. /* append */
  575. job_fifo_last->next = i;
  576. job_fifo_last = i;
  577. }
  578. p_state->job_fifo_size++;
  579. if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
  580. p_state->peak_job_fifo_size = p_state->job_fifo_size;
  581. /* unlock the mutex */
  582. pthread_mutex_unlock(&job_mutex);
  583. /* ask for someone to attend it */
  584. sem_post(job_sem);
  585. }
  586. }
  587. void job_wait(xs_val **job)
  588. /* waits for an available job */
  589. {
  590. *job = NULL;
  591. if (sem_wait(job_sem) == 0) {
  592. /* lock the mutex */
  593. pthread_mutex_lock(&job_mutex);
  594. /* dequeue */
  595. job_fifo_item *i = job_fifo_first;
  596. if (i != NULL) {
  597. job_fifo_first = i->next;
  598. if (job_fifo_first == NULL)
  599. job_fifo_last = NULL;
  600. *job = i->job;
  601. xs_free(i);
  602. p_state->job_fifo_size--;
  603. }
  604. /* unlock the mutex */
  605. pthread_mutex_unlock(&job_mutex);
  606. }
  607. }
  608. static void *job_thread(void *arg)
  609. /* job thread */
  610. {
  611. int pid = (int)(uintptr_t)arg;
  612. srv_debug(1, xs_fmt("job thread %d started", pid));
  613. for (;;) {
  614. xs *job = NULL;
  615. p_state->th_state[pid] = THST_WAIT;
  616. job_wait(&job);
  617. if (job == NULL) /* corrupted message? */
  618. continue;
  619. if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
  620. break;
  621. else
  622. if (xs_type(job) == XSTYPE_DATA) {
  623. /* it's a socket */
  624. FILE *f = NULL;
  625. p_state->th_state[pid] = THST_IN;
  626. xs_data_get(&f, job);
  627. if (f != NULL)
  628. httpd_connection(f);
  629. }
  630. else {
  631. /* it's a q_item */
  632. p_state->th_state[pid] = THST_QUEUE;
  633. process_queue_item(job);
  634. }
  635. }
  636. p_state->th_state[pid] = THST_STOP;
  637. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  638. return NULL;
  639. }
  640. /* background thread sleep control */
  641. static pthread_mutex_t sleep_mutex;
  642. static pthread_cond_t sleep_cond;
  643. static void *background_thread(void *arg)
  644. /* background thread (queue management and other things) */
  645. {
  646. time_t t, purge_time, rss_time;
  647. (void)arg;
  648. t = time(NULL);
  649. /* first purge time */
  650. purge_time = t + 10 * 60;
  651. /* first RSS polling time */
  652. rss_time = t + 15 * 60;
  653. srv_log(xs_fmt("background thread started"));
  654. enqueue_fsck();
  655. while (p_state->srv_running) {
  656. int cnt = 0;
  657. p_state->th_state[0] = THST_QUEUE;
  658. {
  659. xs *list = user_list();
  660. const char *uid;
  661. /* process queues for all users */
  662. xs_list_foreach(list, uid) {
  663. snac user;
  664. if (user_open(&user, uid)) {
  665. cnt += process_user_queue(&user);
  666. user_free(&user);
  667. }
  668. }
  669. }
  670. /* global queue */
  671. cnt += process_queue();
  672. t = time(NULL);
  673. /* time to purge? */
  674. if (t > purge_time) {
  675. /* next purge time is tomorrow */
  676. purge_time = t + 24 * 60 * 60;
  677. xs *q_item = xs_dict_new();
  678. q_item = xs_dict_append(q_item, "type", "purge");
  679. job_post(q_item, 0);
  680. }
  681. /* time to poll the RSS? */
  682. if (t > rss_time) {
  683. /* next RSS poll time */
  684. int hours = xs_number_get(xs_dict_get_def(srv_config, "rss_hashtag_poll_hours", "4"));
  685. /* don't hammer servers too much */
  686. if (hours < 1)
  687. hours = 1;
  688. rss_time = t + 60 * 60 * hours;
  689. xs *q_item = xs_dict_new();
  690. q_item = xs_dict_append(q_item, "type", "rss_hashtag_poll");
  691. job_post(q_item, 0);
  692. }
  693. if (cnt == 0) {
  694. /* sleep 3 seconds */
  695. p_state->th_state[0] = THST_WAIT;
  696. #ifdef USE_POLL_FOR_SLEEP
  697. poll(NULL, 0, 3 * 1000);
  698. #else
  699. struct timespec ts;
  700. clock_gettime(CLOCK_REALTIME, &ts);
  701. ts.tv_sec += 3;
  702. pthread_mutex_lock(&sleep_mutex);
  703. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  704. pthread_mutex_unlock(&sleep_mutex);
  705. #endif
  706. }
  707. }
  708. p_state->th_state[0] = THST_STOP;
  709. srv_log(xs_fmt("background thread stopped"));
  710. return NULL;
  711. }
  712. void term_handler(int s)
  713. {
  714. (void)s;
  715. longjmp(on_break, 1);
  716. }
  717. srv_state *srv_state_op(xs_str **fname, int op)
  718. /* opens or deletes the shared memory object */
  719. {
  720. int fd;
  721. srv_state *ss = NULL;
  722. if (*fname == NULL)
  723. *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
  724. switch (op) {
  725. case 0: /* open for writing */
  726. #ifdef WITHOUT_SHM
  727. errno = ENOTSUP;
  728. #else
  729. if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
  730. ftruncate(fd, sizeof(*ss));
  731. if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
  732. MAP_SHARED, fd, 0)) == MAP_FAILED)
  733. ss = NULL;
  734. close(fd);
  735. }
  736. #endif
  737. if (ss == NULL) {
  738. /* shared memory error: just create a plain structure */
  739. srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
  740. ss = malloc(sizeof(*ss));
  741. }
  742. /* init structure */
  743. *ss = (srv_state){0};
  744. ss->s_size = sizeof(*ss);
  745. break;
  746. case 1: /* open for reading */
  747. #ifdef WITHOUT_SHM
  748. errno = ENOTSUP;
  749. #else
  750. if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
  751. if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
  752. ss = NULL;
  753. close(fd);
  754. }
  755. #endif
  756. if (ss == NULL) {
  757. /* shared memory error */
  758. srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
  759. }
  760. else
  761. if (ss->s_size != sizeof(*ss)) {
  762. srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
  763. ss->s_size, sizeof(*ss)));
  764. munmap(ss, sizeof(*ss));
  765. ss = NULL;
  766. }
  767. break;
  768. case 2: /* unlink */
  769. #ifndef WITHOUT_SHM
  770. if (*fname)
  771. shm_unlink(*fname);
  772. #endif
  773. break;
  774. }
  775. return ss;
  776. }
  777. void httpd(void)
  778. /* starts the server */
  779. {
  780. const char *address = NULL;
  781. const char *port = NULL;
  782. xs *full_address = NULL;
  783. int rs;
  784. pthread_t threads[MAX_THREADS] = {0};
  785. int n;
  786. xs *sem_name = NULL;
  787. xs *shm_name = NULL;
  788. sem_t anon_job_sem;
  789. xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
  790. int pidfd;
  791. {
  792. /* do some pidfile locking acrobatics */
  793. if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
  794. srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
  795. return;
  796. }
  797. if (lockf(pidfd, F_TLOCK, 1) == -1) {
  798. srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
  799. close(pidfd);
  800. return;
  801. }
  802. ftruncate(pidfd, 0);
  803. xs *s = xs_fmt("%d\n", (int)getpid());
  804. write(pidfd, s, strlen(s));
  805. }
  806. address = xs_dict_get(srv_config, "address");
  807. if (*address == '/') {
  808. rs = xs_unix_socket_server(address, NULL);
  809. full_address = xs_fmt("unix:%s", address);
  810. }
  811. else {
  812. port = xs_number_str(xs_dict_get(srv_config, "port"));
  813. full_address = xs_fmt("%s:%s", address, port);
  814. rs = xs_socket_server(address, port);
  815. }
  816. if (rs == -1) {
  817. srv_log(xs_fmt("cannot bind socket to %s", full_address));
  818. return;
  819. }
  820. /* setup the server stat structure */
  821. p_state = srv_state_op(&shm_name, 0);
  822. p_state->srv_start_time = time(NULL);
  823. p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
  824. p_state->srv_running = 1;
  825. signal(SIGPIPE, SIG_IGN);
  826. signal(SIGTERM, term_handler);
  827. signal(SIGINT, term_handler);
  828. srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
  829. full_address, USER_AGENT));
  830. /* show the number of usable file descriptors */
  831. struct rlimit r;
  832. getrlimit(RLIMIT_NOFILE, &r);
  833. srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  834. (int) r.rlim_cur, (int) r.rlim_max));
  835. /* initialize the job control engine */
  836. pthread_mutex_init(&job_mutex, NULL);
  837. sem_name = xs_fmt("/job_%d", getpid());
  838. job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
  839. if (job_sem == NULL) {
  840. /* error opening a named semaphore; try with an anonymous one */
  841. if (sem_init(&anon_job_sem, 0, 0) != -1)
  842. job_sem = &anon_job_sem;
  843. }
  844. if (job_sem == NULL) {
  845. srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
  846. return;
  847. }
  848. /* initialize sleep control */
  849. pthread_mutex_init(&sleep_mutex, NULL);
  850. pthread_cond_init(&sleep_cond, NULL);
  851. p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  852. #ifdef _SC_NPROCESSORS_ONLN
  853. if (p_state->n_threads == 0) {
  854. /* get number of CPUs on the machine */
  855. p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  856. }
  857. #endif
  858. if (p_state->n_threads < 4)
  859. p_state->n_threads = 4;
  860. if (p_state->n_threads > MAX_THREADS)
  861. p_state->n_threads = MAX_THREADS;
  862. srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
  863. /* thread #0 is the background thread */
  864. pthread_create(&threads[0], NULL, background_thread, NULL);
  865. /* the rest of threads are for job processing */
  866. char *ptr = (char *) 0x1;
  867. for (n = 1; n < p_state->n_threads; n++)
  868. pthread_create(&threads[n], NULL, job_thread, ptr++);
  869. if (setjmp(on_break) == 0) {
  870. for (;;) {
  871. int cs = xs_socket_accept(rs);
  872. if (cs != -1) {
  873. FILE *f = fdopen(cs, "r+");
  874. xs *job = xs_data_new(&f, sizeof(FILE *));
  875. job_post(job, 1);
  876. } else {
  877. srv_log(xs_fmt("error: xs_socket_accept failed: %s", strerror(errno)));
  878. break;
  879. }
  880. }
  881. }
  882. p_state->srv_running = 0;
  883. /* send as many exit jobs as working threads */
  884. for (n = 1; n < p_state->n_threads; n++)
  885. job_post(xs_stock(XSTYPE_FALSE), 0);
  886. /* wait for all the threads to exit */
  887. for (n = 0; n < p_state->n_threads; n++)
  888. pthread_join(threads[n], NULL);
  889. sem_close(job_sem);
  890. sem_unlink(sem_name);
  891. srv_state_op(&shm_name, 2);
  892. xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
  893. srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
  894. p_state->use_fcgi ? " (FastCGI)" : "",
  895. full_address, uptime));
  896. unlink(pidfile);
  897. }