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