gamemode.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. /*
  2. Copyright (c) 2017-2018, Feral Interactive
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of Feral Interactive nor the names of its contributors
  12. may be used to endorse or promote products derived from this software
  13. without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #define _GNU_SOURCE
  27. #include "gamemode.h"
  28. #include "daemon_config.h"
  29. #include "governors-query.h"
  30. #include "governors.h"
  31. #include "ioprio.h"
  32. #include "logging.h"
  33. #include <ctype.h>
  34. #include <fcntl.h>
  35. #include <linux/limits.h>
  36. #include <linux/sched.h>
  37. #include <pthread.h>
  38. #include <pwd.h>
  39. #include <sched.h>
  40. #include <signal.h>
  41. #include <stdatomic.h>
  42. #include <stdio.h>
  43. #include <string.h>
  44. #include <sys/param.h>
  45. #include <sys/resource.h>
  46. #include <sys/sysinfo.h>
  47. #include <sys/types.h>
  48. #include <systemd/sd-daemon.h>
  49. /* SCHED_ISO may not be defined as it is a reserved value not yet
  50. * implemented in official kernel sources, see linux/sched.h.
  51. */
  52. #ifndef SCHED_ISO
  53. #define SCHED_ISO 4
  54. #endif
  55. /* Priority to renice the process to.
  56. */
  57. #define NICE_DEFAULT_PRIORITY -4
  58. /* Value clamping helper.
  59. */
  60. #define CLAMP(lbound, ubound, value) MIN(MIN(lbound, ubound), MAX(MAX(lbound, ubound), value))
  61. /* Little helper to safely print into a buffer, returns a newly allocated string
  62. */
  63. #define safe_snprintf(b, s, ...) \
  64. (snprintf(b, sizeof(b), s, __VA_ARGS__) < (ssize_t)sizeof(b) ? strndup(b, sizeof(b)) : NULL)
  65. /**
  66. * Helper function: Test, if haystack ends with needle.
  67. */
  68. static inline const char *strtail(const char *haystack, const char *needle)
  69. {
  70. char *pos = strstr(haystack, needle);
  71. if (pos && (strlen(pos) == strlen(needle)))
  72. return pos;
  73. return NULL;
  74. }
  75. /**
  76. * The GameModeClient encapsulates the remote connection, providing a list
  77. * form to contain the pid and credentials.
  78. */
  79. typedef struct GameModeClient {
  80. pid_t pid; /**< Process ID */
  81. struct GameModeClient *next; /**<Next client in the list */
  82. char *executable; /**<Process executable */
  83. } GameModeClient;
  84. struct GameModeContext {
  85. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  86. _Atomic int refcount; /**<Allow cycling the game mode */
  87. GameModeClient *client; /**<Pointer to first client */
  88. GameModeConfig *config; /**<Pointer to config object */
  89. char initial_cpu_mode[64]; /**<Only updates when we can */
  90. /* Reaper control */
  91. struct {
  92. pthread_t thread;
  93. bool running;
  94. pthread_mutex_t mutex;
  95. pthread_cond_t condition;
  96. } reaper;
  97. };
  98. static GameModeContext instance = { 0 };
  99. /* Maximum number of concurrent processes we'll sanely support */
  100. #define MAX_GAMES 256
  101. /**
  102. * Protect against signals
  103. */
  104. static volatile bool had_context_init = false;
  105. static GameModeClient *game_mode_client_new(pid_t pid, char *exe);
  106. static void game_mode_client_free(GameModeClient *client);
  107. static bool game_mode_context_has_client(GameModeContext *self, pid_t client);
  108. static int game_mode_context_num_clients(GameModeContext *self);
  109. static void *game_mode_context_reaper(void *userdata);
  110. static void game_mode_context_enter(GameModeContext *self);
  111. static void game_mode_context_leave(GameModeContext *self);
  112. static char *game_mode_context_find_exe(pid_t pid);
  113. void game_mode_context_init(GameModeContext *self)
  114. {
  115. if (had_context_init) {
  116. LOG_ERROR("Context already initialised\n");
  117. return;
  118. }
  119. had_context_init = true;
  120. self->refcount = ATOMIC_VAR_INIT(0);
  121. /* clear the initial string */
  122. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  123. /* Initialise the config */
  124. self->config = config_create();
  125. config_init(self->config);
  126. pthread_rwlock_init(&self->rwlock, NULL);
  127. pthread_mutex_init(&self->reaper.mutex, NULL);
  128. pthread_cond_init(&self->reaper.condition, NULL);
  129. /* Get the reaper thread going */
  130. self->reaper.running = true;
  131. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  132. FATAL_ERROR("Couldn't construct a new thread");
  133. }
  134. }
  135. void game_mode_context_destroy(GameModeContext *self)
  136. {
  137. if (!had_context_init) {
  138. return;
  139. }
  140. /* Leave game mode now */
  141. if (game_mode_context_num_clients(self) > 0) {
  142. game_mode_context_leave(self);
  143. }
  144. had_context_init = false;
  145. game_mode_client_free(self->client);
  146. self->reaper.running = false;
  147. /* We might be stuck waiting, so wake it up again */
  148. pthread_mutex_lock(&self->reaper.mutex);
  149. pthread_cond_signal(&self->reaper.condition);
  150. pthread_mutex_unlock(&self->reaper.mutex);
  151. /* Join the thread as soon as possible */
  152. pthread_join(self->reaper.thread, NULL);
  153. pthread_cond_destroy(&self->reaper.condition);
  154. pthread_mutex_destroy(&self->reaper.mutex);
  155. /* Destroy the config object */
  156. config_destroy(self->config);
  157. pthread_rwlock_destroy(&self->rwlock);
  158. }
  159. /**
  160. * Apply scheduling policies
  161. *
  162. * This tries to change the scheduler of the client to soft realtime mode
  163. * available in some kernels as SCHED_ISO. It also tries to adjust the nice
  164. * level. If some of each fail, ignore this and log a warning.
  165. *
  166. * We don't need to store the current values because when the client exits,
  167. * everything will be good: Scheduling is only applied to the client and
  168. * its children.
  169. */
  170. static void game_mode_apply_scheduler(GameModeContext *self, pid_t client)
  171. {
  172. LOG_MSG("Setting scheduling policies...\n");
  173. /*
  174. * read configuration "renice" (1..20)
  175. */
  176. long int renice = 0;
  177. config_get_renice_value(self->config, &renice);
  178. if ((renice < 1) || (renice > 20)) {
  179. LOG_ERROR("Renice value [%ld] defaulted to [%d].\n", renice, -NICE_DEFAULT_PRIORITY);
  180. renice = NICE_DEFAULT_PRIORITY;
  181. } else {
  182. renice = -renice;
  183. }
  184. /*
  185. * don't adjust priority if it was already adjusted
  186. */
  187. if (getpriority(PRIO_PROCESS, (id_t)client) != 0) {
  188. LOG_ERROR("Client [%d] already reniced, ignoring.\n", client);
  189. } else if (setpriority(PRIO_PROCESS, (id_t)client, (int)renice)) {
  190. LOG_ERROR(
  191. "Renicing client [%d] failed with error %d, ignoring (your user may not have "
  192. "permission to do this).\n",
  193. client,
  194. errno);
  195. }
  196. /*
  197. * read configuration "softrealtime" (on, off, auto)
  198. */
  199. char softrealtime[CONFIG_VALUE_MAX] = { 0 };
  200. config_get_soft_realtime(self->config, softrealtime);
  201. /*
  202. * Enable unconditionally or auto-detect soft realtime usage,
  203. * auto detection is based on observations where dual-core CPU suffered
  204. * priority inversion problems with the graphics driver thus running
  205. * slower as a result, so enable only with more than 3 cores.
  206. */
  207. bool enable_softrealtime = (strcmp(softrealtime, "on") == 0) || (get_nprocs() > 3);
  208. /*
  209. * Actually apply the scheduler policy if not explicitly turned off
  210. */
  211. if (!(strcmp(softrealtime, "off") == 0) && (enable_softrealtime)) {
  212. const struct sched_param p = { .sched_priority = 0 };
  213. if (sched_setscheduler(client, SCHED_ISO | SCHED_RESET_ON_FORK, &p)) {
  214. LOG_ERROR(
  215. "Setting client [%d] to SCHED_ISO failed with error %d, ignoring (your "
  216. "kernel may not support this).\n",
  217. client,
  218. errno);
  219. }
  220. } else {
  221. LOG_ERROR("Not using softrealtime, setting is '%s'.\n", softrealtime);
  222. }
  223. }
  224. /**
  225. * Apply io priorities
  226. *
  227. * This tries to change the io priority of the client to a value specified
  228. * and can possibly reduce lags or latency when a game has to load assets
  229. * on demand.
  230. */
  231. static void game_mode_apply_ioprio(GameModeContext *self, pid_t client)
  232. {
  233. LOG_MSG("Setting scheduling policies...\n");
  234. /*
  235. * read configuration "ioprio" (0..7)
  236. */
  237. int ioprio = 0;
  238. config_get_ioprio_value(self->config, &ioprio);
  239. if (IOPRIO_RESET_DEFAULT == ioprio) {
  240. LOG_MSG("IO priority will be reset to default behavior (based on CPU priority).\n");
  241. ioprio = 0;
  242. } else if (IOPRIO_DONT_SET == ioprio) {
  243. return;
  244. } else {
  245. /* maybe clamp the value */
  246. int invalid_ioprio = ioprio;
  247. ioprio = CLAMP(0, 7, ioprio);
  248. if (ioprio != invalid_ioprio)
  249. LOG_ERROR("IO priority value %d invalid, clamping to %d\n", invalid_ioprio, ioprio);
  250. /* We support only IOPRIO_CLASS_BE as IOPRIO_CLASS_RT required CAP_SYS_ADMIN */
  251. ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, ioprio);
  252. }
  253. /*
  254. * Actually apply the io priority
  255. */
  256. int c = IOPRIO_PRIO_CLASS(ioprio), p = IOPRIO_PRIO_DATA(ioprio);
  257. if (ioprio_set(IOPRIO_WHO_PROCESS, client, ioprio) == 0) {
  258. if (0 == ioprio)
  259. LOG_MSG("Resetting client [%d] IO priority.\n", client);
  260. else
  261. LOG_MSG("Setting client [%d] IO priority to (%d,%d).\n", client, c, p);
  262. } else {
  263. LOG_ERROR("Setting client [%d] IO priority to (%d,%d) failed with error %d, ignoring\n",
  264. client,
  265. c,
  266. p,
  267. errno);
  268. }
  269. }
  270. /**
  271. * Pivot into game mode.
  272. *
  273. * This is only possible after game_mode_context_init has made a GameModeContext
  274. * usable, and should always be followed by a game_mode_context_leave.
  275. */
  276. static void game_mode_context_enter(GameModeContext *self)
  277. {
  278. LOG_MSG("Entering Game Mode...\n");
  279. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  280. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  281. memset(scripts, 0, sizeof(scripts));
  282. config_get_gamemode_start_scripts(self->config, scripts);
  283. unsigned int i = 0;
  284. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  285. LOG_MSG("Executing script [%s]\n", scripts[i]);
  286. int err;
  287. if ((err = system(scripts[i])) != 0) {
  288. /* Log the failure, but this is not fatal */
  289. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  290. }
  291. i++;
  292. }
  293. /* Read the initial governor state so we can revert it correctly */
  294. const char *initial_state = get_gov_state();
  295. if (initial_state) {
  296. /* store the initial cpu governor mode */
  297. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  298. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  299. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  300. /* Choose the desired governor */
  301. char desired[CONFIG_VALUE_MAX] = { 0 };
  302. config_get_desired_governor(self->config, desired);
  303. const char *desiredGov = desired[0] != '\0' ? desired : "performance";
  304. /* set the governor to performance */
  305. if (!set_governors(desiredGov)) {
  306. /* if the set fails, clear the initial mode so we don't try and reset it back and fail
  307. * again, presumably */
  308. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  309. }
  310. }
  311. }
  312. /**
  313. * Pivot out of game mode.
  314. *
  315. * Should only be called after both init and game_mode_context_enter have
  316. * been performed.
  317. */
  318. static void game_mode_context_leave(GameModeContext *self)
  319. {
  320. LOG_MSG("Leaving Game Mode...\n");
  321. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  322. /* Reset the governer state back to initial */
  323. if (self->initial_cpu_mode[0] != '\0') {
  324. /* Choose the governor to reset to, using the config to override */
  325. char defaultgov[CONFIG_VALUE_MAX] = { 0 };
  326. config_get_default_governor(self->config, defaultgov);
  327. const char *gov_mode = defaultgov[0] != '\0' ? defaultgov : self->initial_cpu_mode;
  328. set_governors(gov_mode);
  329. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  330. }
  331. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  332. memset(scripts, 0, sizeof(scripts));
  333. config_get_gamemode_end_scripts(self->config, scripts);
  334. unsigned int i = 0;
  335. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  336. LOG_MSG("Executing script [%s]\n", scripts[i]);
  337. int err;
  338. if ((err = system(scripts[i])) != 0) {
  339. /* Log the failure, but this is not fatal */
  340. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  341. }
  342. i++;
  343. }
  344. }
  345. /**
  346. * Automatically expire all dead processes
  347. *
  348. * This has to take special care to ensure thread safety and ensuring that our
  349. * pointer is never cached incorrectly.
  350. */
  351. static void game_mode_context_auto_expire(GameModeContext *self)
  352. {
  353. bool removing = true;
  354. while (removing) {
  355. pthread_rwlock_rdlock(&self->rwlock);
  356. removing = false;
  357. /* Each time we hit an expired game, start the loop back */
  358. for (GameModeClient *client = self->client; client; client = client->next) {
  359. if (kill(client->pid, 0) != 0) {
  360. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  361. pthread_rwlock_unlock(&self->rwlock);
  362. game_mode_context_unregister(self, client->pid);
  363. removing = true;
  364. break;
  365. }
  366. }
  367. if (!removing) {
  368. pthread_rwlock_unlock(&self->rwlock);
  369. break;
  370. }
  371. }
  372. }
  373. /**
  374. * Determine if the client is already known to the context
  375. */
  376. static bool game_mode_context_has_client(GameModeContext *self, pid_t client)
  377. {
  378. bool found = false;
  379. pthread_rwlock_rdlock(&self->rwlock);
  380. /* Walk all clients and find a matching pid */
  381. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  382. if (cl->pid == client) {
  383. found = true;
  384. break;
  385. }
  386. }
  387. pthread_rwlock_unlock(&self->rwlock);
  388. return found;
  389. }
  390. /**
  391. * Helper to grab the current number of clients we know about
  392. */
  393. static int game_mode_context_num_clients(GameModeContext *self)
  394. {
  395. return atomic_load(&self->refcount);
  396. }
  397. bool game_mode_context_register(GameModeContext *self, pid_t client)
  398. {
  399. /* Construct a new client if we can */
  400. GameModeClient *cl = NULL;
  401. char *executable = NULL;
  402. /* Cap the total number of active clients */
  403. if (game_mode_context_num_clients(self) + 1 > MAX_GAMES) {
  404. LOG_ERROR("Max games (%d) reached, not registering %d\n", MAX_GAMES, client);
  405. return false;
  406. }
  407. errno = 0;
  408. /* Check the PID first to spare a potentially expensive lookup for the exe */
  409. if (game_mode_context_has_client(self, client)) {
  410. LOG_ERROR("Addition requested for already known process [%d]\n", client);
  411. goto error_cleanup;
  412. }
  413. /* Lookup the executable first */
  414. executable = game_mode_context_find_exe(client);
  415. if (!executable)
  416. goto error_cleanup;
  417. /* Check our blacklist and whitelist */
  418. if (!config_get_client_whitelisted(self->config, executable)) {
  419. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", executable);
  420. goto error_cleanup;
  421. } else if (config_get_client_blacklisted(self->config, executable)) {
  422. LOG_MSG("Client [%s] was rejected (in blacklist)\n", executable);
  423. goto error_cleanup;
  424. }
  425. /* From now on we depend on the client, initialize it */
  426. cl = game_mode_client_new(client, executable);
  427. if (cl)
  428. executable = NULL; // ownership has been delegated
  429. else
  430. goto error_cleanup;
  431. /* Begin a write lock now to insert our new client at list start */
  432. pthread_rwlock_wrlock(&self->rwlock);
  433. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  434. /* Update the list */
  435. cl->next = self->client;
  436. self->client = cl;
  437. pthread_rwlock_unlock(&self->rwlock);
  438. /* First add, init */
  439. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  440. game_mode_context_enter(self);
  441. }
  442. /* Apply scheduler policies */
  443. game_mode_apply_scheduler(self, client);
  444. /* Apply io priorities */
  445. game_mode_apply_ioprio(self, client);
  446. return true;
  447. error_cleanup:
  448. if (errno != 0)
  449. LOG_ERROR("Failed to register client [%d]: %s\n", client, strerror(errno));
  450. free(executable);
  451. game_mode_client_free(cl);
  452. return false;
  453. }
  454. bool game_mode_context_unregister(GameModeContext *self, pid_t client)
  455. {
  456. GameModeClient *cl = NULL;
  457. GameModeClient *prev = NULL;
  458. bool found = false;
  459. /* Requires locking. */
  460. pthread_rwlock_wrlock(&self->rwlock);
  461. for (prev = cl = self->client; cl; cl = cl->next) {
  462. if (cl->pid != client) {
  463. prev = cl;
  464. continue;
  465. }
  466. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  467. /* Found it */
  468. found = true;
  469. prev->next = cl->next;
  470. if (cl == self->client) {
  471. self->client = cl->next;
  472. }
  473. cl->next = NULL;
  474. game_mode_client_free(cl);
  475. break;
  476. }
  477. /* Unlock here, potentially yielding */
  478. pthread_rwlock_unlock(&self->rwlock);
  479. if (!found) {
  480. LOG_ERROR("Removal requested for unknown process [%d]\n", client);
  481. return false;
  482. }
  483. /* When we hit bottom then end the game mode */
  484. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  485. game_mode_context_leave(self);
  486. }
  487. return true;
  488. }
  489. int game_mode_context_query_status(GameModeContext *self, pid_t client)
  490. {
  491. GameModeClient *cl = NULL;
  492. int ret = 0;
  493. /*
  494. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  495. * see game_mode_context_register and game_mode_context_unregister
  496. */
  497. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  498. ret++;
  499. /* Check if the current client is registered */
  500. /* Requires locking. */
  501. pthread_rwlock_rdlock(&self->rwlock);
  502. for (cl = self->client; cl; cl = cl->next) {
  503. if (cl->pid != client) {
  504. continue;
  505. }
  506. /* Found it */
  507. ret++;
  508. break;
  509. }
  510. /* Unlock here, potentially yielding */
  511. pthread_rwlock_unlock(&self->rwlock);
  512. }
  513. return ret;
  514. }
  515. /**
  516. * Construct a new GameModeClient for the given process ID
  517. *
  518. * This is deliberately OOM safe
  519. */
  520. static GameModeClient *game_mode_client_new(pid_t pid, char *executable)
  521. {
  522. GameModeClient c = {
  523. .executable = executable,
  524. .next = NULL,
  525. .pid = pid,
  526. };
  527. GameModeClient *ret = NULL;
  528. ret = calloc(1, sizeof(struct GameModeClient));
  529. if (!ret) {
  530. return NULL;
  531. }
  532. *ret = c;
  533. return ret;
  534. }
  535. /**
  536. * Free a client and the next element in the list.
  537. */
  538. static void game_mode_client_free(GameModeClient *client)
  539. {
  540. if (!client) {
  541. return;
  542. }
  543. if (client->next) {
  544. game_mode_client_free(client->next);
  545. }
  546. if (client->executable) {
  547. free(client->executable);
  548. }
  549. free(client);
  550. }
  551. /**
  552. * We continuously run until told otherwise.
  553. */
  554. static void *game_mode_context_reaper(void *userdata)
  555. {
  556. /* Stack, not allocated, won't disappear. */
  557. GameModeContext *self = userdata;
  558. long reaper_interval = 0.0f;
  559. config_get_reaper_thread_frequency(self->config, &reaper_interval);
  560. struct timespec ts = { 0, 0 };
  561. ts.tv_sec = time(NULL) + reaper_interval;
  562. while (self->reaper.running) {
  563. /* Wait for condition */
  564. pthread_mutex_lock(&self->reaper.mutex);
  565. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  566. pthread_mutex_unlock(&self->reaper.mutex);
  567. /* Highly possible the main thread woke us up to exit */
  568. if (!self->reaper.running) {
  569. return NULL;
  570. }
  571. /* Expire remaining entries */
  572. game_mode_context_auto_expire(self);
  573. ts.tv_sec = time(NULL) + reaper_interval;
  574. }
  575. return NULL;
  576. }
  577. GameModeContext *game_mode_context_instance()
  578. {
  579. return &instance;
  580. }
  581. /**
  582. * Lookup the process environment for a specific variable or return NULL.
  583. * Requires an open directory FD from /proc/PID.
  584. */
  585. static char *game_mode_lookup_proc_env(int proc_fd, const char *var)
  586. {
  587. char *environ = NULL;
  588. int fd = openat(proc_fd, "environ", O_RDONLY | O_CLOEXEC);
  589. if (fd != -1) {
  590. FILE *stream = fdopen(fd, "r");
  591. if (stream) {
  592. /* Read every \0 terminated line from the environment */
  593. char *line = NULL;
  594. size_t len = 0;
  595. size_t pos = strlen(var) + 1;
  596. while (!environ && (getdelim(&line, &len, 0, stream) != -1)) {
  597. /* Find a match including the "=" suffix */
  598. if ((len > pos) && (strncmp(line, var, strlen(var)) == 0) && (line[pos - 1] == '='))
  599. environ = strndup(line + pos, len - pos);
  600. }
  601. free(line);
  602. fclose(stream);
  603. } else
  604. close(fd);
  605. }
  606. /* If found variable is empty, skip it */
  607. if (environ && !strlen(environ)) {
  608. free(environ);
  609. environ = NULL;
  610. }
  611. return environ;
  612. }
  613. /**
  614. * Lookup the home directory of the user in a safe way.
  615. */
  616. static char *game_mode_lookup_user_home(void)
  617. {
  618. /* Try loading env HOME first */
  619. const char *home = secure_getenv("HOME");
  620. if (!home) {
  621. /* If HOME is not defined (or out of context), fall back to passwd */
  622. struct passwd *pw = getpwuid(getuid());
  623. if (!pw)
  624. return NULL;
  625. home = pw->pw_dir;
  626. }
  627. /* Try to allocate into our heap */
  628. return home ? strdup(home) : NULL;
  629. }
  630. /**
  631. * Attempt to resolve the exe for wine-preloader.
  632. * This function is used if game_mode_context_find_exe() identified the
  633. * process as wine-preloader. Returns NULL when resolve fails.
  634. */
  635. static char *game_mode_resolve_wine_preloader(pid_t pid)
  636. {
  637. char buffer[PATH_MAX];
  638. char *proc_path = NULL, *wine_exe = NULL, *wineprefix = NULL;
  639. int proc_fd = -1;
  640. if (!(proc_path = safe_snprintf(buffer, "/proc/%d", pid)))
  641. goto fail;
  642. /* Open the directory, we are potentially reading multiple files from it */
  643. if (-1 == (proc_fd = open(proc_path, O_RDONLY | O_CLOEXEC)))
  644. goto fail_proc;
  645. /* Open the command line */
  646. int fd = openat(proc_fd, "cmdline", O_RDONLY | O_CLOEXEC);
  647. if (fd != -1) {
  648. FILE *stream = fdopen(fd, "r");
  649. if (stream) {
  650. char *argv = NULL;
  651. size_t args = 0;
  652. int argc = 0;
  653. while (!wine_exe && (argc++ < 2) && (getdelim(&argv, &args, 0, stream) != -1)) {
  654. /* If we see the wine loader here, we have to use the next argument */
  655. if (strtail(argv, "/wine") || strtail(argv, "/wine64"))
  656. continue;
  657. free(wine_exe); // just in case
  658. /* Check presence of the drive letter, we assume that below */
  659. wine_exe = args > 2 && argv[1] == ':' ? strndup(argv, args) : NULL;
  660. }
  661. free(argv);
  662. fclose(stream);
  663. } else
  664. close(fd);
  665. }
  666. /* Did we get wine exe from cmdline? */
  667. if (wine_exe)
  668. LOG_MSG("Detected wine exe for client %d [%s].\n", pid, wine_exe);
  669. else
  670. goto fail_cmdline;
  671. /* Open the process environment and find the WINEPREFIX */
  672. errno = 0;
  673. if (!(wineprefix = game_mode_lookup_proc_env(proc_fd, "WINEPREFIX"))) {
  674. /* Lookup user home instead only if there was no error */
  675. char *home = NULL;
  676. if (errno == 0)
  677. home = game_mode_lookup_user_home();
  678. /* Append "/.wine" if we found the user home */
  679. if (home)
  680. wineprefix = safe_snprintf(buffer, "%s/.wine", home);
  681. /* Cleanup and check result */
  682. free(home);
  683. if (!wineprefix)
  684. goto fail_env;
  685. }
  686. /* Wine prefix was detected, log this for diagnostics */
  687. LOG_MSG("Detected wine prefix for client %d: '%s'\n", pid, wineprefix);
  688. /* Convert Windows to Unix path separators */
  689. char *ix = wine_exe;
  690. while (ix != NULL)
  691. (ix = strchr(ix, '\\')) && (*ix++ = '/');
  692. /* Convert the drive letter to lcase because wine handles it this way in the prefix */
  693. wine_exe[0] = (char)tolower(wine_exe[0]);
  694. /* Convert relative wine exe path to full unix path */
  695. char *wine_path = safe_snprintf(buffer, "%s/dosdevices/%s", wineprefix, wine_exe);
  696. free(wine_exe);
  697. wine_exe = wine_path ? realpath(wine_path, NULL) : NULL;
  698. free(wine_path);
  699. /* Fine? Successo? Fortuna! */
  700. if (wine_exe)
  701. LOG_MSG("Successfully mapped wine client %d [%s].\n", pid, wine_exe);
  702. else
  703. goto fail;
  704. error_cleanup:
  705. close(proc_fd);
  706. free(wineprefix);
  707. free(proc_path);
  708. return wine_exe;
  709. fail:
  710. LOG_ERROR("Unable to find wine executable for client %d: %s\n", pid, strerror(errno));
  711. goto error_cleanup;
  712. fail_cmdline:
  713. LOG_ERROR("Wine loader has no accepted cmdline for client %d yet, deferring.\n", pid);
  714. goto error_cleanup;
  715. fail_env:
  716. LOG_ERROR("Failed to access process environment in '%s': %s\n", proc_path, strerror(errno));
  717. goto error_cleanup;
  718. fail_proc:
  719. LOG_ERROR("Failed to access process data in '%s': %s\n", proc_path, strerror(errno));
  720. goto error_cleanup;
  721. }
  722. /**
  723. * Attempt to locate the exe for the process.
  724. * We might run into issues if the process is running under an odd umask.
  725. */
  726. static char *game_mode_context_find_exe(pid_t pid)
  727. {
  728. char buffer[PATH_MAX];
  729. char *proc_path = NULL, *wine_exe = NULL;
  730. if (!(proc_path = safe_snprintf(buffer, "/proc/%d/exe", pid)))
  731. goto fail;
  732. /* Allocate the realpath if possible */
  733. char *exe = realpath(proc_path, NULL);
  734. free(proc_path);
  735. if (!exe)
  736. goto fail;
  737. /* Detect if the process is a wine loader process */
  738. if (strtail(exe, "/wine-preloader") || strtail(exe, "/wine64-preloader")) {
  739. LOG_MSG("Detected wine preloader for client %d [%s].\n", pid, exe);
  740. goto wine_preloader;
  741. }
  742. if (strtail(exe, "/wine") || strtail(exe, "/wine64")) {
  743. LOG_MSG("Detected wine loader for client %d [%s].\n", pid, exe);
  744. goto wine_preloader;
  745. }
  746. return exe;
  747. wine_preloader:
  748. wine_exe = game_mode_resolve_wine_preloader(pid);
  749. if (wine_exe) {
  750. free(exe);
  751. exe = wine_exe;
  752. return exe;
  753. }
  754. /* We have to ignore this because the wine process is in some sort
  755. * of respawn mode
  756. */
  757. free(exe);
  758. fail:
  759. if (errno != 0) // otherwise a proper message was logged before
  760. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  761. return NULL;
  762. }