Deprecate the pam_console/pam_foreground flag-file directory
[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 dbus_bool_t
410 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int  desired,
411                                            DBusError    *error)
412 {
413   struct rlimit lim;
414
415   /* No point to doing this practically speaking
416    * if we're not uid 0.  We expect the system
417    * bus to use this before we change UID, and
418    * the session bus takes the Linux default,
419    * currently 1024 for cur and 4096 for max.
420    */
421   if (getuid () != 0)
422     {
423       /* not an error, we're probably the session bus */
424       return TRUE;
425     }
426
427   if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
428     {
429       dbus_set_error (error, _dbus_error_from_errno (errno),
430                       "Failed to get fd limit: %s", _dbus_strerror (errno));
431       return FALSE;
432     }
433
434   if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= desired)
435     {
436       /* not an error, everything is fine */
437       return TRUE;
438     }
439
440   /* Ignore "maximum limit", assume we have the "superuser"
441    * privileges.  On Linux this is CAP_SYS_RESOURCE.
442    */
443   lim.rlim_cur = lim.rlim_max = desired;
444
445   if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
446     {
447       dbus_set_error (error, _dbus_error_from_errno (errno),
448                       "Failed to set fd limit to %u: %s",
449                       desired, _dbus_strerror (errno));
450       return FALSE;
451     }
452
453   return TRUE;
454 }
455
456 dbus_bool_t
457 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
458                                DBusError  *error)
459 {
460   if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
461     {
462       dbus_set_error (error, _dbus_error_from_errno (errno),
463                       "Failed to restore old fd limit: %s",
464                       _dbus_strerror (errno));
465       return FALSE;
466     }
467
468   return TRUE;
469 }
470
471 #else /* !HAVE_SETRLIMIT */
472
473 static void
474 fd_limit_not_supported (DBusError *error)
475 {
476   dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
477                   "cannot change fd limit on this platform");
478 }
479
480 DBusRLimit *
481 _dbus_rlimit_save_fd_limit (DBusError *error)
482 {
483   fd_limit_not_supported (error);
484   return NULL;
485 }
486
487 dbus_bool_t
488 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int  desired,
489                                            DBusError    *error)
490 {
491   fd_limit_not_supported (error);
492   return FALSE;
493 }
494
495 dbus_bool_t
496 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
497                                DBusError  *error)
498 {
499   fd_limit_not_supported (error);
500   return FALSE;
501 }
502
503 #endif
504
505 void
506 _dbus_rlimit_free (DBusRLimit *lim)
507 {
508   dbus_free (lim);
509 }
510
511 /** Installs a UNIX signal handler
512  *
513  * @param sig the signal to handle
514  * @param handler the handler
515  */
516 void
517 _dbus_set_signal_handler (int               sig,
518                           DBusSignalHandler handler)
519 {
520   struct sigaction act;
521   sigset_t empty_mask;
522   
523   sigemptyset (&empty_mask);
524   act.sa_handler = handler;
525   act.sa_mask    = empty_mask;
526   act.sa_flags   = 0;
527   sigaction (sig,  &act, NULL);
528 }
529
530 /** Checks if a file exists
531 *
532 * @param file full path to the file
533 * @returns #TRUE if file exists
534 */
535 dbus_bool_t 
536 _dbus_file_exists (const char *file)
537 {
538   return (access (file, F_OK) == 0);
539 }
540
541 /** Checks if user is at the console
542 *
543 * @param username user to check
544 * @param error return location for errors
545 * @returns #TRUE is the user is at the consolei and there are no errors
546 */
547 dbus_bool_t 
548 _dbus_user_at_console (const char *username,
549                        DBusError  *error)
550 {
551 #ifdef DBUS_CONSOLE_AUTH_DIR
552   DBusString u, f;
553   dbus_bool_t result;
554
555   result = FALSE;
556   if (!_dbus_string_init (&f))
557     {
558       _DBUS_SET_OOM (error);
559       return FALSE;
560     }
561
562   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
563     {
564       _DBUS_SET_OOM (error);
565       goto out;
566     }
567
568   _dbus_string_init_const (&u, username);
569
570   if (!_dbus_concat_dir_and_file (&f, &u))
571     {
572       _DBUS_SET_OOM (error);
573       goto out;
574     }
575
576   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
577
578  out:
579   _dbus_string_free (&f);
580
581   return result;
582 #else
583   return FALSE;
584 #endif
585 }
586
587
588 /**
589  * Checks whether the filename is an absolute path
590  *
591  * @param filename the filename
592  * @returns #TRUE if an absolute path
593  */
594 dbus_bool_t
595 _dbus_path_is_absolute (const DBusString *filename)
596 {
597   if (_dbus_string_get_length (filename) > 0)
598     return _dbus_string_get_byte (filename, 0) == '/';
599   else
600     return FALSE;
601 }
602
603 /**
604  * stat() wrapper.
605  *
606  * @param filename the filename to stat
607  * @param statbuf the stat info to fill in
608  * @param error return location for error
609  * @returns #FALSE if error was set
610  */
611 dbus_bool_t
612 _dbus_stat (const DBusString *filename,
613             DBusStat         *statbuf,
614             DBusError        *error)
615 {
616   const char *filename_c;
617   struct stat sb;
618
619   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
620   
621   filename_c = _dbus_string_get_const_data (filename);
622
623   if (stat (filename_c, &sb) < 0)
624     {
625       dbus_set_error (error, _dbus_error_from_errno (errno),
626                       "%s", _dbus_strerror (errno));
627       return FALSE;
628     }
629
630   statbuf->mode = sb.st_mode;
631   statbuf->nlink = sb.st_nlink;
632   statbuf->uid = sb.st_uid;
633   statbuf->gid = sb.st_gid;
634   statbuf->size = sb.st_size;
635   statbuf->atime = sb.st_atime;
636   statbuf->mtime = sb.st_mtime;
637   statbuf->ctime = sb.st_ctime;
638
639   return TRUE;
640 }
641
642
643 /**
644  * Internals of directory iterator
645  */
646 struct DBusDirIter
647 {
648   DIR *d; /**< The DIR* from opendir() */
649   
650 };
651
652 /**
653  * Open a directory to iterate over.
654  *
655  * @param filename the directory name
656  * @param error exception return object or #NULL
657  * @returns new iterator, or #NULL on error
658  */
659 DBusDirIter*
660 _dbus_directory_open (const DBusString *filename,
661                       DBusError        *error)
662 {
663   DIR *d;
664   DBusDirIter *iter;
665   const char *filename_c;
666
667   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
668   
669   filename_c = _dbus_string_get_const_data (filename);
670
671   d = opendir (filename_c);
672   if (d == NULL)
673     {
674       dbus_set_error (error, _dbus_error_from_errno (errno),
675                       "Failed to read directory \"%s\": %s",
676                       filename_c,
677                       _dbus_strerror (errno));
678       return NULL;
679     }
680   iter = dbus_new0 (DBusDirIter, 1);
681   if (iter == NULL)
682     {
683       closedir (d);
684       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
685                       "Could not allocate memory for directory iterator");
686       return NULL;
687     }
688
689   iter->d = d;
690
691   return iter;
692 }
693
694 /**
695  * Get next file in the directory. Will not return "." or ".."  on
696  * UNIX. If an error occurs, the contents of "filename" are
697  * undefined. The error is never set if the function succeeds.
698  *
699  * This function is not re-entrant, and not necessarily thread-safe.
700  * Only use it for test code or single-threaded utilities.
701  *
702  * @param iter the iterator
703  * @param filename string to be set to the next file in the dir
704  * @param error return location for error
705  * @returns #TRUE if filename was filled in with a new filename
706  */
707 dbus_bool_t
708 _dbus_directory_get_next_file (DBusDirIter      *iter,
709                                DBusString       *filename,
710                                DBusError        *error)
711 {
712   struct dirent *ent;
713   int err;
714
715   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
716
717  again:
718   errno = 0;
719   ent = readdir (iter->d);
720
721   if (!ent)
722     {
723       err = errno;
724
725       if (err != 0)
726         dbus_set_error (error,
727                         _dbus_error_from_errno (err),
728                         "%s", _dbus_strerror (err));
729
730       return FALSE;
731     }
732   else if (ent->d_name[0] == '.' &&
733            (ent->d_name[1] == '\0' ||
734             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
735     goto again;
736   else
737     {
738       _dbus_string_set_length (filename, 0);
739       if (!_dbus_string_append (filename, ent->d_name))
740         {
741           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
742                           "No memory to read directory entry");
743           return FALSE;
744         }
745       else
746         {
747           return TRUE;
748         }
749     }
750 }
751
752 /**
753  * Closes a directory iteration.
754  */
755 void
756 _dbus_directory_close (DBusDirIter *iter)
757 {
758   closedir (iter->d);
759   dbus_free (iter);
760 }
761
762 static dbus_bool_t
763 fill_user_info_from_group (struct group  *g,
764                            DBusGroupInfo *info,
765                            DBusError     *error)
766 {
767   _dbus_assert (g->gr_name != NULL);
768   
769   info->gid = g->gr_gid;
770   info->groupname = _dbus_strdup (g->gr_name);
771
772   /* info->members = dbus_strdupv (g->gr_mem) */
773   
774   if (info->groupname == NULL)
775     {
776       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
777       return FALSE;
778     }
779
780   return TRUE;
781 }
782
783 static dbus_bool_t
784 fill_group_info (DBusGroupInfo    *info,
785                  dbus_gid_t        gid,
786                  const DBusString *groupname,
787                  DBusError        *error)
788 {
789   const char *group_c_str;
790
791   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
792   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
793
794   if (groupname)
795     group_c_str = _dbus_string_get_const_data (groupname);
796   else
797     group_c_str = NULL;
798   
799   /* For now assuming that the getgrnam() and getgrgid() flavors
800    * always correspond to the pwnam flavors, if not we have
801    * to add more configure checks.
802    */
803   
804 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
805   {
806     struct group *g;
807     int result;
808     size_t buflen;
809     char *buf;
810     struct group g_str;
811     dbus_bool_t b;
812
813     /* retrieve maximum needed size for buf */
814     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
815
816     /* sysconf actually returns a long, but everything else expects size_t,
817      * so just recast here.
818      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
819      */
820     if ((long) buflen <= 0)
821       buflen = 1024;
822
823     result = -1;
824     while (1)
825       {
826         buf = dbus_malloc (buflen);
827         if (buf == NULL)
828           {
829             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
830             return FALSE;
831           }
832
833         g = NULL;
834 #ifdef HAVE_POSIX_GETPWNAM_R
835         if (group_c_str)
836           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
837                                &g);
838         else
839           result = getgrgid_r (gid, &g_str, buf, buflen,
840                                &g);
841 #else
842         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
843         result = 0;
844 #endif /* !HAVE_POSIX_GETPWNAM_R */
845         /* Try a bigger buffer if ERANGE was returned:
846            https://bugs.freedesktop.org/show_bug.cgi?id=16727
847         */
848         if (result == ERANGE && buflen < 512 * 1024)
849           {
850             dbus_free (buf);
851             buflen *= 2;
852           }
853         else
854           {
855             break;
856           }
857       }
858
859     if (result == 0 && g == &g_str)
860       {
861         b = fill_user_info_from_group (g, info, error);
862         dbus_free (buf);
863         return b;
864       }
865     else
866       {
867         dbus_set_error (error, _dbus_error_from_errno (errno),
868                         "Group %s unknown or failed to look it up\n",
869                         group_c_str ? group_c_str : "???");
870         dbus_free (buf);
871         return FALSE;
872       }
873   }
874 #else /* ! HAVE_GETPWNAM_R */
875   {
876     /* I guess we're screwed on thread safety here */
877     struct group *g;
878
879     g = getgrnam (group_c_str);
880
881     if (g != NULL)
882       {
883         return fill_user_info_from_group (g, info, error);
884       }
885     else
886       {
887         dbus_set_error (error, _dbus_error_from_errno (errno),
888                         "Group %s unknown or failed to look it up\n",
889                         group_c_str ? group_c_str : "???");
890         return FALSE;
891       }
892   }
893 #endif  /* ! HAVE_GETPWNAM_R */
894 }
895
896 /**
897  * Initializes the given DBusGroupInfo struct
898  * with information about the given group name.
899  *
900  * @param info the group info struct
901  * @param groupname name of group
902  * @param error the error return
903  * @returns #FALSE if error is set
904  */
905 dbus_bool_t
906 _dbus_group_info_fill (DBusGroupInfo    *info,
907                        const DBusString *groupname,
908                        DBusError        *error)
909 {
910   return fill_group_info (info, DBUS_GID_UNSET,
911                           groupname, error);
912
913 }
914
915 /**
916  * Initializes the given DBusGroupInfo struct
917  * with information about the given group ID.
918  *
919  * @param info the group info struct
920  * @param gid group ID
921  * @param error the error return
922  * @returns #FALSE if error is set
923  */
924 dbus_bool_t
925 _dbus_group_info_fill_gid (DBusGroupInfo *info,
926                            dbus_gid_t     gid,
927                            DBusError     *error)
928 {
929   return fill_group_info (info, gid, NULL, error);
930 }
931
932 /**
933  * Parse a UNIX user from the bus config file. On Windows, this should
934  * simply always fail (just return #FALSE).
935  *
936  * @param username the username text
937  * @param uid_p place to return the uid
938  * @returns #TRUE on success
939  */
940 dbus_bool_t
941 _dbus_parse_unix_user_from_config (const DBusString  *username,
942                                    dbus_uid_t        *uid_p)
943 {
944   return _dbus_get_user_id (username, uid_p);
945
946 }
947
948 /**
949  * Parse a UNIX group from the bus config file. On Windows, this should
950  * simply always fail (just return #FALSE).
951  *
952  * @param groupname the groupname text
953  * @param gid_p place to return the gid
954  * @returns #TRUE on success
955  */
956 dbus_bool_t
957 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
958                                     dbus_gid_t        *gid_p)
959 {
960   return _dbus_get_group_id (groupname, gid_p);
961 }
962
963 /**
964  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
965  * just calls _dbus_groups_from_uid(). On Windows, should always
966  * fail since we don't know any UNIX groups.
967  *
968  * @param uid the UID
969  * @param group_ids return location for array of group IDs
970  * @param n_group_ids return location for length of returned array
971  * @returns #TRUE if the UID existed and we got some credentials
972  */
973 dbus_bool_t
974 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
975                             dbus_gid_t          **group_ids,
976                             int                  *n_group_ids)
977 {
978   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
979 }
980
981 /**
982  * Checks to see if the UNIX user ID is at the console.
983  * Should always fail on Windows (set the error to
984  * #DBUS_ERROR_NOT_SUPPORTED).
985  *
986  * @param uid UID of person to check 
987  * @param error return location for errors
988  * @returns #TRUE if the UID is the same as the console user and there are no errors
989  */
990 dbus_bool_t
991 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
992                                DBusError         *error)
993 {
994   return _dbus_is_console_user (uid, error);
995
996 }
997
998 /**
999  * Checks to see if the UNIX user ID matches the UID of
1000  * the process. Should always return #FALSE on Windows.
1001  *
1002  * @param uid the UNIX user ID
1003  * @returns #TRUE if this uid owns the process.
1004  */
1005 dbus_bool_t
1006 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1007 {
1008   return uid == _dbus_geteuid ();
1009 }
1010
1011 /**
1012  * Checks to see if the Windows user SID matches the owner of
1013  * the process. Should always return #FALSE on UNIX.
1014  *
1015  * @param windows_sid the Windows user SID
1016  * @returns #TRUE if this user owns the process.
1017  */
1018 dbus_bool_t
1019 _dbus_windows_user_is_process_owner (const char *windows_sid)
1020 {
1021   return FALSE;
1022 }
1023
1024 /** @} */ /* End of DBusInternalsUtils functions */
1025
1026 /**
1027  * @addtogroup DBusString
1028  *
1029  * @{
1030  */
1031 /**
1032  * Get the directory name from a complete filename
1033  * @param filename the filename
1034  * @param dirname string to append directory name to
1035  * @returns #FALSE if no memory
1036  */
1037 dbus_bool_t
1038 _dbus_string_get_dirname  (const DBusString *filename,
1039                            DBusString       *dirname)
1040 {
1041   int sep;
1042   
1043   _dbus_assert (filename != dirname);
1044   _dbus_assert (filename != NULL);
1045   _dbus_assert (dirname != NULL);
1046
1047   /* Ignore any separators on the end */
1048   sep = _dbus_string_get_length (filename);
1049   if (sep == 0)
1050     return _dbus_string_append (dirname, "."); /* empty string passed in */
1051     
1052   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1053     --sep;
1054
1055   _dbus_assert (sep >= 0);
1056   
1057   if (sep == 0)
1058     return _dbus_string_append (dirname, "/");
1059   
1060   /* Now find the previous separator */
1061   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1062   if (sep < 0)
1063     return _dbus_string_append (dirname, ".");
1064   
1065   /* skip multiple separators */
1066   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1067     --sep;
1068
1069   _dbus_assert (sep >= 0);
1070   
1071   if (sep == 0 &&
1072       _dbus_string_get_byte (filename, 0) == '/')
1073     return _dbus_string_append (dirname, "/");
1074   else
1075     return _dbus_string_copy_len (filename, 0, sep - 0,
1076                                   dirname, _dbus_string_get_length (dirname));
1077 }
1078 /** @} */ /* DBusString stuff */
1079
1080 static void
1081 string_squash_nonprintable (DBusString *str)
1082 {
1083   unsigned char *buf;
1084   int i, len; 
1085   
1086   buf = _dbus_string_get_udata (str);
1087   len = _dbus_string_get_length (str);
1088   
1089   for (i = 0; i < len; i++)
1090     {
1091       unsigned char c = (unsigned char) buf[i];
1092       if (c == '\0')
1093         buf[i] = ' ';
1094       else if (c < 0x20 || c > 127)
1095         buf[i] = '?';
1096     }
1097 }
1098
1099 /**
1100  * Get a printable string describing the command used to execute
1101  * the process with pid.  This string should only be used for
1102  * informative purposes such as logging; it may not be trusted.
1103  * 
1104  * The command is guaranteed to be printable ASCII and no longer
1105  * than max_len.
1106  * 
1107  * @param pid Process id
1108  * @param str Append command to this string
1109  * @param max_len Maximum length of returned command
1110  * @param error return location for errors
1111  * @returns #FALSE on error
1112  */
1113 dbus_bool_t 
1114 _dbus_command_for_pid (unsigned long  pid,
1115                        DBusString    *str,
1116                        int            max_len,
1117                        DBusError     *error)
1118 {
1119   /* This is all Linux-specific for now */
1120   DBusString path;
1121   DBusString cmdline;
1122   int fd;
1123   
1124   if (!_dbus_string_init (&path)) 
1125     {
1126       _DBUS_SET_OOM (error);
1127       return FALSE;
1128     }
1129   
1130   if (!_dbus_string_init (&cmdline))
1131     {
1132       _DBUS_SET_OOM (error);
1133       _dbus_string_free (&path);
1134       return FALSE;
1135     }
1136   
1137   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1138     goto oom;
1139   
1140   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1141   if (fd < 0) 
1142     {
1143       dbus_set_error (error,
1144                       _dbus_error_from_errno (errno),
1145                       "Failed to open \"%s\": %s",
1146                       _dbus_string_get_const_data (&path),
1147                       _dbus_strerror (errno));
1148       goto fail;
1149     }
1150   
1151   if (!_dbus_read (fd, &cmdline, max_len))
1152     {
1153       dbus_set_error (error,
1154                       _dbus_error_from_errno (errno),
1155                       "Failed to read from \"%s\": %s",
1156                       _dbus_string_get_const_data (&path),
1157                       _dbus_strerror (errno));      
1158       _dbus_close (fd, NULL);
1159       goto fail;
1160     }
1161   
1162   if (!_dbus_close (fd, error))
1163     goto fail;
1164   
1165   string_squash_nonprintable (&cmdline);  
1166
1167   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1168     goto oom;
1169
1170   _dbus_string_free (&cmdline);  
1171   _dbus_string_free (&path);
1172   return TRUE;
1173 oom:
1174   _DBUS_SET_OOM (error);
1175 fail:
1176   _dbus_string_free (&cmdline);
1177   _dbus_string_free (&path);
1178   return FALSE;
1179 }
1180
1181 /**
1182  * Replace the DBUS_PREFIX in the given path, in-place, by the
1183  * current D-Bus installation directory. On Unix this function
1184  * does nothing, successfully.
1185  *
1186  * @param path path to edit
1187  * @return #FALSE on OOM
1188  */
1189 dbus_bool_t
1190 _dbus_replace_install_prefix (DBusString *path)
1191 {
1192   return TRUE;
1193 }
1194
1195 static dbus_bool_t
1196 ensure_owned_directory (const char *label,
1197                         const DBusString *string,
1198                         dbus_bool_t create,
1199                         DBusError *error)
1200 {
1201   const char *dir = _dbus_string_get_const_data (string);
1202   struct stat buf;
1203
1204   if (create && !_dbus_ensure_directory (string, error))
1205     return FALSE;
1206
1207   /*
1208    * The stat()-based checks in this function are to protect against
1209    * mistakes, not malice. We are working in a directory that is meant
1210    * to be trusted; but if a user has used `su` or similar to escalate
1211    * their privileges without correctly clearing the environment, the
1212    * XDG_RUNTIME_DIR in the environment might still be the user's
1213    * and not root's. We don't want to write root-owned files into that
1214    * directory, so just warn and don't provide support for transient
1215    * services in that case.
1216    *
1217    * In particular, we use stat() and not lstat() so that if we later
1218    * decide to use a different directory name for transient services,
1219    * we can drop in a compatibility symlink without breaking older
1220    * libdbus.
1221    */
1222
1223   if (stat (dir, &buf) != 0)
1224     {
1225       int saved_errno = errno;
1226
1227       dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1228                       "%s \"%s\" not available: %s", label, dir,
1229                       _dbus_strerror (saved_errno));
1230       return FALSE;
1231     }
1232
1233   if (!S_ISDIR (buf.st_mode))
1234     {
1235       dbus_set_error (error, DBUS_ERROR_FAILED, "%s \"%s\" is not a directory",
1236                       label, dir);
1237       return FALSE;
1238     }
1239
1240   if (buf.st_uid != geteuid ())
1241     {
1242       dbus_set_error (error, DBUS_ERROR_FAILED,
1243                       "%s \"%s\" is owned by uid %ld, not our uid %ld",
1244                       label, dir, (long) buf.st_uid, (long) geteuid ());
1245       return FALSE;
1246     }
1247
1248   /* This is just because we have the stat() results already, so we might
1249    * as well check opportunistically. */
1250   if ((S_IWOTH | S_IWGRP) & buf.st_mode)
1251     {
1252       dbus_set_error (error, DBUS_ERROR_FAILED,
1253                       "%s \"%s\" can be written by others (mode 0%o)",
1254                       label, dir, buf.st_mode);
1255       return FALSE;
1256     }
1257
1258   return TRUE;
1259 }
1260
1261 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1262 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1263
1264 /**
1265  * Returns the standard directories for a session bus to look for
1266  * transient service activation files.
1267  *
1268  * @param dirs the directory list we are returning
1269  * @returns #FALSE on error
1270  */
1271 dbus_bool_t
1272 _dbus_set_up_transient_session_servicedirs (DBusList  **dirs,
1273                                             DBusError  *error)
1274 {
1275   const char *xdg_runtime_dir;
1276   DBusString services;
1277   DBusString dbus1;
1278   DBusString xrd;
1279   dbus_bool_t ret = FALSE;
1280   char *data = NULL;
1281
1282   if (!_dbus_string_init (&dbus1))
1283     {
1284       _DBUS_SET_OOM (error);
1285       return FALSE;
1286     }
1287
1288   if (!_dbus_string_init (&services))
1289     {
1290       _dbus_string_free (&dbus1);
1291       _DBUS_SET_OOM (error);
1292       return FALSE;
1293     }
1294
1295   if (!_dbus_string_init (&xrd))
1296     {
1297       _dbus_string_free (&dbus1);
1298       _dbus_string_free (&services);
1299       _DBUS_SET_OOM (error);
1300       return FALSE;
1301     }
1302
1303   xdg_runtime_dir = _dbus_getenv ("XDG_RUNTIME_DIR");
1304
1305   /* Not an error, we just can't have transient session services */
1306   if (xdg_runtime_dir == NULL)
1307     {
1308       _dbus_verbose ("XDG_RUNTIME_DIR is unset: transient session services "
1309                      "not available here\n");
1310       ret = TRUE;
1311       goto out;
1312     }
1313
1314   if (!_dbus_string_append (&xrd, xdg_runtime_dir) ||
1315       !_dbus_string_append_printf (&dbus1, "%s/dbus-1",
1316                                    xdg_runtime_dir) ||
1317       !_dbus_string_append_printf (&services, "%s/dbus-1/services",
1318                                    xdg_runtime_dir))
1319     {
1320       _DBUS_SET_OOM (error);
1321       goto out;
1322     }
1323
1324   if (!ensure_owned_directory ("XDG_RUNTIME_DIR", &xrd, FALSE, error) ||
1325       !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &dbus1, TRUE,
1326                                error) ||
1327       !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &services,
1328                                TRUE, error))
1329     goto out;
1330
1331   if (!_dbus_string_steal_data (&services, &data) ||
1332       !_dbus_list_append (dirs, data))
1333     {
1334       _DBUS_SET_OOM (error);
1335       goto out;
1336     }
1337
1338   _dbus_verbose ("Transient service directory is %s\n", data);
1339   /* Ownership was transferred to @dirs */
1340   data = NULL;
1341   ret = TRUE;
1342
1343 out:
1344   _dbus_string_free (&dbus1);
1345   _dbus_string_free (&services);
1346   _dbus_string_free (&xrd);
1347   dbus_free (data);
1348   return ret;
1349 }
1350
1351 /**
1352  * Returns the standard directories for a session bus to look for service
1353  * activation files
1354  *
1355  * On UNIX this should be the standard xdg freedesktop.org data directories:
1356  *
1357  * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
1358  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1359  *
1360  * and
1361  *
1362  * DBUS_DATADIR
1363  *
1364  * @param dirs the directory list we are returning
1365  * @returns #FALSE on OOM
1366  */
1367
1368 dbus_bool_t
1369 _dbus_get_standard_session_servicedirs (DBusList **dirs)
1370 {
1371   const char *xdg_data_home;
1372   const char *xdg_data_dirs;
1373   DBusString servicedir_path;
1374
1375   if (!_dbus_string_init (&servicedir_path))
1376     return FALSE;
1377
1378   xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
1379   xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
1380
1381   if (xdg_data_home != NULL)
1382     {
1383       if (!_dbus_string_append (&servicedir_path, xdg_data_home))
1384         goto oom;
1385     }
1386   else
1387     {
1388       const DBusString *homedir;
1389       DBusString local_share;
1390
1391       if (!_dbus_homedir_from_current_process (&homedir))
1392         goto oom;
1393
1394       if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
1395         goto oom;
1396
1397       _dbus_string_init_const (&local_share, "/.local/share");
1398       if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
1399         goto oom;
1400     }
1401
1402   if (!_dbus_string_append (&servicedir_path, ":"))
1403     goto oom;
1404
1405   if (xdg_data_dirs != NULL)
1406     {
1407       if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
1408         goto oom;
1409
1410       if (!_dbus_string_append (&servicedir_path, ":"))
1411         goto oom;
1412     }
1413   else
1414     {
1415       if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
1416         goto oom;
1417     }
1418
1419   /*
1420    * add configured datadir to defaults
1421    * this may be the same as an xdg dir
1422    * however the config parser should take
1423    * care of duplicates
1424    */
1425   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
1426     goto oom;
1427
1428   if (!_dbus_split_paths_and_append (&servicedir_path,
1429                                      DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1430                                      dirs))
1431     goto oom;
1432
1433   _dbus_string_free (&servicedir_path);
1434   return TRUE;
1435
1436  oom:
1437   _dbus_string_free (&servicedir_path);
1438   return FALSE;
1439 }
1440
1441
1442 /**
1443  * Returns the standard directories for a system bus to look for service
1444  * activation files
1445  *
1446  * On UNIX this should be the standard xdg freedesktop.org data directories:
1447  *
1448  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1449  *
1450  * and
1451  *
1452  * DBUS_DATADIR
1453  *
1454  * On Windows there is no system bus and this function can return nothing.
1455  *
1456  * @param dirs the directory list we are returning
1457  * @returns #FALSE on OOM
1458  */
1459
1460 dbus_bool_t
1461 _dbus_get_standard_system_servicedirs (DBusList **dirs)
1462 {
1463   /*
1464    * DBUS_DATADIR may be the same as one of the standard directories. However,
1465    * the config parser should take care of the duplicates.
1466    *
1467    * Also, append /lib as counterpart of /usr/share on the root
1468    * directory (the root directory does not know /share), in order to
1469    * facilitate early boot system bus activation where /usr might not
1470    * be available.
1471    */
1472   static const char standard_search_path[] =
1473     "/usr/local/share:"
1474     "/usr/share:"
1475     DBUS_DATADIR ":"
1476     "/lib";
1477   DBusString servicedir_path;
1478
1479   _dbus_string_init_const (&servicedir_path, standard_search_path);
1480
1481   return _dbus_split_paths_and_append (&servicedir_path,
1482                                        DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1483                                        dirs);
1484 }
1485
1486 /**
1487  * Get the absolute path of the system.conf file
1488  * (there is no system bus on Windows so this can just
1489  * return FALSE and print a warning or something)
1490  *
1491  * @param str the string to append to, which must be empty on entry
1492  * @returns #FALSE if no memory
1493  */
1494 dbus_bool_t
1495 _dbus_get_system_config_file (DBusString *str)
1496 {
1497   _dbus_assert (_dbus_string_get_length (str) == 0);
1498
1499   return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
1500 }
1501
1502 /**
1503  * Get the absolute path of the session.conf file.
1504  *
1505  * @param str the string to append to, which must be empty on entry
1506  * @returns #FALSE if no memory
1507  */
1508 dbus_bool_t
1509 _dbus_get_session_config_file (DBusString *str)
1510 {
1511   _dbus_assert (_dbus_string_get_length (str) == 0);
1512
1513   return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
1514 }