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