1
0

httpd.c 13 KB

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