httpd.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /* snac - A simple, minimalistic ActivityPub instance */
  2. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  3. #include "xs.h"
  4. #include "xs_io.h"
  5. #include "xs_json.h"
  6. #include "xs_socket.h"
  7. #include "xs_unix_socket.h"
  8. #include "xs_httpd.h"
  9. #include "xs_mime.h"
  10. #include "xs_time.h"
  11. #include "xs_openssl.h"
  12. #include "xs_fcgi.h"
  13. #include "xs_html.h"
  14. #include "snac.h"
  15. #include <setjmp.h>
  16. #include <pthread.h>
  17. #include <semaphore.h>
  18. #include <fcntl.h>
  19. #include <stdint.h>
  20. #include <sys/resource.h> // for getrlimit()
  21. #include <sys/mman.h>
  22. #ifdef USE_POLL_FOR_SLEEP
  23. #include <poll.h>
  24. #endif
  25. /** server state **/
  26. srv_state *p_state = NULL;
  27. /** job control **/
  28. /* mutex to access the lists of jobs */
  29. static pthread_mutex_t job_mutex;
  30. /* semaphore to trigger job processing */
  31. static sem_t *job_sem;
  32. typedef struct job_fifo_item {
  33. struct job_fifo_item *next;
  34. xs_val *job;
  35. } job_fifo_item;
  36. static job_fifo_item *job_fifo_first = NULL;
  37. static job_fifo_item *job_fifo_last = NULL;
  38. /** other global data **/
  39. static jmp_buf on_break;
  40. /** code **/
  41. /* nodeinfo 2.0 template */
  42. const char *nodeinfo_2_0_template = ""
  43. "{\"version\":\"2.0\","
  44. "\"software\":{\"name\":\"snac\",\"version\":\"" VERSION "\"},"
  45. "\"protocols\":[\"activitypub\"],"
  46. "\"services\":{\"outbound\":[],\"inbound\":[]},"
  47. "\"usage\":{\"users\":{\"total\":%d,\"activeMonth\":%d,\"activeHalfyear\":%d},"
  48. "\"localPosts\":%d},"
  49. "\"openRegistrations\":false,\"metadata\":{}}";
  50. xs_str *nodeinfo_2_0(void)
  51. /* builds a nodeinfo json object */
  52. {
  53. int n_utotal = 0;
  54. int n_umonth = 0;
  55. int n_uhyear = 0;
  56. int n_posts = 0;
  57. xs *users = user_list();
  58. xs_list *p = users;
  59. const char *v;
  60. double now = (double)time(NULL);
  61. while (xs_list_iter(&p, &v)) {
  62. /* build the full path name to the last usage log */
  63. xs *llfn = xs_fmt("%s/user/%s/lastlog.txt", srv_basedir, v);
  64. double llsecs = now - mtime(llfn);
  65. if (llsecs < 60 * 60 * 24 * 30 * 6) {
  66. n_uhyear++;
  67. if (llsecs < 60 * 60 * 24 * 30)
  68. n_umonth++;
  69. }
  70. n_utotal++;
  71. /* build the file to each user public.idx */
  72. xs *pidxfn = xs_fmt("%s/user/%s/public.idx", srv_basedir, v);
  73. n_posts += index_len(pidxfn);
  74. }
  75. return xs_fmt(nodeinfo_2_0_template, n_utotal, n_umonth, n_uhyear, n_posts);
  76. }
  77. static xs_str *greeting_html(void)
  78. /* processes and returns greeting.html */
  79. {
  80. /* try to open greeting.html */
  81. xs *fn = xs_fmt("%s/greeting.html", srv_basedir);
  82. FILE *f;
  83. xs_str *s = NULL;
  84. if ((f = fopen(fn, "r")) != NULL) {
  85. s = xs_readall(f);
  86. fclose(f);
  87. /* replace %host% */
  88. s = xs_replace_i(s, "%host%", xs_dict_get(srv_config, "host"));
  89. const char *adm_email = xs_dict_get(srv_config, "admin_email");
  90. if (xs_is_null(adm_email) || *adm_email == '\0')
  91. adm_email = "the administrator of this instance";
  92. /* replace %admin_email */
  93. s = xs_replace_i(s, "%admin_email%", adm_email);
  94. /* does it have a %userlist% mark? */
  95. if (xs_str_in(s, "%userlist%") != -1) {
  96. const char *host = xs_dict_get(srv_config, "host");
  97. xs *list = user_list();
  98. xs_list *p = list;
  99. const xs_str *uid;
  100. xs_html *ul = xs_html_tag("ul",
  101. xs_html_attr("class", "snac-user-list"));
  102. p = list;
  103. while (xs_list_iter(&p, &uid)) {
  104. snac user;
  105. if (user_open(&user, uid)) {
  106. xs_html_add(ul,
  107. xs_html_tag("li",
  108. xs_html_tag("a",
  109. xs_html_attr("href", user.actor),
  110. xs_html_text("@"),
  111. xs_html_text(uid),
  112. xs_html_text("@"),
  113. xs_html_text(host),
  114. xs_html_text(" ("),
  115. xs_html_text(xs_dict_get(user.config, "name")),
  116. xs_html_text(")"))));
  117. user_free(&user);
  118. }
  119. }
  120. xs *s1 = xs_html_render(ul);
  121. s = xs_replace_i(s, "%userlist%", s1);
  122. }
  123. }
  124. return s;
  125. }
  126. int server_get_handler(xs_dict *req, const char *q_path,
  127. char **body, int *b_size, char **ctype)
  128. /* basic server services */
  129. {
  130. int status = 0;
  131. /* is it the server root? */
  132. if (*q_path == '\0') {
  133. const xs_dict *q_vars = xs_dict_get(req, "q_vars");
  134. const char *t = NULL;
  135. if (xs_type(q_vars) == XSTYPE_DICT && (t = xs_dict_get(q_vars, "t"))) {
  136. /** search by tag **/
  137. int skip = 0;
  138. int show = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  139. const char *v;
  140. if ((v = xs_dict_get(q_vars, "skip")) != NULL)
  141. skip = atoi(v);
  142. if ((v = xs_dict_get(q_vars, "show")) != NULL)
  143. show = atoi(v);
  144. xs *tl = tag_search(t, skip, show + 1);
  145. int more = 0;
  146. if (xs_list_len(tl) >= show + 1) {
  147. /* drop the last one */
  148. tl = xs_list_del(tl, -1);
  149. more = 1;
  150. }
  151. const char *accept = xs_dict_get(req, "accept");
  152. if (!xs_is_null(accept) && strcmp(accept, "application/rss+xml") == 0) {
  153. xs *link = xs_fmt("%s/?t=%s", srv_baseurl, t);
  154. *body = timeline_to_rss(NULL, tl, link, link, link);
  155. *ctype = "application/rss+xml; charset=utf-8";
  156. }
  157. else {
  158. xs *page = xs_fmt("?t=%s", t);
  159. xs *title = xs_fmt(L("Search results for tag #%s"), t);
  160. *body = html_timeline(NULL, tl, 0, skip, show, more, title, page, 0, NULL);
  161. }
  162. }
  163. else
  164. if (xs_type(xs_dict_get(srv_config, "show_instance_timeline")) == XSTYPE_TRUE) {
  165. /** instance timeline **/
  166. xs *tl = timeline_instance_list(0, 30);
  167. *body = html_timeline(NULL, tl, 0, 0, 0, 0,
  168. L("Recent posts by users in this instance"), NULL, 0, NULL);
  169. }
  170. else
  171. *body = greeting_html();
  172. if (*body)
  173. status = HTTP_STATUS_OK;
  174. }
  175. else
  176. if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
  177. status = HTTP_STATUS_OK;
  178. *body = xs_base64_dec(default_avatar_base64(), b_size);
  179. *ctype = "image/png";
  180. }
  181. else
  182. if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
  183. status = HTTP_STATUS_OK;
  184. *ctype = "application/json; charset=utf-8";
  185. *body = xs_fmt("{\"links\":["
  186. "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
  187. "\"href\":\"%s/nodeinfo_2_0\"}]}",
  188. srv_baseurl);
  189. }
  190. else
  191. if (strcmp(q_path, "/.well-known/host-meta") == 0) {
  192. status = HTTP_STATUS_OK;
  193. *ctype = "application/xrd+xml";
  194. *body = xs_fmt("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  195. "<XRD>"
  196. "<Link rel=\"lrdd\" type=\"application/xrd+xml\" template=\"https://%s/.well-known/webfinger?resource={uri}\"/>"
  197. "</XRD>", xs_dict_get(srv_config, "host"));
  198. }
  199. else
  200. if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
  201. status = HTTP_STATUS_OK;
  202. *ctype = "application/json; charset=utf-8";
  203. *body = nodeinfo_2_0();
  204. }
  205. else
  206. if (strcmp(q_path, "/robots.txt") == 0) {
  207. status = HTTP_STATUS_OK;
  208. *ctype = "text/plain";
  209. *body = xs_str_new("User-agent: *\n"
  210. "Disallow: /\n");
  211. }
  212. if (status != 0)
  213. srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
  214. return status;
  215. }
  216. void httpd_connection(FILE *f)
  217. /* the connection processor */
  218. {
  219. xs *req;
  220. const char *method;
  221. int status = 0;
  222. xs_str *body = NULL;
  223. int b_size = 0;
  224. char *ctype = NULL;
  225. xs *headers = xs_dict_new();
  226. xs *q_path = NULL;
  227. xs *payload = NULL;
  228. xs *etag = NULL;
  229. xs *last_modified = NULL;
  230. int p_size = 0;
  231. const char *p;
  232. int fcgi_id;
  233. if (p_state->use_fcgi)
  234. req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
  235. else
  236. req = xs_httpd_request(f, &payload, &p_size);
  237. if (req == NULL) {
  238. /* probably because a timeout */
  239. fclose(f);
  240. return;
  241. }
  242. if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
  243. /* missing needed headers; discard */
  244. fclose(f);
  245. return;
  246. }
  247. q_path = xs_dup(p);
  248. /* crop the q_path from leading / and the prefix */
  249. if (xs_endswith(q_path, "/"))
  250. q_path = xs_crop_i(q_path, 0, -1);
  251. p = xs_dict_get(srv_config, "prefix");
  252. if (xs_startswith(q_path, p))
  253. q_path = xs_crop_i(q_path, strlen(p), 0);
  254. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  255. /* cascade through */
  256. if (status == 0)
  257. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  258. if (status == 0)
  259. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  260. if (status == 0)
  261. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  262. #ifndef NO_MASTODON_API
  263. if (status == 0)
  264. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  265. if (status == 0)
  266. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype);
  267. #endif /* NO_MASTODON_API */
  268. if (status == 0)
  269. status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag, &last_modified);
  270. }
  271. else
  272. if (strcmp(method, "POST") == 0) {
  273. #ifndef NO_MASTODON_API
  274. if (status == 0)
  275. status = oauth_post_handler(req, q_path,
  276. payload, p_size, &body, &b_size, &ctype);
  277. if (status == 0)
  278. status = mastoapi_post_handler(req, q_path,
  279. payload, p_size, &body, &b_size, &ctype);
  280. #endif
  281. if (status == 0)
  282. status = activitypub_post_handler(req, q_path,
  283. payload, p_size, &body, &b_size, &ctype);
  284. if (status == 0)
  285. status = html_post_handler(req, q_path,
  286. payload, p_size, &body, &b_size, &ctype);
  287. }
  288. else
  289. if (strcmp(method, "PUT") == 0) {
  290. #ifndef NO_MASTODON_API
  291. if (status == 0)
  292. status = mastoapi_put_handler(req, q_path,
  293. payload, p_size, &body, &b_size, &ctype);
  294. #endif
  295. }
  296. else
  297. if (strcmp(method, "PATCH") == 0) {
  298. #ifndef NO_MASTODON_API
  299. if (status == 0)
  300. status = mastoapi_patch_handler(req, q_path,
  301. payload, p_size, &body, &b_size, &ctype);
  302. #endif
  303. }
  304. else
  305. if (strcmp(method, "OPTIONS") == 0) {
  306. const char *methods = "OPTIONS, GET, HEAD, POST, PUT, DELETE";
  307. headers = xs_dict_append(headers, "allow", methods);
  308. headers = xs_dict_append(headers, "access-control-allow-methods", methods);
  309. status = HTTP_STATUS_OK;
  310. }
  311. else
  312. if (strcmp(method, "DELETE") == 0) {
  313. #ifndef NO_MASTODON_API
  314. if (status == 0)
  315. status = mastoapi_delete_handler(req, q_path,
  316. payload, p_size, &body, &b_size, &ctype);
  317. #endif
  318. }
  319. /* unattended? it's an error */
  320. if (status == 0) {
  321. srv_archive_error("unattended_method", "unattended method", req, payload);
  322. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  323. status = HTTP_STATUS_NOT_FOUND;
  324. }
  325. if (status == HTTP_STATUS_FORBIDDEN)
  326. body = xs_str_new("<h1>403 Forbidden</h1>");
  327. if (status == HTTP_STATUS_NOT_FOUND)
  328. body = xs_str_new("<h1>404 Not Found</h1>");
  329. if (status == HTTP_STATUS_BAD_REQUEST && body != NULL)
  330. body = xs_str_new("<h1>400 Bad Request</h1>");
  331. if (status == HTTP_STATUS_SEE_OTHER)
  332. headers = xs_dict_append(headers, "location", body);
  333. if (status == HTTP_STATUS_UNAUTHORIZED && body) {
  334. xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
  335. body, xs_dict_get(srv_config, "host"));
  336. headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
  337. headers = xs_dict_append(headers, "Cache-Control", "no-cache, must-revalidate, max-age=0");
  338. }
  339. if (ctype == NULL)
  340. ctype = "text/html; charset=utf-8";
  341. headers = xs_dict_append(headers, "content-type", ctype);
  342. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  343. if (!xs_is_null(etag))
  344. headers = xs_dict_append(headers, "etag", etag);
  345. if (!xs_is_null(last_modified))
  346. headers = xs_dict_append(headers, "last-modified", last_modified);
  347. /* if there are any additional headers, add them */
  348. const xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
  349. if (xs_type(more_headers) == XSTYPE_DICT) {
  350. const char *k, *v;
  351. int c = 0;
  352. while (xs_dict_next(more_headers, &k, &v, &c))
  353. headers = xs_dict_set(headers, k, v);
  354. }
  355. if (b_size == 0 && body != NULL)
  356. b_size = strlen(body);
  357. /* if it was a HEAD, no body will be sent */
  358. if (strcmp(method, "HEAD") == 0)
  359. body = xs_free(body);
  360. headers = xs_dict_append(headers, "access-control-allow-origin", "*");
  361. headers = xs_dict_append(headers, "access-control-allow-headers", "*");
  362. if (p_state->use_fcgi)
  363. xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
  364. else
  365. xs_httpd_response(f, status, http_status_text(status), headers, body, b_size);
  366. fclose(f);
  367. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  368. /* JSON validation check */
  369. if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
  370. xs *j = xs_json_loads(body);
  371. if (j == NULL) {
  372. srv_log(xs_fmt("bad JSON"));
  373. srv_archive_error("bad_json", "bad JSON", req, body);
  374. }
  375. }
  376. xs_free(body);
  377. }
  378. void job_post(const xs_val *job, int urgent)
  379. /* posts a job for the threads to process it */
  380. {
  381. if (job != NULL) {
  382. /* lock the mutex */
  383. pthread_mutex_lock(&job_mutex);
  384. job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
  385. *i = (job_fifo_item){ NULL, xs_dup(job) };
  386. if (job_fifo_first == NULL)
  387. job_fifo_first = job_fifo_last = i;
  388. else
  389. if (urgent) {
  390. /* prepend */
  391. i->next = job_fifo_first;
  392. job_fifo_first = i;
  393. }
  394. else {
  395. /* append */
  396. job_fifo_last->next = i;
  397. job_fifo_last = i;
  398. }
  399. p_state->job_fifo_size++;
  400. if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
  401. p_state->peak_job_fifo_size = p_state->job_fifo_size;
  402. /* unlock the mutex */
  403. pthread_mutex_unlock(&job_mutex);
  404. /* ask for someone to attend it */
  405. sem_post(job_sem);
  406. }
  407. }
  408. void job_wait(xs_val **job)
  409. /* waits for an available job */
  410. {
  411. *job = NULL;
  412. if (sem_wait(job_sem) == 0) {
  413. /* lock the mutex */
  414. pthread_mutex_lock(&job_mutex);
  415. /* dequeue */
  416. job_fifo_item *i = job_fifo_first;
  417. if (i != NULL) {
  418. job_fifo_first = i->next;
  419. if (job_fifo_first == NULL)
  420. job_fifo_last = NULL;
  421. *job = i->job;
  422. xs_free(i);
  423. p_state->job_fifo_size--;
  424. }
  425. /* unlock the mutex */
  426. pthread_mutex_unlock(&job_mutex);
  427. }
  428. }
  429. static void *job_thread(void *arg)
  430. /* job thread */
  431. {
  432. int pid = (int)(uintptr_t)arg;
  433. srv_debug(1, xs_fmt("job thread %d started", pid));
  434. for (;;) {
  435. xs *job = NULL;
  436. p_state->th_state[pid] = THST_WAIT;
  437. job_wait(&job);
  438. if (job == NULL) /* corrupted message? */
  439. continue;
  440. if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
  441. break;
  442. else
  443. if (xs_type(job) == XSTYPE_DATA) {
  444. /* it's a socket */
  445. FILE *f = NULL;
  446. p_state->th_state[pid] = THST_IN;
  447. xs_data_get(&f, job);
  448. if (f != NULL)
  449. httpd_connection(f);
  450. }
  451. else {
  452. /* it's a q_item */
  453. p_state->th_state[pid] = THST_QUEUE;
  454. process_queue_item(job);
  455. }
  456. }
  457. p_state->th_state[pid] = THST_STOP;
  458. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  459. return NULL;
  460. }
  461. /* background thread sleep control */
  462. static pthread_mutex_t sleep_mutex;
  463. static pthread_cond_t sleep_cond;
  464. static void *background_thread(void *arg)
  465. /* background thread (queue management and other things) */
  466. {
  467. time_t purge_time;
  468. (void)arg;
  469. /* first purge time */
  470. purge_time = time(NULL) + 10 * 60;
  471. srv_log(xs_fmt("background thread started"));
  472. while (p_state->srv_running) {
  473. time_t t;
  474. int cnt = 0;
  475. p_state->th_state[0] = THST_QUEUE;
  476. {
  477. xs *list = user_list();
  478. char *p;
  479. const char *uid;
  480. /* process queues for all users */
  481. p = list;
  482. while (xs_list_iter(&p, &uid)) {
  483. snac snac;
  484. if (user_open(&snac, uid)) {
  485. cnt += process_user_queue(&snac);
  486. user_free(&snac);
  487. }
  488. }
  489. }
  490. /* global queue */
  491. cnt += process_queue();
  492. /* time to purge? */
  493. if ((t = time(NULL)) > purge_time) {
  494. /* next purge time is tomorrow */
  495. purge_time = t + 24 * 60 * 60;
  496. xs *q_item = xs_dict_new();
  497. q_item = xs_dict_append(q_item, "type", "purge");
  498. job_post(q_item, 0);
  499. }
  500. if (cnt == 0) {
  501. /* sleep 3 seconds */
  502. p_state->th_state[0] = THST_WAIT;
  503. #ifdef USE_POLL_FOR_SLEEP
  504. poll(NULL, 0, 3 * 1000);
  505. #else
  506. struct timespec ts;
  507. clock_gettime(CLOCK_REALTIME, &ts);
  508. ts.tv_sec += 3;
  509. pthread_mutex_lock(&sleep_mutex);
  510. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  511. pthread_mutex_unlock(&sleep_mutex);
  512. #endif
  513. }
  514. }
  515. p_state->th_state[0] = THST_STOP;
  516. srv_log(xs_fmt("background thread stopped"));
  517. return NULL;
  518. }
  519. void term_handler(int s)
  520. {
  521. (void)s;
  522. longjmp(on_break, 1);
  523. }
  524. srv_state *srv_state_op(xs_str **fname, int op)
  525. /* opens or deletes the shared memory object */
  526. {
  527. int fd;
  528. srv_state *ss = NULL;
  529. if (*fname == NULL)
  530. *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
  531. switch (op) {
  532. case 0: /* open for writing */
  533. #ifdef WITHOUT_SHM
  534. errno = ENOTSUP;
  535. #else
  536. if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
  537. ftruncate(fd, sizeof(*ss));
  538. if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
  539. MAP_SHARED, fd, 0)) == MAP_FAILED)
  540. ss = NULL;
  541. close(fd);
  542. }
  543. #endif
  544. if (ss == NULL) {
  545. /* shared memory error: just create a plain structure */
  546. srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
  547. ss = malloc(sizeof(*ss));
  548. }
  549. /* init structure */
  550. *ss = (srv_state){0};
  551. ss->s_size = sizeof(*ss);
  552. break;
  553. case 1: /* open for reading */
  554. #ifdef WITHOUT_SHM
  555. errno = ENOTSUP;
  556. #else
  557. if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
  558. if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
  559. ss = NULL;
  560. close(fd);
  561. }
  562. #endif
  563. if (ss == NULL) {
  564. /* shared memory error */
  565. srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
  566. }
  567. else
  568. if (ss->s_size != sizeof(*ss)) {
  569. srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
  570. ss->s_size, sizeof(*ss)));
  571. munmap(ss, sizeof(*ss));
  572. ss = NULL;
  573. }
  574. break;
  575. case 2: /* unlink */
  576. #ifndef WITHOUT_SHM
  577. if (*fname)
  578. shm_unlink(*fname);
  579. #endif
  580. break;
  581. }
  582. return ss;
  583. }
  584. void httpd(void)
  585. /* starts the server */
  586. {
  587. const char *address = NULL;
  588. const char *port = NULL;
  589. xs *full_address = NULL;
  590. int rs;
  591. pthread_t threads[MAX_THREADS] = {0};
  592. int n;
  593. xs *sem_name = NULL;
  594. xs *shm_name = NULL;
  595. sem_t anon_job_sem;
  596. xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
  597. address = xs_dict_get(srv_config, "address");
  598. if (*address == '/') {
  599. rs = xs_unix_socket_server(address, NULL);
  600. full_address = xs_fmt("unix:%s", address);
  601. }
  602. else {
  603. port = xs_number_str(xs_dict_get(srv_config, "port"));
  604. full_address = xs_fmt("%s:%s", address, port);
  605. rs = xs_socket_server(address, port);
  606. }
  607. if (rs == -1) {
  608. srv_log(xs_fmt("cannot bind socket to %s", full_address));
  609. return;
  610. }
  611. /* setup the server stat structure */
  612. p_state = srv_state_op(&shm_name, 0);
  613. p_state->srv_start_time = time(NULL);
  614. p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
  615. p_state->srv_running = 1;
  616. signal(SIGPIPE, SIG_IGN);
  617. signal(SIGTERM, term_handler);
  618. signal(SIGINT, term_handler);
  619. srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
  620. full_address, USER_AGENT));
  621. {
  622. FILE *f;
  623. if ((f = fopen(pidfile, "w")) != NULL) {
  624. fprintf(f, "%d\n", getpid());
  625. fclose(f);
  626. }
  627. else
  628. srv_log(xs_fmt("Cannot create %s: %s", pidfile, strerror(errno)));
  629. }
  630. /* show the number of usable file descriptors */
  631. struct rlimit r;
  632. getrlimit(RLIMIT_NOFILE, &r);
  633. srv_debug(1, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  634. (int) r.rlim_cur, (int) r.rlim_max));
  635. /* initialize the job control engine */
  636. pthread_mutex_init(&job_mutex, NULL);
  637. sem_name = xs_fmt("/job_%d", getpid());
  638. job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
  639. if (job_sem == NULL) {
  640. /* error opening a named semaphore; try with an anonymous one */
  641. if (sem_init(&anon_job_sem, 0, 0) != -1)
  642. job_sem = &anon_job_sem;
  643. }
  644. if (job_sem == NULL) {
  645. srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
  646. return;
  647. }
  648. /* initialize sleep control */
  649. pthread_mutex_init(&sleep_mutex, NULL);
  650. pthread_cond_init(&sleep_cond, NULL);
  651. p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  652. #ifdef _SC_NPROCESSORS_ONLN
  653. if (p_state->n_threads == 0) {
  654. /* get number of CPUs on the machine */
  655. p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  656. }
  657. #endif
  658. if (p_state->n_threads < 4)
  659. p_state->n_threads = 4;
  660. if (p_state->n_threads > MAX_THREADS)
  661. p_state->n_threads = MAX_THREADS;
  662. srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
  663. /* thread #0 is the background thread */
  664. pthread_create(&threads[0], NULL, background_thread, NULL);
  665. /* the rest of threads are for job processing */
  666. char *ptr = (char *) 0x1;
  667. for (n = 1; n < p_state->n_threads; n++)
  668. pthread_create(&threads[n], NULL, job_thread, ptr++);
  669. if (setjmp(on_break) == 0) {
  670. for (;;) {
  671. int cs = xs_socket_accept(rs);
  672. if (cs != -1) {
  673. FILE *f = fdopen(cs, "r+");
  674. xs *job = xs_data_new(&f, sizeof(FILE *));
  675. job_post(job, 1);
  676. }
  677. else
  678. break;
  679. }
  680. }
  681. p_state->srv_running = 0;
  682. /* send as many exit jobs as working threads */
  683. for (n = 1; n < p_state->n_threads; n++)
  684. job_post(xs_stock(XSTYPE_FALSE), 0);
  685. /* wait for all the threads to exit */
  686. for (n = 0; n < p_state->n_threads; n++)
  687. pthread_join(threads[n], NULL);
  688. sem_close(job_sem);
  689. sem_unlink(sem_name);
  690. srv_state_op(&shm_name, 2);
  691. xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
  692. srv_log(xs_fmt("httpd%s stop %s (run time: %s)",
  693. p_state->use_fcgi ? " (FastCGI)" : "",
  694. full_address, uptime));
  695. unlink(pidfile);
  696. }