Merge branch 'fd-passing'
[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 #include "dbus-sysdeps.h"
25 #include "dbus-sysdeps-unix.h"
26 #include "dbus-internals.h"
27 #include "dbus-protocol.h"
28 #include "dbus-string.h"
29 #define DBUS_USERDB_INCLUDES_PRIVATE 1
30 #include "dbus-userdb.h"
31 #include "dbus-test.h"
32
33 #include <sys/types.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <stdio.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <sys/stat.h>
42 #include <grp.h>
43 #include <sys/socket.h>
44 #include <dirent.h>
45 #include <sys/un.h>
46 #include <syslog.h>
47 #include <syslog.h>
48 #ifdef HAVE_LIBAUDIT
49 #include <sys/prctl.h>
50 #include <sys/capability.h>
51 #include <libaudit.h>
52 #endif /* HAVE_LIBAUDIT */
53
54 #ifdef HAVE_SYS_SYSLIMITS_H
55 #include <sys/syslimits.h>
56 #endif
57
58 #ifndef O_BINARY
59 #define O_BINARY 0
60 #endif
61
62 /**
63  * @addtogroup DBusInternalsUtils
64  * @{
65  */
66
67
68 /**
69  * Does the chdir, fork, setsid, etc. to become a daemon process.
70  *
71  * @param pidfile #NULL, or pidfile to create
72  * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
73  * @param error return location for errors
74  * @param keep_umask #TRUE to keep the original umask
75  * @returns #FALSE on failure
76  */
77 dbus_bool_t
78 _dbus_become_daemon (const DBusString *pidfile,
79                      DBusPipe         *print_pid_pipe,
80                      DBusError        *error,
81                      dbus_bool_t       keep_umask)
82 {
83   const char *s;
84   pid_t child_pid;
85   int dev_null_fd;
86
87   _dbus_verbose ("Becoming a daemon...\n");
88
89   _dbus_verbose ("chdir to /\n");
90   if (chdir ("/") < 0)
91     {
92       dbus_set_error (error, DBUS_ERROR_FAILED,
93                       "Could not chdir() to root directory");
94       return FALSE;
95     }
96
97   _dbus_verbose ("forking...\n");
98   switch ((child_pid = fork ()))
99     {
100     case -1:
101       _dbus_verbose ("fork failed\n");
102       dbus_set_error (error, _dbus_error_from_errno (errno),
103                       "Failed to fork daemon: %s", _dbus_strerror (errno));
104       return FALSE;
105       break;
106
107     case 0:
108       _dbus_verbose ("in child, closing std file descriptors\n");
109
110       /* silently ignore failures here, if someone
111        * doesn't have /dev/null we may as well try
112        * to continue anyhow
113        */
114       
115       dev_null_fd = open ("/dev/null", O_RDWR);
116       if (dev_null_fd >= 0)
117         {
118           dup2 (dev_null_fd, 0);
119           dup2 (dev_null_fd, 1);
120           
121           s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
122           if (s == NULL || *s == '\0')
123             dup2 (dev_null_fd, 2);
124           else
125             _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
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", print_pid_pipe->fd_or_handle);
258       
259       if (!_dbus_string_init (&pid))
260         {
261           _DBUS_SET_OOM (error);
262           return FALSE;
263         }
264           
265       if (!_dbus_string_append_int (&pid, pid_to_write) ||
266           !_dbus_string_append (&pid, "\n"))
267         {
268           _dbus_string_free (&pid);
269           _DBUS_SET_OOM (error);
270           return FALSE;
271         }
272           
273       bytes = _dbus_string_get_length (&pid);
274       if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
275         {
276           /* _dbus_pipe_write sets error only on failure, not short write */
277           if (error != NULL && !dbus_error_is_set(error))
278             {
279               dbus_set_error (error, DBUS_ERROR_FAILED,
280                               "Printing message bus PID: did not write enough bytes\n");
281             }
282           _dbus_string_free (&pid);
283           return FALSE;
284         }
285           
286       _dbus_string_free (&pid);
287     }
288   else
289     {
290       _dbus_verbose ("No pid pipe to write to\n");
291     }
292
293   return TRUE;
294 }
295
296 /**
297  * Verify that after the fork we can successfully change to this user.
298  *
299  * @param user the username given in the daemon configuration
300  * @returns #TRUE if username is valid
301  */
302 dbus_bool_t
303 _dbus_verify_daemon_user (const char *user)
304 {
305   DBusString u;
306
307   _dbus_string_init_const (&u, user);
308
309   return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
310 }
311
312 /**
313  * Changes the user and group the bus is running as.
314  *
315  * @param user the user to become
316  * @param error return location for errors
317  * @returns #FALSE on failure
318  */
319 dbus_bool_t
320 _dbus_change_to_daemon_user  (const char    *user,
321                               DBusError     *error)
322 {
323   dbus_uid_t uid;
324   dbus_gid_t gid;
325   DBusString u;
326 #ifdef HAVE_LIBAUDIT
327   dbus_bool_t we_were_root;
328   cap_t new_caps;
329 #endif
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 #ifdef HAVE_LIBAUDIT
342   we_were_root = _dbus_geteuid () == 0;
343   new_caps = NULL;
344   /* have a tmp set of caps that we use to transition to the usr/grp dbus should
345    * run as ... doesn't really help. But keeps people happy.
346    */
347     
348   if (we_were_root)
349     {
350       cap_value_t new_cap_list[] = { CAP_AUDIT_WRITE };
351       cap_value_t tmp_cap_list[] = { CAP_AUDIT_WRITE, CAP_SETUID, CAP_SETGID };
352       cap_t tmp_caps = cap_init();
353         
354       if (!tmp_caps || !(new_caps = cap_init ()))
355         {
356           dbus_set_error (error, DBUS_ERROR_FAILED,
357                           "Failed to initialize drop of capabilities: %s\n",
358                           _dbus_strerror (errno));
359
360           if (tmp_caps)
361             cap_free (tmp_caps);
362
363           return FALSE;
364         }
365
366       /* assume these work... */
367       cap_set_flag (new_caps, CAP_PERMITTED, 1, new_cap_list, CAP_SET);
368       cap_set_flag (new_caps, CAP_EFFECTIVE, 1, new_cap_list, CAP_SET);
369       cap_set_flag (tmp_caps, CAP_PERMITTED, 3, tmp_cap_list, CAP_SET);
370       cap_set_flag (tmp_caps, CAP_EFFECTIVE, 3, tmp_cap_list, CAP_SET);
371       
372       if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
373         {
374           dbus_set_error (error, _dbus_error_from_errno (errno),
375                           "Failed to set keep-capabilities: %s\n",
376                           _dbus_strerror (errno));
377           cap_free (tmp_caps);
378           goto fail;
379         }
380         
381       if (cap_set_proc (tmp_caps) == -1)
382         {
383           dbus_set_error (error, DBUS_ERROR_FAILED,
384                           "Failed to drop capabilities: %s\n",
385                           _dbus_strerror (errno));
386           cap_free (tmp_caps);
387           goto fail;
388         }
389       cap_free (tmp_caps);
390     }
391 #endif /* HAVE_LIBAUDIT */
392   
393   /* setgroups() only works if we are a privileged process,
394    * so we don't return error on failure; the only possible
395    * failure is that we don't have perms to do it.
396    *
397    * not sure this is right, maybe if setuid()
398    * is going to work then setgroups() should also work.
399    */
400   if (setgroups (0, NULL) < 0)
401     _dbus_warn ("Failed to drop supplementary groups: %s\n",
402                 _dbus_strerror (errno));
403   
404   /* Set GID first, or the setuid may remove our permission
405    * to change the GID
406    */
407   if (setgid (gid) < 0)
408     {
409       dbus_set_error (error, _dbus_error_from_errno (errno),
410                       "Failed to set GID to %lu: %s", gid,
411                       _dbus_strerror (errno));
412       goto fail;
413     }
414   
415   if (setuid (uid) < 0)
416     {
417       dbus_set_error (error, _dbus_error_from_errno (errno),
418                       "Failed to set UID to %lu: %s", uid,
419                       _dbus_strerror (errno));
420       goto fail;
421     }
422   
423 #ifdef HAVE_LIBAUDIT
424   if (we_were_root)
425     {
426       if (cap_set_proc (new_caps))
427         {
428           dbus_set_error (error, DBUS_ERROR_FAILED,
429                           "Failed to drop capabilities: %s\n",
430                           _dbus_strerror (errno));
431           goto fail;
432         }
433       cap_free (new_caps);
434
435       /* should always work, if it did above */      
436       if (prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0) == -1)
437         {
438           dbus_set_error (error, _dbus_error_from_errno (errno),
439                           "Failed to unset keep-capabilities: %s\n",
440                           _dbus_strerror (errno));
441           return FALSE;
442         }
443     }
444 #endif
445
446  return TRUE;
447
448  fail:
449 #ifdef HAVE_LIBAUDIT
450  if (!we_were_root)
451    {
452      /* should always work, if it did above */
453      prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0);
454      cap_free (new_caps);
455    }
456 #endif
457
458  return FALSE;
459 }
460
461 void 
462 _dbus_init_system_log (void)
463 {
464   openlog ("dbus", LOG_PID, LOG_DAEMON);
465 }
466
467 /**
468  * Log an informative message.  Intended for use primarily by
469  * the system bus.
470  *
471  * @param msg a printf-style format string
472  * @param args arguments for the format string
473  */
474 void 
475 _dbus_log_info (const char *msg, va_list args)
476 {
477   vsyslog (LOG_DAEMON|LOG_NOTICE, msg, args);
478 }
479
480 /**
481  * Log a security-related message.  Intended for use primarily by
482  * the system bus.
483  *
484  * @param msg a printf-style format string
485  * @param args arguments for the format string
486  */
487 void 
488 _dbus_log_security (const char *msg, va_list args)
489 {
490   vsyslog (LOG_AUTH|LOG_NOTICE, msg, args);
491 }
492
493 /** Installs a UNIX signal handler
494  *
495  * @param sig the signal to handle
496  * @param handler the handler
497  */
498 void
499 _dbus_set_signal_handler (int               sig,
500                           DBusSignalHandler handler)
501 {
502   struct sigaction act;
503   sigset_t empty_mask;
504   
505   sigemptyset (&empty_mask);
506   act.sa_handler = handler;
507   act.sa_mask    = empty_mask;
508   act.sa_flags   = 0;
509   sigaction (sig,  &act, NULL);
510 }
511
512
513 /**
514  * Removes a directory; Directory must be empty
515  * 
516  * @param filename directory filename
517  * @param error initialized error object
518  * @returns #TRUE on success
519  */
520 dbus_bool_t
521 _dbus_delete_directory (const DBusString *filename,
522                         DBusError        *error)
523 {
524   const char *filename_c;
525   
526   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
527
528   filename_c = _dbus_string_get_const_data (filename);
529
530   if (rmdir (filename_c) != 0)
531     {
532       dbus_set_error (error, DBUS_ERROR_FAILED,
533                       "Failed to remove directory %s: %s\n",
534                       filename_c, _dbus_strerror (errno));
535       return FALSE;
536     }
537   
538   return TRUE;
539 }
540
541 /** Checks if a file exists
542 *
543 * @param file full path to the file
544 * @returns #TRUE if file exists
545 */
546 dbus_bool_t 
547 _dbus_file_exists (const char *file)
548 {
549   return (access (file, F_OK) == 0);
550 }
551
552 /** Checks if user is at the console
553 *
554 * @param username user to check
555 * @param error return location for errors
556 * @returns #TRUE is the user is at the consolei and there are no errors
557 */
558 dbus_bool_t 
559 _dbus_user_at_console (const char *username,
560                        DBusError  *error)
561 {
562
563   DBusString f;
564   dbus_bool_t result;
565
566   result = FALSE;
567   if (!_dbus_string_init (&f))
568     {
569       _DBUS_SET_OOM (error);
570       return FALSE;
571     }
572
573   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
574     {
575       _DBUS_SET_OOM (error);
576       goto out;
577     }
578
579
580   if (!_dbus_string_append (&f, username))
581     {
582       _DBUS_SET_OOM (error);
583       goto out;
584     }
585
586   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
587
588  out:
589   _dbus_string_free (&f);
590
591   return result;
592 }
593
594
595 /**
596  * Checks whether the filename is an absolute path
597  *
598  * @param filename the filename
599  * @returns #TRUE if an absolute path
600  */
601 dbus_bool_t
602 _dbus_path_is_absolute (const DBusString *filename)
603 {
604   if (_dbus_string_get_length (filename) > 0)
605     return _dbus_string_get_byte (filename, 0) == '/';
606   else
607     return FALSE;
608 }
609
610 /**
611  * stat() wrapper.
612  *
613  * @param filename the filename to stat
614  * @param statbuf the stat info to fill in
615  * @param error return location for error
616  * @returns #FALSE if error was set
617  */
618 dbus_bool_t
619 _dbus_stat (const DBusString *filename,
620             DBusStat         *statbuf,
621             DBusError        *error)
622 {
623   const char *filename_c;
624   struct stat sb;
625
626   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
627   
628   filename_c = _dbus_string_get_const_data (filename);
629
630   if (stat (filename_c, &sb) < 0)
631     {
632       dbus_set_error (error, _dbus_error_from_errno (errno),
633                       "%s", _dbus_strerror (errno));
634       return FALSE;
635     }
636
637   statbuf->mode = sb.st_mode;
638   statbuf->nlink = sb.st_nlink;
639   statbuf->uid = sb.st_uid;
640   statbuf->gid = sb.st_gid;
641   statbuf->size = sb.st_size;
642   statbuf->atime = sb.st_atime;
643   statbuf->mtime = sb.st_mtime;
644   statbuf->ctime = sb.st_ctime;
645
646   return TRUE;
647 }
648
649
650 /**
651  * Internals of directory iterator
652  */
653 struct DBusDirIter
654 {
655   DIR *d; /**< The DIR* from opendir() */
656   
657 };
658
659 /**
660  * Open a directory to iterate over.
661  *
662  * @param filename the directory name
663  * @param error exception return object or #NULL
664  * @returns new iterator, or #NULL on error
665  */
666 DBusDirIter*
667 _dbus_directory_open (const DBusString *filename,
668                       DBusError        *error)
669 {
670   DIR *d;
671   DBusDirIter *iter;
672   const char *filename_c;
673
674   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
675   
676   filename_c = _dbus_string_get_const_data (filename);
677
678   d = opendir (filename_c);
679   if (d == NULL)
680     {
681       dbus_set_error (error, _dbus_error_from_errno (errno),
682                       "Failed to read directory \"%s\": %s",
683                       filename_c,
684                       _dbus_strerror (errno));
685       return NULL;
686     }
687   iter = dbus_new0 (DBusDirIter, 1);
688   if (iter == NULL)
689     {
690       closedir (d);
691       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
692                       "Could not allocate memory for directory iterator");
693       return NULL;
694     }
695
696   iter->d = d;
697
698   return iter;
699 }
700
701 /* Calculate the required buffer size (in bytes) for directory
702  * entries read from the given directory handle.  Return -1 if this
703  * this cannot be done. 
704  *
705  * If you use autoconf, include fpathconf and dirfd in your
706  * AC_CHECK_FUNCS list.  Otherwise use some other method to detect
707  * and use them where available.
708  */
709 static dbus_bool_t
710 dirent_buf_size(DIR * dirp, size_t *size)
711 {
712  long name_max;
713 #   if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
714 #      if defined(HAVE_DIRFD)
715           name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
716 #      elif defined(HAVE_DDFD)
717           name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
718 #      else
719           name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
720 #      endif /* HAVE_DIRFD */
721      if (name_max == -1)
722 #           if defined(NAME_MAX)
723              name_max = NAME_MAX;
724 #           else
725              return FALSE;
726 #           endif
727 #   elif defined(MAXNAMELEN)
728      name_max = MAXNAMELEN;
729 #   else
730 #       if defined(NAME_MAX)
731          name_max = NAME_MAX;
732 #       else
733 #           error "buffer size for readdir_r cannot be determined"
734 #       endif
735 #   endif
736   if (size)
737     *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
738   else
739     return FALSE;
740
741   return TRUE;
742 }
743
744 /**
745  * Get next file in the directory. Will not return "." or ".."  on
746  * UNIX. If an error occurs, the contents of "filename" are
747  * undefined. The error is never set if the function succeeds.
748  *
749  * @param iter the iterator
750  * @param filename string to be set to the next file in the dir
751  * @param error return location for error
752  * @returns #TRUE if filename was filled in with a new filename
753  */
754 dbus_bool_t
755 _dbus_directory_get_next_file (DBusDirIter      *iter,
756                                DBusString       *filename,
757                                DBusError        *error)
758 {
759   struct dirent *d, *ent;
760   size_t buf_size;
761   int err;
762
763   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
764  
765   if (!dirent_buf_size (iter->d, &buf_size))
766     {
767       dbus_set_error (error, DBUS_ERROR_FAILED,
768                       "Can't calculate buffer size when reading directory");
769       return FALSE;
770     }
771
772   d = (struct dirent *)dbus_malloc (buf_size);
773   if (!d)
774     {
775       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
776                       "No memory to read directory entry");
777       return FALSE;
778     }
779
780  again:
781   err = readdir_r (iter->d, d, &ent);
782   if (err || !ent)
783     {
784       if (err != 0)
785         dbus_set_error (error,
786                         _dbus_error_from_errno (err),
787                         "%s", _dbus_strerror (err));
788
789       dbus_free (d);
790       return FALSE;
791     }
792   else if (ent->d_name[0] == '.' &&
793            (ent->d_name[1] == '\0' ||
794             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
795     goto again;
796   else
797     {
798       _dbus_string_set_length (filename, 0);
799       if (!_dbus_string_append (filename, ent->d_name))
800         {
801           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
802                           "No memory to read directory entry");
803           dbus_free (d);
804           return FALSE;
805         }
806       else
807         {
808           dbus_free (d);
809           return TRUE;
810         }
811     }
812 }
813
814 /**
815  * Closes a directory iteration.
816  */
817 void
818 _dbus_directory_close (DBusDirIter *iter)
819 {
820   closedir (iter->d);
821   dbus_free (iter);
822 }
823
824 static dbus_bool_t
825 fill_user_info_from_group (struct group  *g,
826                            DBusGroupInfo *info,
827                            DBusError     *error)
828 {
829   _dbus_assert (g->gr_name != NULL);
830   
831   info->gid = g->gr_gid;
832   info->groupname = _dbus_strdup (g->gr_name);
833
834   /* info->members = dbus_strdupv (g->gr_mem) */
835   
836   if (info->groupname == NULL)
837     {
838       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
839       return FALSE;
840     }
841
842   return TRUE;
843 }
844
845 static dbus_bool_t
846 fill_group_info (DBusGroupInfo    *info,
847                  dbus_gid_t        gid,
848                  const DBusString *groupname,
849                  DBusError        *error)
850 {
851   const char *group_c_str;
852
853   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
854   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
855
856   if (groupname)
857     group_c_str = _dbus_string_get_const_data (groupname);
858   else
859     group_c_str = NULL;
860   
861   /* For now assuming that the getgrnam() and getgrgid() flavors
862    * always correspond to the pwnam flavors, if not we have
863    * to add more configure checks.
864    */
865   
866 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
867   {
868     struct group *g;
869     int result;
870     size_t buflen;
871     char *buf;
872     struct group g_str;
873     dbus_bool_t b;
874
875     /* retrieve maximum needed size for buf */
876     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
877
878     /* sysconf actually returns a long, but everything else expects size_t,
879      * so just recast here.
880      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
881      */
882     if ((long) buflen <= 0)
883       buflen = 1024;
884
885     result = -1;
886     while (1)
887       {
888         buf = dbus_malloc (buflen);
889         if (buf == NULL)
890           {
891             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
892             return FALSE;
893           }
894
895         g = NULL;
896 #ifdef HAVE_POSIX_GETPWNAM_R
897         if (group_c_str)
898           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
899                                &g);
900         else
901           result = getgrgid_r (gid, &g_str, buf, buflen,
902                                &g);
903 #else
904         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
905         result = 0;
906 #endif /* !HAVE_POSIX_GETPWNAM_R */
907         /* Try a bigger buffer if ERANGE was returned:
908            https://bugs.freedesktop.org/show_bug.cgi?id=16727
909         */
910         if (result == ERANGE && buflen < 512 * 1024)
911           {
912             dbus_free (buf);
913             buflen *= 2;
914           }
915         else
916           {
917             break;
918           }
919       }
920
921     if (result == 0 && g == &g_str)
922       {
923         b = fill_user_info_from_group (g, info, error);
924         dbus_free (buf);
925         return b;
926       }
927     else
928       {
929         dbus_set_error (error, _dbus_error_from_errno (errno),
930                         "Group %s unknown or failed to look it up\n",
931                         group_c_str ? group_c_str : "???");
932         dbus_free (buf);
933         return FALSE;
934       }
935   }
936 #else /* ! HAVE_GETPWNAM_R */
937   {
938     /* I guess we're screwed on thread safety here */
939     struct group *g;
940
941     g = getgrnam (group_c_str);
942
943     if (g != NULL)
944       {
945         return fill_user_info_from_group (g, info, error);
946       }
947     else
948       {
949         dbus_set_error (error, _dbus_error_from_errno (errno),
950                         "Group %s unknown or failed to look it up\n",
951                         group_c_str ? group_c_str : "???");
952         return FALSE;
953       }
954   }
955 #endif  /* ! HAVE_GETPWNAM_R */
956 }
957
958 /**
959  * Initializes the given DBusGroupInfo struct
960  * with information about the given group name.
961  *
962  * @param info the group info struct
963  * @param groupname name of group
964  * @param error the error return
965  * @returns #FALSE if error is set
966  */
967 dbus_bool_t
968 _dbus_group_info_fill (DBusGroupInfo    *info,
969                        const DBusString *groupname,
970                        DBusError        *error)
971 {
972   return fill_group_info (info, DBUS_GID_UNSET,
973                           groupname, error);
974
975 }
976
977 /**
978  * Initializes the given DBusGroupInfo struct
979  * with information about the given group ID.
980  *
981  * @param info the group info struct
982  * @param gid group ID
983  * @param error the error return
984  * @returns #FALSE if error is set
985  */
986 dbus_bool_t
987 _dbus_group_info_fill_gid (DBusGroupInfo *info,
988                            dbus_gid_t     gid,
989                            DBusError     *error)
990 {
991   return fill_group_info (info, gid, NULL, error);
992 }
993
994 /**
995  * Parse a UNIX user from the bus config file. On Windows, this should
996  * simply always fail (just return #FALSE).
997  *
998  * @param username the username text
999  * @param uid_p place to return the uid
1000  * @returns #TRUE on success
1001  */
1002 dbus_bool_t
1003 _dbus_parse_unix_user_from_config (const DBusString  *username,
1004                                    dbus_uid_t        *uid_p)
1005 {
1006   return _dbus_get_user_id (username, uid_p);
1007
1008 }
1009
1010 /**
1011  * Parse a UNIX group from the bus config file. On Windows, this should
1012  * simply always fail (just return #FALSE).
1013  *
1014  * @param groupname the groupname text
1015  * @param gid_p place to return the gid
1016  * @returns #TRUE on success
1017  */
1018 dbus_bool_t
1019 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
1020                                     dbus_gid_t        *gid_p)
1021 {
1022   return _dbus_get_group_id (groupname, gid_p);
1023 }
1024
1025 /**
1026  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
1027  * just calls _dbus_groups_from_uid(). On Windows, should always
1028  * fail since we don't know any UNIX groups.
1029  *
1030  * @param uid the UID
1031  * @param group_ids return location for array of group IDs
1032  * @param n_group_ids return location for length of returned array
1033  * @returns #TRUE if the UID existed and we got some credentials
1034  */
1035 dbus_bool_t
1036 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
1037                             dbus_gid_t          **group_ids,
1038                             int                  *n_group_ids)
1039 {
1040   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1041 }
1042
1043 /**
1044  * Checks to see if the UNIX user ID is at the console.
1045  * Should always fail on Windows (set the error to
1046  * #DBUS_ERROR_NOT_SUPPORTED).
1047  *
1048  * @param uid UID of person to check 
1049  * @param error return location for errors
1050  * @returns #TRUE if the UID is the same as the console user and there are no errors
1051  */
1052 dbus_bool_t
1053 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
1054                                DBusError         *error)
1055 {
1056   return _dbus_is_console_user (uid, error);
1057
1058 }
1059
1060 /**
1061  * Checks to see if the UNIX user ID matches the UID of
1062  * the process. Should always return #FALSE on Windows.
1063  *
1064  * @param uid the UNIX user ID
1065  * @returns #TRUE if this uid owns the process.
1066  */
1067 dbus_bool_t
1068 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1069 {
1070   return uid == _dbus_geteuid ();
1071 }
1072
1073 /**
1074  * Checks to see if the Windows user SID matches the owner of
1075  * the process. Should always return #FALSE on UNIX.
1076  *
1077  * @param windows_sid the Windows user SID
1078  * @returns #TRUE if this user owns the process.
1079  */
1080 dbus_bool_t
1081 _dbus_windows_user_is_process_owner (const char *windows_sid)
1082 {
1083   return FALSE;
1084 }
1085
1086 /** @} */ /* End of DBusInternalsUtils functions */
1087
1088 /**
1089  * @addtogroup DBusString
1090  *
1091  * @{
1092  */
1093 /**
1094  * Get the directory name from a complete filename
1095  * @param filename the filename
1096  * @param dirname string to append directory name to
1097  * @returns #FALSE if no memory
1098  */
1099 dbus_bool_t
1100 _dbus_string_get_dirname  (const DBusString *filename,
1101                            DBusString       *dirname)
1102 {
1103   int sep;
1104   
1105   _dbus_assert (filename != dirname);
1106   _dbus_assert (filename != NULL);
1107   _dbus_assert (dirname != NULL);
1108
1109   /* Ignore any separators on the end */
1110   sep = _dbus_string_get_length (filename);
1111   if (sep == 0)
1112     return _dbus_string_append (dirname, "."); /* empty string passed in */
1113     
1114   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1115     --sep;
1116
1117   _dbus_assert (sep >= 0);
1118   
1119   if (sep == 0)
1120     return _dbus_string_append (dirname, "/");
1121   
1122   /* Now find the previous separator */
1123   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1124   if (sep < 0)
1125     return _dbus_string_append (dirname, ".");
1126   
1127   /* skip multiple separators */
1128   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1129     --sep;
1130
1131   _dbus_assert (sep >= 0);
1132   
1133   if (sep == 0 &&
1134       _dbus_string_get_byte (filename, 0) == '/')
1135     return _dbus_string_append (dirname, "/");
1136   else
1137     return _dbus_string_copy_len (filename, 0, sep - 0,
1138                                   dirname, _dbus_string_get_length (dirname));
1139 }
1140 /** @} */ /* DBusString stuff */
1141
1142 static void
1143 string_squash_nonprintable (DBusString *str)
1144 {
1145   char *buf;
1146   int i, len; 
1147   
1148   buf = _dbus_string_get_data (str);
1149   len = _dbus_string_get_length (str);
1150   
1151   for (i = 0; i < len; i++)
1152     {
1153           unsigned char c = (unsigned char) buf[i];
1154       if (c == '\0')
1155         c = ' ';
1156       else if (c < 0x20 || c > 127)
1157         c = '?';
1158     }
1159 }
1160
1161 /**
1162  * Get a printable string describing the command used to execute
1163  * the process with pid.  This string should only be used for
1164  * informative purposes such as logging; it may not be trusted.
1165  * 
1166  * The command is guaranteed to be printable ASCII and no longer
1167  * than max_len.
1168  * 
1169  * @param pid Process id
1170  * @param str Append command to this string
1171  * @param max_len Maximum length of returned command
1172  * @param error return location for errors
1173  * @returns #FALSE on error
1174  */
1175 dbus_bool_t 
1176 _dbus_command_for_pid (unsigned long  pid,
1177                        DBusString    *str,
1178                        int            max_len,
1179                        DBusError     *error)
1180 {
1181   /* This is all Linux-specific for now */
1182   DBusString path;
1183   DBusString cmdline;
1184   int fd;
1185   
1186   if (!_dbus_string_init (&path)) 
1187     {
1188       _DBUS_SET_OOM (error);
1189       return FALSE;
1190     }
1191   
1192   if (!_dbus_string_init (&cmdline))
1193     {
1194       _DBUS_SET_OOM (error);
1195       _dbus_string_free (&path);
1196       return FALSE;
1197     }
1198   
1199   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1200     goto oom;
1201   
1202   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1203   if (fd < 0) 
1204     {
1205       dbus_set_error (error,
1206                       _dbus_error_from_errno (errno),
1207                       "Failed to open \"%s\": %s",
1208                       _dbus_string_get_const_data (&path),
1209                       _dbus_strerror (errno));
1210       goto fail;
1211     }
1212   
1213   if (!_dbus_read (fd, &cmdline, max_len))
1214     {
1215       dbus_set_error (error,
1216                       _dbus_error_from_errno (errno),
1217                       "Failed to read from \"%s\": %s",
1218                       _dbus_string_get_const_data (&path),
1219                       _dbus_strerror (errno));      
1220       goto fail;
1221     }
1222   
1223   if (!_dbus_close (fd, error))
1224     goto fail;
1225   
1226   string_squash_nonprintable (&cmdline);  
1227   
1228   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1229     goto oom;
1230   
1231   _dbus_string_free (&cmdline);  
1232   _dbus_string_free (&path);
1233   return TRUE;
1234 oom:
1235   _DBUS_SET_OOM (error);
1236 fail:
1237   _dbus_string_free (&cmdline);
1238   _dbus_string_free (&path);
1239   return FALSE;
1240 }