httpd.c 15 KB

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