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