httpd.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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 * const 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 * const 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 * const 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 && xs_is_string(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\",\"href\":\"%s/nodeinfo_2_0\"},"
  232. "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.1\",\"href\":\"%s/nodeinfo_2_1\"}"
  233. "]}",
  234. srv_baseurl, srv_baseurl);
  235. }
  236. else
  237. if (strcmp(q_path, "/.well-known/host-meta") == 0) {
  238. status = HTTP_STATUS_OK;
  239. *ctype = "application/xrd+xml";
  240. *body = xs_fmt("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  241. "<XRD>"
  242. "<Link rel=\"lrdd\" type=\"application/xrd+xml\" template=\"https://%s/.well-known/webfinger?resource={uri}\"/>"
  243. "</XRD>", xs_dict_get(srv_config, "host"));
  244. }
  245. else
  246. if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
  247. status = HTTP_STATUS_OK;
  248. *ctype = "application/json; charset=utf-8";
  249. *body = nodeinfo_2_0();
  250. }
  251. else
  252. if (strcmp(q_path, "/nodeinfo_2_1") == 0) {
  253. xs *s = nodeinfo_2_0();
  254. xs *j = xs_json_loads(s);
  255. j = xs_dict_set(j, "version", "2.1");
  256. j = xs_dict_set_path(j, "software.repository", WHAT_IS_SNAC_URL);
  257. j = xs_dict_set_path(j, "software.homepage", SNAC_DOC_URL);
  258. status = HTTP_STATUS_OK;
  259. *ctype = "application/json; charset=utf-8";
  260. *body = xs_json_dumps(j, 4);
  261. }
  262. else
  263. if (strcmp(q_path, "/robots.txt") == 0) {
  264. status = HTTP_STATUS_OK;
  265. *ctype = "text/plain";
  266. *body = xs_str_new("User-agent: *\n"
  267. "Disallow: /\n");
  268. }
  269. else
  270. if (strcmp(q_path, "/style.css") == 0) {
  271. FILE *f;
  272. xs *css_fn = xs_fmt("%s/style.css", srv_basedir);
  273. if ((f = fopen(css_fn, "r")) != NULL) {
  274. *body = xs_readall(f);
  275. fclose(f);
  276. status = HTTP_STATUS_OK;
  277. *ctype = "text/css";
  278. }
  279. }
  280. else
  281. if (strcmp(q_path, "/share") == 0) {
  282. const xs_dict *q_vars = xs_dict_get(req, "q_vars");
  283. const char *url = xs_dict_get(q_vars, "url");
  284. const char *text = xs_dict_get(q_vars, "text");
  285. xs *s = NULL;
  286. if (xs_type(text) == XSTYPE_STRING) {
  287. if (xs_type(url) == XSTYPE_STRING)
  288. s = xs_fmt("%s:\n\n%s\n", text, url);
  289. else
  290. s = xs_fmt("%s\n", text);
  291. }
  292. else
  293. if (xs_type(url) == XSTYPE_STRING)
  294. s = xs_fmt("%s\n", url);
  295. else
  296. s = xs_str_new(NULL);
  297. status = HTTP_STATUS_OK;
  298. *ctype = "text/html; charset=utf-8";
  299. *body = xs_fmt(share_page,
  300. xs_dict_get(srv_config, "host"),
  301. srv_baseurl,
  302. xs_dict_get(srv_config, "host"),
  303. srv_baseurl,
  304. s,
  305. USER_AGENT
  306. );
  307. }
  308. else
  309. if (strcmp(q_path, "/authorize_interaction") == 0) {
  310. const xs_dict *q_vars = xs_dict_get(req, "q_vars");
  311. const char *uri = xs_dict_get(q_vars, "uri");
  312. if (xs_is_string(uri)) {
  313. status = HTTP_STATUS_OK;
  314. *ctype = "text/html; charset=utf-8";
  315. *body = xs_fmt(authorize_interaction_page,
  316. xs_dict_get(srv_config, "host"),
  317. srv_baseurl,
  318. xs_dict_get(srv_config, "host"),
  319. srv_baseurl,
  320. uri,
  321. uri,
  322. USER_AGENT
  323. );
  324. }
  325. }
  326. if (status != 0)
  327. srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
  328. return status;
  329. }
  330. int server_post_handler(const xs_dict *req, const char *q_path,
  331. char *payload, int p_size,
  332. char **body, int *b_size, char **ctype)
  333. {
  334. int status = 0;
  335. (void)payload;
  336. (void)p_size;
  337. (void)body;
  338. (void)b_size;
  339. (void)ctype;
  340. if (strcmp(q_path, "/webmention-hook") == 0) {
  341. status = HTTP_STATUS_BAD_REQUEST;
  342. const xs_dict *p_vars = xs_dict_get(req, "p_vars");
  343. if (!xs_is_dict(p_vars))
  344. return status;
  345. const char *source = xs_dict_get(p_vars, "source");
  346. const char *target = xs_dict_get(p_vars, "target");
  347. if (!xs_is_string(source) || !xs_is_string(target)) {
  348. srv_debug(1, xs_fmt("webmention-hook bad source or target"));
  349. return status;
  350. }
  351. if (!xs_startswith(target, srv_baseurl)) {
  352. srv_debug(1, xs_fmt("webmention-hook unknown target %s", target));
  353. return status;
  354. }
  355. /* get the user */
  356. xs *s1 = xs_replace(target, srv_baseurl, "");
  357. xs *l1 = xs_split(s1, "/");
  358. const char *uid = xs_list_get(l1, 1);
  359. snac user;
  360. if (!xs_is_string(uid) || !user_open(&user, uid)) {
  361. srv_debug(1, xs_fmt("webmention-hook cannot find user for %s", target));
  362. return status;
  363. }
  364. int r = xs_webmention_hook(source, target, USER_AGENT);
  365. if (r > 0) {
  366. notify_add(&user, "Webmention", NULL, source, target, xs_stock(XSTYPE_DICT));
  367. timeline_touch(&user);
  368. }
  369. srv_log(xs_fmt("webmention-hook source=%s target=%s %d", source, target, r));
  370. user_free(&user);
  371. status = HTTP_STATUS_OK;
  372. }
  373. return status;
  374. }
  375. void httpd_connection(FILE *f)
  376. /* the connection processor */
  377. {
  378. xs *req;
  379. const char *method;
  380. int status = 0;
  381. xs_str *body = NULL;
  382. int b_size = 0;
  383. char *ctype = NULL;
  384. xs *headers = xs_dict_new();
  385. xs *q_path = NULL;
  386. xs *payload = NULL;
  387. xs *etag = NULL;
  388. xs *last_modified = NULL;
  389. xs *link = NULL;
  390. int p_size = 0;
  391. const char *p;
  392. int fcgi_id;
  393. if (p_state->use_fcgi)
  394. req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
  395. else
  396. req = xs_httpd_request(f, &payload, &p_size);
  397. if (req == NULL) {
  398. /* probably because a timeout */
  399. fclose(f);
  400. return;
  401. }
  402. if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
  403. /* missing needed headers; discard */
  404. fclose(f);
  405. return;
  406. }
  407. q_path = xs_dup(p);
  408. /* crop the q_path from leading / and the prefix */
  409. if (xs_endswith(q_path, "/"))
  410. q_path = xs_crop_i(q_path, 0, -1);
  411. p = xs_dict_get(srv_config, "prefix");
  412. if (xs_startswith(q_path, p))
  413. q_path = xs_crop_i(q_path, strlen(p), 0);
  414. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  415. /* cascade through */
  416. if (status == 0)
  417. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  418. if (status == 0)
  419. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  420. if (status == 0)
  421. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  422. #ifndef NO_MASTODON_API
  423. if (status == 0)
  424. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  425. if (status == 0)
  426. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype, &link);
  427. #endif /* NO_MASTODON_API */
  428. if (status == 0)
  429. status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag, &last_modified);
  430. }
  431. else
  432. if (strcmp(method, "POST") == 0) {
  433. if (status == 0)
  434. status = server_post_handler(req, q_path,
  435. payload, p_size, &body, &b_size, &ctype);
  436. #ifndef NO_MASTODON_API
  437. if (status == 0)
  438. status = oauth_post_handler(req, q_path,
  439. payload, p_size, &body, &b_size, &ctype);
  440. if (status == 0)
  441. status = mastoapi_post_handler(req, q_path,
  442. payload, p_size, &body, &b_size, &ctype);
  443. #endif
  444. if (status == 0)
  445. status = activitypub_post_handler(req, q_path,
  446. payload, p_size, &body, &b_size, &ctype);
  447. if (status == 0)
  448. status = html_post_handler(req, q_path,
  449. payload, p_size, &body, &b_size, &ctype);
  450. }
  451. else
  452. if (strcmp(method, "PUT") == 0) {
  453. #ifndef NO_MASTODON_API
  454. if (status == 0)
  455. status = mastoapi_put_handler(req, q_path,
  456. payload, p_size, &body, &b_size, &ctype);
  457. #endif
  458. }
  459. else
  460. if (strcmp(method, "PATCH") == 0) {
  461. #ifndef NO_MASTODON_API
  462. if (status == 0)
  463. status = mastoapi_patch_handler(req, q_path,
  464. payload, p_size, &body, &b_size, &ctype);
  465. #endif
  466. }
  467. else
  468. if (strcmp(method, "OPTIONS") == 0) {
  469. const char *methods = "OPTIONS, GET, HEAD, POST, PUT, DELETE";
  470. headers = xs_dict_append(headers, "allow", methods);
  471. headers = xs_dict_append(headers, "access-control-allow-methods", methods);
  472. status = HTTP_STATUS_OK;
  473. }
  474. else
  475. if (strcmp(method, "DELETE") == 0) {
  476. #ifndef NO_MASTODON_API
  477. if (status == 0)
  478. status = mastoapi_delete_handler(req, q_path,
  479. payload, p_size, &body, &b_size, &ctype);
  480. #endif
  481. }
  482. /* unattended? it's an error */
  483. if (status == 0) {
  484. srv_archive_error("unattended_method", "unattended method", req, payload);
  485. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  486. status = HTTP_STATUS_NOT_FOUND;
  487. }
  488. if (status == HTTP_STATUS_FORBIDDEN)
  489. body = xs_str_new("<h1>403 Forbidden (" USER_AGENT ")</h1>");
  490. if (status == HTTP_STATUS_NOT_FOUND)
  491. body = xs_str_new("<h1>404 Not Found (" USER_AGENT ")</h1>");
  492. if (status == HTTP_STATUS_BAD_REQUEST && body != NULL)
  493. body = xs_str_new("<h1>400 Bad Request (" USER_AGENT ")</h1>");
  494. if (status == HTTP_STATUS_SEE_OTHER)
  495. headers = xs_dict_append(headers, "location", body);
  496. if (status == HTTP_STATUS_UNAUTHORIZED && body) {
  497. xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
  498. body, xs_dict_get(srv_config, "host"));
  499. headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
  500. headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
  501. }
  502. if (ctype == NULL)
  503. ctype = "text/html; charset=utf-8";
  504. headers = xs_dict_append(headers, "content-type", ctype);
  505. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  506. if (!xs_is_null(etag))
  507. headers = xs_dict_append(headers, "etag", etag);
  508. if (!xs_is_null(last_modified))
  509. headers = xs_dict_append(headers, "last-modified", last_modified);
  510. if (!xs_is_null(link))
  511. headers = xs_dict_append(headers, "Link", link);
  512. /* if there are any additional headers, add them */
  513. const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
  514. if (xs_type(more_headers) == XSTYPE_DICT) {
  515. const char *k, *v;
  516. int c = 0;
  517. while (xs_dict_next(more_headers, &k, &v, &c))
  518. headers = xs_dict_set(headers, k, v);
  519. }
  520. if (b_size == 0 && body != NULL)
  521. b_size = strlen(body);
  522. /* if it was a HEAD, no body will be sent */
  523. if (strcmp(method, "HEAD") == 0)
  524. body = xs_free(body);
  525. headers = xs_dict_append(headers, "access-control-allow-origin", "*");
  526. headers = xs_dict_append(headers, "access-control-allow-headers", "*");
  527. headers = xs_dict_append(headers, "access-control-expose-headers", "Link");
  528. /* disable any form of fucking JavaScript */
  529. headers = xs_dict_append(headers, "Content-Security-Policy", "script-src ;");
  530. if (p_state->use_fcgi)
  531. xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
  532. else
  533. xs_httpd_response(f, status, http_status_text(status), headers, body, b_size);
  534. fclose(f);
  535. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  536. /* JSON validation check */
  537. if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
  538. xs *j = xs_json_loads(body);
  539. if (j == NULL) {
  540. srv_log(xs_fmt("bad JSON"));
  541. srv_archive_error("bad_json", "bad JSON", req, body);
  542. }
  543. }
  544. xs_free(body);
  545. }
  546. void job_post(const xs_val *job, int urgent)
  547. /* posts a job for the threads to process it */
  548. {
  549. if (job != NULL) {
  550. /* lock the mutex */
  551. pthread_mutex_lock(&job_mutex);
  552. job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
  553. *i = (job_fifo_item){ NULL, xs_dup(job) };
  554. if (job_fifo_first == NULL)
  555. job_fifo_first = job_fifo_last = i;
  556. else
  557. if (urgent) {
  558. /* prepend */
  559. i->next = job_fifo_first;
  560. job_fifo_first = i;
  561. }
  562. else {
  563. /* append */
  564. job_fifo_last->next = i;
  565. job_fifo_last = i;
  566. }
  567. p_state->job_fifo_size++;
  568. if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
  569. p_state->peak_job_fifo_size = p_state->job_fifo_size;
  570. /* unlock the mutex */
  571. pthread_mutex_unlock(&job_mutex);
  572. /* ask for someone to attend it */
  573. sem_post(job_sem);
  574. }
  575. }
  576. void job_wait(xs_val **job)
  577. /* waits for an available job */
  578. {
  579. *job = NULL;
  580. if (sem_wait(job_sem) == 0) {
  581. /* lock the mutex */
  582. pthread_mutex_lock(&job_mutex);
  583. /* dequeue */
  584. job_fifo_item *i = job_fifo_first;
  585. if (i != NULL) {
  586. job_fifo_first = i->next;
  587. if (job_fifo_first == NULL)
  588. job_fifo_last = NULL;
  589. *job = i->job;
  590. xs_free(i);
  591. p_state->job_fifo_size--;
  592. }
  593. /* unlock the mutex */
  594. pthread_mutex_unlock(&job_mutex);
  595. }
  596. }
  597. static void *job_thread(void *arg)
  598. /* job thread */
  599. {
  600. int pid = (int)(uintptr_t)arg;
  601. srv_debug(1, xs_fmt("job thread %d started", pid));
  602. for (;;) {
  603. xs *job = NULL;
  604. p_state->th_state[pid] = THST_WAIT;
  605. job_wait(&job);
  606. if (job == NULL) /* corrupted message? */
  607. continue;
  608. if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
  609. break;
  610. else
  611. if (xs_type(job) == XSTYPE_DATA) {
  612. /* it's a socket */
  613. FILE *f = NULL;
  614. p_state->th_state[pid] = THST_IN;
  615. xs_data_get(&f, job);
  616. if (f != NULL)
  617. httpd_connection(f);
  618. }
  619. else {
  620. /* it's a q_item */
  621. p_state->th_state[pid] = THST_QUEUE;
  622. process_queue_item(job);
  623. }
  624. }
  625. p_state->th_state[pid] = THST_STOP;
  626. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  627. return NULL;
  628. }
  629. /* background thread sleep control */
  630. static pthread_mutex_t sleep_mutex;
  631. static pthread_cond_t sleep_cond;
  632. static void *background_thread(void *arg)
  633. /* background thread (queue management and other things) */
  634. {
  635. time_t t, purge_time, rss_time;
  636. (void)arg;
  637. t = time(NULL);
  638. /* first purge time */
  639. purge_time = t + 10 * 60;
  640. /* first RSS polling time */
  641. rss_time = t + 15 * 60;
  642. srv_log(xs_fmt("background thread started"));
  643. enqueue_fsck();
  644. while (p_state->srv_running) {
  645. int cnt = 0;
  646. p_state->th_state[0] = THST_QUEUE;
  647. {
  648. xs *list = user_list();
  649. const char *uid;
  650. /* process queues for all users */
  651. xs_list_foreach(list, uid) {
  652. snac user;
  653. if (user_open(&user, uid)) {
  654. cnt += process_user_queue(&user);
  655. user_free(&user);
  656. }
  657. }
  658. }
  659. /* global queue */
  660. cnt += process_queue();
  661. t = time(NULL);
  662. /* time to purge? */
  663. if (t > purge_time) {
  664. /* next purge time is tomorrow */
  665. purge_time = t + 24 * 60 * 60;
  666. xs *q_item = xs_dict_new();
  667. q_item = xs_dict_append(q_item, "type", "purge");
  668. job_post(q_item, 0);
  669. }
  670. /* time to poll the RSS? */
  671. if (t > rss_time) {
  672. /* next RSS poll time */
  673. int hours = xs_number_get(xs_dict_get_def(srv_config, "rss_hashtag_poll_hours", "4"));
  674. /* don't hammer servers too much */
  675. if (hours < 1)
  676. hours = 1;
  677. rss_time = t + 60 * 60 * hours;
  678. xs *q_item = xs_dict_new();
  679. q_item = xs_dict_append(q_item, "type", "rss_hashtag_poll");
  680. job_post(q_item, 0);
  681. }
  682. if (cnt == 0) {
  683. /* sleep 3 seconds */
  684. p_state->th_state[0] = THST_WAIT;
  685. #ifdef USE_POLL_FOR_SLEEP
  686. poll(NULL, 0, 3 * 1000);
  687. #else
  688. struct timespec ts;
  689. clock_gettime(CLOCK_REALTIME, &ts);
  690. ts.tv_sec += 3;
  691. pthread_mutex_lock(&sleep_mutex);
  692. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  693. pthread_mutex_unlock(&sleep_mutex);
  694. #endif
  695. }
  696. }
  697. p_state->th_state[0] = THST_STOP;
  698. srv_log(xs_fmt("background thread stopped"));
  699. return NULL;
  700. }
  701. void term_handler(int s)
  702. {
  703. (void)s;
  704. longjmp(on_break, 1);
  705. }
  706. srv_state *srv_state_op(xs_str **fname, int op)
  707. /* opens or deletes the shared memory object */
  708. {
  709. int fd;
  710. srv_state *ss = NULL;
  711. if (*fname == NULL)
  712. *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
  713. switch (op) {
  714. case 0: /* open for writing */
  715. #ifdef WITHOUT_SHM
  716. errno = ENOTSUP;
  717. #else
  718. if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
  719. ftruncate(fd, sizeof(*ss));
  720. if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
  721. MAP_SHARED, fd, 0)) == MAP_FAILED)
  722. ss = NULL;
  723. close(fd);
  724. }
  725. #endif
  726. if (ss == NULL) {
  727. /* shared memory error: just create a plain structure */
  728. srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
  729. ss = malloc(sizeof(*ss));
  730. }
  731. /* init structure */
  732. *ss = (srv_state){0};
  733. ss->s_size = sizeof(*ss);
  734. break;
  735. case 1: /* open for reading */
  736. #ifdef WITHOUT_SHM
  737. errno = ENOTSUP;
  738. #else
  739. if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
  740. if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
  741. ss = NULL;
  742. close(fd);
  743. }
  744. #endif
  745. if (ss == NULL) {
  746. /* shared memory error */
  747. srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
  748. }
  749. else
  750. if (ss->s_size != sizeof(*ss)) {
  751. srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
  752. ss->s_size, sizeof(*ss)));
  753. munmap(ss, sizeof(*ss));
  754. ss = NULL;
  755. }
  756. break;
  757. case 2: /* unlink */
  758. #ifndef WITHOUT_SHM
  759. if (*fname)
  760. shm_unlink(*fname);
  761. #endif
  762. break;
  763. }
  764. return ss;
  765. }
  766. void httpd(void)
  767. /* starts the server */
  768. {
  769. const char *address = NULL;
  770. const char *port = NULL;
  771. xs *full_address = NULL;
  772. int rs;
  773. pthread_t threads[MAX_THREADS] = {0};
  774. int n;
  775. xs *sem_name = NULL;
  776. xs *shm_name = NULL;
  777. sem_t anon_job_sem;
  778. xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
  779. int pidfd;
  780. {
  781. /* do some pidfile locking acrobatics */
  782. if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
  783. srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
  784. return;
  785. }
  786. if (lockf(pidfd, F_TLOCK, 1) == -1) {
  787. srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
  788. close(pidfd);
  789. return;
  790. }
  791. ftruncate(pidfd, 0);
  792. xs *s = xs_fmt("%d\n", (int)getpid());
  793. write(pidfd, s, strlen(s));
  794. }
  795. address = xs_dict_get(srv_config, "address");
  796. if (*address == '/') {
  797. rs = xs_unix_socket_server(address, NULL);
  798. full_address = xs_fmt("unix:%s", address);
  799. }
  800. else {
  801. port = xs_number_str(xs_dict_get(srv_config, "port"));
  802. full_address = xs_fmt("%s:%s", address, port);
  803. rs = xs_socket_server(address, port);
  804. }
  805. if (rs == -1) {
  806. srv_log(xs_fmt("cannot bind socket to %s", full_address));
  807. return;
  808. }
  809. /* setup the server stat structure */
  810. p_state = srv_state_op(&shm_name, 0);
  811. p_state->srv_start_time = time(NULL);
  812. p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
  813. p_state->srv_running = 1;
  814. signal(SIGPIPE, SIG_IGN);
  815. signal(SIGTERM, term_handler);
  816. signal(SIGINT, term_handler);
  817. srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
  818. full_address, USER_AGENT));
  819. /* show the number of usable file descriptors */
  820. struct rlimit r;
  821. getrlimit(RLIMIT_NOFILE, &r);
  822. srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  823. (int) r.rlim_cur, (int) r.rlim_max));
  824. /* initialize the job control engine */
  825. pthread_mutex_init(&job_mutex, NULL);
  826. sem_name = xs_fmt("/job_%d", getpid());
  827. job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
  828. if (job_sem == NULL) {
  829. /* error opening a named semaphore; try with an anonymous one */
  830. if (sem_init(&anon_job_sem, 0, 0) != -1)
  831. job_sem = &anon_job_sem;
  832. }
  833. if (job_sem == NULL) {
  834. srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
  835. return;
  836. }
  837. /* initialize sleep control */
  838. pthread_mutex_init(&sleep_mutex, NULL);
  839. pthread_cond_init(&sleep_cond, NULL);
  840. p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  841. #ifdef _SC_NPROCESSORS_ONLN
  842. if (p_state->n_threads == 0) {
  843. /* get number of CPUs on the machine */
  844. p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  845. }
  846. #endif
  847. if (p_state->n_threads < 4)
  848. p_state->n_threads = 4;
  849. if (p_state->n_threads > MAX_THREADS)
  850. p_state->n_threads = MAX_THREADS;
  851. srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
  852. /* thread #0 is the background thread */
  853. pthread_create(&threads[0], NULL, background_thread, NULL);
  854. /* the rest of threads are for job processing */
  855. char *ptr = (char *) 0x1;
  856. for (n = 1; n < p_state->n_threads; n++)
  857. pthread_create(&threads[n], NULL, job_thread, ptr++);
  858. if (setjmp(on_break) == 0) {
  859. for (;;) {
  860. int cs = xs_socket_accept(rs);
  861. if (cs != -1) {
  862. FILE *f = fdopen(cs, "r+");
  863. xs *job = xs_data_new(&f, sizeof(FILE *));
  864. job_post(job, 1);
  865. }
  866. else
  867. break;
  868. }
  869. }
  870. p_state->srv_running = 0;
  871. /* send as many exit jobs as working threads */
  872. for (n = 1; n < p_state->n_threads; n++)
  873. job_post(xs_stock(XSTYPE_FALSE), 0);
  874. /* wait for all the threads to exit */
  875. for (n = 0; n < p_state->n_threads; n++)
  876. pthread_join(threads[n], NULL);
  877. sem_close(job_sem);
  878. sem_unlink(sem_name);
  879. srv_state_op(&shm_name, 2);
  880. xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
  881. srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
  882. p_state->use_fcgi ? " (FastCGI)" : "",
  883. full_address, uptime));
  884. unlink(pidfile);
  885. }