httpd.c 33 KB

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