client.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /*
  2. * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). All
  3. * rights reserved.
  4. * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /**
  25. * @file
  26. *
  27. * This file contains functionality for identifying clients by various
  28. * means. The primary purpose of identification is to simply aid in
  29. * finding out which clients are using X server and how they are using
  30. * it. For example, it's often necessary to monitor what requests
  31. * clients are executing (to spot bad behaviour) and how they are
  32. * allocating resources in X server (to spot excessive resource
  33. * usage).
  34. *
  35. * This framework automatically allocates information, that can be
  36. * used for client identification, when a client connects to the
  37. * server. The information is freed when the client disconnects. The
  38. * allocated information is just a collection of various IDs, such as
  39. * PID and process name for local clients, that are likely to be
  40. * useful in analyzing X server usage.
  41. *
  42. * Users of the framework can query ID information about clients at
  43. * any time. To avoid repeated polling of IDs the users can also
  44. * subscribe for notifications about the availability of ID
  45. * information. IDs have been allocated before ClientStateCallback is
  46. * called with ClientStateInitial state. Similarly the IDs will be
  47. * released after ClientStateCallback is called with ClientStateGone
  48. * state.
  49. *
  50. * Author: Rami Ylimäki <rami.ylimaki@vincit.fi>
  51. */
  52. #include <sys/stat.h>
  53. #include <fcntl.h>
  54. #include <unistd.h>
  55. #include "client.h"
  56. #include "os.h"
  57. #include "dixstruct.h"
  58. #ifdef __sun
  59. #include <errno.h>
  60. #include <procfs.h>
  61. #endif
  62. #ifdef __OpenBSD__
  63. #include <sys/param.h>
  64. #include <sys/sysctl.h>
  65. #include <sys/types.h>
  66. #include <kvm.h>
  67. #include <limits.h>
  68. #endif
  69. /**
  70. * Try to determine a PID for a client from its connection
  71. * information. This should be called only once when new client has
  72. * connected, use GetClientPid to determine the PID at other times.
  73. *
  74. * @param[in] client Connection linked to some process.
  75. *
  76. * @return PID of the client. Error (-1) if PID can't be determined
  77. * for the client.
  78. *
  79. * @see GetClientPid
  80. */
  81. pid_t
  82. DetermineClientPid(struct _Client * client)
  83. {
  84. LocalClientCredRec *lcc = NULL;
  85. pid_t pid = -1;
  86. if (client == NullClient)
  87. return pid;
  88. if (client == serverClient)
  89. return getpid();
  90. if (GetLocalClientCreds(client, &lcc) != -1) {
  91. if (lcc->fieldsSet & LCC_PID_SET)
  92. pid = lcc->pid;
  93. FreeLocalClientCreds(lcc);
  94. }
  95. return pid;
  96. }
  97. /**
  98. * Try to determine a command line string for a client based on its
  99. * PID. Note that mapping PID to a command hasn't been implemented for
  100. * some operating systems. This should be called only once when a new
  101. * client has connected, use GetClientCmdName/Args to determine the
  102. * string at other times.
  103. *
  104. * @param[in] pid Process ID of a client.
  105. * @param[out] cmdname Client process name without arguments. You must
  106. * release this by calling free. On error NULL is
  107. * returned. Pass NULL if you aren't interested in
  108. * this value.
  109. * @param[out] cmdargs Arguments to client process. Useful for
  110. * identifying a client that is executed from a
  111. * launcher program. You must release this by
  112. * calling free. On error NULL is returned. Pass
  113. * NULL if you aren't interested in this value.
  114. *
  115. * @see GetClientCmdName/Args
  116. */
  117. void
  118. DetermineClientCmd(pid_t pid, const char **cmdname, const char **cmdargs)
  119. {
  120. char path[PATH_MAX + 1];
  121. int totsize = 0;
  122. int fd = 0;
  123. if (cmdname)
  124. *cmdname = NULL;
  125. if (cmdargs)
  126. *cmdargs = NULL;
  127. if (pid == -1)
  128. return;
  129. #ifdef __sun /* Solaris */
  130. /* Solaris does not support /proc/pid/cmdline, but makes information
  131. * similar to what ps shows available in a binary structure in the
  132. * /proc/pid/psinfo file. */
  133. if (snprintf(path, sizeof(path), "/proc/%d/psinfo", pid) < 0)
  134. return;
  135. fd = open(path, O_RDONLY);
  136. if (fd < 0) {
  137. ErrorF("Failed to open %s: %s\n", path, strerror(errno));
  138. return;
  139. }
  140. else {
  141. psinfo_t psinfo = { 0 };
  142. char *sp;
  143. totsize = read(fd, &psinfo, sizeof(psinfo_t));
  144. close(fd);
  145. if (totsize <= 0)
  146. return;
  147. /* pr_psargs is the first PRARGSZ (80) characters of the command
  148. * line string - assume up to the first space is the command name,
  149. * since it's not delimited. While there is also pr_fname, that's
  150. * more limited, giving only the first 16 chars of the basename of
  151. * the file that was exec'ed, thus cutting off many long gnome
  152. * command names, or returning "isapython2.6" for all python scripts.
  153. */
  154. psinfo.pr_psargs[PRARGSZ - 1] = '\0';
  155. sp = strchr(psinfo.pr_psargs, ' ');
  156. if (sp)
  157. *sp++ = '\0';
  158. if (cmdname)
  159. *cmdname = strdup(psinfo.pr_psargs);
  160. if (cmdargs && sp)
  161. *cmdargs = strdup(sp);
  162. }
  163. #elif defined(__OpenBSD__)
  164. /* on OpenBSD use kvm_getargv() */
  165. {
  166. kvm_t *kd;
  167. char errbuf[_POSIX2_LINE_MAX];
  168. char **argv;
  169. struct kinfo_proc *kp;
  170. size_t len = 0;
  171. int i, n;
  172. kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
  173. if (kd == NULL)
  174. return;
  175. kp = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc),
  176. &n);
  177. if (n != 1)
  178. return;
  179. argv = kvm_getargv(kd, kp, 0);
  180. *cmdname = strdup(argv[0]);
  181. i = 1;
  182. while (argv[i] != NULL) {
  183. len += strlen(argv[i]) + 1;
  184. i++;
  185. }
  186. *cmdargs = calloc(1, len);
  187. i = 1;
  188. while (argv[i] != NULL) {
  189. strlcat(*cmdargs, argv[i], len);
  190. strlcat(*cmdargs, " ", len);
  191. i++;
  192. }
  193. kvm_close(kd);
  194. }
  195. #else /* Linux using /proc/pid/cmdline */
  196. /* Check if /proc/pid/cmdline exists. It's not supported on all
  197. * operating systems. */
  198. if (snprintf(path, sizeof(path), "/proc/%d/cmdline", pid) < 0)
  199. return;
  200. fd = open(path, O_RDONLY);
  201. if (fd < 0)
  202. return;
  203. /* Read the contents of /proc/pid/cmdline. It should contain the
  204. * process name and arguments. */
  205. totsize = read(fd, path, sizeof(path));
  206. close(fd);
  207. if (totsize <= 0)
  208. return;
  209. path[totsize - 1] = '\0';
  210. /* Contruct the process name without arguments. */
  211. if (cmdname) {
  212. *cmdname = strdup(path);
  213. }
  214. /* Construct the arguments for client process. */
  215. if (cmdargs) {
  216. int cmdsize = strlen(path) + 1;
  217. int argsize = totsize - cmdsize;
  218. char *args = NULL;
  219. if (argsize > 0)
  220. args = malloc(argsize);
  221. if (args) {
  222. int i = 0;
  223. for (i = 0; i < (argsize - 1); ++i) {
  224. const char c = path[cmdsize + i];
  225. args[i] = (c == '\0') ? ' ' : c;
  226. }
  227. args[argsize - 1] = '\0';
  228. *cmdargs = args;
  229. }
  230. }
  231. #endif
  232. }
  233. /**
  234. * Called when a new client connects. Allocates client ID information.
  235. *
  236. * @param[in] client Recently connected client.
  237. */
  238. void
  239. ReserveClientIds(struct _Client *client)
  240. {
  241. #ifdef CLIENTIDS
  242. if (client == NullClient)
  243. return;
  244. assert(!client->clientIds);
  245. client->clientIds = calloc(1, sizeof(ClientIdRec));
  246. if (!client->clientIds)
  247. return;
  248. client->clientIds->pid = DetermineClientPid(client);
  249. if (client->clientIds->pid != -1)
  250. DetermineClientCmd(client->clientIds->pid, &client->clientIds->cmdname,
  251. &client->clientIds->cmdargs);
  252. DebugF("client(%lx): Reserved pid(%d).\n",
  253. (unsigned long) client->clientAsMask, client->clientIds->pid);
  254. DebugF("client(%lx): Reserved cmdname(%s) and cmdargs(%s).\n",
  255. (unsigned long) client->clientAsMask,
  256. client->clientIds->cmdname ? client->clientIds->cmdname : "NULL",
  257. client->clientIds->cmdargs ? client->clientIds->cmdargs : "NULL");
  258. #endif /* CLIENTIDS */
  259. }
  260. /**
  261. * Called when an existing client disconnects. Frees client ID
  262. * information.
  263. *
  264. * @param[in] client Recently disconnected client.
  265. */
  266. void
  267. ReleaseClientIds(struct _Client *client)
  268. {
  269. #ifdef CLIENTIDS
  270. if (client == NullClient)
  271. return;
  272. if (!client->clientIds)
  273. return;
  274. DebugF("client(%lx): Released pid(%d).\n",
  275. (unsigned long) client->clientAsMask, client->clientIds->pid);
  276. DebugF("client(%lx): Released cmdline(%s) and cmdargs(%s).\n",
  277. (unsigned long) client->clientAsMask,
  278. client->clientIds->cmdname ? client->clientIds->cmdname : "NULL",
  279. client->clientIds->cmdargs ? client->clientIds->cmdargs : "NULL");
  280. free((void *) client->clientIds->cmdname); /* const char * */
  281. free((void *) client->clientIds->cmdargs); /* const char * */
  282. free(client->clientIds);
  283. client->clientIds = NULL;
  284. #endif /* CLIENTIDS */
  285. }
  286. /**
  287. * Get cached PID of a client.
  288. *
  289. * param[in] client Client whose PID has been already cached.
  290. *
  291. * @return Cached client PID. Error (-1) if called:
  292. * - before ClientStateInitial client state notification
  293. * - after ClientStateGone client state notification
  294. * - for remote clients
  295. *
  296. * @see DetermineClientPid
  297. */
  298. pid_t
  299. GetClientPid(struct _Client *client)
  300. {
  301. if (client == NullClient)
  302. return -1;
  303. if (!client->clientIds)
  304. return -1;
  305. return client->clientIds->pid;
  306. }
  307. /**
  308. * Get cached command name string of a client.
  309. *
  310. * param[in] client Client whose command line string has been already
  311. * cached.
  312. *
  313. * @return Cached client command name. Error (NULL) if called:
  314. * - before ClientStateInitial client state notification
  315. * - after ClientStateGone client state notification
  316. * - for remote clients
  317. * - on OS that doesn't support mapping of PID to command line
  318. *
  319. * @see DetermineClientCmd
  320. */
  321. const char *
  322. GetClientCmdName(struct _Client *client)
  323. {
  324. if (client == NullClient)
  325. return NULL;
  326. if (!client->clientIds)
  327. return NULL;
  328. return client->clientIds->cmdname;
  329. }
  330. /**
  331. * Get cached command arguments string of a client.
  332. *
  333. * param[in] client Client whose command line string has been already
  334. * cached.
  335. *
  336. * @return Cached client command arguments. Error (NULL) if called:
  337. * - before ClientStateInitial client state notification
  338. * - after ClientStateGone client state notification
  339. * - for remote clients
  340. * - on OS that doesn't support mapping of PID to command line
  341. *
  342. * @see DetermineClientCmd
  343. */
  344. const char *
  345. GetClientCmdArgs(struct _Client *client)
  346. {
  347. if (client == NullClient)
  348. return NULL;
  349. if (!client->clientIds)
  350. return NULL;
  351. return client->clientIds->cmdargs;
  352. }