1
0

httpd.c 32 KB

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