httpd.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. static void *purge_thread(void *arg)
  186. /* spawned purge */
  187. {
  188. srv_log(xs_dup("purge start"));
  189. purge_all();
  190. srv_log(xs_dup("purge end"));
  191. return NULL;
  192. }
  193. static void *background_thread(void *arg)
  194. /* background thread (queue management and other things) */
  195. {
  196. time_t purge_time;
  197. /* first purge time */
  198. purge_time = time(NULL) + 10 * 60;
  199. srv_log(xs_fmt("background thread started"));
  200. while (srv_running) {
  201. time_t t;
  202. {
  203. xs *list = user_list();
  204. char *p, *uid;
  205. /* process queues for all users */
  206. p = list;
  207. while (xs_list_iter(&p, &uid)) {
  208. snac snac;
  209. if (user_open(&snac, uid)) {
  210. process_user_queue(&snac);
  211. user_free(&snac);
  212. }
  213. }
  214. }
  215. /* global queue */
  216. process_queue();
  217. /* time to purge? */
  218. if ((t = time(NULL)) > purge_time) {
  219. pthread_t pth;
  220. pthread_create(&pth, NULL, purge_thread, NULL);
  221. pthread_detach(pth);
  222. /* next purge time is tomorrow */
  223. purge_time = t + 24 * 60 * 60;
  224. }
  225. /* sleep 3 seconds */
  226. pthread_mutex_t dummy_mutex = PTHREAD_MUTEX_INITIALIZER;
  227. pthread_cond_t dummy_cond = PTHREAD_COND_INITIALIZER;
  228. struct timespec ts;
  229. clock_gettime(CLOCK_REALTIME, &ts);
  230. ts.tv_sec += 3;
  231. pthread_mutex_lock(&dummy_mutex);
  232. while (pthread_cond_timedwait(&dummy_cond, &dummy_mutex, &ts) == 0);
  233. pthread_mutex_unlock(&dummy_mutex);
  234. }
  235. srv_log(xs_fmt("background thread stopped"));
  236. return NULL;
  237. }
  238. static void *connection_thread(void *arg)
  239. /* connection thread */
  240. {
  241. httpd_connection((FILE *)arg);
  242. return NULL;
  243. }
  244. /** job control **/
  245. /* mutex to access the lists of jobs */
  246. static pthread_mutex_t job_mutex;
  247. /* semaphre to trigger job processing */
  248. static sem_t job_sem;
  249. /* fifo of jobs */
  250. xs_list *job_fifo = NULL;
  251. void job_post(const xs_val *job)
  252. /* posts a job for the threads to process it */
  253. {
  254. /* lock the mutex */
  255. pthread_mutex_lock(&job_mutex);
  256. /* add to the fifo */
  257. job_fifo = xs_list_append(job_fifo, job);
  258. /* unlock the mutex */
  259. pthread_mutex_unlock(&job_mutex);
  260. /* ask for someone to attend it */
  261. sem_post(&job_sem);
  262. }
  263. void job_wait(xs_val **job)
  264. /* waits for an available job */
  265. {
  266. *job = NULL;
  267. if (sem_wait(&job_sem) == 0) {
  268. /* lock the mutex */
  269. pthread_mutex_lock(&job_mutex);
  270. /* dequeue */
  271. job_fifo = xs_list_shift(job_fifo, job);
  272. /* unlock the mutex */
  273. pthread_mutex_unlock(&job_mutex);
  274. }
  275. }
  276. #ifndef MAX_THREADS
  277. #define MAX_THREADS 256
  278. #endif
  279. void httpd(void)
  280. /* starts the server */
  281. {
  282. char *address;
  283. int port;
  284. int rs;
  285. pthread_t threads[MAX_THREADS];
  286. int n_threads = 0;
  287. address = xs_dict_get(srv_config, "address");
  288. port = xs_number_get(xs_dict_get(srv_config, "port"));
  289. if ((rs = xs_socket_server(address, port)) == -1) {
  290. srv_log(xs_fmt("cannot bind socket to %s:%d", address, port));
  291. return;
  292. }
  293. srv_running = 1;
  294. signal(SIGPIPE, SIG_IGN);
  295. signal(SIGTERM, term_handler);
  296. signal(SIGINT, term_handler);
  297. srv_log(xs_fmt("httpd start %s:%d %s", address, port, USER_AGENT));
  298. /* initialize the job control engine */
  299. pthread_mutex_init(&job_mutex, NULL);
  300. sem_init(&job_sem, 0, 0);
  301. job_fifo = xs_list_new();
  302. #ifdef _SC_NPROCESSORS_ONLN
  303. /* get number of CPUs on the machine */
  304. n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  305. #endif
  306. if (n_threads < 4)
  307. n_threads = 4;
  308. if (n_threads > MAX_THREADS)
  309. n_threads = MAX_THREADS;
  310. srv_debug(0, xs_fmt("using %d threads", n_threads));
  311. /* thread #0 is the background thread */
  312. pthread_create(&threads[0], NULL, background_thread, NULL);
  313. if (setjmp(on_break) == 0) {
  314. for (;;) {
  315. FILE *f = xs_socket_accept(rs);
  316. pthread_t cth;
  317. pthread_create(&cth, NULL, connection_thread, f);
  318. pthread_detach(cth);
  319. }
  320. }
  321. srv_running = 0;
  322. /* wait for the background thread to end */
  323. pthread_join(threads[0], NULL);
  324. job_fifo = xs_free(job_fifo);
  325. srv_log(xs_fmt("httpd stop %s:%d", address, port));
  326. }