httpd.c 14 KB

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