httpd.c 32 KB

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