httpd.c 22 KB

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