httpd.c 17 KB

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