httpd.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. if (status == 0)
  149. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  150. if (status == 0)
  151. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype);
  152. if (status == 0)
  153. status = html_get_handler(req, q_path, &body, &b_size, &ctype);
  154. }
  155. else
  156. if (strcmp(method, "POST") == 0) {
  157. if (status == 0)
  158. status = oauth_post_handler(req, q_path,
  159. payload, p_size, &body, &b_size, &ctype);
  160. if (status == 0)
  161. status = mastoapi_post_handler(req, q_path,
  162. payload, p_size, &body, &b_size, &ctype);
  163. if (status == 0)
  164. status = activitypub_post_handler(req, q_path,
  165. payload, p_size, &body, &b_size, &ctype);
  166. if (status == 0)
  167. status = html_post_handler(req, q_path,
  168. payload, p_size, &body, &b_size, &ctype);
  169. }
  170. /* let's go */
  171. headers = xs_dict_new();
  172. /* unattended? it's an error */
  173. if (status == 0) {
  174. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  175. status = 404;
  176. }
  177. if (status == 404)
  178. body = xs_str_new("<h1>404 Not Found</h1>");
  179. if (status == 400 && body != NULL)
  180. body = xs_str_new("<h1>400 Bad Request</h1>");
  181. if (status == 303)
  182. headers = xs_dict_append(headers, "location", body);
  183. if (status == 401)
  184. headers = xs_dict_append(headers, "WWW-Authenticate", "Basic realm=\"IDENTIFY\"");
  185. if (ctype == NULL)
  186. ctype = "text/html; charset=utf-8";
  187. headers = xs_dict_append(headers, "content-type", ctype);
  188. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  189. if (b_size == 0 && body != NULL)
  190. b_size = strlen(body);
  191. /* if it was a HEAD, no body will be sent */
  192. if (strcmp(method, "HEAD") == 0)
  193. body = xs_free(body);
  194. xs_httpd_response(f, status, headers, body, b_size);
  195. fclose(f);
  196. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  197. xs_free(body);
  198. }
  199. static jmp_buf on_break;
  200. void term_handler(int s)
  201. {
  202. longjmp(on_break, 1);
  203. }
  204. /** job control **/
  205. /* mutex to access the lists of jobs */
  206. static pthread_mutex_t job_mutex;
  207. /* semaphre to trigger job processing */
  208. static sem_t job_sem;
  209. /* fifo of jobs */
  210. xs_list *job_fifo = NULL;
  211. int job_fifo_ready(void)
  212. /* returns true if the job fifo is ready */
  213. {
  214. return job_fifo != NULL;
  215. }
  216. void job_post(const xs_val *job, int urgent)
  217. /* posts a job for the threads to process it */
  218. {
  219. if (job != NULL) {
  220. /* lock the mutex */
  221. pthread_mutex_lock(&job_mutex);
  222. /* add to the fifo */
  223. if (job_fifo != NULL) {
  224. if (urgent)
  225. job_fifo = xs_list_insert(job_fifo, 0, job);
  226. else
  227. job_fifo = xs_list_append(job_fifo, job);
  228. }
  229. /* unlock the mutex */
  230. pthread_mutex_unlock(&job_mutex);
  231. }
  232. /* ask for someone to attend it */
  233. sem_post(&job_sem);
  234. }
  235. void job_wait(xs_val **job)
  236. /* waits for an available job */
  237. {
  238. *job = NULL;
  239. if (sem_wait(&job_sem) == 0) {
  240. /* lock the mutex */
  241. pthread_mutex_lock(&job_mutex);
  242. /* dequeue */
  243. if (job_fifo != NULL)
  244. job_fifo = xs_list_shift(job_fifo, job);
  245. /* unlock the mutex */
  246. pthread_mutex_unlock(&job_mutex);
  247. }
  248. }
  249. #ifndef MAX_THREADS
  250. #define MAX_THREADS 256
  251. #endif
  252. static void *job_thread(void *arg)
  253. /* job thread */
  254. {
  255. int pid = (char *) arg - (char *) 0x0;
  256. srv_debug(1, xs_fmt("job thread %d started", pid));
  257. for (;;) {
  258. xs *job = NULL;
  259. job_wait(&job);
  260. srv_debug(2, xs_fmt("job thread %d wake up", pid));
  261. if (job == NULL)
  262. break;
  263. if (xs_type(job) == XSTYPE_DATA) {
  264. /* it's a socket */
  265. FILE *f = NULL;
  266. xs_data_get(job, &f);
  267. if (f != NULL)
  268. httpd_connection(f);
  269. }
  270. else {
  271. /* it's a q_item */
  272. process_queue_item(job);
  273. }
  274. }
  275. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  276. return NULL;
  277. }
  278. /* background thread sleep control */
  279. static pthread_mutex_t sleep_mutex;
  280. static pthread_cond_t sleep_cond;
  281. static void *background_thread(void *arg)
  282. /* background thread (queue management and other things) */
  283. {
  284. time_t purge_time;
  285. /* first purge time */
  286. purge_time = time(NULL) + 10 * 60;
  287. srv_log(xs_fmt("background thread started"));
  288. while (srv_running) {
  289. time_t t;
  290. int cnt = 0;
  291. {
  292. xs *list = user_list();
  293. char *p, *uid;
  294. /* process queues for all users */
  295. p = list;
  296. while (xs_list_iter(&p, &uid)) {
  297. snac snac;
  298. if (user_open(&snac, uid)) {
  299. cnt += process_user_queue(&snac);
  300. user_free(&snac);
  301. }
  302. }
  303. }
  304. /* global queue */
  305. cnt += process_queue();
  306. /* time to purge? */
  307. if ((t = time(NULL)) > purge_time) {
  308. /* next purge time is tomorrow */
  309. purge_time = t + 24 * 60 * 60;
  310. xs *q_item = xs_dict_new();
  311. q_item = xs_dict_append(q_item, "type", "purge");
  312. job_post(q_item, 0);
  313. }
  314. if (cnt == 0) {
  315. /* sleep 3 seconds */
  316. #ifdef USE_POLL_FOR_SLEEP
  317. poll(NULL, 0, 3 * 1000);
  318. #else
  319. struct timespec ts;
  320. clock_gettime(CLOCK_REALTIME, &ts);
  321. ts.tv_sec += 3;
  322. pthread_mutex_lock(&sleep_mutex);
  323. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  324. pthread_mutex_unlock(&sleep_mutex);
  325. #endif
  326. }
  327. }
  328. srv_log(xs_fmt("background thread stopped"));
  329. return NULL;
  330. }
  331. void httpd(void)
  332. /* starts the server */
  333. {
  334. char *address;
  335. int port;
  336. int rs;
  337. pthread_t threads[MAX_THREADS] = {0};
  338. int n_threads = 0;
  339. int n;
  340. address = xs_dict_get(srv_config, "address");
  341. port = xs_number_get(xs_dict_get(srv_config, "port"));
  342. if ((rs = xs_socket_server(address, port)) == -1) {
  343. srv_log(xs_fmt("cannot bind socket to %s:%d", address, port));
  344. return;
  345. }
  346. srv_running = 1;
  347. signal(SIGPIPE, SIG_IGN);
  348. signal(SIGTERM, term_handler);
  349. signal(SIGINT, term_handler);
  350. srv_log(xs_fmt("httpd start %s:%d %s", address, port, USER_AGENT));
  351. /* show the number of usable file descriptors */
  352. struct rlimit r;
  353. getrlimit(RLIMIT_NOFILE, &r);
  354. srv_debug(0, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  355. (int) r.rlim_cur, (int) r.rlim_max));
  356. /* initialize the job control engine */
  357. pthread_mutex_init(&job_mutex, NULL);
  358. sem_init(&job_sem, 0, 0);
  359. job_fifo = xs_list_new();
  360. /* initialize sleep control */
  361. pthread_mutex_init(&sleep_mutex, NULL);
  362. pthread_cond_init(&sleep_cond, NULL);
  363. n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  364. #ifdef _SC_NPROCESSORS_ONLN
  365. if (n_threads == 0) {
  366. /* get number of CPUs on the machine */
  367. n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  368. }
  369. #endif
  370. if (n_threads < 4)
  371. n_threads = 4;
  372. if (n_threads > MAX_THREADS)
  373. n_threads = MAX_THREADS;
  374. srv_debug(0, xs_fmt("using %d threads", n_threads));
  375. /* thread #0 is the background thread */
  376. pthread_create(&threads[0], NULL, background_thread, NULL);
  377. /* the rest of threads are for job processing */
  378. char *ptr = (char *) 0x1;
  379. for (n = 1; n < n_threads; n++)
  380. pthread_create(&threads[n], NULL, job_thread, ptr++);
  381. if (setjmp(on_break) == 0) {
  382. for (;;) {
  383. FILE *f = xs_socket_accept(rs);
  384. if (f != NULL) {
  385. xs *job = xs_data_new(&f, sizeof(FILE *));
  386. job_post(job, 1);
  387. }
  388. else
  389. break;
  390. }
  391. }
  392. srv_running = 0;
  393. /* send as many empty jobs as working threads */
  394. for (n = 1; n < n_threads; n++)
  395. job_post(NULL, 0);
  396. /* wait for all the threads to exit */
  397. for (n = 0; n < n_threads; n++)
  398. pthread_join(threads[n], NULL);
  399. pthread_mutex_lock(&job_mutex);
  400. job_fifo = xs_free(job_fifo);
  401. pthread_mutex_unlock(&job_mutex);
  402. srv_log(xs_fmt("httpd stop %s:%d", address, port));
  403. }