httpd.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 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. /* susie.png */
  14. const char *susie =
  15. "iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQAAAAC"
  16. "CEkxzAAAAUUlEQVQoz43R0QkAMQwCUDdw/y3dwE"
  17. "vsvzlL4X1IoQkAisKmwfAFT3RgJHbQezpSRoXEq"
  18. "eqCL9BJBf7h3QbOCCxV5EVWMEMwG7K1/WODtlvx"
  19. "AYTtEsDU9F34AAAAAElFTkSuQmCC";
  20. /* nodeinfo 2.0 template */
  21. const char *nodeinfo_2_0_template = ""
  22. "{\"version\":\"2.0\","
  23. "\"software\":{\"name\":\"snac\",\"version\":\"" VERSION "\"},"
  24. "\"protocols\":[\"activitypub\"],"
  25. "\"services\":{\"outbound\":[],\"inbound\":[]},"
  26. "\"usage\":{\"users\":{\"total\":%d,\"activeMonth\":%d,\"activeHalfyear\":%d},"
  27. "\"localPosts\":%d},"
  28. "\"openRegistrations\":false,\"metadata\":{}}";
  29. d_char *nodeinfo_2_0(void)
  30. /* builds a nodeinfo json object */
  31. {
  32. xs *users = user_list();
  33. int n_users = xs_list_len(users);
  34. int n_posts = 0; /* to be implemented someday */
  35. return xs_fmt(nodeinfo_2_0_template, n_users, n_users, n_users, n_posts);
  36. }
  37. int server_get_handler(d_char *req, char *q_path,
  38. char **body, int *b_size, char **ctype)
  39. /* basic server services */
  40. {
  41. int status = 0;
  42. /* is it the server root? */
  43. if (*q_path == '\0') {
  44. /* try to open greeting.html */
  45. xs *fn = xs_fmt("%s/greeting.html", srv_basedir);
  46. FILE *f;
  47. if ((f = fopen(fn, "r")) != NULL) {
  48. d_char *s = xs_readall(f);
  49. fclose(f);
  50. status = 200;
  51. /* replace %host% */
  52. s = xs_replace_i(s, "%host%", xs_dict_get(srv_config, "host"));
  53. /* does it have a %userlist% mark? */
  54. if (xs_str_in(s, "%userlist%") != -1) {
  55. char *host = xs_dict_get(srv_config, "host");
  56. xs *list = user_list();
  57. char *p, *uid;
  58. xs *ul = xs_str_new("<ul class=\"snac-user-list\">\n");
  59. p = list;
  60. while (xs_list_iter(&p, &uid)) {
  61. snac snac;
  62. if (user_open(&snac, uid)) {
  63. xs *u = xs_fmt(
  64. "<li><a href=\"%s\">@%s@%s (%s)</a></li>\n",
  65. snac.actor, uid, host,
  66. xs_dict_get(snac.config, "name"));
  67. ul = xs_str_cat(ul, u);
  68. user_free(&snac);
  69. }
  70. }
  71. ul = xs_str_cat(ul, "</ul>\n");
  72. s = xs_replace_i(s, "%userlist%", ul);
  73. }
  74. *body = s;
  75. }
  76. }
  77. else
  78. if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
  79. status = 200;
  80. *body = xs_base64_dec(susie, b_size);
  81. *ctype = "image/png";
  82. }
  83. else
  84. if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
  85. status = 200;
  86. *ctype = "application/json; charset=utf-8";
  87. *body = xs_fmt("{\"links\":["
  88. "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
  89. "\"href\":\"%s/nodeinfo_2_0\"}]}",
  90. srv_baseurl);
  91. }
  92. else
  93. if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
  94. status = 200;
  95. *ctype = "application/json; charset=utf-8";
  96. *body = nodeinfo_2_0();
  97. }
  98. if (status != 0)
  99. srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
  100. return status;
  101. }
  102. void httpd_connection(FILE *f)
  103. /* the connection processor */
  104. {
  105. xs *req;
  106. char *method;
  107. int status = 0;
  108. d_char *body = NULL;
  109. int b_size = 0;
  110. char *ctype = NULL;
  111. xs *headers = NULL;
  112. xs *q_path = NULL;
  113. xs *payload = NULL;
  114. int p_size = 0;
  115. char *p;
  116. req = xs_httpd_request(f, &payload, &p_size);
  117. if (req == NULL) {
  118. /* probably because a timeout */
  119. fclose(f);
  120. return;
  121. }
  122. method = xs_dict_get(req, "method");
  123. q_path = xs_dup(xs_dict_get(req, "path"));
  124. /* crop the q_path from leading / and the prefix */
  125. if (xs_endswith(q_path, "/"))
  126. q_path = xs_crop(q_path, 0, -1);
  127. p = xs_dict_get(srv_config, "prefix");
  128. if (xs_startswith(q_path, p))
  129. q_path = xs_crop(q_path, strlen(p), 0);
  130. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  131. /* cascade through */
  132. if (status == 0)
  133. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  134. if (status == 0)
  135. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  136. if (status == 0)
  137. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  138. if (status == 0)
  139. status = html_get_handler(req, q_path, &body, &b_size, &ctype);
  140. }
  141. else
  142. if (strcmp(method, "POST") == 0) {
  143. if (status == 0)
  144. status = activitypub_post_handler(req, q_path,
  145. payload, p_size, &body, &b_size, &ctype);
  146. if (status == 0)
  147. status = html_post_handler(req, q_path,
  148. payload, p_size, &body, &b_size, &ctype);
  149. }
  150. /* let's go */
  151. headers = xs_dict_new();
  152. /* unattended? it's an error */
  153. if (status == 0) {
  154. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  155. status = 404;
  156. }
  157. if (status == 404)
  158. body = xs_str_new("<h1>404 Not Found</h1>");
  159. if (status == 400)
  160. body = xs_str_new("<h1>400 Bad Request</h1>");
  161. if (status == 303)
  162. headers = xs_dict_append(headers, "location", body);
  163. if (status == 401)
  164. headers = xs_dict_append(headers, "WWW-Authenticate", "Basic realm=\"IDENTIFY\"");
  165. if (ctype == NULL)
  166. ctype = "text/html; charset=utf-8";
  167. headers = xs_dict_append(headers, "content-type", ctype);
  168. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  169. if (b_size == 0 && body != NULL)
  170. b_size = strlen(body);
  171. /* if it was a HEAD, no body will be sent */
  172. if (strcmp(method, "HEAD") == 0)
  173. body = xs_free(body);
  174. xs_httpd_response(f, status, headers, body, b_size);
  175. fclose(f);
  176. srv_archive("RECV", req, payload, p_size, status, headers, body, b_size);
  177. xs_free(body);
  178. }
  179. static jmp_buf on_break;
  180. void term_handler(int s)
  181. {
  182. longjmp(on_break, 1);
  183. }
  184. static void *purge_thread(void *arg)
  185. /* spawned purge */
  186. {
  187. srv_log(xs_dup("purge start"));
  188. purge_all();
  189. srv_log(xs_dup("purge end"));
  190. return NULL;
  191. }
  192. static void *queue_thread(void *arg)
  193. /* queue thread (queue management) */
  194. {
  195. pthread_mutex_t dummy_mutex = PTHREAD_MUTEX_INITIALIZER;
  196. pthread_cond_t dummy_cond = PTHREAD_COND_INITIALIZER;
  197. time_t purge_time;
  198. /* first purge time */
  199. purge_time = time(NULL) + 10 * 60;
  200. srv_log(xs_fmt("queue thread start"));
  201. while (srv_running) {
  202. time_t t;
  203. {
  204. xs *list = user_list();
  205. char *p, *uid;
  206. /* process queues for all users */
  207. p = list;
  208. while (xs_list_iter(&p, &uid)) {
  209. snac snac;
  210. if (user_open(&snac, uid)) {
  211. process_queue(&snac);
  212. user_free(&snac);
  213. }
  214. }
  215. }
  216. /* time to purge? */
  217. if ((t = time(NULL)) > purge_time) {
  218. pthread_t pth;
  219. pthread_create(&pth, NULL, purge_thread, NULL);
  220. /* next purge time is tomorrow */
  221. purge_time = t + 24 * 60 * 60;
  222. }
  223. /* sleep 3 seconds */
  224. struct timespec ts;
  225. clock_gettime(CLOCK_REALTIME, &ts);
  226. ts.tv_sec += 3;
  227. pthread_mutex_lock(&dummy_mutex);
  228. while (pthread_cond_timedwait(&dummy_cond, &dummy_mutex, &ts) == 0);
  229. pthread_mutex_unlock(&dummy_mutex);
  230. }
  231. srv_log(xs_fmt("queue thread stop"));
  232. return NULL;
  233. }
  234. static void *connection_thread(void *arg)
  235. /* connection thread */
  236. {
  237. httpd_connection((FILE *)arg);
  238. return NULL;
  239. }
  240. int threaded_connections = 1;
  241. void httpd(void)
  242. /* starts the server */
  243. {
  244. char *address;
  245. int port;
  246. int rs;
  247. pthread_t htid;
  248. address = xs_dict_get(srv_config, "address");
  249. port = xs_number_get(xs_dict_get(srv_config, "port"));
  250. if ((rs = xs_socket_server(address, port)) == -1) {
  251. srv_log(xs_fmt("cannot bind socket to %s:%d", address, port));
  252. return;
  253. }
  254. srv_running = 1;
  255. signal(SIGPIPE, SIG_IGN);
  256. signal(SIGTERM, term_handler);
  257. signal(SIGINT, term_handler);
  258. srv_log(xs_fmt("httpd start %s:%d %s", address, port, USER_AGENT));
  259. pthread_create(&htid, NULL, queue_thread, NULL);
  260. if (setjmp(on_break) == 0) {
  261. for (;;) {
  262. FILE *f = xs_socket_accept(rs);
  263. if (threaded_connections) {
  264. pthread_t cth;
  265. pthread_create(&cth, NULL, connection_thread, f);
  266. pthread_detach(cth);
  267. }
  268. else
  269. httpd_connection(f);
  270. }
  271. }
  272. srv_running = 0;
  273. /* wait for the helper thread to end */
  274. pthread_join(htid, NULL);
  275. srv_log(xs_fmt("httpd stop %s:%d", address, port));
  276. }