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 <stdlib.h>
39 #include <string.h>
40 #include <signal.h>
41 #include <unistd.h>
42 #include <stdio.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <syslog.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 
67 /**
68  * @addtogroup DBusInternalsUtils
69  * @{
70  */
71 
72 
73 /**
74  * Does the chdir, fork, setsid, etc. to become a daemon process.
75  *
76  * @param pidfile #NULL, or pidfile to create
77  * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
78  * @param error return location for errors
79  * @param keep_umask #TRUE to keep the original umask
80  * @returns #FALSE on failure
81  */
82 dbus_bool_t
_dbus_become_daemon(const DBusString * pidfile,DBusPipe * print_pid_pipe,DBusError * error,dbus_bool_t keep_umask)83 _dbus_become_daemon (const DBusString *pidfile,
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     {
97       dbus_set_error (error, DBUS_ERROR_FAILED,
98                       "Could not chdir() to root directory");
99       return FALSE;
100     }
101 
102   _dbus_verbose ("forking...\n");
103   switch ((child_pid = fork ()))
104     {
105     case -1:
106       _dbus_verbose ("fork failed\n");
107       dbus_set_error (error, _dbus_error_from_errno (errno),
108                       "Failed to fork daemon: %s", _dbus_strerror (errno));
109       return FALSE;
110       break;
111 
112     case 0:
113       _dbus_verbose ("in child, closing std file descriptors\n");
114 
115       flags = DBUS_FORCE_STDIN_NULL | DBUS_FORCE_STDOUT_NULL;
116       s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
117 
118       if (s == NULL || *s == '\0')
119         flags |= DBUS_FORCE_STDERR_NULL;
120       else
121         _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
122 
123       if (!_dbus_ensure_standard_fds (flags, &s))
124         {
125           _dbus_warn ("%s: %s", s, _dbus_strerror (errno));
126           _exit (1);
127         }
128 
129       if (!keep_umask)
130         {
131           /* Get a predictable umask */
132           _dbus_verbose ("setting umask\n");
133           umask (022);
134         }
135 
136       _dbus_verbose ("calling setsid()\n");
137       if (setsid () == -1)
138         _dbus_assert_not_reached ("setsid() failed");
139 
140       break;
141 
142     default:
143       if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
144                                              child_pid, error))
145         {
146           _dbus_verbose ("pid file or pipe write failed: %s\n",
147                          error->message);
148           kill (child_pid, SIGTERM);
149           return FALSE;
150         }
151 
152       _dbus_verbose ("parent exiting\n");
153       _exit (0);
154       break;
155     }
156 
157   return TRUE;
158 }
159 
160 
161 /**
162  * Creates a file containing the process ID.
163  *
164  * @param filename the filename to write to
165  * @param pid our process ID
166  * @param error return location for errors
167  * @returns #FALSE on failure
168  */
169 static dbus_bool_t
_dbus_write_pid_file(const DBusString * filename,unsigned long pid,DBusError * error)170 _dbus_write_pid_file (const DBusString *filename,
171                       unsigned long     pid,
172 		      DBusError        *error)
173 {
174   const char *cfilename;
175   int fd;
176   FILE *f;
177 
178   cfilename = _dbus_string_get_const_data (filename);
179 
180   fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
181 
182   if (fd < 0)
183     {
184       dbus_set_error (error, _dbus_error_from_errno (errno),
185                       "Failed to open \"%s\": %s", cfilename,
186                       _dbus_strerror (errno));
187       return FALSE;
188     }
189 
190   if ((f = fdopen (fd, "w")) == NULL)
191     {
192       dbus_set_error (error, _dbus_error_from_errno (errno),
193                       "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
194       _dbus_close (fd, NULL);
195       return FALSE;
196     }
197 
198   if (fprintf (f, "%lu\n", pid) < 0)
199     {
200       dbus_set_error (error, _dbus_error_from_errno (errno),
201                       "Failed to write to \"%s\": %s", cfilename,
202                       _dbus_strerror (errno));
203 
204       fclose (f);
205       return FALSE;
206     }
207 
208   if (fclose (f) == EOF)
209     {
210       dbus_set_error (error, _dbus_error_from_errno (errno),
211                       "Failed to close \"%s\": %s", cfilename,
212                       _dbus_strerror (errno));
213       return FALSE;
214     }
215 
216   return TRUE;
217 }
218 
219 /**
220  * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
221  * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
222  * NULL.
223  *
224  * @param pidfile the file to write to or #NULL
225  * @param print_pid_pipe the pipe to write to or #NULL
226  * @param pid_to_write the pid to write out
227  * @param error error on failure
228  * @returns FALSE if error is set
229  */
230 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)231 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
232                                   DBusPipe         *print_pid_pipe,
233                                   dbus_pid_t        pid_to_write,
234                                   DBusError        *error)
235 {
236   if (pidfile)
237     {
238       _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
239       if (!_dbus_write_pid_file (pidfile,
240                                  pid_to_write,
241                                  error))
242         {
243           _dbus_verbose ("pid file write failed\n");
244           _DBUS_ASSERT_ERROR_IS_SET(error);
245           return FALSE;
246         }
247     }
248   else
249     {
250       _dbus_verbose ("No pid file requested\n");
251     }
252 
253   if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
254     {
255       DBusString pid;
256       int bytes;
257 
258       _dbus_verbose ("writing our pid to pipe %d\n",
259                      print_pid_pipe->fd);
260 
261       if (!_dbus_string_init (&pid))
262         {
263           _DBUS_SET_OOM (error);
264           return FALSE;
265         }
266 
267       if (!_dbus_string_append_int (&pid, pid_to_write) ||
268           !_dbus_string_append (&pid, "\n"))
269         {
270           _dbus_string_free (&pid);
271           _DBUS_SET_OOM (error);
272           return FALSE;
273         }
274 
275       bytes = _dbus_string_get_length (&pid);
276       if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
277         {
278           /* _dbus_pipe_write sets error only on failure, not short write */
279           if (error != NULL && !dbus_error_is_set(error))
280             {
281               dbus_set_error (error, DBUS_ERROR_FAILED,
282                               "Printing message bus PID: did not write enough bytes\n");
283             }
284           _dbus_string_free (&pid);
285           return FALSE;
286         }
287 
288       _dbus_string_free (&pid);
289     }
290   else
291     {
292       _dbus_verbose ("No pid pipe to write to\n");
293     }
294 
295   return TRUE;
296 }
297 
298 /**
299  * Verify that after the fork we can successfully change to this user.
300  *
301  * @param user the username given in the daemon configuration
302  * @returns #TRUE if username is valid
303  */
304 dbus_bool_t
_dbus_verify_daemon_user(const char * user)305 _dbus_verify_daemon_user (const char *user)
306 {
307   DBusString u;
308 
309   _dbus_string_init_const (&u, user);
310 
311   return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
312 }
313 
314 
315 /* The HAVE_LIBAUDIT case lives in selinux.c */
316 #ifndef HAVE_LIBAUDIT
317 /**
318  * Changes the user and group the bus is running as.
319  *
320  * @param user the user to become
321  * @param error return location for errors
322  * @returns #FALSE on failure
323  */
324 dbus_bool_t
_dbus_change_to_daemon_user(const char * user,DBusError * error)325 _dbus_change_to_daemon_user  (const char    *user,
326                               DBusError     *error)
327 {
328   dbus_uid_t uid;
329   dbus_gid_t gid;
330   DBusString u;
331 
332   _dbus_string_init_const (&u, user);
333 
334   if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
335     {
336       dbus_set_error (error, DBUS_ERROR_FAILED,
337                       "User '%s' does not appear to exist?",
338                       user);
339       return FALSE;
340     }
341 
342   /* setgroups() only works if we are a privileged process,
343    * so we don't return error on failure; the only possible
344    * failure is that we don't have perms to do it.
345    *
346    * not sure this is right, maybe if setuid()
347    * is going to work then setgroups() should also work.
348    */
349   if (setgroups (0, NULL) < 0)
350     _dbus_warn ("Failed to drop supplementary groups: %s",
351                 _dbus_strerror (errno));
352 
353   /* Set GID first, or the setuid may remove our permission
354    * to change the GID
355    */
356   if (setgid (gid) < 0)
357     {
358       dbus_set_error (error, _dbus_error_from_errno (errno),
359                       "Failed to set GID to %lu: %s", gid,
360                       _dbus_strerror (errno));
361       return FALSE;
362     }
363 
364   if (setuid (uid) < 0)
365     {
366       dbus_set_error (error, _dbus_error_from_errno (errno),
367                       "Failed to set UID to %lu: %s", uid,
368                       _dbus_strerror (errno));
369       return FALSE;
370     }
371 
372   return TRUE;
373 }
374 #endif /* !HAVE_LIBAUDIT */
375 
376 #ifdef HAVE_SETRLIMIT
377 
378 /* We assume that if we have setrlimit, we also have getrlimit and
379  * struct rlimit.
380  */
381 
382 struct DBusRLimit {
383     struct rlimit lim;
384 };
385 
386 DBusRLimit *
_dbus_rlimit_save_fd_limit(DBusError * error)387 _dbus_rlimit_save_fd_limit (DBusError *error)
388 {
389   DBusRLimit *self;
390 
391   self = dbus_new0 (DBusRLimit, 1);
392 
393   if (self == NULL)
394     {
395       _DBUS_SET_OOM (error);
396       return NULL;
397     }
398 
399   if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
400     {
401       dbus_set_error (error, _dbus_error_from_errno (errno),
402                       "Failed to get fd limit: %s", _dbus_strerror (errno));
403       dbus_free (self);
404       return NULL;
405     }
406 
407   return self;
408 }
409 
410 /* Enough fds that we shouldn't run out, even if several uids work
411  * together to carry out a denial-of-service attack. This happens to be
412  * the same number that systemd < 234 would normally use. */
413 #define ENOUGH_FDS 65536
414 
415 dbus_bool_t
_dbus_rlimit_raise_fd_limit(DBusError * error)416 _dbus_rlimit_raise_fd_limit (DBusError *error)
417 {
418   struct rlimit old, lim;
419 
420   if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
421     {
422       dbus_set_error (error, _dbus_error_from_errno (errno),
423                       "Failed to get fd limit: %s", _dbus_strerror (errno));
424       return FALSE;
425     }
426 
427   old = lim;
428 
429   if (getuid () == 0)
430     {
431       /* We are privileged, so raise the soft limit to at least
432        * ENOUGH_FDS, and the hard limit to at least the desired soft
433        * limit. This assumes we can exercise CAP_SYS_RESOURCE on Linux,
434        * or other OSs' equivalents. */
435       if (lim.rlim_cur != RLIM_INFINITY &&
436           lim.rlim_cur < ENOUGH_FDS)
437         lim.rlim_cur = ENOUGH_FDS;
438 
439       if (lim.rlim_max != RLIM_INFINITY &&
440           lim.rlim_max < lim.rlim_cur)
441         lim.rlim_max = lim.rlim_cur;
442     }
443 
444   /* Raise the soft limit to match the hard limit, which we can do even
445    * if we are unprivileged. In particular, systemd >= 240 will normally
446    * set rlim_cur to 1024 and rlim_max to 512*1024, recent Debian
447    * versions end up setting rlim_cur to 1024 and rlim_max to 1024*1024,
448    * and older and non-systemd Linux systems would typically set rlim_cur
449    * to 1024 and rlim_max to 4096. */
450   if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
451     lim.rlim_cur = lim.rlim_max;
452 
453   /* Early-return if there is nothing to do. */
454   if (lim.rlim_max == old.rlim_max &&
455       lim.rlim_cur == old.rlim_cur)
456     return TRUE;
457 
458   if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
459     {
460       dbus_set_error (error, _dbus_error_from_errno (errno),
461                       "Failed to set fd limit to %lu: %s",
462                       (unsigned long) lim.rlim_cur,
463                       _dbus_strerror (errno));
464       return FALSE;
465     }
466 
467   return TRUE;
468 }
469 
470 dbus_bool_t
_dbus_rlimit_restore_fd_limit(DBusRLimit * saved,DBusError * error)471 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
472                                DBusError  *error)
473 {
474   if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
475     {
476       dbus_set_error (error, _dbus_error_from_errno (errno),
477                       "Failed to restore old fd limit: %s",
478                       _dbus_strerror (errno));
479       return FALSE;
480     }
481 
482   return TRUE;
483 }
484 
485 #else /* !HAVE_SETRLIMIT */
486 
487 static void
fd_limit_not_supported(DBusError * error)488 fd_limit_not_supported (DBusError *error)
489 {
490   dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
491                   "cannot change fd limit on this platform");
492 }
493 
494 DBusRLimit *
_dbus_rlimit_save_fd_limit(DBusError * error)495 _dbus_rlimit_save_fd_limit (DBusError *error)
496 {
497   fd_limit_not_supported (error);
498   return NULL;
499 }
500 
501 dbus_bool_t
_dbus_rlimit_raise_fd_limit(DBusError * error)502 _dbus_rlimit_raise_fd_limit (DBusError *error)
503 {
504   fd_limit_not_supported (error);
505   return FALSE;
506 }
507 
508 dbus_bool_t
_dbus_rlimit_restore_fd_limit(DBusRLimit * saved,DBusError * error)509 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
510                                DBusError  *error)
511 {
512   fd_limit_not_supported (error);
513   return FALSE;
514 }
515 
516 #endif
517 
518 void
_dbus_rlimit_free(DBusRLimit * lim)519 _dbus_rlimit_free (DBusRLimit *lim)
520 {
521   dbus_free (lim);
522 }
523 
524 /** Installs a UNIX signal handler
525  *
526  * @param sig the signal to handle
527  * @param handler the handler
528  */
529 void
_dbus_set_signal_handler(int sig,DBusSignalHandler handler)530 _dbus_set_signal_handler (int               sig,
531                           DBusSignalHandler handler)
532 {
533   struct sigaction act;
534   sigset_t empty_mask;
535 
536   sigemptyset (&empty_mask);
537   act.sa_handler = handler;
538   act.sa_mask    = empty_mask;
539   act.sa_flags   = 0;
540   sigaction (sig,  &act, NULL);
541 }
542 
543 /** Checks if a file exists
544 *
545 * @param file full path to the file
546 * @returns #TRUE if file exists
547 */
548 dbus_bool_t
_dbus_file_exists(const char * file)549 _dbus_file_exists (const char *file)
550 {
551   return (access (file, F_OK) == 0);
552 }
553 
554 /** Checks if user is at the console
555 *
556 * @param username user to check
557 * @param error return location for errors
558 * @returns #TRUE is the user is at the consolei and there are no errors
559 */
560 dbus_bool_t
_dbus_user_at_console(const char * username,DBusError * error)561 _dbus_user_at_console (const char *username,
562                        DBusError  *error)
563 {
564 #ifdef DBUS_CONSOLE_AUTH_DIR
565   DBusString u, f;
566   dbus_bool_t result;
567 
568   result = FALSE;
569   if (!_dbus_string_init (&f))
570     {
571       _DBUS_SET_OOM (error);
572       return FALSE;
573     }
574 
575   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
576     {
577       _DBUS_SET_OOM (error);
578       goto out;
579     }
580 
581   _dbus_string_init_const (&u, username);
582 
583   if (!_dbus_concat_dir_and_file (&f, &u))
584     {
585       _DBUS_SET_OOM (error);
586       goto out;
587     }
588 
589   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
590 
591  out:
592   _dbus_string_free (&f);
593 
594   return result;
595 #else
596   return FALSE;
597 #endif
598 }
599 
600 
601 /**
602  * Checks whether the filename is an absolute path
603  *
604  * @param filename the filename
605  * @returns #TRUE if an absolute path
606  */
607 dbus_bool_t
_dbus_path_is_absolute(const DBusString * filename)608 _dbus_path_is_absolute (const DBusString *filename)
609 {
610   if (_dbus_string_get_length (filename) > 0)
611     return _dbus_string_get_byte (filename, 0) == '/';
612   else
613     return FALSE;
614 }
615 
616 /**
617  * stat() wrapper.
618  *
619  * @param filename the filename to stat
620  * @param statbuf the stat info to fill in
621  * @param error return location for error
622  * @returns #FALSE if error was set
623  */
624 dbus_bool_t
_dbus_stat(const DBusString * filename,DBusStat * statbuf,DBusError * error)625 _dbus_stat (const DBusString *filename,
626             DBusStat         *statbuf,
627             DBusError        *error)
628 {
629   const char *filename_c;
630   struct stat sb;
631 
632   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
633 
634   filename_c = _dbus_string_get_const_data (filename);
635 
636   if (stat (filename_c, &sb) < 0)
637     {
638       dbus_set_error (error, _dbus_error_from_errno (errno),
639                       "%s", _dbus_strerror (errno));
640       return FALSE;
641     }
642 
643   statbuf->mode = sb.st_mode;
644   statbuf->nlink = sb.st_nlink;
645   statbuf->uid = sb.st_uid;
646   statbuf->gid = sb.st_gid;
647   statbuf->size = sb.st_size;
648   statbuf->atime = sb.st_atime;
649   statbuf->mtime = sb.st_mtime;
650   statbuf->ctime = sb.st_ctime;
651 
652   return TRUE;
653 }
654 
655 
656 /**
657  * Internals of directory iterator
658  */
659 struct DBusDirIter
660 {
661   DIR *d; /**< The DIR* from opendir() */
662 
663 };
664 
665 /**
666  * Open a directory to iterate over.
667  *
668  * @param filename the directory name
669  * @param error exception return object or #NULL
670  * @returns new iterator, or #NULL on error
671  */
672 DBusDirIter*
_dbus_directory_open(const DBusString * filename,DBusError * error)673 _dbus_directory_open (const DBusString *filename,
674                       DBusError        *error)
675 {
676   DIR *d;
677   DBusDirIter *iter;
678   const char *filename_c;
679 
680   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
681 
682   filename_c = _dbus_string_get_const_data (filename);
683 
684   d = opendir (filename_c);
685   if (d == NULL)
686     {
687       dbus_set_error (error, _dbus_error_from_errno (errno),
688                       "Failed to read directory \"%s\": %s",
689                       filename_c,
690                       _dbus_strerror (errno));
691       return NULL;
692     }
693   iter = dbus_new0 (DBusDirIter, 1);
694   if (iter == NULL)
695     {
696       closedir (d);
697       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
698                       "Could not allocate memory for directory iterator");
699       return NULL;
700     }
701 
702   iter->d = d;
703 
704   return iter;
705 }
706 
707 /**
708  * Get next file in the directory. Will not return "." or ".."  on
709  * UNIX. If an error occurs, the contents of "filename" are
710  * undefined. The error is never set if the function succeeds.
711  *
712  * This function is not re-entrant, and not necessarily thread-safe.
713  * Only use it for test code or single-threaded utilities.
714  *
715  * @param iter the iterator
716  * @param filename string to be set to the next file in the dir
717  * @param error return location for error
718  * @returns #TRUE if filename was filled in with a new filename
719  */
720 dbus_bool_t
_dbus_directory_get_next_file(DBusDirIter * iter,DBusString * filename,DBusError * error)721 _dbus_directory_get_next_file (DBusDirIter      *iter,
722                                DBusString       *filename,
723                                DBusError        *error)
724 {
725   struct dirent *ent;
726   int err;
727 
728   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
729 
730  again:
731   errno = 0;
732   ent = readdir (iter->d);
733 
734   if (!ent)
735     {
736       err = errno;
737 
738       if (err != 0)
739         dbus_set_error (error,
740                         _dbus_error_from_errno (err),
741                         "%s", _dbus_strerror (err));
742 
743       return FALSE;
744     }
745   else if (ent->d_name[0] == '.' &&
746            (ent->d_name[1] == '\0' ||
747             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
748     goto again;
749   else
750     {
751       _dbus_string_set_length (filename, 0);
752       if (!_dbus_string_append (filename, ent->d_name))
753         {
754           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
755                           "No memory to read directory entry");
756           return FALSE;
757         }
758       else
759         {
760           return TRUE;
761         }
762     }
763 }
764 
765 /**
766  * Closes a directory iteration.
767  */
768 void
_dbus_directory_close(DBusDirIter * iter)769 _dbus_directory_close (DBusDirIter *iter)
770 {
771   closedir (iter->d);
772   dbus_free (iter);
773 }
774 
775 static dbus_bool_t
fill_user_info_from_group(struct group * g,DBusGroupInfo * info,DBusError * error)776 fill_user_info_from_group (struct group  *g,
777                            DBusGroupInfo *info,
778                            DBusError     *error)
779 {
780   _dbus_assert (g->gr_name != NULL);
781 
782   info->gid = g->gr_gid;
783   info->groupname = _dbus_strdup (g->gr_name);
784 
785   /* info->members = dbus_strdupv (g->gr_mem) */
786 
787   if (info->groupname == NULL)
788     {
789       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
790       return FALSE;
791     }
792 
793   return TRUE;
794 }
795 
796 static dbus_bool_t
fill_group_info(DBusGroupInfo * info,dbus_gid_t gid,const DBusString * groupname,DBusError * error)797 fill_group_info (DBusGroupInfo    *info,
798                  dbus_gid_t        gid,
799                  const DBusString *groupname,
800                  DBusError        *error)
801 {
802   const char *group_c_str;
803 
804   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
805   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
806 
807   if (groupname)
808     group_c_str = _dbus_string_get_const_data (groupname);
809   else
810     group_c_str = NULL;
811 
812   /* For now assuming that the getgrnam() and getgrgid() flavors
813    * always correspond to the pwnam flavors, if not we have
814    * to add more configure checks.
815    */
816 
817 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
818   {
819     struct group *g;
820     int result;
821     size_t buflen;
822     char *buf;
823     struct group g_str;
824     dbus_bool_t b;
825 
826     /* retrieve maximum needed size for buf */
827     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
828 
829     /* sysconf actually returns a long, but everything else expects size_t,
830      * so just recast here.
831      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
832      */
833     if ((long) buflen <= 0)
834       buflen = 1024;
835 
836     result = -1;
837     while (1)
838       {
839         buf = dbus_malloc (buflen);
840         if (buf == NULL)
841           {
842             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
843             return FALSE;
844           }
845 
846         g = NULL;
847 #ifdef HAVE_POSIX_GETPWNAM_R
848         if (group_c_str)
849           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
850                                &g);
851         else
852           result = getgrgid_r (gid, &g_str, buf, buflen,
853                                &g);
854 #else
855         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
856         result = 0;
857 #endif /* !HAVE_POSIX_GETPWNAM_R */
858         /* Try a bigger buffer if ERANGE was returned:
859            https://bugs.freedesktop.org/show_bug.cgi?id=16727
860         */
861         if (result == ERANGE && buflen < 512 * 1024)
862           {
863             dbus_free (buf);
864             buflen *= 2;
865           }
866         else
867           {
868             break;
869           }
870       }
871 
872     if (result == 0 && g == &g_str)
873       {
874         b = fill_user_info_from_group (g, info, error);
875         dbus_free (buf);
876         return b;
877       }
878     else
879       {
880         dbus_set_error (error, _dbus_error_from_errno (errno),
881                         "Group %s unknown or failed to look it up\n",
882                         group_c_str ? group_c_str : "???");
883         dbus_free (buf);
884         return FALSE;
885       }
886   }
887 #else /* ! HAVE_GETPWNAM_R */
888   {
889     /* I guess we're screwed on thread safety here */
890     struct group *g;
891 
892     g = getgrnam (group_c_str);
893 
894     if (g != NULL)
895       {
896         return fill_user_info_from_group (g, info, error);
897       }
898     else
899       {
900         dbus_set_error (error, _dbus_error_from_errno (errno),
901                         "Group %s unknown or failed to look it up\n",
902                         group_c_str ? group_c_str : "???");
903         return FALSE;
904       }
905   }
906 #endif  /* ! HAVE_GETPWNAM_R */
907 }
908 
909 /**
910  * Initializes the given DBusGroupInfo struct
911  * with information about the given group name.
912  *
913  * @param info the group info struct
914  * @param groupname name of group
915  * @param error the error return
916  * @returns #FALSE if error is set
917  */
918 dbus_bool_t
_dbus_group_info_fill(DBusGroupInfo * info,const DBusString * groupname,DBusError * error)919 _dbus_group_info_fill (DBusGroupInfo    *info,
920                        const DBusString *groupname,
921                        DBusError        *error)
922 {
923   return fill_group_info (info, DBUS_GID_UNSET,
924                           groupname, error);
925 
926 }
927 
928 /**
929  * Initializes the given DBusGroupInfo struct
930  * with information about the given group ID.
931  *
932  * @param info the group info struct
933  * @param gid group ID
934  * @param error the error return
935  * @returns #FALSE if error is set
936  */
937 dbus_bool_t
_dbus_group_info_fill_gid(DBusGroupInfo * info,dbus_gid_t gid,DBusError * error)938 _dbus_group_info_fill_gid (DBusGroupInfo *info,
939                            dbus_gid_t     gid,
940                            DBusError     *error)
941 {
942   return fill_group_info (info, gid, NULL, error);
943 }
944 
945 /**
946  * Parse a UNIX user from the bus config file. On Windows, this should
947  * simply always fail (just return #FALSE).
948  *
949  * @param username the username text
950  * @param uid_p place to return the uid
951  * @returns #TRUE on success
952  */
953 dbus_bool_t
_dbus_parse_unix_user_from_config(const DBusString * username,dbus_uid_t * uid_p)954 _dbus_parse_unix_user_from_config (const DBusString  *username,
955                                    dbus_uid_t        *uid_p)
956 {
957   return _dbus_get_user_id (username, uid_p);
958 
959 }
960 
961 /**
962  * Parse a UNIX group from the bus config file. On Windows, this should
963  * simply always fail (just return #FALSE).
964  *
965  * @param groupname the groupname text
966  * @param gid_p place to return the gid
967  * @returns #TRUE on success
968  */
969 dbus_bool_t
_dbus_parse_unix_group_from_config(const DBusString * groupname,dbus_gid_t * gid_p)970 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
971                                     dbus_gid_t        *gid_p)
972 {
973   return _dbus_get_group_id (groupname, gid_p);
974 }
975 
976 /**
977  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
978  * just calls _dbus_groups_from_uid(). On Windows, should always
979  * fail since we don't know any UNIX groups.
980  *
981  * @param uid the UID
982  * @param group_ids return location for array of group IDs
983  * @param n_group_ids return location for length of returned array
984  * @returns #TRUE if the UID existed and we got some credentials
985  */
986 dbus_bool_t
_dbus_unix_groups_from_uid(dbus_uid_t uid,dbus_gid_t ** group_ids,int * n_group_ids)987 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
988                             dbus_gid_t          **group_ids,
989                             int                  *n_group_ids)
990 {
991   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
992 }
993 
994 /**
995  * Checks to see if the UNIX user ID is at the console.
996  * Should always fail on Windows (set the error to
997  * #DBUS_ERROR_NOT_SUPPORTED).
998  *
999  * @param uid UID of person to check
1000  * @param error return location for errors
1001  * @returns #TRUE if the UID is the same as the console user and there are no errors
1002  */
1003 dbus_bool_t
_dbus_unix_user_is_at_console(dbus_uid_t uid,DBusError * error)1004 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
1005                                DBusError         *error)
1006 {
1007   return _dbus_is_console_user (uid, error);
1008 
1009 }
1010 
1011 /**
1012  * Checks to see if the UNIX user ID matches the UID of
1013  * the process. Should always return #FALSE on Windows.
1014  *
1015  * @param uid the UNIX user ID
1016  * @returns #TRUE if this uid owns the process.
1017  */
1018 dbus_bool_t
_dbus_unix_user_is_process_owner(dbus_uid_t uid)1019 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1020 {
1021   return uid == _dbus_geteuid ();
1022 }
1023 
1024 /**
1025  * Checks to see if the Windows user SID matches the owner of
1026  * the process. Should always return #FALSE on UNIX.
1027  *
1028  * @param windows_sid the Windows user SID
1029  * @returns #TRUE if this user owns the process.
1030  */
1031 dbus_bool_t
_dbus_windows_user_is_process_owner(const char * windows_sid)1032 _dbus_windows_user_is_process_owner (const char *windows_sid)
1033 {
1034   return FALSE;
1035 }
1036 
1037 /** @} */ /* End of DBusInternalsUtils functions */
1038 
1039 /**
1040  * @addtogroup DBusString
1041  *
1042  * @{
1043  */
1044 /**
1045  * Get the directory name from a complete filename
1046  * @param filename the filename
1047  * @param dirname string to append directory name to
1048  * @returns #FALSE if no memory
1049  */
1050 dbus_bool_t
_dbus_string_get_dirname(const DBusString * filename,DBusString * dirname)1051 _dbus_string_get_dirname  (const DBusString *filename,
1052                            DBusString       *dirname)
1053 {
1054   int sep;
1055 
1056   _dbus_assert (filename != dirname);
1057   _dbus_assert (filename != NULL);
1058   _dbus_assert (dirname != NULL);
1059 
1060   /* Ignore any separators on the end */
1061   sep = _dbus_string_get_length (filename);
1062   if (sep == 0)
1063     return _dbus_string_append (dirname, "."); /* empty string passed in */
1064 
1065   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1066     --sep;
1067 
1068   _dbus_assert (sep >= 0);
1069 
1070   if (sep == 0)
1071     return _dbus_string_append (dirname, "/");
1072 
1073   /* Now find the previous separator */
1074   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1075   if (sep < 0)
1076     return _dbus_string_append (dirname, ".");
1077 
1078   /* skip multiple separators */
1079   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1080     --sep;
1081 
1082   _dbus_assert (sep >= 0);
1083 
1084   if (sep == 0 &&
1085       _dbus_string_get_byte (filename, 0) == '/')
1086     return _dbus_string_append (dirname, "/");
1087   else
1088     return _dbus_string_copy_len (filename, 0, sep - 0,
1089                                   dirname, _dbus_string_get_length (dirname));
1090 }
1091 /** @} */ /* DBusString stuff */
1092 
1093 static void
string_squash_nonprintable(DBusString * str)1094 string_squash_nonprintable (DBusString *str)
1095 {
1096   unsigned char *buf;
1097   int i, len;
1098 
1099   buf = _dbus_string_get_udata (str);
1100   len = _dbus_string_get_length (str);
1101 
1102   for (i = 0; i < len; i++)
1103     {
1104       unsigned char c = (unsigned char) buf[i];
1105       if (c == '\0')
1106         buf[i] = ' ';
1107       else if (c < 0x20 || c > 127)
1108         buf[i] = '?';
1109     }
1110 }
1111 
1112 /**
1113  * Get a printable string describing the command used to execute
1114  * the process with pid.  This string should only be used for
1115  * informative purposes such as logging; it may not be trusted.
1116  *
1117  * The command is guaranteed to be printable ASCII and no longer
1118  * than max_len.
1119  *
1120  * @param pid Process id
1121  * @param str Append command to this string
1122  * @param max_len Maximum length of returned command
1123  * @param error return location for errors
1124  * @returns #FALSE on error
1125  */
1126 dbus_bool_t
_dbus_command_for_pid(unsigned long pid,DBusString * str,int max_len,DBusError * error)1127 _dbus_command_for_pid (unsigned long  pid,
1128                        DBusString    *str,
1129                        int            max_len,
1130                        DBusError     *error)
1131 {
1132   /* This is all Linux-specific for now */
1133   DBusString path;
1134   DBusString cmdline;
1135   int fd;
1136 
1137   if (!_dbus_string_init (&path))
1138     {
1139       _DBUS_SET_OOM (error);
1140       return FALSE;
1141     }
1142 
1143   if (!_dbus_string_init (&cmdline))
1144     {
1145       _DBUS_SET_OOM (error);
1146       _dbus_string_free (&path);
1147       return FALSE;
1148     }
1149 
1150   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1151     goto oom;
1152 
1153   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1154   if (fd < 0)
1155     {
1156       dbus_set_error (error,
1157                       _dbus_error_from_errno (errno),
1158                       "Failed to open \"%s\": %s",
1159                       _dbus_string_get_const_data (&path),
1160                       _dbus_strerror (errno));
1161       goto fail;
1162     }
1163 
1164   if (!_dbus_read (fd, &cmdline, max_len))
1165     {
1166       dbus_set_error (error,
1167                       _dbus_error_from_errno (errno),
1168                       "Failed to read from \"%s\": %s",
1169                       _dbus_string_get_const_data (&path),
1170                       _dbus_strerror (errno));
1171       _dbus_close (fd, NULL);
1172       goto fail;
1173     }
1174 
1175   if (!_dbus_close (fd, error))
1176     goto fail;
1177 
1178   string_squash_nonprintable (&cmdline);
1179 
1180   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1181     goto oom;
1182 
1183   _dbus_string_free (&cmdline);
1184   _dbus_string_free (&path);
1185   return TRUE;
1186 oom:
1187   _DBUS_SET_OOM (error);
1188 fail:
1189   _dbus_string_free (&cmdline);
1190   _dbus_string_free (&path);
1191   return FALSE;
1192 }
1193 
1194 /**
1195  * Replace the DBUS_PREFIX in the given path, in-place, by the
1196  * current D-Bus installation directory. On Unix this function
1197  * does nothing, successfully.
1198  *
1199  * @param path path to edit
1200  * @return #FALSE on OOM
1201  */
1202 dbus_bool_t
_dbus_replace_install_prefix(DBusString * path)1203 _dbus_replace_install_prefix (DBusString *path)
1204 {
1205   return TRUE;
1206 }
1207 
1208 static dbus_bool_t
ensure_owned_directory(const char * label,const DBusString * string,dbus_bool_t create,DBusError * error)1209 ensure_owned_directory (const char *label,
1210                         const DBusString *string,
1211                         dbus_bool_t create,
1212                         DBusError *error)
1213 {
1214   const char *dir = _dbus_string_get_const_data (string);
1215   struct stat buf;
1216 
1217   if (create && !_dbus_ensure_directory (string, error))
1218     return FALSE;
1219 
1220   /*
1221    * The stat()-based checks in this function are to protect against
1222    * mistakes, not malice. We are working in a directory that is meant
1223    * to be trusted; but if a user has used `su` or similar to escalate
1224    * their privileges without correctly clearing the environment, the
1225    * XDG_RUNTIME_DIR in the environment might still be the user's
1226    * and not root's. We don't want to write root-owned files into that
1227    * directory, so just warn and don't provide support for transient
1228    * services in that case.
1229    *
1230    * In particular, we use stat() and not lstat() so that if we later
1231    * decide to use a different directory name for transient services,
1232    * we can drop in a compatibility symlink without breaking older
1233    * libdbus.
1234    */
1235 
1236   if (stat (dir, &buf) != 0)
1237     {
1238       int saved_errno = errno;
1239 
1240       dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1241                       "%s \"%s\" not available: %s", label, dir,
1242                       _dbus_strerror (saved_errno));
1243       return FALSE;
1244     }
1245 
1246   if (!S_ISDIR (buf.st_mode))
1247     {
1248       dbus_set_error (error, DBUS_ERROR_FAILED, "%s \"%s\" is not a directory",
1249                       label, dir);
1250       return FALSE;
1251     }
1252 
1253   if (buf.st_uid != geteuid ())
1254     {
1255       dbus_set_error (error, DBUS_ERROR_FAILED,
1256                       "%s \"%s\" is owned by uid %ld, not our uid %ld",
1257                       label, dir, (long) buf.st_uid, (long) geteuid ());
1258       return FALSE;
1259     }
1260 
1261   /* This is just because we have the stat() results already, so we might
1262    * as well check opportunistically. */
1263   if ((S_IWOTH | S_IWGRP) & buf.st_mode)
1264     {
1265       dbus_set_error (error, DBUS_ERROR_FAILED,
1266                       "%s \"%s\" can be written by others (mode 0%o)",
1267                       label, dir, buf.st_mode);
1268       return FALSE;
1269     }
1270 
1271   return TRUE;
1272 }
1273 
1274 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1275 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1276 
1277 /**
1278  * Returns the standard directories for a session bus to look for
1279  * transient service activation files.
1280  *
1281  * @param dirs the directory list we are returning
1282  * @returns #FALSE on error
1283  */
1284 dbus_bool_t
_dbus_set_up_transient_session_servicedirs(DBusList ** dirs,DBusError * error)1285 _dbus_set_up_transient_session_servicedirs (DBusList  **dirs,
1286                                             DBusError  *error)
1287 {
1288   const char *xdg_runtime_dir;
1289   DBusString services;
1290   DBusString dbus1;
1291   DBusString xrd;
1292   dbus_bool_t ret = FALSE;
1293   char *data = NULL;
1294 
1295   if (!_dbus_string_init (&dbus1))
1296     {
1297       _DBUS_SET_OOM (error);
1298       return FALSE;
1299     }
1300 
1301   if (!_dbus_string_init (&services))
1302     {
1303       _dbus_string_free (&dbus1);
1304       _DBUS_SET_OOM (error);
1305       return FALSE;
1306     }
1307 
1308   if (!_dbus_string_init (&xrd))
1309     {
1310       _dbus_string_free (&dbus1);
1311       _dbus_string_free (&services);
1312       _DBUS_SET_OOM (error);
1313       return FALSE;
1314     }
1315 
1316   xdg_runtime_dir = _dbus_getenv ("XDG_RUNTIME_DIR");
1317 
1318   /* Not an error, we just can't have transient session services */
1319   if (xdg_runtime_dir == NULL)
1320     {
1321       _dbus_verbose ("XDG_RUNTIME_DIR is unset: transient session services "
1322                      "not available here\n");
1323       ret = TRUE;
1324       goto out;
1325     }
1326 
1327   if (!_dbus_string_append (&xrd, xdg_runtime_dir) ||
1328       !_dbus_string_append_printf (&dbus1, "%s/dbus-1",
1329                                    xdg_runtime_dir) ||
1330       !_dbus_string_append_printf (&services, "%s/dbus-1/services",
1331                                    xdg_runtime_dir))
1332     {
1333       _DBUS_SET_OOM (error);
1334       goto out;
1335     }
1336 
1337   if (!ensure_owned_directory ("XDG_RUNTIME_DIR", &xrd, FALSE, error) ||
1338       !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &dbus1, TRUE,
1339                                error) ||
1340       !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &services,
1341                                TRUE, error))
1342     goto out;
1343 
1344   if (!_dbus_string_steal_data (&services, &data) ||
1345       !_dbus_list_append (dirs, data))
1346     {
1347       _DBUS_SET_OOM (error);
1348       goto out;
1349     }
1350 
1351   _dbus_verbose ("Transient service directory is %s\n", data);
1352   /* Ownership was transferred to @dirs */
1353   data = NULL;
1354   ret = TRUE;
1355 
1356 out:
1357   _dbus_string_free (&dbus1);
1358   _dbus_string_free (&services);
1359   _dbus_string_free (&xrd);
1360   dbus_free (data);
1361   return ret;
1362 }
1363 
1364 /**
1365  * Returns the standard directories for a session bus to look for service
1366  * activation files
1367  *
1368  * On UNIX this should be the standard xdg freedesktop.org data directories:
1369  *
1370  * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
1371  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1372  *
1373  * and
1374  *
1375  * DBUS_DATADIR
1376  *
1377  * @param dirs the directory list we are returning
1378  * @returns #FALSE on OOM
1379  */
1380 
1381 dbus_bool_t
_dbus_get_standard_session_servicedirs(DBusList ** dirs)1382 _dbus_get_standard_session_servicedirs (DBusList **dirs)
1383 {
1384   const char *xdg_data_home;
1385   const char *xdg_data_dirs;
1386   DBusString servicedir_path;
1387 
1388   if (!_dbus_string_init (&servicedir_path))
1389     return FALSE;
1390 
1391   xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
1392   xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
1393 
1394   if (xdg_data_home != NULL)
1395     {
1396       if (!_dbus_string_append (&servicedir_path, xdg_data_home))
1397         goto oom;
1398     }
1399   else
1400     {
1401       const DBusString *homedir;
1402       DBusString local_share;
1403 
1404       if (!_dbus_homedir_from_current_process (&homedir))
1405         goto oom;
1406 
1407       if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
1408         goto oom;
1409 
1410       _dbus_string_init_const (&local_share, "/.local/share");
1411       if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
1412         goto oom;
1413     }
1414 
1415   if (!_dbus_string_append (&servicedir_path, ":"))
1416     goto oom;
1417 
1418   if (xdg_data_dirs != NULL)
1419     {
1420       if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
1421         goto oom;
1422 
1423       if (!_dbus_string_append (&servicedir_path, ":"))
1424         goto oom;
1425     }
1426   else
1427     {
1428       if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
1429         goto oom;
1430     }
1431 
1432   /*
1433    * add configured datadir to defaults
1434    * this may be the same as an xdg dir
1435    * however the config parser should take
1436    * care of duplicates
1437    */
1438   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
1439     goto oom;
1440 
1441   if (!_dbus_split_paths_and_append (&servicedir_path,
1442                                      DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1443                                      dirs))
1444     goto oom;
1445 
1446   _dbus_string_free (&servicedir_path);
1447   return TRUE;
1448 
1449  oom:
1450   _dbus_string_free (&servicedir_path);
1451   return FALSE;
1452 }
1453 
1454 
1455 /**
1456  * Returns the standard directories for a system bus to look for service
1457  * activation files
1458  *
1459  * On UNIX this should be the standard xdg freedesktop.org data directories:
1460  *
1461  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1462  *
1463  * and
1464  *
1465  * DBUS_DATADIR
1466  *
1467  * On Windows there is no system bus and this function can return nothing.
1468  *
1469  * @param dirs the directory list we are returning
1470  * @returns #FALSE on OOM
1471  */
1472 
1473 dbus_bool_t
_dbus_get_standard_system_servicedirs(DBusList ** dirs)1474 _dbus_get_standard_system_servicedirs (DBusList **dirs)
1475 {
1476   /*
1477    * DBUS_DATADIR may be the same as one of the standard directories. However,
1478    * the config parser should take care of the duplicates.
1479    *
1480    * Also, append /lib as counterpart of /usr/share on the root
1481    * directory (the root directory does not know /share), in order to
1482    * facilitate early boot system bus activation where /usr might not
1483    * be available.
1484    */
1485   static const char standard_search_path[] =
1486     "/usr/local/share:"
1487     "/usr/share:"
1488     DBUS_DATADIR ":"
1489     "/lib";
1490   DBusString servicedir_path;
1491 
1492   _dbus_string_init_const (&servicedir_path, standard_search_path);
1493 
1494   return _dbus_split_paths_and_append (&servicedir_path,
1495                                        DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1496                                        dirs);
1497 }
1498 
1499 /**
1500  * Get the absolute path of the system.conf file
1501  * (there is no system bus on Windows so this can just
1502  * return FALSE and print a warning or something)
1503  *
1504  * @param str the string to append to, which must be empty on entry
1505  * @returns #FALSE if no memory
1506  */
1507 dbus_bool_t
_dbus_get_system_config_file(DBusString * str)1508 _dbus_get_system_config_file (DBusString *str)
1509 {
1510   _dbus_assert (_dbus_string_get_length (str) == 0);
1511 
1512   return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
1513 }
1514 
1515 /**
1516  * Get the absolute path of the session.conf file.
1517  *
1518  * @param str the string to append to, which must be empty on entry
1519  * @returns #FALSE if no memory
1520  */
1521 dbus_bool_t
_dbus_get_session_config_file(DBusString * str)1522 _dbus_get_session_config_file (DBusString *str)
1523 {
1524   _dbus_assert (_dbus_string_get_length (str) == 0);
1525 
1526   return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
1527 }
1528 
1529 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1530 
1531 /*
1532  * Set uid to a machine-readable authentication identity (numeric Unix
1533  * uid or ConvertSidToStringSid-style Windows SID) that is likely to exist,
1534  * and differs from the identity of the current process.
1535  *
1536  * @param uid Populated with a machine-readable authentication identity
1537  *    on success
1538  * @returns #FALSE if no memory
1539  */
1540 dbus_bool_t
_dbus_test_append_different_uid(DBusString * uid)1541 _dbus_test_append_different_uid (DBusString *uid)
1542 {
1543   if (geteuid () == 0)
1544     return _dbus_string_append (uid, "65534");
1545   else
1546     return _dbus_string_append (uid, "0");
1547 }
1548 
1549 /*
1550  * Set uid to a human-readable authentication identity (login name)
1551  * that is likely to exist, and differs from the identity of the current
1552  * process. This function currently only exists on Unix platforms.
1553  *
1554  * @param uid Populated with a machine-readable authentication identity
1555  *    on success
1556  * @returns #FALSE if no memory
1557  */
1558 dbus_bool_t
_dbus_test_append_different_username(DBusString * username)1559 _dbus_test_append_different_username (DBusString *username)
1560 {
1561   if (geteuid () == 0)
1562     return _dbus_string_append (username, "nobody");
1563   else
1564     return _dbus_string_append (username, "root");
1565 }
1566 
1567 #endif
1568