httpd.c 15 KB

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