httpd.c 14 KB

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