httpd.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2023 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_httpd.h"
  8. #include "xs_mime.h"
  9. #include "xs_time.h"
  10. #include "xs_openssl.h"
  11. #include "xs_fcgi.h"
  12. #include "xs_html.h"
  13. #include "snac.h"
  14. #include <setjmp.h>
  15. #include <pthread.h>
  16. #include <semaphore.h>
  17. #include <fcntl.h>
  18. #include <stdint.h>
  19. #include <sys/resource.h> // for getrlimit()
  20. #ifdef USE_POLL_FOR_SLEEP
  21. #include <poll.h>
  22. #endif
  23. int use_fcgi = 0;
  24. int srv_running = 0;
  25. time_t srv_start_time = 0;
  26. /* nodeinfo 2.0 template */
  27. const char *nodeinfo_2_0_template = ""
  28. "{\"version\":\"2.0\","
  29. "\"software\":{\"name\":\"snac\",\"version\":\"" VERSION "\"},"
  30. "\"protocols\":[\"activitypub\"],"
  31. "\"services\":{\"outbound\":[],\"inbound\":[]},"
  32. "\"usage\":{\"users\":{\"total\":%d,\"activeMonth\":%d,\"activeHalfyear\":%d},"
  33. "\"localPosts\":%d},"
  34. "\"openRegistrations\":false,\"metadata\":{}}";
  35. xs_str *nodeinfo_2_0(void)
  36. /* builds a nodeinfo json object */
  37. {
  38. int n_utotal = 0;
  39. int n_umonth = 0;
  40. int n_uhyear = 0;
  41. int n_posts = 0;
  42. xs *users = user_list();
  43. xs_list *p;
  44. char *v;
  45. p = users;
  46. while (xs_list_iter(&p, &v)) {
  47. /* build the full path name to the last usage log */
  48. xs *llfn = xs_fmt("%s/user/%s/lastlog.txt", srv_basedir, v);
  49. double llsecs = (double)time(NULL) - mtime(llfn);
  50. if (llsecs < 60 * 60 * 24 * 30 * 6) {
  51. n_uhyear++;
  52. if (llsecs < 60 * 60 * 24 * 30)
  53. n_umonth++;
  54. }
  55. n_utotal++;
  56. /* build the file to each user public.idx */
  57. xs *pidxfn = xs_fmt("%s/user/%s/private.idx", srv_basedir, v);
  58. n_posts += index_len(pidxfn);
  59. }
  60. return xs_fmt(nodeinfo_2_0_template, n_utotal, n_umonth, n_uhyear, n_posts);
  61. }
  62. static xs_str *greeting_html(void)
  63. /* processes and returns greeting.html */
  64. {
  65. /* try to open greeting.html */
  66. xs *fn = xs_fmt("%s/greeting.html", srv_basedir);
  67. FILE *f;
  68. xs_str *s = NULL;
  69. if ((f = fopen(fn, "r")) != NULL) {
  70. s = xs_readall(f);
  71. fclose(f);
  72. /* replace %host% */
  73. s = xs_replace_i(s, "%host%", xs_dict_get(srv_config, "host"));
  74. const char *adm_email = xs_dict_get(srv_config, "admin_email");
  75. if (xs_is_null(adm_email) || *adm_email == '\0')
  76. adm_email = "the administrator of this instance";
  77. /* replace %admin_email */
  78. s = xs_replace_i(s, "%admin_email%", adm_email);
  79. /* does it have a %userlist% mark? */
  80. if (xs_str_in(s, "%userlist%") != -1) {
  81. char *host = xs_dict_get(srv_config, "host");
  82. xs *list = user_list();
  83. xs_list *p = list;
  84. xs_str *uid;
  85. xs_html *ul = xs_html_tag("ul",
  86. xs_html_attr("class", "snac-user-list"));
  87. p = list;
  88. while (xs_list_iter(&p, &uid)) {
  89. snac user;
  90. if (user_open(&user, uid)) {
  91. xs_html_add(ul,
  92. xs_html_tag("li",
  93. xs_html_tag("a",
  94. xs_html_attr("href", user.actor),
  95. xs_html_text("@"),
  96. xs_html_text(uid),
  97. xs_html_text("@"),
  98. xs_html_text(host),
  99. xs_html_text(" ("),
  100. xs_html_text(xs_dict_get(user.config, "name")),
  101. xs_html_text(")"))));
  102. user_free(&user);
  103. }
  104. }
  105. xs *s1 = xs_html_render(ul);
  106. s = xs_replace_i(s, "%userlist%", s1);
  107. }
  108. }
  109. return s;
  110. }
  111. int server_get_handler(xs_dict *req, const char *q_path,
  112. char **body, int *b_size, char **ctype)
  113. /* basic server services */
  114. {
  115. int status = 0;
  116. (void)req;
  117. /* is it the server root? */
  118. if (*q_path == '\0') {
  119. xs_dict *q_vars = xs_dict_get(req, "q_vars");
  120. char *t = NULL;
  121. if (xs_type(q_vars) == XSTYPE_DICT && (t = xs_dict_get(q_vars, "t"))) {
  122. int skip = 0;
  123. int show = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  124. char *v;
  125. if ((v = xs_dict_get(q_vars, "skip")) != NULL)
  126. skip = atoi(v);
  127. if ((v = xs_dict_get(q_vars, "show")) != NULL)
  128. show = atoi(v);
  129. xs *tl = tag_search(t, skip, show + 1);
  130. int more = 0;
  131. if (xs_list_len(tl) >= show + 1) {
  132. /* drop the last one */
  133. tl = xs_list_del(tl, -1);
  134. more = 1;
  135. }
  136. *body = html_timeline(NULL, tl, 0, skip, show, more, t);
  137. }
  138. else
  139. if (xs_type(xs_dict_get(srv_config, "show_instance_timeline")) == XSTYPE_TRUE) {
  140. xs *tl = timeline_instance_list(0, 30);
  141. *body = html_timeline(NULL, tl, 0, 0, 0, 0, NULL);
  142. }
  143. else
  144. *body = greeting_html();
  145. if (*body)
  146. status = 200;
  147. }
  148. else
  149. if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
  150. status = 200;
  151. *body = xs_base64_dec(default_avatar_base64(), b_size);
  152. *ctype = "image/png";
  153. }
  154. else
  155. if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
  156. status = 200;
  157. *ctype = "application/json; charset=utf-8";
  158. *body = xs_fmt("{\"links\":["
  159. "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
  160. "\"href\":\"%s/nodeinfo_2_0\"}]}",
  161. srv_baseurl);
  162. }
  163. else
  164. if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
  165. status = 200;
  166. *ctype = "application/json; charset=utf-8";
  167. *body = nodeinfo_2_0();
  168. }
  169. else
  170. if (strcmp(q_path, "/robots.txt") == 0) {
  171. status = 200;
  172. *ctype = "text/plain";
  173. *body = xs_str_new("User-agent: *\n"
  174. "Disallow: /\n");
  175. }
  176. else
  177. if (strcmp(q_path, "/status.txt") == 0) {
  178. status = 200;
  179. *ctype = "text/plain";
  180. *body = xs_str_new("UP\n");
  181. xs *uptime = xs_str_time_diff(time(NULL) - srv_start_time);
  182. srv_log(xs_fmt("status: uptime: %s", uptime));
  183. }
  184. if (status != 0)
  185. srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
  186. return status;
  187. }
  188. void httpd_connection(FILE *f)
  189. /* the connection processor */
  190. {
  191. xs *req;
  192. char *method;
  193. int status = 0;
  194. xs_str *body = NULL;
  195. int b_size = 0;
  196. char *ctype = NULL;
  197. xs *headers = xs_dict_new();
  198. xs *q_path = NULL;
  199. xs *payload = NULL;
  200. xs *etag = NULL;
  201. int p_size = 0;
  202. char *p;
  203. int fcgi_id;
  204. if (use_fcgi)
  205. req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
  206. else
  207. req = xs_httpd_request(f, &payload, &p_size);
  208. if (req == NULL) {
  209. /* probably because a timeout */
  210. fclose(f);
  211. return;
  212. }
  213. if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
  214. /* missing needed headers; discard */
  215. fclose(f);
  216. return;
  217. }
  218. q_path = xs_dup(p);
  219. /* crop the q_path from leading / and the prefix */
  220. if (xs_endswith(q_path, "/"))
  221. q_path = xs_crop_i(q_path, 0, -1);
  222. p = xs_dict_get(srv_config, "prefix");
  223. if (xs_startswith(q_path, p))
  224. q_path = xs_crop_i(q_path, strlen(p), 0);
  225. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  226. /* cascade through */
  227. if (status == 0)
  228. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  229. if (status == 0)
  230. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  231. if (status == 0)
  232. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  233. #ifndef NO_MASTODON_API
  234. if (status == 0)
  235. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  236. if (status == 0)
  237. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype);
  238. #endif /* NO_MASTODON_API */
  239. if (status == 0)
  240. status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag);
  241. }
  242. else
  243. if (strcmp(method, "POST") == 0) {
  244. #ifndef NO_MASTODON_API
  245. if (status == 0)
  246. status = oauth_post_handler(req, q_path,
  247. payload, p_size, &body, &b_size, &ctype);
  248. if (status == 0)
  249. status = mastoapi_post_handler(req, q_path,
  250. payload, p_size, &body, &b_size, &ctype);
  251. #endif
  252. if (status == 0)
  253. status = activitypub_post_handler(req, q_path,
  254. payload, p_size, &body, &b_size, &ctype);
  255. if (status == 0)
  256. status = html_post_handler(req, q_path,
  257. payload, p_size, &body, &b_size, &ctype);
  258. }
  259. else
  260. if (strcmp(method, "PUT") == 0) {
  261. #ifndef NO_MASTODON_API
  262. if (status == 0)
  263. status = mastoapi_put_handler(req, q_path,
  264. payload, p_size, &body, &b_size, &ctype);
  265. #endif
  266. }
  267. else
  268. if (strcmp(method, "OPTIONS") == 0) {
  269. status = 200;
  270. }
  271. /* unattended? it's an error */
  272. if (status == 0) {
  273. srv_archive_error("unattended_method", "unattended method", req, payload);
  274. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  275. status = 404;
  276. }
  277. if (status == 403)
  278. body = xs_str_new("<h1>403 Forbidden</h1>");
  279. if (status == 404)
  280. body = xs_str_new("<h1>404 Not Found</h1>");
  281. if (status == 400 && body != NULL)
  282. body = xs_str_new("<h1>400 Bad Request</h1>");
  283. if (status == 303)
  284. headers = xs_dict_append(headers, "location", body);
  285. if (status == 401) {
  286. xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
  287. body, xs_dict_get(srv_config, "host"));
  288. headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
  289. }
  290. if (ctype == NULL)
  291. ctype = "text/html; charset=utf-8";
  292. headers = xs_dict_append(headers, "content-type", ctype);
  293. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  294. if (!xs_is_null(etag))
  295. headers = xs_dict_append(headers, "etag", etag);
  296. /* if there are any additional headers, add them */
  297. xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
  298. if (xs_type(more_headers) == XSTYPE_DICT) {
  299. char *k, *v;
  300. while (xs_dict_iter(&more_headers, &k, &v))
  301. headers = xs_dict_set(headers, k, v);
  302. }
  303. if (b_size == 0 && body != NULL)
  304. b_size = strlen(body);
  305. /* if it was a HEAD, no body will be sent */
  306. if (strcmp(method, "HEAD") == 0)
  307. body = xs_free(body);
  308. headers = xs_dict_append(headers, "access-control-allow-origin", "*");
  309. headers = xs_dict_append(headers, "access-control-allow-headers", "*");
  310. if (use_fcgi)
  311. xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
  312. else
  313. xs_httpd_response(f, status, headers, body, b_size);
  314. fclose(f);
  315. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  316. /* JSON validation check */
  317. if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
  318. xs *j = xs_json_loads(body);
  319. if (j == NULL) {
  320. srv_log(xs_fmt("bad JSON"));
  321. srv_archive_error("bad_json", "bad JSON", req, body);
  322. }
  323. }
  324. xs_free(body);
  325. }
  326. static jmp_buf on_break;
  327. void term_handler(int s)
  328. {
  329. (void)s;
  330. longjmp(on_break, 1);
  331. }
  332. /** job control **/
  333. /* mutex to access the lists of jobs */
  334. static pthread_mutex_t job_mutex;
  335. /* semaphre to trigger job processing */
  336. static sem_t *job_sem;
  337. /* fifo of jobs */
  338. xs_list *job_fifo = NULL;
  339. int job_fifo_ready(void)
  340. /* returns true if the job fifo is ready */
  341. {
  342. return job_fifo != NULL;
  343. }
  344. void job_post(const xs_val *job, int urgent)
  345. /* posts a job for the threads to process it */
  346. {
  347. if (job != NULL) {
  348. /* lock the mutex */
  349. pthread_mutex_lock(&job_mutex);
  350. /* add to the fifo */
  351. if (job_fifo != NULL) {
  352. if (urgent)
  353. job_fifo = xs_list_insert(job_fifo, 0, job);
  354. else
  355. job_fifo = xs_list_append(job_fifo, job);
  356. }
  357. /* unlock the mutex */
  358. pthread_mutex_unlock(&job_mutex);
  359. }
  360. /* ask for someone to attend it */
  361. sem_post(job_sem);
  362. }
  363. void job_wait(xs_val **job)
  364. /* waits for an available job */
  365. {
  366. *job = NULL;
  367. if (sem_wait(job_sem) == 0) {
  368. /* lock the mutex */
  369. pthread_mutex_lock(&job_mutex);
  370. /* dequeue */
  371. if (job_fifo != NULL)
  372. job_fifo = xs_list_shift(job_fifo, job);
  373. /* unlock the mutex */
  374. pthread_mutex_unlock(&job_mutex);
  375. }
  376. }
  377. #ifndef MAX_THREADS
  378. #define MAX_THREADS 256
  379. #endif
  380. static void *job_thread(void *arg)
  381. /* job thread */
  382. {
  383. int pid = (int)(uintptr_t)arg;
  384. srv_debug(1, xs_fmt("job thread %d started", pid));
  385. for (;;) {
  386. xs *job = NULL;
  387. job_wait(&job);
  388. srv_debug(2, xs_fmt("job thread %d wake up", pid));
  389. if (job == NULL)
  390. break;
  391. if (xs_type(job) == XSTYPE_DATA) {
  392. /* it's a socket */
  393. FILE *f = NULL;
  394. xs_data_get(&f, job);
  395. if (f != NULL)
  396. httpd_connection(f);
  397. }
  398. else {
  399. /* it's a q_item */
  400. process_queue_item(job);
  401. }
  402. }
  403. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  404. return NULL;
  405. }
  406. /* background thread sleep control */
  407. static pthread_mutex_t sleep_mutex;
  408. static pthread_cond_t sleep_cond;
  409. static void *background_thread(void *arg)
  410. /* background thread (queue management and other things) */
  411. {
  412. time_t purge_time;
  413. (void)arg;
  414. /* first purge time */
  415. purge_time = time(NULL) + 10 * 60;
  416. srv_log(xs_fmt("background thread started"));
  417. while (srv_running) {
  418. time_t t;
  419. int cnt = 0;
  420. {
  421. xs *list = user_list();
  422. char *p, *uid;
  423. /* process queues for all users */
  424. p = list;
  425. while (xs_list_iter(&p, &uid)) {
  426. snac snac;
  427. if (user_open(&snac, uid)) {
  428. cnt += process_user_queue(&snac);
  429. user_free(&snac);
  430. }
  431. }
  432. }
  433. /* global queue */
  434. cnt += process_queue();
  435. /* time to purge? */
  436. if ((t = time(NULL)) > purge_time) {
  437. /* next purge time is tomorrow */
  438. purge_time = t + 24 * 60 * 60;
  439. xs *q_item = xs_dict_new();
  440. q_item = xs_dict_append(q_item, "type", "purge");
  441. job_post(q_item, 0);
  442. }
  443. if (cnt == 0) {
  444. /* sleep 3 seconds */
  445. #ifdef USE_POLL_FOR_SLEEP
  446. poll(NULL, 0, 3 * 1000);
  447. #else
  448. struct timespec ts;
  449. clock_gettime(CLOCK_REALTIME, &ts);
  450. ts.tv_sec += 3;
  451. pthread_mutex_lock(&sleep_mutex);
  452. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  453. pthread_mutex_unlock(&sleep_mutex);
  454. #endif
  455. }
  456. }
  457. srv_log(xs_fmt("background thread stopped"));
  458. return NULL;
  459. }
  460. void httpd(void)
  461. /* starts the server */
  462. {
  463. const char *address;
  464. const char *port;
  465. int rs;
  466. pthread_t threads[MAX_THREADS] = {0};
  467. int n_threads = 0;
  468. int n;
  469. char sem_name[24];
  470. sem_t anon_job_sem;
  471. srv_start_time = time(NULL);
  472. use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
  473. address = xs_dict_get(srv_config, "address");
  474. port = xs_number_str(xs_dict_get(srv_config, "port"));
  475. if ((rs = xs_socket_server(address, port)) == -1) {
  476. srv_log(xs_fmt("cannot bind socket to %s:%s", address, port));
  477. return;
  478. }
  479. srv_running = 1;
  480. signal(SIGPIPE, SIG_IGN);
  481. signal(SIGTERM, term_handler);
  482. signal(SIGINT, term_handler);
  483. srv_log(xs_fmt("httpd%s start %s:%s %s", use_fcgi ? " (FastCGI)" : "",
  484. address, port, USER_AGENT));
  485. /* show the number of usable file descriptors */
  486. struct rlimit r;
  487. getrlimit(RLIMIT_NOFILE, &r);
  488. srv_debug(0, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  489. (int) r.rlim_cur, (int) r.rlim_max));
  490. /* initialize the job control engine */
  491. pthread_mutex_init(&job_mutex, NULL);
  492. snprintf(sem_name, sizeof(sem_name), "/job_%d", getpid());
  493. job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
  494. if (job_sem == NULL) {
  495. /* error opening a named semaphore; try with an anonymous one */
  496. if (sem_init(&anon_job_sem, 0, 0) != -1)
  497. job_sem = &anon_job_sem;
  498. }
  499. if (job_sem == NULL) {
  500. srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
  501. return;
  502. }
  503. job_fifo = xs_list_new();
  504. /* initialize sleep control */
  505. pthread_mutex_init(&sleep_mutex, NULL);
  506. pthread_cond_init(&sleep_cond, NULL);
  507. n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  508. #ifdef _SC_NPROCESSORS_ONLN
  509. if (n_threads == 0) {
  510. /* get number of CPUs on the machine */
  511. n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  512. }
  513. #endif
  514. if (n_threads < 4)
  515. n_threads = 4;
  516. if (n_threads > MAX_THREADS)
  517. n_threads = MAX_THREADS;
  518. srv_debug(0, xs_fmt("using %d threads", n_threads));
  519. /* thread #0 is the background thread */
  520. pthread_create(&threads[0], NULL, background_thread, NULL);
  521. /* the rest of threads are for job processing */
  522. char *ptr = (char *) 0x1;
  523. for (n = 1; n < n_threads; n++)
  524. pthread_create(&threads[n], NULL, job_thread, ptr++);
  525. if (setjmp(on_break) == 0) {
  526. for (;;) {
  527. FILE *f = xs_socket_accept(rs);
  528. if (f != NULL) {
  529. xs *job = xs_data_new(&f, sizeof(FILE *));
  530. job_post(job, 1);
  531. }
  532. else
  533. break;
  534. }
  535. }
  536. srv_running = 0;
  537. /* send as many empty jobs as working threads */
  538. for (n = 1; n < n_threads; n++)
  539. job_post(NULL, 0);
  540. /* wait for all the threads to exit */
  541. for (n = 0; n < n_threads; n++)
  542. pthread_join(threads[n], NULL);
  543. pthread_mutex_lock(&job_mutex);
  544. job_fifo = xs_free(job_fifo);
  545. pthread_mutex_unlock(&job_mutex);
  546. sem_close(job_sem);
  547. sem_unlink(sem_name);
  548. xs *uptime = xs_str_time_diff(time(NULL) - srv_start_time);
  549. srv_log(xs_fmt("httpd%s stop %s:%s (run time: %s)", use_fcgi ? " (FastCGI)" : "",
  550. address, port, uptime));
  551. }