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