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