httpd.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. if (job_fifo != NULL)
  200. job_fifo = xs_list_append(job_fifo, job);
  201. /* unlock the mutex */
  202. pthread_mutex_unlock(&job_mutex);
  203. }
  204. /* ask for someone to attend it */
  205. sem_post(&job_sem);
  206. }
  207. void job_wait(xs_val **job)
  208. /* waits for an available job */
  209. {
  210. *job = NULL;
  211. if (sem_wait(&job_sem) == 0) {
  212. /* lock the mutex */
  213. pthread_mutex_lock(&job_mutex);
  214. /* dequeue */
  215. if (job_fifo != NULL)
  216. job_fifo = xs_list_shift(job_fifo, job);
  217. /* unlock the mutex */
  218. pthread_mutex_unlock(&job_mutex);
  219. }
  220. }
  221. #ifndef MAX_THREADS
  222. #define MAX_THREADS 256
  223. #endif
  224. static void *job_thread(void *arg)
  225. /* job thread */
  226. {
  227. int pid = (char *) arg - (char *) 0x0;
  228. srv_debug(1, xs_fmt("job thread %d started", pid));
  229. for (;;) {
  230. xs *job = NULL;
  231. job_wait(&job);
  232. srv_debug(1, xs_fmt("job thread %d wake up", pid));
  233. if (job == NULL)
  234. break;
  235. if (xs_type(job) == XSTYPE_DATA) {
  236. /* it's a socket */
  237. FILE *f = NULL;
  238. xs_data_get(job, &f);
  239. if (f != NULL)
  240. httpd_connection(f);
  241. }
  242. else {
  243. /* it's a q_item */
  244. process_queue_item(job);
  245. }
  246. }
  247. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  248. return NULL;
  249. }
  250. static void *background_thread(void *arg)
  251. /* background thread (queue management and other things) */
  252. {
  253. time_t purge_time;
  254. /* first purge time */
  255. purge_time = time(NULL) + 10 * 60;
  256. srv_log(xs_fmt("background thread started"));
  257. while (srv_running) {
  258. time_t t;
  259. {
  260. xs *list = user_list();
  261. char *p, *uid;
  262. /* process queues for all users */
  263. p = list;
  264. while (xs_list_iter(&p, &uid)) {
  265. snac snac;
  266. if (user_open(&snac, uid)) {
  267. process_user_queue(&snac);
  268. user_free(&snac);
  269. }
  270. }
  271. }
  272. /* global queue */
  273. process_queue();
  274. /* time to purge? */
  275. if ((t = time(NULL)) > purge_time) {
  276. /* next purge time is tomorrow */
  277. purge_time = t + 24 * 60 * 60;
  278. xs *q_item = xs_dict_new();
  279. q_item = xs_dict_append(q_item, "type", "purge");
  280. job_post(q_item);
  281. }
  282. /* sleep 3 seconds */
  283. pthread_mutex_t dummy_mutex = PTHREAD_MUTEX_INITIALIZER;
  284. pthread_cond_t dummy_cond = PTHREAD_COND_INITIALIZER;
  285. struct timespec ts;
  286. clock_gettime(CLOCK_REALTIME, &ts);
  287. ts.tv_sec += 3;
  288. pthread_mutex_lock(&dummy_mutex);
  289. while (pthread_cond_timedwait(&dummy_cond, &dummy_mutex, &ts) == 0);
  290. pthread_mutex_unlock(&dummy_mutex);
  291. }
  292. srv_log(xs_fmt("background thread stopped"));
  293. return NULL;
  294. }
  295. void httpd(void)
  296. /* starts the server */
  297. {
  298. char *address;
  299. int port;
  300. int rs;
  301. pthread_t threads[MAX_THREADS] = {0};
  302. int n_threads = 0;
  303. int n;
  304. address = xs_dict_get(srv_config, "address");
  305. port = xs_number_get(xs_dict_get(srv_config, "port"));
  306. if ((rs = xs_socket_server(address, port)) == -1) {
  307. srv_log(xs_fmt("cannot bind socket to %s:%d", address, port));
  308. return;
  309. }
  310. srv_running = 1;
  311. signal(SIGPIPE, SIG_IGN);
  312. signal(SIGTERM, term_handler);
  313. signal(SIGINT, term_handler);
  314. srv_log(xs_fmt("httpd start %s:%d %s", address, port, USER_AGENT));
  315. /* initialize the job control engine */
  316. pthread_mutex_init(&job_mutex, NULL);
  317. sem_init(&job_sem, 0, 0);
  318. job_fifo = xs_list_new();
  319. n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  320. #ifdef _SC_NPROCESSORS_ONLN
  321. if (n_threads == 0) {
  322. /* get number of CPUs on the machine */
  323. n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  324. }
  325. #endif
  326. if (n_threads < 4)
  327. n_threads = 4;
  328. if (n_threads > MAX_THREADS)
  329. n_threads = MAX_THREADS;
  330. srv_debug(0, xs_fmt("using %d threads", n_threads));
  331. /* thread #0 is the background thread */
  332. pthread_create(&threads[0], NULL, background_thread, NULL);
  333. /* the rest of threads are for job processing */
  334. char *ptr = (char *) 0x1;
  335. for (n = 1; n < n_threads; n++)
  336. pthread_create(&threads[n], NULL, job_thread, ptr++);
  337. if (setjmp(on_break) == 0) {
  338. for (;;) {
  339. FILE *f = xs_socket_accept(rs);
  340. xs *job = xs_data_new(&f, sizeof(FILE *));
  341. job_post(job);
  342. }
  343. }
  344. srv_running = 0;
  345. /* send as many empty jobs as working threads */
  346. for (n = 1; n < n_threads; n++)
  347. job_post(NULL);
  348. /* wait for all the threads to exit */
  349. for (n = 0; n < n_threads; n++)
  350. pthread_join(threads[n], NULL);
  351. pthread_mutex_lock(&job_mutex);
  352. job_fifo = xs_free(job_fifo);
  353. pthread_mutex_unlock(&job_mutex);
  354. srv_log(xs_fmt("httpd stop %s:%d", address, port));
  355. }