httpd.c 31 KB

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