httpd.c 18 KB

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