httpd.c 12 KB

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