D-Bus  1.13.6
dbus-sysdeps-util-unix.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps-util-unix.c Would be in dbus-sysdeps-unix.c, but not used in libdbus
3  *
4  * Copyright (C) 2002, 2003, 2004, 2005 Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24 
25 #include <config.h>
26 #include "dbus-sysdeps.h"
27 #include "dbus-sysdeps-unix.h"
28 #include "dbus-internals.h"
29 #include "dbus-list.h"
30 #include "dbus-pipe.h"
31 #include "dbus-protocol.h"
32 #include "dbus-string.h"
33 #define DBUS_USERDB_INCLUDES_PRIVATE 1
34 #include "dbus-userdb.h"
35 #include "dbus-test.h"
36 
37 #include <sys/types.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <signal.h>
42 #include <unistd.h>
43 #include <stdio.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <sys/stat.h>
47 #ifdef HAVE_SYS_RESOURCE_H
48 #include <sys/resource.h>
49 #endif
50 #include <grp.h>
51 #include <sys/socket.h>
52 #include <dirent.h>
53 #include <sys/un.h>
54 
55 #ifdef HAVE_SYS_SYSLIMITS_H
56 #include <sys/syslimits.h>
57 #endif
58 
59 #ifdef HAVE_SYSTEMD
60 #include <systemd/sd-daemon.h>
61 #endif
62 
63 #ifndef O_BINARY
64 #define O_BINARY 0
65 #endif
66 
84  DBusPipe *print_pid_pipe,
85  DBusError *error,
86  dbus_bool_t keep_umask)
87 {
88  const char *s;
89  pid_t child_pid;
90  DBusEnsureStandardFdsFlags flags;
91 
92  _dbus_verbose ("Becoming a daemon...\n");
93 
94  _dbus_verbose ("chdir to /\n");
95  if (chdir ("/") < 0)
96  {
98  "Could not chdir() to root directory");
99  return FALSE;
100  }
101 
102  _dbus_verbose ("forking...\n");
103 
104  /* Make sure our output buffers aren't redundantly printed by both the
105  * parent and the child */
106  fflush (stdout);
107  fflush (stderr);
108 
109  switch ((child_pid = fork ()))
110  {
111  case -1:
112  _dbus_verbose ("fork failed\n");
113  dbus_set_error (error, _dbus_error_from_errno (errno),
114  "Failed to fork daemon: %s", _dbus_strerror (errno));
115  return FALSE;
116  break;
117 
118  case 0:
119  _dbus_verbose ("in child, closing std file descriptors\n");
120 
121  flags = DBUS_FORCE_STDIN_NULL | DBUS_FORCE_STDOUT_NULL;
122  s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
123 
124  if (s == NULL || *s == '\0')
125  flags |= DBUS_FORCE_STDERR_NULL;
126  else
127  _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
128 
129  if (!_dbus_ensure_standard_fds (flags, &s))
130  {
131  _dbus_warn ("%s: %s", s, _dbus_strerror (errno));
132  _exit (1);
133  }
134 
135  if (!keep_umask)
136  {
137  /* Get a predictable umask */
138  _dbus_verbose ("setting umask\n");
139  umask (022);
140  }
141 
142  _dbus_verbose ("calling setsid()\n");
143  if (setsid () == -1)
144  _dbus_assert_not_reached ("setsid() failed");
145 
146  break;
147 
148  default:
149  if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
150  child_pid, error))
151  {
152  _dbus_verbose ("pid file or pipe write failed: %s\n",
153  error->message);
154  kill (child_pid, SIGTERM);
155  return FALSE;
156  }
157 
158  _dbus_verbose ("parent exiting\n");
159  _exit (0);
160  break;
161  }
162 
163  return TRUE;
164 }
165 
166 
175 static dbus_bool_t
176 _dbus_write_pid_file (const DBusString *filename,
177  unsigned long pid,
178  DBusError *error)
179 {
180  const char *cfilename;
181  int fd;
182  FILE *f;
183 
184  cfilename = _dbus_string_get_const_data (filename);
185 
186  fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
187 
188  if (fd < 0)
189  {
190  dbus_set_error (error, _dbus_error_from_errno (errno),
191  "Failed to open \"%s\": %s", cfilename,
192  _dbus_strerror (errno));
193  return FALSE;
194  }
195 
196  if ((f = fdopen (fd, "w")) == NULL)
197  {
198  dbus_set_error (error, _dbus_error_from_errno (errno),
199  "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
200  _dbus_close (fd, NULL);
201  return FALSE;
202  }
203 
204  if (fprintf (f, "%lu\n", pid) < 0)
205  {
206  dbus_set_error (error, _dbus_error_from_errno (errno),
207  "Failed to write to \"%s\": %s", cfilename,
208  _dbus_strerror (errno));
209 
210  fclose (f);
211  return FALSE;
212  }
213 
214  if (fclose (f) == EOF)
215  {
216  dbus_set_error (error, _dbus_error_from_errno (errno),
217  "Failed to close \"%s\": %s", cfilename,
218  _dbus_strerror (errno));
219  return FALSE;
220  }
221 
222  return TRUE;
223 }
224 
238  DBusPipe *print_pid_pipe,
239  dbus_pid_t pid_to_write,
240  DBusError *error)
241 {
242  if (pidfile)
243  {
244  _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
245  if (!_dbus_write_pid_file (pidfile,
246  pid_to_write,
247  error))
248  {
249  _dbus_verbose ("pid file write failed\n");
250  _DBUS_ASSERT_ERROR_IS_SET(error);
251  return FALSE;
252  }
253  }
254  else
255  {
256  _dbus_verbose ("No pid file requested\n");
257  }
258 
259  if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
260  {
261  DBusString pid;
262  int bytes;
263 
264  _dbus_verbose ("writing our pid to pipe %d\n",
265  print_pid_pipe->fd);
266 
267  if (!_dbus_string_init (&pid))
268  {
269  _DBUS_SET_OOM (error);
270  return FALSE;
271  }
272 
273  if (!_dbus_string_append_int (&pid, pid_to_write) ||
274  !_dbus_string_append (&pid, "\n"))
275  {
276  _dbus_string_free (&pid);
277  _DBUS_SET_OOM (error);
278  return FALSE;
279  }
280 
281  bytes = _dbus_string_get_length (&pid);
282  if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
283  {
284  /* _dbus_pipe_write sets error only on failure, not short write */
285  if (error != NULL && !dbus_error_is_set(error))
286  {
288  "Printing message bus PID: did not write enough bytes\n");
289  }
290  _dbus_string_free (&pid);
291  return FALSE;
292  }
293 
294  _dbus_string_free (&pid);
295  }
296  else
297  {
298  _dbus_verbose ("No pid pipe to write to\n");
299  }
300 
301  return TRUE;
302 }
303 
311 _dbus_verify_daemon_user (const char *user)
312 {
313  DBusString u;
314 
315  _dbus_string_init_const (&u, user);
316 
318 }
319 
320 
321 /* The HAVE_LIBAUDIT case lives in selinux.c */
322 #ifndef HAVE_LIBAUDIT
323 
331 _dbus_change_to_daemon_user (const char *user,
332  DBusError *error)
333 {
334  dbus_uid_t uid;
335  dbus_gid_t gid;
336  DBusString u;
337 
338  _dbus_string_init_const (&u, user);
339 
340  if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
341  {
343  "User '%s' does not appear to exist?",
344  user);
345  return FALSE;
346  }
347 
348  /* setgroups() only works if we are a privileged process,
349  * so we don't return error on failure; the only possible
350  * failure is that we don't have perms to do it.
351  *
352  * not sure this is right, maybe if setuid()
353  * is going to work then setgroups() should also work.
354  */
355  if (setgroups (0, NULL) < 0)
356  _dbus_warn ("Failed to drop supplementary groups: %s",
357  _dbus_strerror (errno));
358 
359  /* Set GID first, or the setuid may remove our permission
360  * to change the GID
361  */
362  if (setgid (gid) < 0)
363  {
364  dbus_set_error (error, _dbus_error_from_errno (errno),
365  "Failed to set GID to %lu: %s", gid,
366  _dbus_strerror (errno));
367  return FALSE;
368  }
369 
370  if (setuid (uid) < 0)
371  {
372  dbus_set_error (error, _dbus_error_from_errno (errno),
373  "Failed to set UID to %lu: %s", uid,
374  _dbus_strerror (errno));
375  return FALSE;
376  }
377 
378  return TRUE;
379 }
380 #endif /* !HAVE_LIBAUDIT */
381 
382 #ifdef HAVE_SETRLIMIT
383 
384 /* We assume that if we have setrlimit, we also have getrlimit and
385  * struct rlimit.
386  */
387 
388 struct DBusRLimit {
389  struct rlimit lim;
390 };
391 
392 DBusRLimit *
393 _dbus_rlimit_save_fd_limit (DBusError *error)
394 {
395  DBusRLimit *self;
396 
397  self = dbus_new0 (DBusRLimit, 1);
398 
399  if (self == NULL)
400  {
401  _DBUS_SET_OOM (error);
402  return NULL;
403  }
404 
405  if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
406  {
407  dbus_set_error (error, _dbus_error_from_errno (errno),
408  "Failed to get fd limit: %s", _dbus_strerror (errno));
409  dbus_free (self);
410  return NULL;
411  }
412 
413  return self;
414 }
415 
417 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
418  DBusError *error)
419 {
420  struct rlimit lim;
421 
422  /* No point to doing this practically speaking
423  * if we're not uid 0. We expect the system
424  * bus to use this before we change UID, and
425  * the session bus takes the Linux default,
426  * currently 1024 for cur and 4096 for max.
427  */
428  if (getuid () != 0)
429  {
430  /* not an error, we're probably the session bus */
431  return TRUE;
432  }
433 
434  if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
435  {
436  dbus_set_error (error, _dbus_error_from_errno (errno),
437  "Failed to get fd limit: %s", _dbus_strerror (errno));
438  return FALSE;
439  }
440 
441  if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= desired)
442  {
443  /* not an error, everything is fine */
444  return TRUE;
445  }
446 
447  /* Ignore "maximum limit", assume we have the "superuser"
448  * privileges. On Linux this is CAP_SYS_RESOURCE.
449  */
450  lim.rlim_cur = lim.rlim_max = desired;
451 
452  if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
453  {
454  dbus_set_error (error, _dbus_error_from_errno (errno),
455  "Failed to set fd limit to %u: %s",
456  desired, _dbus_strerror (errno));
457  return FALSE;
458  }
459 
460  return TRUE;
461 }
462 
464 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
465  DBusError *error)
466 {
467  if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
468  {
469  dbus_set_error (error, _dbus_error_from_errno (errno),
470  "Failed to restore old fd limit: %s",
471  _dbus_strerror (errno));
472  return FALSE;
473  }
474 
475  return TRUE;
476 }
477 
478 #else /* !HAVE_SETRLIMIT */
479 
480 static void
481 fd_limit_not_supported (DBusError *error)
482 {
484  "cannot change fd limit on this platform");
485 }
486 
487 DBusRLimit *
488 _dbus_rlimit_save_fd_limit (DBusError *error)
489 {
490  fd_limit_not_supported (error);
491  return NULL;
492 }
493 
495 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
496  DBusError *error)
497 {
498  fd_limit_not_supported (error);
499  return FALSE;
500 }
501 
503 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
504  DBusError *error)
505 {
506  fd_limit_not_supported (error);
507  return FALSE;
508 }
509 
510 #endif
511 
512 void
513 _dbus_rlimit_free (DBusRLimit *lim)
514 {
515  dbus_free (lim);
516 }
517 
523 void
525  DBusSignalHandler handler)
526 {
527  struct sigaction act;
528  sigset_t empty_mask;
529 
530  sigemptyset (&empty_mask);
531  act.sa_handler = handler;
532  act.sa_mask = empty_mask;
533  act.sa_flags = 0;
534  sigaction (sig, &act, NULL);
535 }
536 
543 _dbus_file_exists (const char *file)
544 {
545  return (access (file, F_OK) == 0);
546 }
547 
555 _dbus_user_at_console (const char *username,
556  DBusError *error)
557 {
558 #ifdef DBUS_CONSOLE_AUTH_DIR
559  DBusString u, f;
560  dbus_bool_t result;
561 
562  result = FALSE;
563  if (!_dbus_string_init (&f))
564  {
565  _DBUS_SET_OOM (error);
566  return FALSE;
567  }
568 
569  if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
570  {
571  _DBUS_SET_OOM (error);
572  goto out;
573  }
574 
575  _dbus_string_init_const (&u, username);
576 
577  if (!_dbus_concat_dir_and_file (&f, &u))
578  {
579  _DBUS_SET_OOM (error);
580  goto out;
581  }
582 
583  result = _dbus_file_exists (_dbus_string_get_const_data (&f));
584 
585  out:
586  _dbus_string_free (&f);
587 
588  return result;
589 #else
590  return FALSE;
591 #endif
592 }
593 
594 
603 {
604  if (_dbus_string_get_length (filename) > 0)
605  return _dbus_string_get_byte (filename, 0) == '/';
606  else
607  return FALSE;
608 }
609 
619 _dbus_stat (const DBusString *filename,
620  DBusStat *statbuf,
621  DBusError *error)
622 {
623  const char *filename_c;
624  struct stat sb;
625 
626  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
627 
628  filename_c = _dbus_string_get_const_data (filename);
629 
630  if (stat (filename_c, &sb) < 0)
631  {
632  dbus_set_error (error, _dbus_error_from_errno (errno),
633  "%s", _dbus_strerror (errno));
634  return FALSE;
635  }
636 
637  statbuf->mode = sb.st_mode;
638  statbuf->nlink = sb.st_nlink;
639  statbuf->uid = sb.st_uid;
640  statbuf->gid = sb.st_gid;
641  statbuf->size = sb.st_size;
642  statbuf->atime = sb.st_atime;
643  statbuf->mtime = sb.st_mtime;
644  statbuf->ctime = sb.st_ctime;
645 
646  return TRUE;
647 }
648 
649 
654 {
655  DIR *d;
657 };
658 
668  DBusError *error)
669 {
670  DIR *d;
671  DBusDirIter *iter;
672  const char *filename_c;
673 
674  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
675 
676  filename_c = _dbus_string_get_const_data (filename);
677 
678  d = opendir (filename_c);
679  if (d == NULL)
680  {
681  dbus_set_error (error, _dbus_error_from_errno (errno),
682  "Failed to read directory \"%s\": %s",
683  filename_c,
684  _dbus_strerror (errno));
685  return NULL;
686  }
687  iter = dbus_new0 (DBusDirIter, 1);
688  if (iter == NULL)
689  {
690  closedir (d);
692  "Could not allocate memory for directory iterator");
693  return NULL;
694  }
695 
696  iter->d = d;
697 
698  return iter;
699 }
700 
716  DBusString *filename,
717  DBusError *error)
718 {
719  struct dirent *ent;
720  int err;
721 
722  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
723 
724  again:
725  errno = 0;
726  ent = readdir (iter->d);
727 
728  if (!ent)
729  {
730  err = errno;
731 
732  if (err != 0)
733  dbus_set_error (error,
735  "%s", _dbus_strerror (err));
736 
737  return FALSE;
738  }
739  else if (ent->d_name[0] == '.' &&
740  (ent->d_name[1] == '\0' ||
741  (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
742  goto again;
743  else
744  {
745  _dbus_string_set_length (filename, 0);
746  if (!_dbus_string_append (filename, ent->d_name))
747  {
749  "No memory to read directory entry");
750  return FALSE;
751  }
752  else
753  {
754  return TRUE;
755  }
756  }
757 }
758 
762 void
764 {
765  closedir (iter->d);
766  dbus_free (iter);
767 }
768 
769 static dbus_bool_t
770 fill_user_info_from_group (struct group *g,
771  DBusGroupInfo *info,
772  DBusError *error)
773 {
774  _dbus_assert (g->gr_name != NULL);
775 
776  info->gid = g->gr_gid;
777  info->groupname = _dbus_strdup (g->gr_name);
778 
779  /* info->members = dbus_strdupv (g->gr_mem) */
780 
781  if (info->groupname == NULL)
782  {
784  return FALSE;
785  }
786 
787  return TRUE;
788 }
789 
790 static dbus_bool_t
791 fill_group_info (DBusGroupInfo *info,
792  dbus_gid_t gid,
793  const DBusString *groupname,
794  DBusError *error)
795 {
796  const char *group_c_str;
797 
798  _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
799  _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
800 
801  if (groupname)
802  group_c_str = _dbus_string_get_const_data (groupname);
803  else
804  group_c_str = NULL;
805 
806  /* For now assuming that the getgrnam() and getgrgid() flavors
807  * always correspond to the pwnam flavors, if not we have
808  * to add more configure checks.
809  */
810 
811 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
812  {
813  struct group *g;
814  int result;
815  size_t buflen;
816  char *buf;
817  struct group g_str;
818  dbus_bool_t b;
819 
820  /* retrieve maximum needed size for buf */
821  buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
822 
823  /* sysconf actually returns a long, but everything else expects size_t,
824  * so just recast here.
825  * https://bugs.freedesktop.org/show_bug.cgi?id=17061
826  */
827  if ((long) buflen <= 0)
828  buflen = 1024;
829 
830  result = -1;
831  while (1)
832  {
833  buf = dbus_malloc (buflen);
834  if (buf == NULL)
835  {
837  return FALSE;
838  }
839 
840  g = NULL;
841 #ifdef HAVE_POSIX_GETPWNAM_R
842  if (group_c_str)
843  result = getgrnam_r (group_c_str, &g_str, buf, buflen,
844  &g);
845  else
846  result = getgrgid_r (gid, &g_str, buf, buflen,
847  &g);
848 #else
849  g = getgrnam_r (group_c_str, &g_str, buf, buflen);
850  result = 0;
851 #endif /* !HAVE_POSIX_GETPWNAM_R */
852  /* Try a bigger buffer if ERANGE was returned:
853  https://bugs.freedesktop.org/show_bug.cgi?id=16727
854  */
855  if (result == ERANGE && buflen < 512 * 1024)
856  {
857  dbus_free (buf);
858  buflen *= 2;
859  }
860  else
861  {
862  break;
863  }
864  }
865 
866  if (result == 0 && g == &g_str)
867  {
868  b = fill_user_info_from_group (g, info, error);
869  dbus_free (buf);
870  return b;
871  }
872  else
873  {
874  dbus_set_error (error, _dbus_error_from_errno (errno),
875  "Group %s unknown or failed to look it up\n",
876  group_c_str ? group_c_str : "???");
877  dbus_free (buf);
878  return FALSE;
879  }
880  }
881 #else /* ! HAVE_GETPWNAM_R */
882  {
883  /* I guess we're screwed on thread safety here */
884  struct group *g;
885 
886  g = getgrnam (group_c_str);
887 
888  if (g != NULL)
889  {
890  return fill_user_info_from_group (g, info, error);
891  }
892  else
893  {
894  dbus_set_error (error, _dbus_error_from_errno (errno),
895  "Group %s unknown or failed to look it up\n",
896  group_c_str ? group_c_str : "???");
897  return FALSE;
898  }
899  }
900 #endif /* ! HAVE_GETPWNAM_R */
901 }
902 
914  const DBusString *groupname,
915  DBusError *error)
916 {
917  return fill_group_info (info, DBUS_GID_UNSET,
918  groupname, error);
919 
920 }
921 
933  dbus_gid_t gid,
934  DBusError *error)
935 {
936  return fill_group_info (info, gid, NULL, error);
937 }
938 
949  dbus_uid_t *uid_p)
950 {
951  return _dbus_get_user_id (username, uid_p);
952 
953 }
954 
965  dbus_gid_t *gid_p)
966 {
967  return _dbus_get_group_id (groupname, gid_p);
968 }
969 
982  dbus_gid_t **group_ids,
983  int *n_group_ids)
984 {
985  return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
986 }
987 
999  DBusError *error)
1000 {
1001  return _dbus_is_console_user (uid, error);
1002 
1003 }
1004 
1014 {
1015  return uid == _dbus_geteuid ();
1016 }
1017 
1026 _dbus_windows_user_is_process_owner (const char *windows_sid)
1027 {
1028  return FALSE;
1029 }
1030  /* End of DBusInternalsUtils functions */
1032 
1046  DBusString *dirname)
1047 {
1048  int sep;
1049 
1050  _dbus_assert (filename != dirname);
1051  _dbus_assert (filename != NULL);
1052  _dbus_assert (dirname != NULL);
1053 
1054  /* Ignore any separators on the end */
1055  sep = _dbus_string_get_length (filename);
1056  if (sep == 0)
1057  return _dbus_string_append (dirname, "."); /* empty string passed in */
1058 
1059  while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1060  --sep;
1061 
1062  _dbus_assert (sep >= 0);
1063 
1064  if (sep == 0)
1065  return _dbus_string_append (dirname, "/");
1066 
1067  /* Now find the previous separator */
1068  _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1069  if (sep < 0)
1070  return _dbus_string_append (dirname, ".");
1071 
1072  /* skip multiple separators */
1073  while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1074  --sep;
1075 
1076  _dbus_assert (sep >= 0);
1077 
1078  if (sep == 0 &&
1079  _dbus_string_get_byte (filename, 0) == '/')
1080  return _dbus_string_append (dirname, "/");
1081  else
1082  return _dbus_string_copy_len (filename, 0, sep - 0,
1083  dirname, _dbus_string_get_length (dirname));
1084 } /* DBusString stuff */
1086 
1087 static void
1088 string_squash_nonprintable (DBusString *str)
1089 {
1090  unsigned char *buf;
1091  int i, len;
1092 
1093  buf = _dbus_string_get_udata (str);
1094  len = _dbus_string_get_length (str);
1095 
1096  for (i = 0; i < len; i++)
1097  {
1098  unsigned char c = (unsigned char) buf[i];
1099  if (c == '\0')
1100  buf[i] = ' ';
1101  else if (c < 0x20 || c > 127)
1102  buf[i] = '?';
1103  }
1104 }
1105 
1120 dbus_bool_t
1121 _dbus_command_for_pid (unsigned long pid,
1122  DBusString *str,
1123  int max_len,
1124  DBusError *error)
1125 {
1126  /* This is all Linux-specific for now */
1127  DBusString path;
1128  DBusString cmdline;
1129  int fd;
1130 
1131  if (!_dbus_string_init (&path))
1132  {
1133  _DBUS_SET_OOM (error);
1134  return FALSE;
1135  }
1136 
1137  if (!_dbus_string_init (&cmdline))
1138  {
1139  _DBUS_SET_OOM (error);
1140  _dbus_string_free (&path);
1141  return FALSE;
1142  }
1143 
1144  if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1145  goto oom;
1146 
1147  fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1148  if (fd < 0)
1149  {
1150  dbus_set_error (error,
1151  _dbus_error_from_errno (errno),
1152  "Failed to open \"%s\": %s",
1153  _dbus_string_get_const_data (&path),
1154  _dbus_strerror (errno));
1155  goto fail;
1156  }
1157 
1158  if (!_dbus_read (fd, &cmdline, max_len))
1159  {
1160  dbus_set_error (error,
1161  _dbus_error_from_errno (errno),
1162  "Failed to read from \"%s\": %s",
1163  _dbus_string_get_const_data (&path),
1164  _dbus_strerror (errno));
1165  _dbus_close (fd, NULL);
1166  goto fail;
1167  }
1168 
1169  if (!_dbus_close (fd, error))
1170  goto fail;
1171 
1172  string_squash_nonprintable (&cmdline);
1173 
1174  if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1175  goto oom;
1176 
1177  _dbus_string_free (&cmdline);
1178  _dbus_string_free (&path);
1179  return TRUE;
1180 oom:
1181  _DBUS_SET_OOM (error);
1182 fail:
1183  _dbus_string_free (&cmdline);
1184  _dbus_string_free (&path);
1185  return FALSE;
1186 }
1187 
1198 {
1199  return TRUE;
1200 }
1201 
1202 static dbus_bool_t
1203 ensure_owned_directory (const char *label,
1204  const DBusString *string,
1205  dbus_bool_t create,
1206  DBusError *error)
1207 {
1208  const char *dir = _dbus_string_get_const_data (string);
1209  struct stat buf;
1210 
1211  if (create && !_dbus_ensure_directory (string, error))
1212  return FALSE;
1213 
1214  /*
1215  * The stat()-based checks in this function are to protect against
1216  * mistakes, not malice. We are working in a directory that is meant
1217  * to be trusted; but if a user has used `su` or similar to escalate
1218  * their privileges without correctly clearing the environment, the
1219  * XDG_RUNTIME_DIR in the environment might still be the user's
1220  * and not root's. We don't want to write root-owned files into that
1221  * directory, so just warn and don't provide support for transient
1222  * services in that case.
1223  *
1224  * In particular, we use stat() and not lstat() so that if we later
1225  * decide to use a different directory name for transient services,
1226  * we can drop in a compatibility symlink without breaking older
1227  * libdbus.
1228  */
1229 
1230  if (stat (dir, &buf) != 0)
1231  {
1232  int saved_errno = errno;
1233 
1234  dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1235  "%s \"%s\" not available: %s", label, dir,
1236  _dbus_strerror (saved_errno));
1237  return FALSE;
1238  }
1239 
1240  if (!S_ISDIR (buf.st_mode))
1241  {
1242  dbus_set_error (error, DBUS_ERROR_FAILED, "%s \"%s\" is not a directory",
1243  label, dir);
1244  return FALSE;
1245  }
1246 
1247  if (buf.st_uid != geteuid ())
1248  {
1250  "%s \"%s\" is owned by uid %ld, not our uid %ld",
1251  label, dir, (long) buf.st_uid, (long) geteuid ());
1252  return FALSE;
1253  }
1254 
1255  /* This is just because we have the stat() results already, so we might
1256  * as well check opportunistically. */
1257  if ((S_IWOTH | S_IWGRP) & buf.st_mode)
1258  {
1260  "%s \"%s\" can be written by others (mode 0%o)",
1261  label, dir, buf.st_mode);
1262  return FALSE;
1263  }
1264 
1265  return TRUE;
1266 }
1267 
1268 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1269 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1270 
1280  DBusError *error)
1281 {
1282  const char *xdg_runtime_dir;
1283  DBusString services;
1284  DBusString dbus1;
1285  DBusString xrd;
1286  dbus_bool_t ret = FALSE;
1287  char *data = NULL;
1288 
1289  if (!_dbus_string_init (&dbus1))
1290  {
1291  _DBUS_SET_OOM (error);
1292  return FALSE;
1293  }
1294 
1295  if (!_dbus_string_init (&services))
1296  {
1297  _dbus_string_free (&dbus1);
1298  _DBUS_SET_OOM (error);
1299  return FALSE;
1300  }
1301 
1302  if (!_dbus_string_init (&xrd))
1303  {
1304  _dbus_string_free (&dbus1);
1305  _dbus_string_free (&services);
1306  _DBUS_SET_OOM (error);
1307  return FALSE;
1308  }
1309 
1310  xdg_runtime_dir = _dbus_getenv ("XDG_RUNTIME_DIR");
1311 
1312  /* Not an error, we just can't have transient session services */
1313  if (xdg_runtime_dir == NULL)
1314  {
1315  _dbus_verbose ("XDG_RUNTIME_DIR is unset: transient session services "
1316  "not available here\n");
1317  ret = TRUE;
1318  goto out;
1319  }
1320 
1321  if (!_dbus_string_append (&xrd, xdg_runtime_dir) ||
1322  !_dbus_string_append_printf (&dbus1, "%s/dbus-1",
1323  xdg_runtime_dir) ||
1324  !_dbus_string_append_printf (&services, "%s/dbus-1/services",
1325  xdg_runtime_dir))
1326  {
1327  _DBUS_SET_OOM (error);
1328  goto out;
1329  }
1330 
1331  if (!ensure_owned_directory ("XDG_RUNTIME_DIR", &xrd, FALSE, error) ||
1332  !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &dbus1, TRUE,
1333  error) ||
1334  !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &services,
1335  TRUE, error))
1336  goto out;
1337 
1338  if (!_dbus_string_steal_data (&services, &data) ||
1339  !_dbus_list_append (dirs, data))
1340  {
1341  _DBUS_SET_OOM (error);
1342  goto out;
1343  }
1344 
1345  _dbus_verbose ("Transient service directory is %s\n", data);
1346  /* Ownership was transferred to @dirs */
1347  data = NULL;
1348  ret = TRUE;
1349 
1350 out:
1351  _dbus_string_free (&dbus1);
1352  _dbus_string_free (&services);
1353  _dbus_string_free (&xrd);
1354  dbus_free (data);
1355  return ret;
1356 }
1357 
1377 {
1378  const char *xdg_data_home;
1379  const char *xdg_data_dirs;
1380  DBusString servicedir_path;
1381 
1382  if (!_dbus_string_init (&servicedir_path))
1383  return FALSE;
1384 
1385  xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
1386  xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
1387 
1388  if (xdg_data_home != NULL)
1389  {
1390  if (!_dbus_string_append (&servicedir_path, xdg_data_home))
1391  goto oom;
1392  }
1393  else
1394  {
1395  const DBusString *homedir;
1396  DBusString local_share;
1397 
1398  if (!_dbus_homedir_from_current_process (&homedir))
1399  goto oom;
1400 
1401  if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
1402  goto oom;
1403 
1404  _dbus_string_init_const (&local_share, "/.local/share");
1405  if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
1406  goto oom;
1407  }
1408 
1409  if (!_dbus_string_append (&servicedir_path, ":"))
1410  goto oom;
1411 
1412  if (xdg_data_dirs != NULL)
1413  {
1414  if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
1415  goto oom;
1416 
1417  if (!_dbus_string_append (&servicedir_path, ":"))
1418  goto oom;
1419  }
1420  else
1421  {
1422  if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
1423  goto oom;
1424  }
1425 
1426  /*
1427  * add configured datadir to defaults
1428  * this may be the same as an xdg dir
1429  * however the config parser should take
1430  * care of duplicates
1431  */
1432  if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
1433  goto oom;
1434 
1435  if (!_dbus_split_paths_and_append (&servicedir_path,
1436  DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1437  dirs))
1438  goto oom;
1439 
1440  _dbus_string_free (&servicedir_path);
1441  return TRUE;
1442 
1443  oom:
1444  _dbus_string_free (&servicedir_path);
1445  return FALSE;
1446 }
1447 
1448 
1469 {
1470  /*
1471  * DBUS_DATADIR may be the same as one of the standard directories. However,
1472  * the config parser should take care of the duplicates.
1473  *
1474  * Also, append /lib as counterpart of /usr/share on the root
1475  * directory (the root directory does not know /share), in order to
1476  * facilitate early boot system bus activation where /usr might not
1477  * be available.
1478  */
1479  static const char standard_search_path[] =
1480  "/usr/local/share:"
1481  "/usr/share:"
1482  DBUS_DATADIR ":"
1483  "/lib";
1484  DBusString servicedir_path;
1485 
1486  _dbus_string_init_const (&servicedir_path, standard_search_path);
1487 
1488  return _dbus_split_paths_and_append (&servicedir_path,
1489  DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1490  dirs);
1491 }
1492 
1503 {
1504  _dbus_assert (_dbus_string_get_length (str) == 0);
1505 
1506  return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
1507 }
1508 
1517 {
1518  _dbus_assert (_dbus_string_get_length (str) == 0);
1519 
1520  return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
1521 }
1522 
1527 void
1529 {
1530 #ifdef HAVE_SYSTEMD
1531  sd_notify (0, "READY=1");
1532 #endif
1533 }
1534 
1539 void
1541 {
1542 #ifdef HAVE_SYSTEMD
1543  sd_notify (0, "RELOADING=1");
1544 #endif
1545 }
1546 
1551 void
1553 {
1554 #ifdef HAVE_SYSTEMD
1555  /* For systemd, this is the same code */
1557 #endif
1558 }
1559 
1564 void
1566 {
1567 #ifdef HAVE_SYSTEMD
1568  sd_notify (0, "STOPPING=1");
1569 #endif
1570 }
dbus_bool_t _dbus_string_append(DBusString *str, const char *buffer)
Appends a nul-terminated C-style string to a DBusString.
Definition: dbus-string.c:952
dbus_bool_t _dbus_split_paths_and_append(DBusString *dirs, const char *suffix, DBusList **dir_list)
Split paths into a list of char strings.
Definition: dbus-sysdeps.c:236
const char * message
public error message field
Definition: dbus-errors.h:51
#define NULL
A null pointer, defined appropriately for C or C++.
dbus_bool_t _dbus_become_daemon(const DBusString *pidfile, DBusPipe *print_pid_pipe, DBusError *error, dbus_bool_t keep_umask)
Does the chdir, fork, setsid, etc.
dbus_bool_t _dbus_unix_user_is_at_console(dbus_uid_t uid, DBusError *error)
Checks to see if the UNIX user ID is at the console.
dbus_bool_t _dbus_group_info_fill_gid(DBusGroupInfo *info, dbus_gid_t gid, DBusError *error)
Initializes the given DBusGroupInfo struct with information about the given group ID...
dbus_bool_t _dbus_string_get_dirname(const DBusString *filename, DBusString *dirname)
Get the directory name from a complete filename.
dbus_bool_t _dbus_ensure_directory(const DBusString *filename, DBusError *error)
Creates a directory; succeeds if the directory is created or already existed.
void dbus_free(void *memory)
Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().
Definition: dbus-memory.c:703
dbus_bool_t _dbus_path_is_absolute(const DBusString *filename)
Checks whether the filename is an absolute path.
Portable struct with stat() results.
Definition: dbus-sysdeps.h:520
dbus_bool_t _dbus_ensure_standard_fds(DBusEnsureStandardFdsFlags flags, const char **error_str_p)
Ensure that the standard file descriptors stdin, stdout and stderr are open, by opening /dev/null if ...
#define DBUS_ERROR_NOT_SUPPORTED
Requested operation isn&#39;t supported (like ENOSYS on UNIX).
DBUS_PRIVATE_EXPORT dbus_bool_t _dbus_string_append_int(DBusString *str, long value)
Appends an integer to a DBusString.
Definition: dbus-sysdeps.c:363
dbus_bool_t _dbus_groups_from_uid(dbus_uid_t uid, dbus_gid_t **group_ids, int *n_group_ids)
Gets all groups corresponding to the given UID.
dbus_bool_t _dbus_parse_unix_group_from_config(const DBusString *groupname, dbus_gid_t *gid_p)
Parse a UNIX group from the bus config file.
void _dbus_directory_close(DBusDirIter *iter)
Closes a directory iteration.
dbus_bool_t _dbus_is_console_user(dbus_uid_t uid, DBusError *error)
Checks to see if the UID sent in is the console user.
#define _dbus_assert(condition)
Aborts with an error message if the condition is false.
dbus_bool_t _dbus_directory_get_next_file(DBusDirIter *iter, DBusString *filename, DBusError *error)
Get next file in the directory.
unsigned long atime
Access time.
Definition: dbus-sysdeps.h:527
dbus_bool_t _dbus_get_standard_session_servicedirs(DBusList **dirs)
Returns the standard directories for a session bus to look for service activation files...
dbus_bool_t _dbus_concat_dir_and_file(DBusString *dir, const DBusString *next_component)
Appends the given filename to the given directory.
DBusDirIter * _dbus_directory_open(const DBusString *filename, DBusError *error)
Open a directory to iterate over.
dbus_bool_t _dbus_string_init(DBusString *str)
Initializes a string.
Definition: dbus-string.c:175
dbus_bool_t _dbus_command_for_pid(unsigned long pid, DBusString *str, int max_len, DBusError *error)
Get a printable string describing the command used to execute the process with pid.
dbus_bool_t _dbus_get_system_config_file(DBusString *str)
Get the absolute path of the system.conf file (there is no system bus on Windows so this can just ret...
dbus_bool_t _dbus_string_copy(const DBusString *source, int start, DBusString *dest, int insert_at)
Like _dbus_string_move(), but does not delete the section of the source string that&#39;s copied to the d...
Definition: dbus-string.c:1300
char * groupname
Group name.
const char * _dbus_error_from_errno(int error_number)
Converts a UNIX errno, or Windows errno or WinSock error value into a DBusError name.
Definition: dbus-sysdeps.c:599
Internals of directory iterator.
unsigned long mode
File mode.
Definition: dbus-sysdeps.h:522
unsigned long dbus_pid_t
A process ID.
Definition: dbus-sysdeps.h:106
dbus_bool_t _dbus_get_user_id_and_primary_group(const DBusString *username, dbus_uid_t *uid_p, dbus_gid_t *gid_p)
Gets user ID and primary group given username.
dbus_bool_t _dbus_change_to_daemon_user(const char *user, DBusError *error)
Changes the user and group the bus is running as.
DIR * d
The DIR* from opendir()
void * dbus_malloc(size_t bytes)
Allocates the given number of bytes, as with standard malloc().
Definition: dbus-memory.c:463
dbus_gid_t gid
Group owning file.
Definition: dbus-sysdeps.h:525
#define dbus_new0(type, count)
Safe macro for using dbus_malloc0().
Definition: dbus-memory.h:59
dbus_uint32_t dbus_bool_t
A boolean, valid values are TRUE and FALSE.
Definition: dbus-types.h:35
void _dbus_string_init_const(DBusString *str, const char *value)
Initializes a constant string.
Definition: dbus-string.c:190
dbus_bool_t _dbus_get_session_config_file(DBusString *str)
Get the absolute path of the session.conf file.
void _dbus_daemon_report_stopping(void)
Report to a service manager that the daemon calling this function is shutting down.
void _dbus_warn(const char *format,...)
Prints a warning message to stderr.
dbus_bool_t _dbus_list_append(DBusList **list, void *data)
Appends a value to the list.
Definition: dbus-list.c:271
int _dbus_read(int fd, DBusString *buffer, int count)
Thin wrapper around the read() system call that appends the data it reads to the DBusString buffer...
dbus_bool_t _dbus_string_append_printf(DBusString *str, const char *format,...)
Appends a printf-style formatted string to the DBusString.
Definition: dbus-string.c:1131
dbus_bool_t _dbus_group_info_fill(DBusGroupInfo *info, const DBusString *groupname, DBusError *error)
Initializes the given DBusGroupInfo struct with information about the given group name...
dbus_bool_t _dbus_get_group_id(const DBusString *groupname, dbus_gid_t *gid)
Gets group ID given groupname.
Object representing an exception.
Definition: dbus-errors.h:48
void dbus_set_error(DBusError *error, const char *name, const char *format,...)
Assigns an error name and message to a DBusError.
Definition: dbus-errors.c:354
dbus_bool_t _dbus_unix_groups_from_uid(dbus_uid_t uid, dbus_gid_t **group_ids, int *n_group_ids)
Gets all groups corresponding to the given UNIX user ID.
unsigned long ctime
Creation time.
Definition: dbus-sysdeps.h:529
void _dbus_string_free(DBusString *str)
Frees a string created by _dbus_string_init(), and fills it with the same contents as #_DBUS_STRING_I...
Definition: dbus-string.c:264
#define DBUS_GID_UNSET
an invalid GID used to represent an uninitialized dbus_gid_t field
Definition: dbus-sysdeps.h:117
dbus_uid_t _dbus_geteuid(void)
Gets our effective UID.
dbus_bool_t _dbus_file_exists(const char *file)
Checks if a file exists.
#define TRUE
Expands to "1".
unsigned long nlink
Number of hard links.
Definition: dbus-sysdeps.h:523
#define _dbus_assert_not_reached(explanation)
Aborts with an error message if called.
dbus_bool_t _dbus_write_pid_to_file_and_pipe(const DBusString *pidfile, DBusPipe *print_pid_pipe, dbus_pid_t pid_to_write, DBusError *error)
Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a pipe (if non-NULL).
dbus_uid_t uid
User owning file.
Definition: dbus-sysdeps.h:524
#define DBUS_ERROR_FAILED
A generic error; "something went wrong" - see the error message for more.
dbus_bool_t _dbus_verify_daemon_user(const char *user)
Verify that after the fork we can successfully change to this user.
dbus_bool_t _dbus_string_find_byte_backward(const DBusString *str, int start, unsigned char byte, int *found)
Find the given byte scanning backward from the given start.
dbus_bool_t _dbus_homedir_from_current_process(const DBusString **homedir)
Gets homedir of user owning current process.
Definition: dbus-userdb.c:402
Information about a UNIX group.
dbus_bool_t _dbus_stat(const DBusString *filename, DBusStat *statbuf, DBusError *error)
stat() wrapper.
dbus_bool_t _dbus_get_user_id(const DBusString *username, dbus_uid_t *uid)
Gets user ID given username.
void _dbus_set_signal_handler(int sig, DBusSignalHandler handler)
Installs a UNIX signal handler.
A node in a linked list.
Definition: dbus-list.h:34
dbus_bool_t _dbus_unix_user_is_process_owner(dbus_uid_t uid)
Checks to see if the UNIX user ID matches the UID of the process.
void _dbus_daemon_report_ready(void)
Report to a service manager that the daemon calling this function is ready for use.
dbus_bool_t _dbus_replace_install_prefix(DBusString *path)
Replace the DBUS_PREFIX in the given path, in-place, by the current D-Bus installation directory...
dbus_bool_t _dbus_user_at_console(const char *username, DBusError *error)
Checks if user is at the console.
void _dbus_daemon_report_reloaded(void)
Report to a service manager that the daemon calling this function is reloading configuration.
dbus_bool_t _dbus_windows_user_is_process_owner(const char *windows_sid)
Checks to see if the Windows user SID matches the owner of the process.
dbus_bool_t _dbus_set_up_transient_session_servicedirs(DBusList **dirs, DBusError *error)
Returns the standard directories for a session bus to look for transient service activation files...
#define DBUS_ERROR_NO_MEMORY
There was not enough memory to complete an operation.
dbus_bool_t _dbus_close(int fd, DBusError *error)
Closes a file descriptor.
#define FALSE
Expands to "0".
unsigned long mtime
Modify time.
Definition: dbus-sysdeps.h:528
dbus_bool_t _dbus_string_set_length(DBusString *str, int length)
Sets the length of a string.
Definition: dbus-string.c:819
void _dbus_daemon_report_reloading(void)
Report to a service manager that the daemon calling this function is reloading configuration.
dbus_bool_t _dbus_string_copy_len(const DBusString *source, int start, int len, DBusString *dest, int insert_at)
Like _dbus_string_copy(), but can copy a segment from the middle of the source string.
Definition: dbus-string.c:1392
dbus_bool_t _dbus_string_steal_data(DBusString *str, char **data_return)
Like _dbus_string_get_data(), but removes the gotten data from the original string.
Definition: dbus-string.c:658
dbus_gid_t gid
GID.
void(* DBusSignalHandler)(int sig)
A UNIX signal handler.
unsigned long dbus_gid_t
A group ID.
Definition: dbus-sysdeps.h:110
unsigned long size
Size of file.
Definition: dbus-sysdeps.h:526
dbus_bool_t _dbus_parse_unix_user_from_config(const DBusString *username, dbus_uid_t *uid_p)
Parse a UNIX user from the bus config file.
char * _dbus_strdup(const char *str)
Duplicates a string.
const char * _dbus_getenv(const char *varname)
Wrapper for getenv().
Definition: dbus-sysdeps.c:195
unsigned long dbus_uid_t
A user ID.
Definition: dbus-sysdeps.h:108
dbus_bool_t _dbus_get_standard_system_servicedirs(DBusList **dirs)
Returns the standard directories for a system bus to look for service activation files.
dbus_bool_t dbus_error_is_set(const DBusError *error)
Checks whether an error occurred (the error is set).
Definition: dbus-errors.c:329