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