Merge branch 'master' of ssh://git.freedesktop.org/git/dbus/dbus
[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 /**
375  * Log an informative message.  Intended for use primarily by
376  * the system bus.
377  *
378  * @param msg a printf-style format string
379  * @param args arguments for the format string
380  */
381 void 
382 _dbus_log_info (const char *msg, va_list args)
383 {
384   vsyslog (LOG_DAEMON|LOG_NOTICE, msg, args);
385 }
386
387 /**
388  * Log a security-related message.  Intended for use primarily by
389  * the system bus.
390  *
391  * @param msg a printf-style format string
392  * @param args arguments for the format string
393  */
394 void 
395 _dbus_log_security (const char *msg, va_list args)
396 {
397   vsyslog (LOG_AUTH|LOG_NOTICE, msg, args);
398 }
399
400 /** Installs a UNIX signal handler
401  *
402  * @param sig the signal to handle
403  * @param handler the handler
404  */
405 void
406 _dbus_set_signal_handler (int               sig,
407                           DBusSignalHandler handler)
408 {
409   struct sigaction act;
410   sigset_t empty_mask;
411   
412   sigemptyset (&empty_mask);
413   act.sa_handler = handler;
414   act.sa_mask    = empty_mask;
415   act.sa_flags   = 0;
416   sigaction (sig,  &act, NULL);
417 }
418
419 /** Checks if a file exists
420 *
421 * @param file full path to the file
422 * @returns #TRUE if file exists
423 */
424 dbus_bool_t 
425 _dbus_file_exists (const char *file)
426 {
427   return (access (file, F_OK) == 0);
428 }
429
430 /** Checks if user is at the console
431 *
432 * @param username user to check
433 * @param error return location for errors
434 * @returns #TRUE is the user is at the consolei and there are no errors
435 */
436 dbus_bool_t 
437 _dbus_user_at_console (const char *username,
438                        DBusError  *error)
439 {
440
441   DBusString f;
442   dbus_bool_t result;
443
444   result = FALSE;
445   if (!_dbus_string_init (&f))
446     {
447       _DBUS_SET_OOM (error);
448       return FALSE;
449     }
450
451   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
452     {
453       _DBUS_SET_OOM (error);
454       goto out;
455     }
456
457
458   if (!_dbus_string_append (&f, username))
459     {
460       _DBUS_SET_OOM (error);
461       goto out;
462     }
463
464   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
465
466  out:
467   _dbus_string_free (&f);
468
469   return result;
470 }
471
472
473 /**
474  * Checks whether the filename is an absolute path
475  *
476  * @param filename the filename
477  * @returns #TRUE if an absolute path
478  */
479 dbus_bool_t
480 _dbus_path_is_absolute (const DBusString *filename)
481 {
482   if (_dbus_string_get_length (filename) > 0)
483     return _dbus_string_get_byte (filename, 0) == '/';
484   else
485     return FALSE;
486 }
487
488 /**
489  * stat() wrapper.
490  *
491  * @param filename the filename to stat
492  * @param statbuf the stat info to fill in
493  * @param error return location for error
494  * @returns #FALSE if error was set
495  */
496 dbus_bool_t
497 _dbus_stat (const DBusString *filename,
498             DBusStat         *statbuf,
499             DBusError        *error)
500 {
501   const char *filename_c;
502   struct stat sb;
503
504   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
505   
506   filename_c = _dbus_string_get_const_data (filename);
507
508   if (stat (filename_c, &sb) < 0)
509     {
510       dbus_set_error (error, _dbus_error_from_errno (errno),
511                       "%s", _dbus_strerror (errno));
512       return FALSE;
513     }
514
515   statbuf->mode = sb.st_mode;
516   statbuf->nlink = sb.st_nlink;
517   statbuf->uid = sb.st_uid;
518   statbuf->gid = sb.st_gid;
519   statbuf->size = sb.st_size;
520   statbuf->atime = sb.st_atime;
521   statbuf->mtime = sb.st_mtime;
522   statbuf->ctime = sb.st_ctime;
523
524   return TRUE;
525 }
526
527
528 /**
529  * Internals of directory iterator
530  */
531 struct DBusDirIter
532 {
533   DIR *d; /**< The DIR* from opendir() */
534   
535 };
536
537 /**
538  * Open a directory to iterate over.
539  *
540  * @param filename the directory name
541  * @param error exception return object or #NULL
542  * @returns new iterator, or #NULL on error
543  */
544 DBusDirIter*
545 _dbus_directory_open (const DBusString *filename,
546                       DBusError        *error)
547 {
548   DIR *d;
549   DBusDirIter *iter;
550   const char *filename_c;
551
552   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
553   
554   filename_c = _dbus_string_get_const_data (filename);
555
556   d = opendir (filename_c);
557   if (d == NULL)
558     {
559       dbus_set_error (error, _dbus_error_from_errno (errno),
560                       "Failed to read directory \"%s\": %s",
561                       filename_c,
562                       _dbus_strerror (errno));
563       return NULL;
564     }
565   iter = dbus_new0 (DBusDirIter, 1);
566   if (iter == NULL)
567     {
568       closedir (d);
569       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
570                       "Could not allocate memory for directory iterator");
571       return NULL;
572     }
573
574   iter->d = d;
575
576   return iter;
577 }
578
579 /* Calculate the required buffer size (in bytes) for directory
580  * entries read from the given directory handle.  Return -1 if this
581  * this cannot be done. 
582  *
583  * If you use autoconf, include fpathconf and dirfd in your
584  * AC_CHECK_FUNCS list.  Otherwise use some other method to detect
585  * and use them where available.
586  */
587 static dbus_bool_t
588 dirent_buf_size(DIR * dirp, size_t *size)
589 {
590  long name_max;
591 #   if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
592 #      if defined(HAVE_DIRFD)
593           name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
594 #      elif defined(HAVE_DDFD)
595           name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
596 #      else
597           name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
598 #      endif /* HAVE_DIRFD */
599      if (name_max == -1)
600 #           if defined(NAME_MAX)
601              name_max = NAME_MAX;
602 #           else
603              return FALSE;
604 #           endif
605 #   elif defined(MAXNAMELEN)
606      name_max = MAXNAMELEN;
607 #   else
608 #       if defined(NAME_MAX)
609          name_max = NAME_MAX;
610 #       else
611 #           error "buffer size for readdir_r cannot be determined"
612 #       endif
613 #   endif
614   if (size)
615     *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
616   else
617     return FALSE;
618
619   return TRUE;
620 }
621
622 /**
623  * Get next file in the directory. Will not return "." or ".."  on
624  * UNIX. If an error occurs, the contents of "filename" are
625  * undefined. The error is never set if the function succeeds.
626  *
627  * @param iter the iterator
628  * @param filename string to be set to the next file in the dir
629  * @param error return location for error
630  * @returns #TRUE if filename was filled in with a new filename
631  */
632 dbus_bool_t
633 _dbus_directory_get_next_file (DBusDirIter      *iter,
634                                DBusString       *filename,
635                                DBusError        *error)
636 {
637   struct dirent *d, *ent;
638   size_t buf_size;
639   int err;
640
641   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
642  
643   if (!dirent_buf_size (iter->d, &buf_size))
644     {
645       dbus_set_error (error, DBUS_ERROR_FAILED,
646                       "Can't calculate buffer size when reading directory");
647       return FALSE;
648     }
649
650   d = (struct dirent *)dbus_malloc (buf_size);
651   if (!d)
652     {
653       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
654                       "No memory to read directory entry");
655       return FALSE;
656     }
657
658  again:
659   err = readdir_r (iter->d, d, &ent);
660   if (err || !ent)
661     {
662       if (err != 0)
663         dbus_set_error (error,
664                         _dbus_error_from_errno (err),
665                         "%s", _dbus_strerror (err));
666
667       dbus_free (d);
668       return FALSE;
669     }
670   else if (ent->d_name[0] == '.' &&
671            (ent->d_name[1] == '\0' ||
672             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
673     goto again;
674   else
675     {
676       _dbus_string_set_length (filename, 0);
677       if (!_dbus_string_append (filename, ent->d_name))
678         {
679           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
680                           "No memory to read directory entry");
681           dbus_free (d);
682           return FALSE;
683         }
684       else
685         {
686           dbus_free (d);
687           return TRUE;
688         }
689     }
690 }
691
692 /**
693  * Closes a directory iteration.
694  */
695 void
696 _dbus_directory_close (DBusDirIter *iter)
697 {
698   closedir (iter->d);
699   dbus_free (iter);
700 }
701
702 static dbus_bool_t
703 fill_user_info_from_group (struct group  *g,
704                            DBusGroupInfo *info,
705                            DBusError     *error)
706 {
707   _dbus_assert (g->gr_name != NULL);
708   
709   info->gid = g->gr_gid;
710   info->groupname = _dbus_strdup (g->gr_name);
711
712   /* info->members = dbus_strdupv (g->gr_mem) */
713   
714   if (info->groupname == NULL)
715     {
716       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
717       return FALSE;
718     }
719
720   return TRUE;
721 }
722
723 static dbus_bool_t
724 fill_group_info (DBusGroupInfo    *info,
725                  dbus_gid_t        gid,
726                  const DBusString *groupname,
727                  DBusError        *error)
728 {
729   const char *group_c_str;
730
731   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
732   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
733
734   if (groupname)
735     group_c_str = _dbus_string_get_const_data (groupname);
736   else
737     group_c_str = NULL;
738   
739   /* For now assuming that the getgrnam() and getgrgid() flavors
740    * always correspond to the pwnam flavors, if not we have
741    * to add more configure checks.
742    */
743   
744 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
745   {
746     struct group *g;
747     int result;
748     size_t buflen;
749     char *buf;
750     struct group g_str;
751     dbus_bool_t b;
752
753     /* retrieve maximum needed size for buf */
754     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
755
756     /* sysconf actually returns a long, but everything else expects size_t,
757      * so just recast here.
758      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
759      */
760     if ((long) buflen <= 0)
761       buflen = 1024;
762
763     result = -1;
764     while (1)
765       {
766         buf = dbus_malloc (buflen);
767         if (buf == NULL)
768           {
769             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
770             return FALSE;
771           }
772
773         g = NULL;
774 #ifdef HAVE_POSIX_GETPWNAM_R
775         if (group_c_str)
776           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
777                                &g);
778         else
779           result = getgrgid_r (gid, &g_str, buf, buflen,
780                                &g);
781 #else
782         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
783         result = 0;
784 #endif /* !HAVE_POSIX_GETPWNAM_R */
785         /* Try a bigger buffer if ERANGE was returned:
786            https://bugs.freedesktop.org/show_bug.cgi?id=16727
787         */
788         if (result == ERANGE && buflen < 512 * 1024)
789           {
790             dbus_free (buf);
791             buflen *= 2;
792           }
793         else
794           {
795             break;
796           }
797       }
798
799     if (result == 0 && g == &g_str)
800       {
801         b = fill_user_info_from_group (g, info, error);
802         dbus_free (buf);
803         return b;
804       }
805     else
806       {
807         dbus_set_error (error, _dbus_error_from_errno (errno),
808                         "Group %s unknown or failed to look it up\n",
809                         group_c_str ? group_c_str : "???");
810         dbus_free (buf);
811         return FALSE;
812       }
813   }
814 #else /* ! HAVE_GETPWNAM_R */
815   {
816     /* I guess we're screwed on thread safety here */
817     struct group *g;
818
819     g = getgrnam (group_c_str);
820
821     if (g != NULL)
822       {
823         return fill_user_info_from_group (g, info, error);
824       }
825     else
826       {
827         dbus_set_error (error, _dbus_error_from_errno (errno),
828                         "Group %s unknown or failed to look it up\n",
829                         group_c_str ? group_c_str : "???");
830         return FALSE;
831       }
832   }
833 #endif  /* ! HAVE_GETPWNAM_R */
834 }
835
836 /**
837  * Initializes the given DBusGroupInfo struct
838  * with information about the given group name.
839  *
840  * @param info the group info struct
841  * @param groupname name of group
842  * @param error the error return
843  * @returns #FALSE if error is set
844  */
845 dbus_bool_t
846 _dbus_group_info_fill (DBusGroupInfo    *info,
847                        const DBusString *groupname,
848                        DBusError        *error)
849 {
850   return fill_group_info (info, DBUS_GID_UNSET,
851                           groupname, error);
852
853 }
854
855 /**
856  * Initializes the given DBusGroupInfo struct
857  * with information about the given group ID.
858  *
859  * @param info the group info struct
860  * @param gid group ID
861  * @param error the error return
862  * @returns #FALSE if error is set
863  */
864 dbus_bool_t
865 _dbus_group_info_fill_gid (DBusGroupInfo *info,
866                            dbus_gid_t     gid,
867                            DBusError     *error)
868 {
869   return fill_group_info (info, gid, NULL, error);
870 }
871
872 /**
873  * Parse a UNIX user from the bus config file. On Windows, this should
874  * simply always fail (just return #FALSE).
875  *
876  * @param username the username text
877  * @param uid_p place to return the uid
878  * @returns #TRUE on success
879  */
880 dbus_bool_t
881 _dbus_parse_unix_user_from_config (const DBusString  *username,
882                                    dbus_uid_t        *uid_p)
883 {
884   return _dbus_get_user_id (username, uid_p);
885
886 }
887
888 /**
889  * Parse a UNIX group from the bus config file. On Windows, this should
890  * simply always fail (just return #FALSE).
891  *
892  * @param groupname the groupname text
893  * @param gid_p place to return the gid
894  * @returns #TRUE on success
895  */
896 dbus_bool_t
897 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
898                                     dbus_gid_t        *gid_p)
899 {
900   return _dbus_get_group_id (groupname, gid_p);
901 }
902
903 /**
904  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
905  * just calls _dbus_groups_from_uid(). On Windows, should always
906  * fail since we don't know any UNIX groups.
907  *
908  * @param uid the UID
909  * @param group_ids return location for array of group IDs
910  * @param n_group_ids return location for length of returned array
911  * @returns #TRUE if the UID existed and we got some credentials
912  */
913 dbus_bool_t
914 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
915                             dbus_gid_t          **group_ids,
916                             int                  *n_group_ids)
917 {
918   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
919 }
920
921 /**
922  * Checks to see if the UNIX user ID is at the console.
923  * Should always fail on Windows (set the error to
924  * #DBUS_ERROR_NOT_SUPPORTED).
925  *
926  * @param uid UID of person to check 
927  * @param error return location for errors
928  * @returns #TRUE if the UID is the same as the console user and there are no errors
929  */
930 dbus_bool_t
931 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
932                                DBusError         *error)
933 {
934   return _dbus_is_console_user (uid, error);
935
936 }
937
938 /**
939  * Checks to see if the UNIX user ID matches the UID of
940  * the process. Should always return #FALSE on Windows.
941  *
942  * @param uid the UNIX user ID
943  * @returns #TRUE if this uid owns the process.
944  */
945 dbus_bool_t
946 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
947 {
948   return uid == _dbus_geteuid ();
949 }
950
951 /**
952  * Checks to see if the Windows user SID matches the owner of
953  * the process. Should always return #FALSE on UNIX.
954  *
955  * @param windows_sid the Windows user SID
956  * @returns #TRUE if this user owns the process.
957  */
958 dbus_bool_t
959 _dbus_windows_user_is_process_owner (const char *windows_sid)
960 {
961   return FALSE;
962 }
963
964 /** @} */ /* End of DBusInternalsUtils functions */
965
966 /**
967  * @addtogroup DBusString
968  *
969  * @{
970  */
971 /**
972  * Get the directory name from a complete filename
973  * @param filename the filename
974  * @param dirname string to append directory name to
975  * @returns #FALSE if no memory
976  */
977 dbus_bool_t
978 _dbus_string_get_dirname  (const DBusString *filename,
979                            DBusString       *dirname)
980 {
981   int sep;
982   
983   _dbus_assert (filename != dirname);
984   _dbus_assert (filename != NULL);
985   _dbus_assert (dirname != NULL);
986
987   /* Ignore any separators on the end */
988   sep = _dbus_string_get_length (filename);
989   if (sep == 0)
990     return _dbus_string_append (dirname, "."); /* empty string passed in */
991     
992   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
993     --sep;
994
995   _dbus_assert (sep >= 0);
996   
997   if (sep == 0)
998     return _dbus_string_append (dirname, "/");
999   
1000   /* Now find the previous separator */
1001   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1002   if (sep < 0)
1003     return _dbus_string_append (dirname, ".");
1004   
1005   /* skip multiple separators */
1006   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1007     --sep;
1008
1009   _dbus_assert (sep >= 0);
1010   
1011   if (sep == 0 &&
1012       _dbus_string_get_byte (filename, 0) == '/')
1013     return _dbus_string_append (dirname, "/");
1014   else
1015     return _dbus_string_copy_len (filename, 0, sep - 0,
1016                                   dirname, _dbus_string_get_length (dirname));
1017 }
1018 /** @} */ /* DBusString stuff */
1019
1020 static void
1021 string_squash_nonprintable (DBusString *str)
1022 {
1023   unsigned char *buf;
1024   int i, len; 
1025   
1026   buf = _dbus_string_get_data (str);
1027   len = _dbus_string_get_length (str);
1028   
1029   for (i = 0; i < len; i++)
1030     {
1031           unsigned char c = (unsigned char) buf[i];
1032       if (c == '\0')
1033         c = ' ';
1034       else if (c < 0x20 || c > 127)
1035         c = '?';
1036     }
1037 }
1038
1039 /**
1040  * Get a printable string describing the command used to execute
1041  * the process with pid.  This string should only be used for
1042  * informative purposes such as logging; it may not be trusted.
1043  * 
1044  * The command is guaranteed to be printable ASCII and no longer
1045  * than max_len.
1046  * 
1047  * @param pid Process id
1048  * @param str Append command to this string
1049  * @param max_len Maximum length of returned command
1050  * @param error return location for errors
1051  * @returns #FALSE on error
1052  */
1053 dbus_bool_t 
1054 _dbus_command_for_pid (unsigned long  pid,
1055                        DBusString    *str,
1056                        int            max_len,
1057                        DBusError     *error)
1058 {
1059   /* This is all Linux-specific for now */
1060   DBusString path;
1061   DBusString cmdline;
1062   int fd;
1063   
1064   if (!_dbus_string_init (&path)) 
1065     {
1066       _DBUS_SET_OOM (error);
1067       return FALSE;
1068     }
1069   
1070   if (!_dbus_string_init (&cmdline))
1071     {
1072       _DBUS_SET_OOM (error);
1073       _dbus_string_free (&path);
1074       return FALSE;
1075     }
1076   
1077   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1078     goto oom;
1079   
1080   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1081   if (fd < 0) 
1082     {
1083       dbus_set_error (error,
1084                       _dbus_error_from_errno (errno),
1085                       "Failed to open \"%s\": %s",
1086                       _dbus_string_get_const_data (&path),
1087                       _dbus_strerror (errno));
1088       goto fail;
1089     }
1090   
1091   if (!_dbus_read (fd, &cmdline, max_len))
1092     {
1093       dbus_set_error (error,
1094                       _dbus_error_from_errno (errno),
1095                       "Failed to read from \"%s\": %s",
1096                       _dbus_string_get_const_data (&path),
1097                       _dbus_strerror (errno));      
1098       goto fail;
1099     }
1100   
1101   if (!_dbus_close (fd, error))
1102     goto fail;
1103   
1104   string_squash_nonprintable (&cmdline);  
1105   
1106   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1107     goto oom;
1108   
1109   _dbus_string_free (&cmdline);  
1110   _dbus_string_free (&path);
1111   return TRUE;
1112 oom:
1113   _DBUS_SET_OOM (error);
1114 fail:
1115   _dbus_string_free (&cmdline);
1116   _dbus_string_free (&path);
1117   return FALSE;
1118 }