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