httpd.c 11 KB

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