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