httpd.c 14 KB

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