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