httpd.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. int skip = 0;
  137. int show = xs_number_get(xs_dict_get(srv_config, "max_timeline_entries"));
  138. char *v;
  139. if ((v = xs_dict_get(q_vars, "skip")) != NULL)
  140. skip = atoi(v);
  141. if ((v = xs_dict_get(q_vars, "show")) != NULL)
  142. show = atoi(v);
  143. xs *tl = tag_search(t, skip, show + 1);
  144. int more = 0;
  145. if (xs_list_len(tl) >= show + 1) {
  146. /* drop the last one */
  147. tl = xs_list_del(tl, -1);
  148. more = 1;
  149. }
  150. *body = html_timeline(NULL, tl, 0, skip, show, more, t);
  151. }
  152. else
  153. if (xs_type(xs_dict_get(srv_config, "show_instance_timeline")) == XSTYPE_TRUE) {
  154. xs *tl = timeline_instance_list(0, 30);
  155. *body = html_timeline(NULL, tl, 0, 0, 0, 0, NULL);
  156. }
  157. else
  158. *body = greeting_html();
  159. if (*body)
  160. status = 200;
  161. }
  162. else
  163. if (strcmp(q_path, "/susie.png") == 0 || strcmp(q_path, "/favicon.ico") == 0 ) {
  164. status = 200;
  165. *body = xs_base64_dec(default_avatar_base64(), b_size);
  166. *ctype = "image/png";
  167. }
  168. else
  169. if (strcmp(q_path, "/.well-known/nodeinfo") == 0) {
  170. status = 200;
  171. *ctype = "application/json; charset=utf-8";
  172. *body = xs_fmt("{\"links\":["
  173. "{\"rel\":\"http:/" "/nodeinfo.diaspora.software/ns/schema/2.0\","
  174. "\"href\":\"%s/nodeinfo_2_0\"}]}",
  175. srv_baseurl);
  176. }
  177. else
  178. if (strcmp(q_path, "/nodeinfo_2_0") == 0) {
  179. status = 200;
  180. *ctype = "application/json; charset=utf-8";
  181. *body = nodeinfo_2_0();
  182. }
  183. else
  184. if (strcmp(q_path, "/robots.txt") == 0) {
  185. status = 200;
  186. *ctype = "text/plain";
  187. *body = xs_str_new("User-agent: *\n"
  188. "Disallow: /\n");
  189. }
  190. if (status != 0)
  191. srv_debug(1, xs_fmt("server_get_handler serving '%s' %d", q_path, status));
  192. return status;
  193. }
  194. void httpd_connection(FILE *f)
  195. /* the connection processor */
  196. {
  197. xs *req;
  198. char *method;
  199. int status = 0;
  200. xs_str *body = NULL;
  201. int b_size = 0;
  202. char *ctype = NULL;
  203. xs *headers = xs_dict_new();
  204. xs *q_path = NULL;
  205. xs *payload = NULL;
  206. xs *etag = NULL;
  207. int p_size = 0;
  208. char *p;
  209. int fcgi_id;
  210. if (p_state->use_fcgi)
  211. req = xs_fcgi_request(f, &payload, &p_size, &fcgi_id);
  212. else
  213. req = xs_httpd_request(f, &payload, &p_size);
  214. if (req == NULL) {
  215. /* probably because a timeout */
  216. fclose(f);
  217. return;
  218. }
  219. if (!(method = xs_dict_get(req, "method")) || !(p = xs_dict_get(req, "path"))) {
  220. /* missing needed headers; discard */
  221. fclose(f);
  222. return;
  223. }
  224. q_path = xs_dup(p);
  225. /* crop the q_path from leading / and the prefix */
  226. if (xs_endswith(q_path, "/"))
  227. q_path = xs_crop_i(q_path, 0, -1);
  228. p = xs_dict_get(srv_config, "prefix");
  229. if (xs_startswith(q_path, p))
  230. q_path = xs_crop_i(q_path, strlen(p), 0);
  231. if (strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0) {
  232. /* cascade through */
  233. if (status == 0)
  234. status = server_get_handler(req, q_path, &body, &b_size, &ctype);
  235. if (status == 0)
  236. status = webfinger_get_handler(req, q_path, &body, &b_size, &ctype);
  237. if (status == 0)
  238. status = activitypub_get_handler(req, q_path, &body, &b_size, &ctype);
  239. #ifndef NO_MASTODON_API
  240. if (status == 0)
  241. status = oauth_get_handler(req, q_path, &body, &b_size, &ctype);
  242. if (status == 0)
  243. status = mastoapi_get_handler(req, q_path, &body, &b_size, &ctype);
  244. #endif /* NO_MASTODON_API */
  245. if (status == 0)
  246. status = html_get_handler(req, q_path, &body, &b_size, &ctype, &etag);
  247. }
  248. else
  249. if (strcmp(method, "POST") == 0) {
  250. #ifndef NO_MASTODON_API
  251. if (status == 0)
  252. status = oauth_post_handler(req, q_path,
  253. payload, p_size, &body, &b_size, &ctype);
  254. if (status == 0)
  255. status = mastoapi_post_handler(req, q_path,
  256. payload, p_size, &body, &b_size, &ctype);
  257. #endif
  258. if (status == 0)
  259. status = activitypub_post_handler(req, q_path,
  260. payload, p_size, &body, &b_size, &ctype);
  261. if (status == 0)
  262. status = html_post_handler(req, q_path,
  263. payload, p_size, &body, &b_size, &ctype);
  264. }
  265. else
  266. if (strcmp(method, "PUT") == 0) {
  267. #ifndef NO_MASTODON_API
  268. if (status == 0)
  269. status = mastoapi_put_handler(req, q_path,
  270. payload, p_size, &body, &b_size, &ctype);
  271. #endif
  272. }
  273. else
  274. if (strcmp(method, "OPTIONS") == 0) {
  275. status = 200;
  276. }
  277. else
  278. if (strcmp(method, "DELETE") == 0) {
  279. #ifndef NO_MASTODON_API
  280. if (status == 0)
  281. status = mastoapi_delete_handler(req, q_path,
  282. &body, &b_size, &ctype);
  283. #endif
  284. }
  285. /* unattended? it's an error */
  286. if (status == 0) {
  287. srv_archive_error("unattended_method", "unattended method", req, payload);
  288. srv_debug(1, xs_fmt("httpd_connection unattended %s %s", method, q_path));
  289. status = 404;
  290. }
  291. if (status == 403)
  292. body = xs_str_new("<h1>403 Forbidden</h1>");
  293. if (status == 404)
  294. body = xs_str_new("<h1>404 Not Found</h1>");
  295. if (status == 400 && body != NULL)
  296. body = xs_str_new("<h1>400 Bad Request</h1>");
  297. if (status == 303)
  298. headers = xs_dict_append(headers, "location", body);
  299. if (status == 401) {
  300. xs *www_auth = xs_fmt("Basic realm=\"@%s@%s snac login\"",
  301. body, xs_dict_get(srv_config, "host"));
  302. headers = xs_dict_append(headers, "WWW-Authenticate", www_auth);
  303. }
  304. if (ctype == NULL)
  305. ctype = "text/html; charset=utf-8";
  306. headers = xs_dict_append(headers, "content-type", ctype);
  307. headers = xs_dict_append(headers, "x-creator", USER_AGENT);
  308. if (!xs_is_null(etag))
  309. headers = xs_dict_append(headers, "etag", etag);
  310. /* if there are any additional headers, add them */
  311. xs_dict *more_headers = xs_dict_get(srv_config, "http_headers");
  312. if (xs_type(more_headers) == XSTYPE_DICT) {
  313. char *k, *v;
  314. while (xs_dict_iter(&more_headers, &k, &v))
  315. headers = xs_dict_set(headers, k, v);
  316. }
  317. if (b_size == 0 && body != NULL)
  318. b_size = strlen(body);
  319. /* if it was a HEAD, no body will be sent */
  320. if (strcmp(method, "HEAD") == 0)
  321. body = xs_free(body);
  322. headers = xs_dict_append(headers, "access-control-allow-origin", "*");
  323. headers = xs_dict_append(headers, "access-control-allow-headers", "*");
  324. if (p_state->use_fcgi)
  325. xs_fcgi_response(f, status, headers, body, b_size, fcgi_id);
  326. else
  327. xs_httpd_response(f, status, headers, body, b_size);
  328. fclose(f);
  329. srv_archive("RECV", NULL, req, payload, p_size, status, headers, body, b_size);
  330. /* JSON validation check */
  331. if (!xs_is_null(body) && strcmp(ctype, "application/json") == 0) {
  332. xs *j = xs_json_loads(body);
  333. if (j == NULL) {
  334. srv_log(xs_fmt("bad JSON"));
  335. srv_archive_error("bad_json", "bad JSON", req, body);
  336. }
  337. }
  338. xs_free(body);
  339. }
  340. void job_post(const xs_val *job, int urgent)
  341. /* posts a job for the threads to process it */
  342. {
  343. if (job != NULL) {
  344. /* lock the mutex */
  345. pthread_mutex_lock(&job_mutex);
  346. job_fifo_item *i = xs_realloc(NULL, sizeof(job_fifo_item));
  347. *i = (job_fifo_item){ NULL, xs_dup(job) };
  348. if (job_fifo_first == NULL)
  349. job_fifo_first = job_fifo_last = i;
  350. else
  351. if (urgent) {
  352. /* prepend */
  353. i->next = job_fifo_first;
  354. job_fifo_first = i;
  355. }
  356. else {
  357. /* append */
  358. job_fifo_last->next = i;
  359. job_fifo_last = i;
  360. }
  361. p_state->job_fifo_size++;
  362. if (p_state->job_fifo_size > p_state->peak_job_fifo_size)
  363. p_state->peak_job_fifo_size = p_state->job_fifo_size;
  364. /* unlock the mutex */
  365. pthread_mutex_unlock(&job_mutex);
  366. /* ask for someone to attend it */
  367. sem_post(job_sem);
  368. }
  369. }
  370. void job_wait(xs_val **job)
  371. /* waits for an available job */
  372. {
  373. *job = NULL;
  374. if (sem_wait(job_sem) == 0) {
  375. /* lock the mutex */
  376. pthread_mutex_lock(&job_mutex);
  377. /* dequeue */
  378. job_fifo_item *i = job_fifo_first;
  379. if (i != NULL) {
  380. job_fifo_first = i->next;
  381. if (job_fifo_first == NULL)
  382. job_fifo_last = NULL;
  383. *job = i->job;
  384. xs_free(i);
  385. p_state->job_fifo_size--;
  386. }
  387. /* unlock the mutex */
  388. pthread_mutex_unlock(&job_mutex);
  389. }
  390. }
  391. static void *job_thread(void *arg)
  392. /* job thread */
  393. {
  394. int pid = (int)(uintptr_t)arg;
  395. srv_debug(1, xs_fmt("job thread %d started", pid));
  396. for (;;) {
  397. xs *job = NULL;
  398. p_state->th_state[pid] = THST_WAIT;
  399. job_wait(&job);
  400. if (job == NULL) /* corrupted message? */
  401. continue;
  402. if (xs_type(job) == XSTYPE_FALSE) /* special message: exit */
  403. break;
  404. else
  405. if (xs_type(job) == XSTYPE_DATA) {
  406. /* it's a socket */
  407. FILE *f = NULL;
  408. p_state->th_state[pid] = THST_IN;
  409. xs_data_get(&f, job);
  410. if (f != NULL)
  411. httpd_connection(f);
  412. }
  413. else {
  414. /* it's a q_item */
  415. p_state->th_state[pid] = THST_QUEUE;
  416. process_queue_item(job);
  417. }
  418. }
  419. p_state->th_state[pid] = THST_STOP;
  420. srv_debug(1, xs_fmt("job thread %d stopped", pid));
  421. return NULL;
  422. }
  423. /* background thread sleep control */
  424. static pthread_mutex_t sleep_mutex;
  425. static pthread_cond_t sleep_cond;
  426. static void *background_thread(void *arg)
  427. /* background thread (queue management and other things) */
  428. {
  429. time_t purge_time;
  430. (void)arg;
  431. /* first purge time */
  432. purge_time = time(NULL) + 10 * 60;
  433. srv_log(xs_fmt("background thread started"));
  434. while (p_state->srv_running) {
  435. time_t t;
  436. int cnt = 0;
  437. p_state->th_state[0] = THST_QUEUE;
  438. {
  439. xs *list = user_list();
  440. char *p, *uid;
  441. /* process queues for all users */
  442. p = list;
  443. while (xs_list_iter(&p, &uid)) {
  444. snac snac;
  445. if (user_open(&snac, uid)) {
  446. cnt += process_user_queue(&snac);
  447. user_free(&snac);
  448. }
  449. }
  450. }
  451. /* global queue */
  452. cnt += process_queue();
  453. /* time to purge? */
  454. if ((t = time(NULL)) > purge_time) {
  455. /* next purge time is tomorrow */
  456. purge_time = t + 24 * 60 * 60;
  457. xs *q_item = xs_dict_new();
  458. q_item = xs_dict_append(q_item, "type", "purge");
  459. job_post(q_item, 0);
  460. }
  461. if (cnt == 0) {
  462. /* sleep 3 seconds */
  463. p_state->th_state[0] = THST_WAIT;
  464. #ifdef USE_POLL_FOR_SLEEP
  465. poll(NULL, 0, 3 * 1000);
  466. #else
  467. struct timespec ts;
  468. clock_gettime(CLOCK_REALTIME, &ts);
  469. ts.tv_sec += 3;
  470. pthread_mutex_lock(&sleep_mutex);
  471. while (pthread_cond_timedwait(&sleep_cond, &sleep_mutex, &ts) == 0);
  472. pthread_mutex_unlock(&sleep_mutex);
  473. #endif
  474. }
  475. }
  476. p_state->th_state[0] = THST_STOP;
  477. srv_log(xs_fmt("background thread stopped"));
  478. return NULL;
  479. }
  480. void term_handler(int s)
  481. {
  482. (void)s;
  483. longjmp(on_break, 1);
  484. }
  485. srv_state *srv_state_op(xs_str **fname, int op)
  486. /* opens or deletes the shared memory object */
  487. {
  488. int fd;
  489. srv_state *ss = NULL;
  490. if (*fname == NULL)
  491. *fname = xs_fmt("/%s_snac_state", xs_dict_get(srv_config, "host"));
  492. switch (op) {
  493. case 0: /* open for writing */
  494. if ((fd = shm_open(*fname, O_CREAT | O_RDWR, 0666)) != -1) {
  495. ftruncate(fd, sizeof(*ss));
  496. if ((ss = mmap(0, sizeof(*ss), PROT_READ | PROT_WRITE,
  497. MAP_SHARED, fd, 0)) == MAP_FAILED)
  498. ss = NULL;
  499. close(fd);
  500. }
  501. if (ss == NULL) {
  502. /* shared memory error: just create a plain structure */
  503. srv_log(xs_fmt("warning: shm object error (%s)", strerror(errno)));
  504. ss = malloc(sizeof(*ss));
  505. }
  506. /* init structure */
  507. *ss = (srv_state){0};
  508. ss->s_size = sizeof(*ss);
  509. break;
  510. case 1: /* open for reading */
  511. if ((fd = shm_open(*fname, O_RDONLY, 0666)) != -1) {
  512. if ((ss = mmap(0, sizeof(*ss), PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
  513. ss = NULL;
  514. close(fd);
  515. }
  516. if (ss == NULL) {
  517. /* shared memory error */
  518. srv_log(xs_fmt("error: shm object error (%s) server not running?", strerror(errno)));
  519. }
  520. else
  521. if (ss->s_size != sizeof(*ss)) {
  522. srv_log(xs_fmt("error: struct size mismatch (%d != %d)",
  523. ss->s_size, sizeof(*ss)));
  524. munmap(ss, sizeof(*ss));
  525. ss = NULL;
  526. }
  527. break;
  528. case 2: /* unlink */
  529. if (*fname)
  530. shm_unlink(*fname);
  531. break;
  532. }
  533. return ss;
  534. }
  535. void httpd(void)
  536. /* starts the server */
  537. {
  538. const char *address;
  539. const char *port;
  540. int rs;
  541. pthread_t threads[MAX_THREADS] = {0};
  542. int n;
  543. xs *sem_name = NULL;
  544. xs *shm_name = NULL;
  545. sem_t anon_job_sem;
  546. /* setup the server stat structure */
  547. p_state = srv_state_op(&shm_name, 0);
  548. p_state->srv_start_time = time(NULL);
  549. p_state->use_fcgi = xs_type(xs_dict_get(srv_config, "fastcgi")) == XSTYPE_TRUE;
  550. address = xs_dict_get(srv_config, "address");
  551. port = xs_number_str(xs_dict_get(srv_config, "port"));
  552. if ((rs = xs_socket_server(address, port)) == -1) {
  553. srv_log(xs_fmt("cannot bind socket to %s:%s", address, port));
  554. return;
  555. }
  556. p_state->srv_running = 1;
  557. signal(SIGPIPE, SIG_IGN);
  558. signal(SIGTERM, term_handler);
  559. signal(SIGINT, term_handler);
  560. srv_log(xs_fmt("httpd%s start %s:%s %s", p_state->use_fcgi ? " (FastCGI)" : "",
  561. address, port, USER_AGENT));
  562. /* show the number of usable file descriptors */
  563. struct rlimit r;
  564. getrlimit(RLIMIT_NOFILE, &r);
  565. srv_debug(0, xs_fmt("available (rlimit) fds: %d (cur) / %d (max)",
  566. (int) r.rlim_cur, (int) r.rlim_max));
  567. /* initialize the job control engine */
  568. pthread_mutex_init(&job_mutex, NULL);
  569. sem_name = xs_fmt("/job_%d", getpid());
  570. job_sem = sem_open(sem_name, O_CREAT, 0644, 0);
  571. if (job_sem == NULL) {
  572. /* error opening a named semaphore; try with an anonymous one */
  573. if (sem_init(&anon_job_sem, 0, 0) != -1)
  574. job_sem = &anon_job_sem;
  575. }
  576. if (job_sem == NULL) {
  577. srv_log(xs_fmt("fatal error: cannot create semaphore -- cannot continue"));
  578. return;
  579. }
  580. /* initialize sleep control */
  581. pthread_mutex_init(&sleep_mutex, NULL);
  582. pthread_cond_init(&sleep_cond, NULL);
  583. p_state->n_threads = xs_number_get(xs_dict_get(srv_config, "num_threads"));
  584. #ifdef _SC_NPROCESSORS_ONLN
  585. if (p_state->n_threads == 0) {
  586. /* get number of CPUs on the machine */
  587. p_state->n_threads = sysconf(_SC_NPROCESSORS_ONLN);
  588. }
  589. #endif
  590. if (p_state->n_threads < 4)
  591. p_state->n_threads = 4;
  592. if (p_state->n_threads > MAX_THREADS)
  593. p_state->n_threads = MAX_THREADS;
  594. srv_debug(0, xs_fmt("using %d threads", p_state->n_threads));
  595. /* thread #0 is the background thread */
  596. pthread_create(&threads[0], NULL, background_thread, NULL);
  597. /* the rest of threads are for job processing */
  598. char *ptr = (char *) 0x1;
  599. for (n = 1; n < p_state->n_threads; n++)
  600. pthread_create(&threads[n], NULL, job_thread, ptr++);
  601. if (setjmp(on_break) == 0) {
  602. for (;;) {
  603. FILE *f = xs_socket_accept(rs);
  604. if (f != NULL) {
  605. xs *job = xs_data_new(&f, sizeof(FILE *));
  606. job_post(job, 1);
  607. }
  608. else
  609. break;
  610. }
  611. }
  612. p_state->srv_running = 0;
  613. /* send as many exit jobs as working threads */
  614. for (n = 1; n < p_state->n_threads; n++)
  615. job_post(xs_stock_false, 0);
  616. /* wait for all the threads to exit */
  617. for (n = 0; n < p_state->n_threads; n++)
  618. pthread_join(threads[n], NULL);
  619. sem_close(job_sem);
  620. sem_unlink(sem_name);
  621. srv_state_op(&shm_name, 2);
  622. xs *uptime = xs_str_time_diff(time(NULL) - p_state->srv_start_time);
  623. srv_log(xs_fmt("httpd%s stop %s:%s (run time: %s)",
  624. p_state->use_fcgi ? " (FastCGI)" : "",
  625. address, port, uptime));
  626. }