client_impl.c 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. Copyright (c) 2017-2019, 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 <common-helpers.h>
  28. #include <common-pidfds.h>
  29. #include <dbus/dbus.h>
  30. #include <errno.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <sys/stat.h>
  35. #include <sys/types.h>
  36. #include <unistd.h>
  37. // For developmental purposes
  38. #define DO_TRACE 0
  39. // D-Bus name, path, iface
  40. #define DAEMON_DBUS_NAME "com.feralinteractive.GameMode"
  41. #define DAEMON_DBUS_PATH "/com/feralinteractive/GameMode"
  42. #define DAEMON_DBUS_IFACE "com.feralinteractive.GameMode"
  43. #define PORTAL_DBUS_NAME "org.freedesktop.portal.Desktop"
  44. #define PORTAL_DBUS_PATH "/org/freedesktop/portal/desktop"
  45. #define PORTAL_DBUS_IFACE "org.freedesktop.portal.GameMode"
  46. // Cleanup macros
  47. #define _cleanup_(x) __attribute__((cleanup(x)))
  48. #define _cleanup_bus_ _cleanup_(hop_off_the_bus)
  49. #define _cleanup_msg_ _cleanup_(cleanup_msg)
  50. #define _cleanup_dpc_ _cleanup_(cleanup_pending_call)
  51. #define _cleanup_fds_ _cleanup_(cleanup_fd_array)
  52. #ifdef NDEBUG
  53. #define DEBUG(...)
  54. #else
  55. #define DEBUG(...) fprintf(stderr, __VA_ARGS__)
  56. #endif
  57. #if DO_TRACE
  58. #define TRACE(...) fprintf(stderr, __VA_ARGS__)
  59. #else
  60. #define TRACE(...)
  61. #endif
  62. // Prototypes
  63. static int log_error(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
  64. // Storage for error strings
  65. static char error_string[512] = { 0 };
  66. // memory helpers
  67. static void cleanup_fd_array(int **fdlist)
  68. {
  69. if (fdlist == NULL || *fdlist == NULL)
  70. return;
  71. int errsave = errno;
  72. for (int *fd = *fdlist; *fd != -1; fd++) {
  73. TRACE("GM Closing fd %d\n", *fd);
  74. (void)close(*fd);
  75. }
  76. errno = errsave;
  77. free(*fdlist);
  78. }
  79. // Allocate a -1 termianted array of ints
  80. static inline int *alloc_fd_array(int n)
  81. {
  82. int *fds;
  83. size_t count = (size_t)n + 1; /* -1, terminated */
  84. fds = (int *)malloc(sizeof(int) * count);
  85. for (size_t i = 0; i < count; i++)
  86. fds[i] = -1;
  87. return fds;
  88. }
  89. // Helper to check if we are running inside a flatpak
  90. static int in_flatpak(void)
  91. {
  92. static int status = -1;
  93. if (status == -1) {
  94. struct stat sb;
  95. int r;
  96. r = lstat("/.flatpak-info", &sb);
  97. status = r == 0 && sb.st_size > 0;
  98. }
  99. return status;
  100. }
  101. static int log_error(const char *fmt, ...)
  102. {
  103. va_list args;
  104. int n;
  105. va_start(args, fmt);
  106. n = vsnprintf(error_string, sizeof(error_string), fmt, args);
  107. va_end(args);
  108. if (n < 0)
  109. DEBUG("Failed to format error string");
  110. else if ((size_t)n >= sizeof(error_string))
  111. DEBUG("Error log overflow");
  112. fprintf(stderr, "GameMode ERROR: %s\n", error_string);
  113. return -1;
  114. }
  115. static void hop_off_the_bus(DBusConnection **bus)
  116. {
  117. if (bus == NULL)
  118. return;
  119. dbus_connection_unref(*bus);
  120. }
  121. static DBusConnection *hop_on_the_bus(void)
  122. {
  123. DBusConnection *bus;
  124. DBusError err;
  125. dbus_error_init(&err);
  126. bus = dbus_bus_get(DBUS_BUS_SESSION, &err);
  127. if (bus == NULL) {
  128. log_error("Could not connect to bus: %s", err.message);
  129. dbus_error_free(&err);
  130. }
  131. return bus;
  132. }
  133. /* cleanup functions */
  134. static void cleanup_msg(DBusMessage **msg)
  135. {
  136. if (msg == NULL || *msg == NULL)
  137. return;
  138. dbus_message_unref(*msg);
  139. }
  140. static void cleanup_pending_call(DBusPendingCall **call)
  141. {
  142. if (call == NULL || *call == NULL)
  143. return;
  144. dbus_pending_call_unref(*call);
  145. }
  146. /* internal API */
  147. static int make_request(DBusConnection *bus, int native, int use_pidfds, const char *method,
  148. pid_t *pids, int npids, DBusError *error)
  149. {
  150. _cleanup_msg_ DBusMessage *msg = NULL;
  151. _cleanup_dpc_ DBusPendingCall *call = NULL;
  152. _cleanup_fds_ int *fds = NULL;
  153. char action[256] = {
  154. 0,
  155. };
  156. DBusError err;
  157. DBusMessageIter iter;
  158. int res = -1;
  159. TRACE("GM: Incoming request: %s, npids: %d, native: %d pifds: %d\n",
  160. method,
  161. npids,
  162. native,
  163. use_pidfds);
  164. if (use_pidfds) {
  165. fds = alloc_fd_array(npids);
  166. res = open_pidfds(pids, fds, npids);
  167. if (res != npids) {
  168. dbus_set_error(error, DBUS_ERROR_FAILED, "Could not open pidfd for %d", (int)pids[res]);
  169. return -1;
  170. }
  171. if (strstr(method, "ByPID"))
  172. snprintf(action, sizeof(action), "%sFd", method);
  173. else
  174. snprintf(action, sizeof(action), "%sByPIDFd", method);
  175. method = action;
  176. }
  177. TRACE("GM: Making request: %s, npids: %d, native: %d pifds: %d\n",
  178. method,
  179. npids,
  180. native,
  181. use_pidfds);
  182. // If we are inside a flatpak we need to talk to the portal instead
  183. const char *dest = native ? DAEMON_DBUS_NAME : PORTAL_DBUS_NAME;
  184. const char *path = native ? DAEMON_DBUS_PATH : PORTAL_DBUS_PATH;
  185. const char *iface = native ? DAEMON_DBUS_IFACE : PORTAL_DBUS_IFACE;
  186. msg = dbus_message_new_method_call(dest, path, iface, method);
  187. if (!msg) {
  188. dbus_set_error_const(error, DBUS_ERROR_FAILED, "Could not create dbus message");
  189. return -1;
  190. }
  191. dbus_message_iter_init_append(msg, &iter);
  192. for (int i = 0; i < npids; i++) {
  193. dbus_int32_t p;
  194. int type;
  195. if (use_pidfds) {
  196. type = DBUS_TYPE_UNIX_FD;
  197. p = (dbus_int32_t)fds[i];
  198. } else {
  199. type = DBUS_TYPE_INT32;
  200. p = (dbus_int32_t)pids[i];
  201. }
  202. dbus_message_iter_append_basic(&iter, type, &p);
  203. }
  204. dbus_connection_send_with_reply(bus, msg, &call, -1);
  205. dbus_connection_flush(bus);
  206. dbus_message_unref(msg);
  207. msg = NULL;
  208. dbus_pending_call_block(call);
  209. msg = dbus_pending_call_steal_reply(call);
  210. if (msg == NULL) {
  211. dbus_set_error_const(error, DBUS_ERROR_FAILED, "Did not receive a reply");
  212. return -1;
  213. }
  214. dbus_error_init(&err);
  215. res = -1;
  216. if (dbus_set_error_from_message(&err, msg)) {
  217. dbus_set_error(error,
  218. err.name,
  219. "Could not call method '%s' on '%s': %s",
  220. method,
  221. dest,
  222. err.message);
  223. } else if (!dbus_message_iter_init(msg, &iter) ||
  224. dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) {
  225. dbus_set_error(error, DBUS_ERROR_INVALID_SIGNATURE, "Failed to parse response");
  226. } else {
  227. dbus_message_iter_get_basic(&iter, &res);
  228. }
  229. /* free the local error */
  230. if (dbus_error_is_set(&err))
  231. dbus_error_free(&err);
  232. return res;
  233. }
  234. static int gamemode_request(const char *method, pid_t for_pid)
  235. {
  236. _cleanup_bus_ DBusConnection *bus = NULL;
  237. static int use_pidfs = 1;
  238. DBusError err;
  239. pid_t pids[2];
  240. int npids;
  241. int native;
  242. int res = -1;
  243. native = !in_flatpak();
  244. /* pid[0] is the client, i.e. the game
  245. * pid[1] is the requestor, i.e. this process
  246. *
  247. * we setup the array such that pids[1] will always be a valid
  248. * pid, because if we are going to use the pidfd based API,
  249. * both pids are being sent, even if they are the same
  250. */
  251. pids[1] = getpid();
  252. pids[0] = for_pid != 0 ? for_pid : pids[1];
  253. TRACE("GM: [%d] request '%s' received (by: %d) [portal: %s]\n",
  254. (int)pids[0],
  255. method,
  256. (int)pids[1],
  257. (native ? "n" : "y"));
  258. bus = hop_on_the_bus();
  259. if (bus == NULL)
  260. return -1;
  261. dbus_error_init(&err);
  262. retry:
  263. if (for_pid != 0 || use_pidfs)
  264. npids = 2;
  265. else
  266. npids = 1;
  267. res = make_request(bus, native, use_pidfs, method, pids, npids, &err);
  268. if (res == -1 && use_pidfs && dbus_error_is_set(&err)) {
  269. TRACE("GM: Request with pidfds failed (%s). Retrying.\n", err.message);
  270. use_pidfs = 0;
  271. dbus_error_free(&err);
  272. goto retry;
  273. }
  274. if (res == -1 && dbus_error_is_set(&err))
  275. log_error("D-Bus error: %s", err.message);
  276. TRACE("GM: [%d] request '%s' done: %d\n", (int)pids[0], method, res);
  277. if (dbus_error_is_set(&err))
  278. dbus_error_free(&err);
  279. return res;
  280. }
  281. // Get the error string
  282. extern const char *real_gamemode_error_string(void)
  283. {
  284. return error_string;
  285. }
  286. // Wrapper to call RegisterGame
  287. extern int real_gamemode_request_start(void)
  288. {
  289. return gamemode_request("RegisterGame", 0);
  290. }
  291. // Wrapper to call UnregisterGame
  292. extern int real_gamemode_request_end(void)
  293. {
  294. return gamemode_request("UnregisterGame", 0);
  295. }
  296. // Wrapper to call QueryStatus
  297. extern int real_gamemode_query_status(void)
  298. {
  299. return gamemode_request("QueryStatus", 0);
  300. }
  301. // Wrapper to call RegisterGameByPID
  302. extern int real_gamemode_request_start_for(pid_t pid)
  303. {
  304. return gamemode_request("RegisterGameByPID", pid);
  305. }
  306. // Wrapper to call UnregisterGameByPID
  307. extern int real_gamemode_request_end_for(pid_t pid)
  308. {
  309. return gamemode_request("UnregisterGameByPID", pid);
  310. }
  311. // Wrapper to call QueryStatusByPID
  312. extern int real_gamemode_query_status_for(pid_t pid)
  313. {
  314. return gamemode_request("QueryStatusByPID", pid);
  315. }