httpd.c 12 KB

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