diff options
Diffstat (limited to 'src')
81 files changed, 0 insertions, 23193 deletions
diff --git a/src/Makefile.am b/src/Makefile.am deleted file mode 100644 index 5e2267f..0000000 --- a/src/Makefile.am +++ /dev/null @@ -1,5 +0,0 @@ - -SUBDIRS = kit polkit polkit-grant - -clean-local : - rm -f *~ diff --git a/src/kit/Makefile.am b/src/kit/Makefile.am deleted file mode 100644 index 824f48c..0000000 --- a/src/kit/Makefile.am +++ /dev/null @@ -1,79 +0,0 @@ -## Process this file with automake to produce Makefile.in - -NULL = - -INCLUDES = \ - -I$(top_builddir)/src -I$(top_srcdir)/src \ - -DPACKAGE_LIBEXEC_DIR=\""$(libexecdir)"\" \ - -DPACKAGE_SYSCONF_DIR=\""$(sysconfdir)"\" \ - -DPACKAGE_DATA_DIR=\""$(datadir)"\" \ - -DPACKAGE_BIN_DIR=\""$(bindir)"\" \ - -DPACKAGE_LOCALSTATE_DIR=\""$(localstatedir)"\" \ - -DPACKAGE_LOCALE_DIR=\""$(localedir)"\" \ - -DPACKAGE_LIB_DIR=\""$(libdir)"\" \ - -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT \ - -DKIT_COMPILATION \ - @GLIB_CFLAGS@ - -noinst_LTLIBRARIES=libkit.la - - -libkit_la_SOURCES = \ - kit.h \ - kit-test.h kit-test.c \ - kit-memory.h kit-memory.c \ - kit-string.h kit-string.c \ - kit-lib.h kit-lib.c \ - kit-list.h kit-list.c \ - kit-hash.h kit-hash.c \ - kit-file.h kit-file.c \ - kit-spawn.h kit-spawn.c \ - kit-message.h kit-message.c \ - kit-entity.h kit-entity.c \ - $(NULL) - - -## note that TESTS has special meaning (stuff to use in make check) -## so if adding tests not to be run in make check, don't add them to -## TESTS -if KIT_BUILD_TESTS -TESTS_ENVIRONMENT= -TESTS=kit-test - -check_PROGRAMS=$(TESTS) - -kit_test_SOURCES= \ - kit-test-main.c - -kit_test_LDADD=$(top_builddir)/src/kit/libkit.la -kit_test_LDFLAGS=@R_DYNAMIC_LDFLAG@ - -if KIT_GCOV_ENABLED -clean-gcov: - rm -f *.gcov .libs/*.gcda *.gcda - -.PHONY: coverage-report.txt covered-files.txt - -covered-files.txt : - echo $(addprefix src/kit/,$(filter %.c,$(libkit_la_SOURCES))) > covered-files.txt - -coverage-report.txt : covered-files.txt clean-gcov all check - gcov $(filter %.c,$(libkit_la_SOURCES)) -o .libs/ > /dev/null - $(top_srcdir)/test/create-coverage-report.sh "module kit" `cat covered-files.txt` > coverage-report.txt - -check-coverage : coverage-report.txt - cat coverage-report.txt -else -coverage-report.txt: - @echo "Need to reconfigure with --enable-gcov" - -check-coverage: - @echo "Need to reconfigure with --enable-gcov" -endif - -else -TESTS= -endif - -clean-local : - rm -f *~ *.bb *.bbg *.da *.gcov .libs/*.da .libs/*.bbg diff --git a/src/kit/kit-entity.c b/src/kit/kit-entity.c deleted file mode 100644 index bbc2012..0000000 --- a/src/kit/kit-entity.c +++ /dev/null @@ -1,163 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-entity.c : Entity management - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <string.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <errno.h> - -#ifdef BUILT_R_DYNAMIC -#include <execinfo.h> -#endif - -#include <kit/kit-entity.h> -#include <kit/kit-test.h> - -/** - * SECTION:kit-entity - * @title: Entity management - * @short_description: Entity management - * - * Functions used for entity management. - **/ - -#ifdef KIT_BUILD_TESTS - -/** - * kit_getpwnam: - * @username: user name to look up - * - * Like getpwnam(3) from the standard C library but tweaked for unit - * testing. TODO: explain how. - * - * Returns: See getpwnam(3) - */ -struct passwd * -kit_getpwnam (const char *username) -{ - struct passwd *pw; - FILE *f; - const char *passwd_file; - - f = NULL; - pw = NULL; - - if ((passwd_file = getenv ("KIT_TEST_PASSWD_FILE")) == NULL) - return getpwnam (username); - - f = fopen (passwd_file, "r"); - if (f == NULL) - goto out; - - while ((pw = fgetpwent (f)) != NULL) { - if (strcmp (pw->pw_name, username) == 0) - goto out; - } - -out: - if (f != NULL) - fclose (f); - return pw; -} - -/** - * kit_getpwuid: - * @uid: uid to look up - * - * Like getpwuid(3) from the standard C library but tweaked for unit - * testing. TODO: explain how. - * - * Returns: See getpwuid(3) - */ -struct passwd * -kit_getpwuid (uid_t uid) -{ - struct passwd *pw; - FILE *f; - const char *passwd_file; - - f = NULL; - pw = NULL; - - if ((passwd_file = getenv ("KIT_TEST_PASSWD_FILE")) == NULL) - return getpwuid (uid); - - f = fopen (passwd_file, "r"); - if (f == NULL) - goto out; - - while ((pw = fgetpwent (f)) != NULL) { - if (pw->pw_uid == uid) - goto out; - } - -out: - if (f != NULL) - fclose (f); - return pw; -} - -#else - -struct passwd * -kit_getpwnam (const char *username) -{ - return getpwnam (username); -} - -struct passwd * -kit_getpwuid (uid_t uid) -{ - return getpwuid (uid); -} -#endif - - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_entity = { - "kit_entity", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-entity.h b/src/kit/kit-entity.h deleted file mode 100644 index 91b4e51..0000000 --- a/src/kit/kit-entity.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-entity.h : Entity management - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_ENTITY_H -#define KIT_ENTITY_H - -#include <stdarg.h> -#include <stdlib.h> -#include <sys/types.h> -#include <pwd.h> -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -struct passwd *kit_getpwnam (const char *username); -struct passwd *kit_getpwuid (uid_t uid); - -KIT_END_DECLS - -#endif /* KIT_ENTITY_H */ - - diff --git a/src/kit/kit-file.c b/src/kit/kit-file.c deleted file mode 100644 index 438f6c2..0000000 --- a/src/kit/kit-file.c +++ /dev/null @@ -1,367 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-file.c : File utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <sys/types.h> -#include <unistd.h> -#include <fcntl.h> -#include <errno.h> -#include <string.h> -#include <dirent.h> - -#include <kit/kit.h> -#include "kit-test.h" - - -/** - * SECTION:kit-file - * @title: File utilities - * @short_description: File utilities - * - * Various file utilities. - **/ - -#define BUF_SIZE 4096 - -/** - * kit_file_get_contents: - * @path: path to file - * @out_contents: Return location for allocated memory. Free with kit_free(). - * @out_contents_size: Return location for size of the file. - * - * Reads an entire file into allocated memory. - * - * Returns: #TRUE if the file was read into memory; #FALSE if an error - * occured and errno will be set. On OOM, errno will be set to - * ENOMEM. If the file doesn't exist, errno will be set to ENOENT. - */ -kit_bool_t -kit_file_get_contents (const char *path, char **out_contents, size_t *out_contents_size) -{ - int fd; - kit_bool_t ret; - ssize_t num_read; - char *p; - char *q; - size_t total_allocated; - size_t total_size; - char buf[BUF_SIZE]; - - kit_return_val_if_fail (path != NULL, FALSE); - kit_return_val_if_fail (out_contents != NULL, FALSE); - kit_return_val_if_fail (out_contents_size != NULL, FALSE); - - fd = -1; - ret = FALSE; - *out_contents = NULL; - p = NULL; - - fd = open (path, O_RDONLY); - if (fd == -1) - goto out; - - p = kit_malloc (BUF_SIZE); - if (p == NULL) { - errno = ENOMEM; - goto out; - } - total_allocated = BUF_SIZE; - total_size = 0; - - do { - again: - num_read = read (fd, buf, BUF_SIZE); - if (num_read == -1) { - if (errno == EINTR) - goto again; - else - goto out; - } - - - if (total_size + num_read > total_allocated) { - total_allocated += BUF_SIZE; - q = kit_realloc (p, total_allocated); - if (q == NULL) { - errno = ENOMEM; - goto out; - } - p = q; - } - - memcpy (p + total_size, buf, num_read); - total_size += num_read; - - } while (num_read > 0); - - /* add terminating zero */ - if (total_size + 1 > total_allocated) { - total_allocated += BUF_SIZE; - q = kit_realloc (p, total_allocated); - if (q == NULL) { - errno = ENOMEM; - goto out; - } - p = q; - } - p[total_size] = '\0'; - - *out_contents = p; - *out_contents_size = total_size; - ret = TRUE; - -out: - if (fd >= 0) { - again2: - if (close (fd) != 0) { - if (errno == EINTR) - goto again2; - else - ret = FALSE; - } - } - - if (!ret) { - kit_free (p); - *out_contents = NULL; - } - - return ret; -} - -static kit_bool_t -_write_to_fd (int fd, const char *str, ssize_t str_len) -{ - kit_bool_t ret; - ssize_t written; - - ret = FALSE; - - written = 0; - while (written < str_len) { - ssize_t ret; - ret = write (fd, str + written, str_len - written); - if (ret < 0) { - if (errno == EAGAIN || errno == EINTR) { - continue; - } else { - goto out; - } - } - written += ret; - } - - ret = TRUE; - -out: - return ret; -} - -/** - * kit_file_set_contents: - * @path: path to file - * @mode: mode for file - * @contents: contents to set - * @contents_size: size of contents - * - * Writes all of contents to a file named @path, with good error - * checking. If a file called @path already exists it will be - * overwritten. This write is atomic in the sense that it is first - * written to a temporary file which is then renamed to the final - * name. - * - * If the file already exists hard links to @path will break. Also - * since the file is recreated, existing permissions, access control - * lists, metadata etc. may be lost. If @path is a symbolic link, the - * link itself will be replaced, not the linked file. - * - * Returns: #TRUE if contents were set; #FALSE if an error occured and - * errno will be set - */ -kit_bool_t -kit_file_set_contents (const char *path, mode_t mode, const char *contents, size_t contents_size) -{ - int fd; - char *path_tmp; - kit_bool_t ret; - - path_tmp = NULL; - ret = FALSE; - - kit_return_val_if_fail ((contents == NULL && contents_size == 0) || (contents != NULL), FALSE); - kit_return_val_if_fail (path != NULL, FALSE); - - path_tmp = kit_strdup_printf ("%s.XXXXXX", path); - if (path_tmp == NULL) { - errno = ENOMEM; - goto out; - } - - fd = mkstemp (path_tmp); - if (fd < 0) { - kit_warning ("Cannot create file '%s': %m", path_tmp); - goto out; - } - if (fchmod (fd, mode) != 0) { - kit_warning ("Cannot change mode for '%s' to 0%o: %m", path_tmp, mode); - close (fd); - unlink (path_tmp); - goto out; - } - - if (contents_size > 0) { - if (!_write_to_fd (fd, contents, contents_size)) { - kit_warning ("Cannot write to file %s: %m", path_tmp); - close (fd); - if (unlink (path_tmp) != 0) { - kit_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - } - close (fd); - - if (rename (path_tmp, path) != 0) { - kit_warning ("Cannot rename %s to %s: %m", path_tmp, path); - if (unlink (path_tmp) != 0) { - kit_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - - ret = TRUE; - -out: - if (path_tmp != NULL) - kit_free (path_tmp); - - return ret; -} - -/** - * _kit_get_num_fd: - * - * Determines the number of open file descriptors - * - * Returns: Number of open file descriptors - */ -size_t -_kit_get_num_fd (void) -{ - DIR *dir; - char buf[128]; - ssize_t num; -#ifdef HAVE_READDIR64 - struct dirent64 *d; -#else - struct dirent *d; -#endif - - num = -1; - - snprintf (buf, sizeof (buf), "/proc/%d/fd", getpid ()); - - dir = opendir (buf); - if (dir == NULL) { - kit_warning ("error calling opendir on %s: %m\n", buf); - goto out; - } - - num = -2; -#ifdef HAVE_READDIR64 - while ((d = readdir64 (dir)) != NULL) { -#else - while ((d = readdir (dir)) != NULL) { -#endif - if (d->d_name == NULL) - continue; - num++; - } - -out: - if (dir != NULL) - closedir (dir); - return num; -} - - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_run_test (void) -{ - char path[] = "/tmp/kit-test"; - char *buf; - size_t buf_size; - char *p; - size_t s; - unsigned int n; - - buf_size = 3 * BUF_SIZE; - if ((buf = kit_malloc (buf_size)) == NULL) - goto out; - - for (n = 0; n < buf_size; n++) - buf[n] = n; - - if (!kit_file_set_contents (path, 0400, buf, buf_size)) { - kit_assert (errno == ENOMEM); - } else { - if (!kit_file_get_contents (path, &p, &s)) { - kit_assert (errno == ENOMEM); - } else { - kit_assert (s == buf_size && memcmp (p, buf, buf_size) == 0); - kit_free (p); - } - - kit_assert (unlink (path) == 0); - - kit_assert (!kit_file_get_contents (path, &p, &s)); - } - - kit_free (buf); - -out: - return TRUE; -} - -KitTest _test_file = { - "kit_file", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-file.h b/src/kit/kit-file.h deleted file mode 100644 index 4fbd84d..0000000 --- a/src/kit/kit-file.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-file.h : File utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_FILE_H -#define KIT_FILE_H - -#include <sys/stat.h> -#include <kit/kit.h> -#ifdef HAVE_SOLARIS -#include <sys/types.h> -#endif - -KIT_BEGIN_DECLS - -kit_bool_t kit_file_get_contents (const char *path, char **out_contents, size_t *out_contents_size); -kit_bool_t kit_file_set_contents (const char *path, mode_t mode, const char *contents, size_t contents_size); - -size_t _kit_get_num_fd (void); - -KIT_END_DECLS - -#endif /* KIT_FILE_H */ - - diff --git a/src/kit/kit-hash.c b/src/kit/kit-hash.c deleted file mode 100644 index b4905e2..0000000 --- a/src/kit/kit-hash.c +++ /dev/null @@ -1,638 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-hash.c : Hash tables - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <kit/kit-memory.h> -#include <kit/kit-hash.h> -#include <kit/kit-test.h> - -/** - * SECTION:kit-hash - * @title: Hash tables - * @short_description: Hash tables - * - * This class provides support for hash tables. - **/ - -struct _KitHashNode; - -typedef struct _KitHashNode { - void *key; - void *value; - struct _KitHashNode *next; -} KitHashNode; - - -/** - * KitHash: - * - * The #KitHash structure not be accessed directly. - */ -struct _KitHash -{ - int refcount; - - int num_top_nodes; - KitHashNode **top_nodes; - - KitHashFunc hash_func; - KitEqualFunc key_equal_func; - KitCopyFunc key_copy_func; - KitCopyFunc value_copy_func; - KitFreeFunc key_destroy_func; - KitFreeFunc value_destroy_func; -}; - -/** - * kit_hash_new: - * @hash_func: The hash function to use - * @key_equal_func: The function used to determine key equality - * @key_copy_func: Function for copying keys or #NULL - * @value_copy_func: Function for copying values or #NULL - * @key_destroy_func: Function for freeing keys or #NULL - * @value_destroy_func: Function for freeing values or #NULL - * - * Creates a new Hash Table. - * - * Returns: The new hash table. Returns #NULL on OOM. - */ -KitHash * -kit_hash_new (KitHashFunc hash_func, - KitEqualFunc key_equal_func, - KitCopyFunc key_copy_func, - KitCopyFunc value_copy_func, - KitFreeFunc key_destroy_func, - KitFreeFunc value_destroy_func) -{ - KitHash *h; - - kit_return_val_if_fail (hash_func != NULL, NULL); - kit_return_val_if_fail (key_equal_func != NULL, NULL); - - h = kit_new0 (KitHash, 1); - if (h == NULL) - goto error; - - h->refcount = 1; - h->hash_func = hash_func; - h->key_copy_func = key_copy_func; - h->value_copy_func = value_copy_func; - h->key_equal_func = key_equal_func; - h->key_destroy_func = key_destroy_func; - h->value_destroy_func = value_destroy_func; - - h->num_top_nodes = 11; /* TODO: configurable? */ - h->top_nodes = kit_new0 (KitHashNode*, h->num_top_nodes); - if (h->top_nodes == NULL) - goto error; - - return h; -error: - if (h != NULL) - kit_hash_unref (h); - return NULL; -} - -/** - * kit_hash_ref: - * @hash: the hash table - * - * Increase reference count. - * - * Returns: the hash table - */ -KitHash * -kit_hash_ref (KitHash *hash) -{ - kit_return_val_if_fail (hash != NULL, hash); - hash->refcount++; - return hash; -} - -/** - * kit_hash_unref: - * @hash: the hash table - * - * Decrease reference count. If reference count drop to zero the hash - * table is freed. - */ -void -kit_hash_unref (KitHash *hash) -{ - kit_return_if_fail (hash != NULL); - - hash->refcount--; - if (hash->refcount > 0) - return; - - if (hash->top_nodes != NULL) { - int n; - - for (n = 0; n < hash->num_top_nodes; n++) { - KitHashNode *node; - KitHashNode *next; - - for (node = hash->top_nodes[n]; node != NULL; node = next) { - if (hash->key_destroy_func != NULL) - hash->key_destroy_func (node->key); - if (hash->value_destroy_func != NULL) - hash->value_destroy_func (node->value); - next = node->next; - kit_free (node); - } - } - } - - kit_free (hash->top_nodes); - kit_free (hash); -} - -/** - * kit_hash_insert: - * @hash: the hash table - * @key: key to insert - * @value: value to insert - * - * Inserts a new key and value into a hash table. If the key already - * exists in the hash table it's current value is replaced with the - * new value. - * - * Returns: #TRUE unless OOM - */ -kit_bool_t -kit_hash_insert (KitHash *hash, - void *key, - void *value) -{ - int bucket; - KitHashNode **nodep; - KitHashNode *node; - void *key_copy; - void *value_copy; - - key_copy = NULL; - value_copy = NULL; - if (hash->key_copy_func != NULL) { - key_copy = hash->key_copy_func (key); - if (key_copy == NULL) { - goto oom; - } - } else { - key_copy = key; - } - if (hash->value_copy_func != NULL) { - value_copy = hash->value_copy_func (value); - if (value_copy == NULL) { - goto oom; - } - } else { - value_copy = value; - } - - bucket = hash->hash_func (key) % hash->num_top_nodes; - - nodep = & (hash->top_nodes [bucket]); - node = hash->top_nodes [bucket]; - while (node != NULL) { - nodep = &(node->next); - - if (hash->key_equal_func (key, node->key)) { - /* replace the value */ - - if (hash->key_destroy_func != NULL) - hash->key_destroy_func (node->key); - if (hash->value_destroy_func != NULL) - hash->value_destroy_func (node->value); - - node->key = key_copy; - node->value = value_copy; - - goto out; - } else { - node = node->next; - } - } - - node = kit_new0 (KitHashNode, 1); - if (node == NULL) - goto oom; - - node->key = key_copy; - node->value = value_copy; - *nodep = node; - -out: - return TRUE; - -oom: - if (key_copy != NULL && hash->key_copy_func != NULL && hash->key_destroy_func != NULL) - hash->key_destroy_func (key_copy); - - if (value_copy != NULL && hash->value_copy_func != NULL && hash->value_destroy_func != NULL) - hash->value_destroy_func (value_copy); - - return FALSE; -} - -/** - * kit_hash_lookup: - * @hash: the hash table - * @key: key to look up - * @found: if not #NULL, will return #TRUE only if the key was found in the hash table - * - * Look up a value in the hash table. - * - * Returns: the value; caller shall not free/unref this value - */ -void * -kit_hash_lookup (KitHash *hash, void *key, kit_bool_t *found) -{ - int bucket; - void *value; - KitHashNode *node; - - value = NULL; - if (found != NULL) - *found = FALSE; - - bucket = hash->hash_func (key) % hash->num_top_nodes; - - node = hash->top_nodes [bucket]; - while (node != NULL) { - if (hash->key_equal_func (key, node->key)) { - /* got it */ - - value = node->value; - if (found != NULL) - *found = TRUE; - goto out; - } else { - node = node->next; - } - } - -out: - return value; -} - - -/** - * kit_hash_foreach: - * @hash: the hash table - * @cb: callback function - * @user_data: user data - * - * Iterate over all elements in a hash table - * - * Returns: #TRUE only if the callback short-circuited the iteration - */ -kit_bool_t -kit_hash_foreach (KitHash *hash, KitHashForeachFunc cb, void *user_data) -{ - int n; - - kit_return_val_if_fail (hash != NULL, FALSE); - kit_return_val_if_fail (cb != NULL, FALSE); - - for (n = 0; n < hash->num_top_nodes; n++) { - KitHashNode *node; - - for (node = hash->top_nodes[n]; node != NULL; node = node->next) { - if (cb (node->key, node->value, user_data, hash)) - return TRUE; - } - } - - return FALSE; -} - -/** - * kit_hash_foreach_remove: - * @hash: the hash table - * @cb: callback function - * @user_data: user data - * - * Iterate over all elements in a hash table. If @cb returns %TRUE, - * the element will be removed. - * - * Returns: Number of key/value pairs removed - */ -size_t -kit_hash_foreach_remove (KitHash *hash, KitHashForeachFunc cb, void *user_data) -{ - int n; - size_t num_rem; - - kit_return_val_if_fail (hash != NULL, FALSE); - kit_return_val_if_fail (cb != NULL, FALSE); - - num_rem = 0; - - for (n = 0; n < hash->num_top_nodes; n++) { - KitHashNode *node; - KitHashNode *node_next; - KitHashNode **prev_node_next; - - prev_node_next = &(hash->top_nodes[n]); - - for (node = hash->top_nodes[n]; node != NULL; node = node_next) { - node_next = node->next; - - if (cb (node->key, node->value, user_data, hash)) { - - if (hash->key_destroy_func != NULL) - hash->key_destroy_func (node->key); - if (hash->value_destroy_func != NULL) - hash->value_destroy_func (node->value); - kit_free (node); - - *prev_node_next = node_next; - num_rem++; - } else { - prev_node_next = &(node->next); - } - } - } - - return num_rem; -} - - -/** - * kit_hash_direct_hash_func: - * @key: the key - * - * Converts a pointer to a hash value. - * - * Returns: a hash value corresponding to the key - */ -uint32_t -kit_hash_direct_hash_func (const void *key) -{ - return (uint32_t) key; -} - -/** - * kit_hash_direct_equal_func: - * @v1: first value - * @v2: second value - * - * Compares two pointers and return #TRUE if they are equal (same address). - * - * Returns: #TRUE only if the values are equal - */ -kit_bool_t -kit_hash_direct_equal_func (const void *v1, const void *v2) -{ - return v1 == v2; -} - -/** - * kit_hash_str_hash_func: - * @key: the key - * - * Converts a string to a hash value. - * - * Returns: a hash value corresponding to the key - */ -uint32_t -kit_hash_str_hash_func (const void *key) -{ - const char *p; - uint32_t hash; - - hash = 0; - for (p = key; *p != '\0'; p++) - hash = hash * 617 ^ *p; - - return hash; -} - -/** - * kit_hash_str_equal_func: - * @v1: first value - * @v2: second value - * - * Compares two strings and return #TRUE if they are equal. - * - * Returns: #TRUE only if the values are equal - */ -kit_bool_t -kit_hash_str_equal_func (const void *v1, const void *v2) -{ - return strcmp (v1, v2) == 0; -} - -/** - * kit_hash_str_copy: - * @p: void pointer to string - * - * Similar to kit_strdup() except for types. - * - * Returns: a void pointer to a copy or #NULL on OOM - */ -void * -kit_hash_str_copy (const void *p) -{ - return (void *) kit_strdup ((const char *) p); -} - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_it1 (void *key, void *value, void *user_data, KitHash *hash) -{ - int *count = (int *) user_data; - *count += 1; - return FALSE; -} - -static kit_bool_t -_it2 (void *key, void *value, void *user_data, KitHash *hash) -{ - int *count = (int *) user_data; - *count += 1; - return TRUE; -} - -static kit_bool_t -_it_sum (void *key, void *value, void *user_data, KitHash *hash) -{ - int *count = (int *) user_data; - *count += (int) value; - return FALSE; -} - -static kit_bool_t -_it_rem (void *key, void *value, void *user_data, KitHash *hash) -{ - if (strlen ((char *) key) > 4) - return TRUE; - else - return FALSE; -} - -static kit_bool_t -_run_test (void) -{ - int count; - KitHash *h; - kit_bool_t found; - - /* string hash tables */ - if ((h = kit_hash_new (kit_hash_str_hash_func, kit_hash_str_equal_func, - kit_hash_str_copy, kit_hash_str_copy, - kit_free, kit_free)) != NULL) { - int n; - char *key; - char *value; - char *test_data[] = {"key1", "val1", - "key2", "val2", - "key3", "val3", - "key4", "val4", - "key5", "val5", - "key6", "val6", - "key7", "val7", - "key8", "val8", - "key9", "val9", - "key10", "val10", - "key11", "val11", - "key12", "val12", - NULL}; - - /* first insert the values */ - for (n = 0; test_data [n*2] != NULL; n++) { - if (!kit_hash_insert (h, test_data [n*2], test_data [n*2 + 1])) { - goto oom; - } - } - - /* then check that we can look them up */ - for (n = 0; test_data [n*2] != NULL; n++) { - key = test_data [n*2]; - value = kit_hash_lookup (h, test_data[n*2], &found); - - kit_assert (found && strcmp (value, test_data[n*2 + 1]) == 0); - } - - /* lookup unknown key */ - kit_assert (kit_hash_lookup (h, "unknown", &found) == NULL && !found); - - /* replace key */ - if (key != NULL) { - if (kit_hash_insert (h, "key1", "val1-replaced")) { - /* check for replaced value */ - value = kit_hash_lookup (h, "key1", &found); - kit_assert (found && value != NULL && strcmp (value, "val1-replaced") == 0); - } - } - - count = 0; - kit_assert (kit_hash_foreach (h, _it1, &count) == FALSE); - kit_assert (count == ((sizeof (test_data) / sizeof (char *) - 1) / 2)); - count = 0; - kit_assert (kit_hash_foreach (h, _it2, &count) == TRUE); - kit_assert (count == 1); - - kit_hash_ref (h); - kit_hash_unref (h); - oom: - - kit_hash_unref (h); - } - - /* direct hash tables */ - if ((h = kit_hash_new (kit_hash_direct_hash_func, kit_hash_direct_equal_func, - NULL, NULL, - NULL, NULL)) != NULL) { - if (kit_hash_insert (h, h, h)) { - kit_assert ((kit_hash_lookup (h, h, &found) == h) && found); - if (kit_hash_insert (h, h, NULL)) { - kit_assert (kit_hash_lookup (h, h, &found) == NULL && found); - } - } - kit_hash_unref (h); - } - - /* remove */ - if ((h = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - kit_hash_str_copy, - NULL, - kit_free, - NULL)) != NULL) { - char *test_data[] = {"key1", - "key2b", - "key3", - "key4", - "key5b", - "key6b", - "key7", - "key8", - NULL}; - int n; - int count; - - /* first insert the values */ - for (n = 0; test_data [n] != NULL; n++) { - if (!kit_hash_insert (h, test_data [n], (void *) (n + 1))) { - goto oom; - } - } - - count = 0; - kit_assert (kit_hash_foreach (h, _it_sum, &count) == FALSE); - kit_assert (count == 1+2+3+4+5+6+7+8); - - kit_assert (kit_hash_foreach_remove (h, _it_rem, &count) == 3); - count = 0; - kit_assert (kit_hash_foreach (h, _it_sum, &count) == FALSE); - kit_assert (count == 1+3+4+7+8); - - kit_hash_unref (h); - } - - - return TRUE; -} - -KitTest _test_hash = { - "kit_hash", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-hash.h b/src/kit/kit-hash.h deleted file mode 100644 index 608c4d5..0000000 --- a/src/kit/kit-hash.h +++ /dev/null @@ -1,144 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-hash.h : Hash tables - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_HASH_H -#define KIT_HASH_H - -#include <stdint.h> -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -struct _KitHash; -typedef struct _KitHash KitHash; - -/** - * KitHashFunc: - * @key: a key - * - * The function is passed a key and should return a hash value. The - * functions kit_hash_direct_hash_func() and - * kit_hash_str_hash_func() provide hash functions which can be - * used when the key is a pointer and an char* respectively. - * - * Returns: the hash value corresponding to the key - */ -typedef uint32_t (*KitHashFunc) (const void *key); - -/** - * KitEqualFunc: - * @key1: first key - * @key2: second key - * - * Determines if two keys are equal. The functions - * kit_hash_direct_equal_func() and kit_hash_str_equal_func() - * provide equality functions which can be used when the key is a - * pointer and an char* respectively. - * - * Returns: #TRUE iff the keys are equal - */ -typedef kit_bool_t (*KitEqualFunc) (const void *key1, const void *key2); - -/** - * KitFreeFunc: - * @p: pointer - * - * Specifies the type of function which is called when a data element - * is destroyed. It is passed the pointer to the data element and - * should free any memory and resources allocated for it. The function - * p_free() or any of the object unref functions can be passed here. - */ -typedef void (*KitFreeFunc) (void *p); - -/** - * KitCopyFunc: - * @p: pointer - * - * Specifies the type of function which is called when a data element - * is to be cloned or reffed. It is passed the pointer to the data - * element and should return a new pointer to a reffed or cloned - * object. The function kit_hash_str_copy() or any of the object - * ref functions can be passed here. - * - * Returns: A copy or ref of the object in question - */ -typedef void *(*KitCopyFunc) (const void *p); - -/** - * KitHashForeachFunc: - * @key: key - * @value: value - * @user_data: user data passed to kit_hash_foreach() - * @hash: the hash table - * - * Type signature for callback function used in kit_hash_foreach(). - * - * Returns: Return #TRUE to short-circuit, e.g. stop the iteration. - */ -typedef kit_bool_t (*KitHashForeachFunc) (void *key, - void *value, - void *user_data, - KitHash *hash); - - -KitHash *kit_hash_new (KitHashFunc hash_func, - KitEqualFunc key_equal_func, - KitCopyFunc key_copy_func, - KitCopyFunc value_copy_func, - KitFreeFunc key_destroy_func, - KitFreeFunc value_destroy_func); - -KitHash *kit_hash_ref (KitHash *hash); -void kit_hash_unref (KitHash *hash); - -kit_bool_t kit_hash_insert (KitHash *hash, void *key, void *value); - -void *kit_hash_lookup (KitHash *hash, void *key, kit_bool_t *found); - -kit_bool_t kit_hash_foreach (KitHash *hash, KitHashForeachFunc cb, void *user_data); - -size_t kit_hash_foreach_remove (KitHash *hash, KitHashForeachFunc cb, void *user_data); - - -uint32_t kit_hash_direct_hash_func (const void *key); -kit_bool_t kit_hash_direct_equal_func (const void *v1, const void *v2); - -uint32_t kit_hash_str_hash_func (const void *key); -kit_bool_t kit_hash_str_equal_func (const void *v1, const void *v2); -void *kit_hash_str_copy (const void *p); - -KIT_END_DECLS - -#endif /* KIT_HASH_H */ - - diff --git a/src/kit/kit-lib.c b/src/kit/kit-lib.c deleted file mode 100644 index a05cc11..0000000 --- a/src/kit/kit-lib.c +++ /dev/null @@ -1,136 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-lib.c : General utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <errno.h> - -#include <kit/kit.h> -#include "kit-test.h" - -#ifndef HAVE_GETLINE -ssize_t -kit_getline (char **lineptr, size_t *n, FILE *stream) -{ - char *line, *p; - long size, copy; - - if (lineptr == NULL || n == NULL) { - errno = EINVAL; - return (ssize_t) -1; - } - - if (ferror (stream)) - return (ssize_t) -1; - - /* Make sure we have a line buffer to start with. */ - if (*lineptr == NULL || *n < 2) /* !seen and no buf yet need 2 chars. */ { -#ifndef MAX_CANON -#define MAX_CANON 256 -#endif - if (!*lineptr) - line = (char *) malloc (MAX_CANON); - else - line = (char *) realloc (*lineptr, MAX_CANON); - if (line == NULL) - return (ssize_t) -1; - *lineptr = line; - *n = MAX_CANON; - } - - line = *lineptr; - size = *n; - - copy = size; - p = line; - - while (1) { - long len; - - while (--copy > 0) { - int c = getc (stream); - - if (c == EOF) - goto lose; - else if ((*p++ = c) == '\n') - goto win; - } - - /* Need to enlarge the line buffer. */ - len = p - line; - size *= 2; - line = (char *) realloc (line, size); - if (line == NULL) - goto lose; - *lineptr = line; - *n = size; - p = line + len; - copy = size - len; - } - -lose: - if (p == *lineptr) - return (ssize_t) -1; - - /* Return a partial line since we got an error in the middle. */ -win: - *p = '\0'; - return p - *lineptr; -} -#else -ssize_t -kit_getline (char **lineptr, size_t *n, FILE *f) -{ - return getline (lineptr, n, f); -} -#endif - -#ifndef HAVE_CLEARENV -extern char **environ; - -int -kit_clearenv (void) -{ - if (environ != NULL) - environ[0] = NULL; - return 0; -} -#else -int -kit_clearenv (void) -{ - return clearenv (); -} -#endif diff --git a/src/kit/kit-lib.h b/src/kit/kit-lib.h deleted file mode 100644 index 523e096..0000000 --- a/src/kit/kit-lib.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-string.h : General utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_LIB_H -#define KIT_LIB_H - -#include <sys/types.h> -#include <stdio.h> - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -ssize_t kit_getline (char **lineptr, size_t *n, FILE *f); - -int kit_clearenv (void); - -KIT_END_DECLS - -#endif /* KIT_LIB_H */ - - diff --git a/src/kit/kit-list.c b/src/kit/kit-list.c deleted file mode 100644 index d3d5367..0000000 --- a/src/kit/kit-list.c +++ /dev/null @@ -1,348 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-list.c : Doubly-linked lists - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <kit/kit.h> -#include "kit-test.h" - -/** - * SECTION:kit-list - * @title: Doubly-linked lists - * @short_description: Doubly-linked lists - * - * This class provides support for doubly-linked lists. - **/ - -/** - * kit_list_append: - * @list: existing list or #NULL to create a new list - * @data: data to append to the list - * - * Append an entry to a list. - * - * Returns: the head of the new list or #NULL on OOM - */ -KitList * -kit_list_append (KitList *list, void *data) -{ - KitList *l; - KitList *j; - - for (j = list; j != NULL && j->next != NULL; j = j->next) - ; - - l = kit_new0 (KitList, 1); - if (l == NULL) - goto oom; - - l->data = data; - l->prev = j; - - if (j != NULL) { - j->next = l; - } else { - list = l; - } - - return list; -oom: - return NULL; -} - -/** - * kit_list_copy: - * @list: existing list - * - * Makes a copy of a list. It is not a deep copy. - * - * Returns: A copy of the new list or #NULL on OOM. Free with kit_list_free(). - **/ -KitList * -kit_list_copy (KitList *list) -{ - KitList *l; - KitList *l2; - KitList *j; - - l = NULL; - for (j = list; j != NULL; j = j->next) { - /* TODO: prepend, then reverse */ - l2 = kit_list_append (l, j->data); - if (l2 == NULL) - goto oom; - l = l2; - } - - return l; -oom: - kit_list_free (l); - return NULL; -} - -/** - * kit_list_prepend: - * @list: existing list or #NULL to create a new list - * @data: data to prepend to the list - * - * Prepend an entry to a list. - * - * Returns: the head of the new list or #NULL on OOM - */ -KitList * -kit_list_prepend (KitList *list, void *data) -{ - KitList *l; - - l = kit_new0 (KitList, 1); - if (l == NULL) - goto oom; - - l->next = list; - l->data = data; - if (list != NULL) { - list->prev = l; - } - -oom: - return l; -} - -/** - * kit_list_delete_link: - * @list: existing list, cannot be #NULL - * @link: link to delete, cannot be #NULL - * - * Delete a link from a list. - * - * Returns: the new head of the list or #NULL if the list is empty after deletion. - */ -KitList * -kit_list_delete_link (KitList *list, KitList *link) -{ - KitList *ret; - - kit_return_val_if_fail (list != NULL, NULL); - kit_return_val_if_fail (link != NULL, NULL); - - if (list == link) - ret = link->next; - else - ret = list; - - if (link->prev != NULL) { - link->prev->next = link->next; - } - - if (link->next != NULL) { - link->next->prev = link->prev; - } - - kit_free (link); - - return ret; -} - -/** - * kit_list_free: - * @list: the list - * - * Frees all links in a list - */ -void -kit_list_free (KitList *list) -{ - KitList *l; - KitList *j; - - for (l = list; l != NULL; l = j) { - j = l->next; - kit_free (l); - } -} - -/** - * kit_list_length: - * @list: the list - * - * Compute the length of a list. - * - * Returns: Number of entries in list - */ -size_t -kit_list_length (KitList *list) -{ - ssize_t n; - KitList *l; - - n = 0; - for (l = list; l != NULL; l = l->next) - n++; - - return n; -} - -/** - * kit_list_foreach: - * @list: the list - * @func: callback function - * @user_data: user data to pass to callback - * - * Iterate over all entries in a list. - * - * Returns: #TRUE only if the callback short-circuited the iteration - */ -kit_bool_t -kit_list_foreach (KitList *list, KitListForeachFunc func, void *user_data) -{ - KitList *l; - - kit_return_val_if_fail (list != NULL, FALSE); - kit_return_val_if_fail (func != NULL, FALSE); - - for (l = list; l != NULL; l = l->next) { - if (func (l->data, user_data, list)) - return TRUE; - } - - return FALSE; -} - - -#ifdef KIT_BUILD_TESTS - -typedef struct { - int num; - int result; -} _Closure; - -static kit_bool_t -_sum (void *data, void *user_data, KitList *list) -{ - _Closure *c = (_Closure*) user_data; - - c->result += ((int) data) * (c->num + 1); - c->num += 1; - - return FALSE; -} - -static kit_bool_t -_sum2 (void *data, void *user_data, KitList *list) -{ - _Closure *c = (_Closure*) user_data; - - if (c->num == 2) - return TRUE; - - c->result += ((int) data) * (c->num + 1); - c->num += 1; - - return FALSE; -} - -static kit_bool_t -_run_test (void) -{ - _Closure c; - int items[] = {1, 2, 3, 4, 5}; - unsigned int num_items = sizeof (items) / sizeof (int); - unsigned int n; - KitList *l; - KitList *j; - - l = NULL; - for (n = 0; n < num_items; n++) { - j = l; - l = kit_list_prepend (l, (void *) items[n]); - if (l == NULL) - goto oom; - } - - kit_assert (kit_list_length (l) == num_items); - c.num = 0; - c.result = 0; - kit_list_foreach (l, _sum, &c); - kit_assert (c.result == 1*5 + 2*4 + 3*3 + 4*2 + 5*1); - - c.num = 0; - c.result = 0; - kit_list_foreach (l, _sum2, &c); - kit_assert (c.result == 1*5 + 2*4); - - l = kit_list_delete_link (l, l); - kit_assert (kit_list_length (l) == num_items - 1); - c.num = 0; - c.result = 0; - kit_list_foreach (l, _sum, &c); - kit_assert (c.result == 1*4 + 2*3 + 3*2 + 4*1); - - l = kit_list_delete_link (l, l->next); - kit_assert (kit_list_length (l) == num_items - 2); - c.num = 0; - c.result = 0; - kit_list_foreach (l, _sum, &c); - kit_assert (c.result == 1*4 + 2*2 + 3*1); - - kit_list_free (l); - - l = NULL; - for (n = 0; n < num_items; n++) { - j = l; - l = kit_list_append (l, (void *) items[n]); - if (l == NULL) - goto oom; - } - - c.num = 0; - c.result = 0; - kit_list_foreach (l, _sum, &c); - kit_assert (c.result == 1*1 + 2*2 + 3*3 + 4*4 + 5*5); - - kit_list_free (l); - - return TRUE; -oom: - kit_list_free (j); - return TRUE; -} - -KitTest _test_list = { - "kit_list", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-list.h b/src/kit/kit-list.h deleted file mode 100644 index 1b22ae2..0000000 --- a/src/kit/kit-list.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-list.h : Doubly-linked list - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_LIST_H -#define KIT_LIST_H - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -struct _KitList; -typedef struct _KitList KitList; - -/** - * KitList: - * @data: the value passed in kit_list_append() and kit_list_prepend() - * @next: the next element in the list or #NULL if this is the last element - * @prev: the previous element in the list or #NULL if this is the last element - * - * Public members of the #KitList data structure - */ -struct _KitList { - void *data; - KitList *next; - KitList *prev; -}; - -/** - * KitListForeachFunc: - * @data: data of link entry - * @user_data: user data passed to kit_list_foreach() - * @list: the list - * - * Type signature for callback function used in kit_list_foreach(). - * - * Returns: Return #TRUE to short-circuit, e.g. stop the iteration. - */ -typedef kit_bool_t (*KitListForeachFunc) (void *data, - void *user_data, - KitList *list); - -KitList *kit_list_append (KitList *list, void *data); -KitList *kit_list_prepend (KitList *list, void *data); -void kit_list_free (KitList *list); -KitList *kit_list_delete_link (KitList *list, KitList *link); - -size_t kit_list_length (KitList *list); -kit_bool_t kit_list_foreach (KitList *list, KitListForeachFunc func, void *user_data); -KitList *kit_list_copy (KitList *list); - - -KIT_END_DECLS - -#endif /* KIT_LIST_H */ - - diff --git a/src/kit/kit-memory.c b/src/kit/kit-memory.c deleted file mode 100644 index bf79fea..0000000 --- a/src/kit/kit-memory.c +++ /dev/null @@ -1,422 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-memory.c : Memory management - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <string.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <errno.h> - -#ifdef BUILT_R_DYNAMIC -#include <execinfo.h> -#endif - -#include <kit/kit-memory.h> -#include <kit/kit-test.h> - -/** - * SECTION:kit-memory - * @title: Memory management - * @short_description: Memory management - * - * Functions used for memory management. - **/ - -#ifdef KIT_BUILD_TESTS - -static int _cur_allocs = 0; -static int _total_allocs = 0; -static int _fail_nth = -1; - - -#if defined(KIT_BUILD_TESTS) && defined(BUILT_R_DYNAMIC) -typedef struct _KitAllocationEntry { - const void *memory; - void *backtrace[100]; - int backtrace_size; - struct _KitAllocationEntry *next; -} KitAllocationEntry; - -static KitAllocationEntry *alloc_list_head = NULL; -#endif - -void -_kit_memory_reset (void) -{ - _cur_allocs = 0; - _total_allocs = 0; - _fail_nth = -1; - -#if defined(KIT_BUILD_TESTS) && defined(BUILT_R_DYNAMIC) - /* TODO: free existing allocs */ - alloc_list_head = NULL; -#endif -} - -int -_kit_memory_get_current_allocations (void) -{ - return _cur_allocs; -} - -int -_kit_memory_get_total_allocations (void) -{ - return _total_allocs; -} - -void -_kit_memory_fail_nth_alloc (int number) -{ - _fail_nth = number; -} - -static inline void -_alloc_add (const void *memory) -{ -#if defined(KIT_BUILD_TESTS) && defined(BUILT_R_DYNAMIC) - KitAllocationEntry *entry; - - entry = malloc (sizeof (KitAllocationEntry)); - entry->memory = memory; - entry->backtrace_size = backtrace (entry->backtrace, 100); - entry->next = alloc_list_head; - - alloc_list_head = entry; -#endif -} - -static inline void -_alloc_remove (const void *memory) -{ -#if defined(KIT_BUILD_TESTS) && defined(BUILT_R_DYNAMIC) - KitAllocationEntry *l; - KitAllocationEntry **prev; - - prev = &alloc_list_head; - for (l = alloc_list_head; l != NULL; l = l->next) { - if (l->memory == memory) { - *prev = l->next; - free (l); - break; - } - - prev = &(l->next); - } -#endif -} - -void -_kit_memory_print_outstanding_allocations (void) -{ -#if defined(KIT_BUILD_TESTS) && defined(BUILT_R_DYNAMIC) - KitAllocationEntry *l; - for (l = alloc_list_head; l != NULL; l = l->next) { - int i; - char **syms; - - syms = backtrace_symbols (l->backtrace, l->backtrace_size); - - i = 0; - while (i < l->backtrace_size) - { - fprintf (stderr, " %s\n", syms[i]); - ++i; - } - fprintf (stderr, "\n"); - fflush (stderr); - - free (syms); - } -#endif -} - - -/** - * kit_malloc: - * @bytes: number of 8-bit bytes to allocate - * - * Allocate memory - * - * Returns: memory location or #NULL on OOM. Free with kit_free(). - */ -void * -kit_malloc (size_t bytes) -{ - void *p; - - if (_fail_nth != -1 && _total_allocs == _fail_nth) { - errno = ENOMEM; - _total_allocs++; - - //fprintf (stderr, " Failing alloc @\n"); - //kit_print_backtrace (); - - return NULL; - } - - p = malloc (bytes); - - if (p != NULL) { - _cur_allocs++; - _total_allocs++; - _alloc_add (p); - } - - return p; -} - -/** - * kit_malloc0: - * @bytes: number of 8-bit bytes to allocate - * - * Allocate memory and zero it. - * - * Returns: memory location or #NULL on OOM. Free with kit_free(). - */ -void * -kit_malloc0 (size_t bytes) -{ - void *p; - - if (_fail_nth != -1 && _total_allocs == _fail_nth) { - errno = ENOMEM; - return NULL; - } - - p = calloc (1, bytes); - - if (p != NULL) { - _cur_allocs++; - _total_allocs++; - _alloc_add (p); - } - - return p; -} - -/** - * kit_realloc: - * @memory: memory previously allocated - * @bytes: new size - * - * Reallocate memory; like realloc(3). - * - * Returns: memory location or #NULL on OOM. Free with kit_free(). - */ -void * -kit_realloc (void *memory, size_t bytes) -{ - void *p; - - if (memory == NULL) - return kit_malloc (bytes); - - if (bytes == 0) { - kit_free (memory); - return memory; - } - - if (_fail_nth != -1 && _total_allocs == _fail_nth) { - errno = ENOMEM; - return NULL; - } - - _alloc_remove (p); - p = realloc (memory, bytes); - if (p != NULL) - _alloc_add (p); - - return p; -} - -/** - * kit_free: - * @memory: pointer to memory allocated with kit_malloc() + friends - * - * Free memory allocated by kit_malloc() + friends. - */ -void -kit_free (void *memory) -{ - free (memory); - if (memory != NULL) { - _alloc_remove (memory); - _cur_allocs--; - } -} - -/*--------------------------------------------------------------------------------------------------------------*/ -#else -/*--------------------------------------------------------------------------------------------------------------*/ - -void * -kit_malloc (size_t bytes) -{ - return malloc (bytes); -} - -void * -kit_malloc0 (size_t bytes) -{ - return calloc (1, bytes); -} - -void * -kit_realloc (void *memory, size_t bytes) -{ - return realloc (memory, bytes); -} - -void -kit_free (void *memory) -{ - free (memory); -} - -void -_kit_memory_reset (void) -{ -} - -int -_kit_memory_get_current_allocations (void) -{ - return -1; -} - -int -_kit_memory_get_total_allocations (void) -{ - return -1; -} - -void -_kit_memory_fail_nth_alloc (int number) -{ -} - -void -_kit_memory_print_outstanding_allocations (void) -{ -} - -#endif /* KIT_BUILD_TESTS */ - -/* There's probably a better place for this function ... */ - -/** - * kit_print_backtrace: - * - * Print a back trace if built with -rdynamic or similar. - */ -void -kit_print_backtrace (void) -{ -#ifdef BUILT_R_DYNAMIC - void *bt[500]; - int bt_size; - int i; - char **syms; - - bt_size = backtrace (bt, 500); - - syms = backtrace_symbols (bt, bt_size); - - i = 0; - while (i < bt_size) - { - fprintf (stderr, " %s\n", syms[i]); - ++i; - } - fprintf (stderr, "\n"); - fflush (stderr); - - free (syms); -#else - fprintf (stderr, " Not built with -rdynamic so unable to print a backtrace\n"); -#endif -} - - - - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_run_test (void) -{ - int n; - char *p; - char *p2; - - if ((p = kit_malloc (1000)) != NULL) { - for (n = 0; n < 1000; n++) - p[n] = n; - - p2 = kit_realloc (p, 2000); - if (p2 != NULL) { - p = p2; - - for (n = 0; n < 2000; n++) - p[n] = n; - } - - kit_free (p); - } - - if ((p = kit_realloc (NULL, 1000)) != NULL) { - for (n = 0; n < 1000; n++) - p[n] = n; - - kit_realloc (p, 0); - } - - if ((p = kit_malloc0 (1000)) != NULL) { - for (n = 0; n < 1000; n++) - kit_assert (p[n] == '\0'); - kit_free (p); - } - - return TRUE; -} - -KitTest _test_memory = { - "kit_memory", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-memory.h b/src/kit/kit-memory.h deleted file mode 100644 index fae2da1..0000000 --- a/src/kit/kit-memory.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-memory.h : Memory management - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_MEMORY_H -#define KIT_MEMORY_H - -#include <stdarg.h> -#include <stdlib.h> -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -void *kit_malloc (size_t bytes); -void *kit_malloc0 (size_t bytes); -void *kit_realloc (void *memory, size_t bytes); -void kit_free (void *memory); - -/** - * kit_new: - * @type: the type of object to allocate - * @count: number of objects to allocate - * - * Allocate memory for @count structures of type @type. - * - * Returns: Allocated memory, cast to a pointer of #type or #NULL on OOM. - */ -#define kit_new(type, count) ((type*)kit_malloc (sizeof (type) * (count))); - -/** - * kit_new0: - * @type: the type of object to allocate - * @count: number of objects to allocate - * - * Allocate zeroed memory for @count structures of type @type. - * - * Returns: Allocated memory, cast to a pointer of #type or #NULL on OOM. - */ -#define kit_new0(type, count) ((type*)kit_malloc0 (sizeof (type) * (count))); - -void _kit_memory_reset (void); -int _kit_memory_get_current_allocations (void); -int _kit_memory_get_total_allocations (void); -void _kit_memory_fail_nth_alloc (int number); -void _kit_memory_print_outstanding_allocations (void); - -KIT_END_DECLS - -#endif /* KIT_MEMORY_H */ - - diff --git a/src/kit/kit-message.c b/src/kit/kit-message.c deleted file mode 100644 index ad09039..0000000 --- a/src/kit/kit-message.c +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-message.c : Message utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <unistd.h> - -#include <kit/kit.h> -#include "kit-test.h" - -/** - * SECTION:kit-message - * @title: Message utilities - * @short_description: Message utilities - * - * Various message and logging utilities. - **/ - -/** - * kit_debug: - * @format: printf(3) style format string - * @...: the parameters to insert into @format - * - * Outputs a debug message on stdout. - */ -void -kit_debug (const char *format, ...) -{ - va_list args; - char buf[1024]; - - kit_return_if_fail (format != NULL); - - va_start (args, format); - vsnprintf (buf, sizeof (buf), format, args); - va_end (args); - - printf ("[INFO %5d] %s\n", getpid (), buf); -} - -/** - * kit_warning: - * @format: printf(3) style format string - * @...: the parameters to insert into @format - * - * Outputs a warning message on stderr. - */ -void -kit_warning (const char *format, ...) -{ - va_list args; - char buf[1024]; - - kit_return_if_fail (format != NULL); - - va_start (args, format); - vsnprintf (buf, sizeof (buf), format, args); - va_end (args); - - fprintf (stderr, "[WARN %5d] %s\n", getpid (), buf); -} - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_run_test (void) -{ - kit_debug ("Debug %d", 42); - kit_warning ("Warning %d %s", 42, "foo"); - return TRUE; -} - -KitTest _test_message = { - "kit_message", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-message.h b/src/kit/kit-message.h deleted file mode 100644 index 7d363b5..0000000 --- a/src/kit/kit-message.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-message.h : Message utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_MESSAGE_H -#define KIT_MESSAGE_H - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -#ifdef __sun -void kit_debug (const char *format, ...); -void kit_warning (const char *format, ...); -#else -void kit_debug (const char *format, ...) __attribute__((__format__ (__printf__, 1, 2))); -void kit_warning (const char *format, ...) __attribute__((__format__ (__printf__, 1, 2))); -#endif - -KIT_END_DECLS - -#endif /* KIT_MESSAGE_H */ - - diff --git a/src/kit/kit-spawn.c b/src/kit/kit-spawn.c deleted file mode 100644 index 080a1bc..0000000 --- a/src/kit/kit-spawn.c +++ /dev/null @@ -1,675 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-spawn.c : Spawn utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <unistd.h> -#include <fcntl.h> -#include <errno.h> -#include <signal.h> - -#include <kit/kit.h> -#include "kit-test.h" - - -/** - * SECTION:kit-spawn - * @title: Spawn utilities - * @short_description: Spawn utilities - * - * Various spawn utilities. - **/ - -static kit_bool_t -set_close_on_exec (int fd, void *data) -{ - if (fd >= (int) data) { - if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0 && errno != EBADF) { - return FALSE; - } - } - - return TRUE; -} - -static kit_bool_t -_fdwalk (kit_bool_t (*callback)(int fd, void *user_data), void *user_data) -{ - int fd; - int max_fd; - - kit_return_val_if_fail (callback != NULL, FALSE); - - max_fd = sysconf (_SC_OPEN_MAX); - for (fd = 0; fd < max_fd; fd++) { - if (!callback (fd, user_data)) - return FALSE; - } - - return TRUE; -} - -static int -_sane_dup2 (int fd1, int fd2) -{ - int ret; - -again: - ret = dup2 (fd1, fd2); - if (ret < 0 && errno == EINTR) - goto again; - - return ret; -} - -static ssize_t -_read_from (int fd, char **out_string) -{ - char buf[4096]; - ssize_t num_read; - -again: - num_read = read (fd, buf, sizeof (buf) - 1); - if (num_read == -1) { - if (errno == EINTR) - goto again; - else - goto out; - } - - if (num_read > 0) { - char *s; - - buf[num_read] = '\0'; - - s = kit_str_append (*out_string, buf); - if (s == NULL) { - errno = ENOMEM; - num_read = -1; - goto out; - } - *out_string = s; - - //kit_debug ("fd=%d read %d bytes: '%s'", fd, num_read, buf); - } - -out: - return num_read; -} - -static ssize_t -_write_to (int fd, char *str) -{ - ssize_t num_written; - -again: - num_written = write (fd, str, strlen (str)); - if (num_written == -1) { - if (errno == EINTR) - goto again; - else - goto out; - } - - //kit_debug ("Wrote %d bytes from '%s'", num_written, str); - -out: - return num_written; -} - -/** - * kit_spawn_sync: - * @working_directory: Working directory for child or #NULL to inherit parents - * @flags: A combination of flags from #KitSpawnFlags - * @argv: #NULL terminated argument vector - * @envp: #NULL terminated environment or #NULL to inherit parents; - * @stdinp: String to write to stdin of child or #NULL - * @stdoutp: Return location for stdout from child or #NULL. Free with kit_free(). - * @stderrp: Return location for stderr from child or #NULL. Free with kit_free(). - * @out_exit_status: Return location for exit status - * - * Executes a child process and waits for the child process to exit - * before returning. The exit status of the child is stored in - * @out_exit_status as it would be returned by waitpid(); standard - * UNIX macros such as WIFEXITED() and WEXITSTATUS() must be used to - * evaluate the exit status. - * - * Returns: #TRUE if the child was executed; #FALSE if an error - * occured and errno will be set. - */ -kit_bool_t -kit_spawn_sync (const char *working_directory, - KitSpawnFlags flags, - char **argv, - char **envp, - char *stdinp, - char **stdoutp, - char **stderrp, - int *out_exit_status) -{ - kit_bool_t ret; - pid_t pid; - int stdin_pipe[2] = {-1, -1}; - int stdout_pipe[2] = {-1, -1}; - int stderr_pipe[2] = {-1, -1}; - - ret = FALSE; - pid = -1; - - kit_return_val_if_fail (argv != NULL, FALSE); - kit_return_val_if_fail (out_exit_status != NULL, FALSE); - kit_return_val_if_fail (! ((flags & KIT_SPAWN_CHILD_INHERITS_STDIN) && stdinp != NULL), FALSE); - kit_return_val_if_fail (! ((flags & KIT_SPAWN_STDOUT_TO_DEV_NULL) && stdoutp != NULL), FALSE); - kit_return_val_if_fail (! ((flags & KIT_SPAWN_STDERR_TO_DEV_NULL) && stderrp != NULL), FALSE); - - if (stdoutp != NULL) - *stdoutp = NULL; - if (stderrp != NULL) - *stderrp = NULL; - - if (stdinp != NULL) { - if (pipe (stdin_pipe) != 0) { - goto out; - } - } - - if (stdoutp != NULL) { - if (pipe (stdout_pipe) != 0) { - goto out; - } - } - - if (stderrp != NULL) { - if (pipe (stderr_pipe) != 0) { - goto out; - } - } - - pid = fork (); - if (pid == -1) { - goto out; - } - - if (pid == 0) { - int fd_null = -1; - - /* child */ - - if ( (!(flags & KIT_SPAWN_CHILD_INHERITS_STDIN)) || - (flags & KIT_SPAWN_STDOUT_TO_DEV_NULL) || - (flags & KIT_SPAWN_STDERR_TO_DEV_NULL)) { - fd_null = open ("/dev/null", O_RDONLY); - if (fd_null < 0) { - exit (128 + errno); - } - } - - signal (SIGPIPE, SIG_DFL); - - /* close unused ends */ - if (stdin_pipe[1] != -1) { - close (stdin_pipe[1]); - } - if (stdout_pipe[0] != -1) { - close (stdout_pipe[0]); - } - if (stderr_pipe[0] != -1) { - close (stderr_pipe[0]); - } - - /* close all open file descriptors of child except stdin, stdout, stderr */ - _fdwalk (set_close_on_exec, (void *) 3); - - /* change working directory */ - if (working_directory != NULL) { - if (chdir (working_directory) != 0) { - exit (128 + errno); - } - } - - /* set stdinp, stdoutp and stderrp */ - - if (stdinp != NULL) { - if (_sane_dup2 (stdin_pipe[0], 0) < 0) { - exit (128 + errno); - } - } else if (! (flags & KIT_SPAWN_CHILD_INHERITS_STDIN)) { - if (_sane_dup2 (fd_null, 0) < 0) { - exit (128 + errno); - } - } - - if (stdoutp != NULL) { - if (_sane_dup2 (stdout_pipe[1], 1) < 0) { - exit (128 + errno); - } - } else if (flags & KIT_SPAWN_STDOUT_TO_DEV_NULL) { - if (_sane_dup2 (fd_null, 1) < 0) { - exit (128 + errno); - } - } - - if (stderrp != NULL) { - if (_sane_dup2 (stderr_pipe[1], 2) < 0) { - exit (128 + errno); - } - } else if (flags & KIT_SPAWN_STDERR_TO_DEV_NULL) { - if (_sane_dup2 (fd_null, 2) < 0) { - exit (128 + errno); - } - } - - if (fd_null != -1) - close (fd_null); - - /* finally, execute the child */ - if (envp != NULL) { - if (execve (argv[0], argv, envp) == -1) { - exit (128 + errno); - } - } else { - if (execv (argv[0], argv) == -1) { - exit (128 + errno); - } - } - - } else { - char *wp; - - /* parent */ - - /* closed unused ends */ - if (stdin_pipe[0] != -1) { - close (stdin_pipe[0]); - } - if (stdout_pipe[1] != -1) { - close (stdout_pipe[1]); - } - if (stderr_pipe[1] != -1) { - close (stderr_pipe[1]); - } - - wp = stdinp; - - while (stdin_pipe[1] != -1 || stdout_pipe[0] != -1 || stderr_pipe[0] != -1) { - int ret; - ssize_t num_read; - ssize_t num_written; - int max; - fd_set read_fds; - fd_set write_fds; - - FD_ZERO (&read_fds); - FD_ZERO (&write_fds); - if (stdin_pipe[1] != -1) { - FD_SET (stdin_pipe[1], &write_fds); - } - if (stdout_pipe[0] != -1) { - FD_SET (stdout_pipe[0], &read_fds); - } - if (stderr_pipe[0] != -1) { - FD_SET (stderr_pipe[0], &read_fds); - } - - max = stdin_pipe[1]; - if (stdout_pipe[0] > max) - max = stdout_pipe[0]; - if (stderr_pipe[0] > max) - max = stderr_pipe[0]; - - ret = select (max + 1, - &read_fds, - &write_fds, - NULL, - NULL); - - if (ret < 0 && errno != EINTR) { - goto out; - } - - if (stdin_pipe[1] != -1) { - num_written = _write_to (stdin_pipe[1], wp); - - if (num_written == -1) { - goto out; - } - - wp += num_written; - if (*wp == '\0') { - close (stdin_pipe[1]); - stdin_pipe[1] = -1; - } - } - - if (stdout_pipe[0] != -1) { - num_read = _read_from (stdout_pipe[0], stdoutp); - if (num_read == 0) { - close (stdout_pipe[0]); - stdout_pipe[0] = -1; - } else if (num_read == -1) { - goto out; - } - } - - if (stderr_pipe[0] != -1) { - num_read = _read_from (stderr_pipe[0], stderrp); - if (num_read == 0) { - close (stderr_pipe[0]); - stderr_pipe[0] = -1; - } else if (num_read == -1) { - goto out; - } - } - } - - if (waitpid (pid, out_exit_status, 0) == -1) { - goto out; - } - pid = -1; - } - - //kit_debug ("exit %d", WEXITSTATUS (*out_exit_status)); - - if (WEXITSTATUS (*out_exit_status) < 128) { - ret = TRUE; - } else { - ret = FALSE; - errno = WEXITSTATUS (*out_exit_status) - 128; - } - -out: - if (pid != -1) { - kill (pid, SIGKILL); - waitpid (pid, out_exit_status, 0); - } - - if (stdin_pipe[1] != -1) - close (stdin_pipe[1]); - if (stdout_pipe[0] != -1) - close (stdout_pipe[0]); - if (stderr_pipe[0] != -1) - close (stderr_pipe[0]); - - if (!ret) { - if (stdoutp != NULL) { - kit_free (*stdoutp); - *stdoutp = NULL; - } - if (stderrp != NULL) { - kit_free (*stderrp); - *stderrp = NULL; - } - } - - return ret; - -} - - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_run_test (void) -{ - char path[] = "/tmp/kit-spawn-test"; - char *script1 = - "#!/bin/sh" "\n" - "echo \"Hello World\"" "\n" - "echo \"Goodbye World\" 1>&2" "\n" - "exit 42" "\n"; - char *script2 = - "#!/bin/sh" "\n" - "exit 43" "\n"; - char *script3 = - "#!/bin/sh" "\n" - "echo -n \"$KIT_TEST_VAR\"" "\n" - "exit 0" "\n"; - char *script4 = - "#!/bin/sh" "\n" - "if [ \"x$KIT_TEST_VAR\" = \"x\" ] ; then" "\n" - " exit 0" "\n" - "fi" "\n" - "exit 1" "\n"; - char *script4b = - "#!/bin/sh" "\n" - "/bin/env > /tmp/food2" "\n" - "if [ \"x$KIT_TEST_VAR\" = \"xfoobar2\" ] ; then" "\n" - " exit 0" "\n" - "fi" "\n" - "exit 1" "\n"; - char *script5 = - "#!/bin/sh" "\n" - "pwd" "\n" - "exit 0" "\n"; - char *script6 = - "#!/bin/sh" "\n" - "read value" "\n" - "echo -n \"$value\"" "\n" - "echo -n \" \"" "\n" - "read value" "\n" - "echo -n \"$value\"" "\n" - "exit 0" "\n"; - char *argv[] = {"/tmp/kit-spawn-test", NULL}; - char *stdoutp; - char *stderrp; - int exit_status; - struct stat statbuf; - - /* script echoing to stdout and stderr */ - if (kit_file_set_contents (path, 0700, script1, strlen (script1))) { - if (kit_spawn_sync ("/", - 0, - argv, - NULL, - NULL, - &stdoutp, - &stderrp, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 42); - kit_assert (stdoutp != NULL && strcmp (stdoutp, "Hello World\n") == 0); - kit_assert (stderrp != NULL && strcmp (stderrp, "Goodbye World\n") == 0); - kit_free (stdoutp); - kit_free (stderrp); - } - - if (kit_spawn_sync ("/", - 0, - argv, - NULL, - NULL, - NULL, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 42); - } - - kit_assert (unlink (path) == 0); - } - - /* silent script */ - if (kit_file_set_contents (path, 0700, script2, strlen (script2))) { - if (kit_spawn_sync ("/", - 0, - argv, - NULL, - NULL, - &stdoutp, - &stderrp, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 43); - kit_assert (stdoutp == NULL); - kit_assert (stderrp == NULL); - } - - kit_assert (unlink (path) == 0); - } - - /* check environment is set */ - if (kit_file_set_contents (path, 0700, script3, strlen (script3))) { - char *envp[] = {"KIT_TEST_VAR=some_value", NULL}; - - if (kit_spawn_sync ("/", - 0, - argv, - envp, - NULL, - &stdoutp, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - kit_assert (stdoutp != NULL && strcmp (stdoutp, "some_value") == 0); - kit_free (stdoutp); - } - - kit_assert (unlink (path) == 0); - } - - /* check environment is replaced */ - if (kit_file_set_contents (path, 0700, script4, strlen (script4))) { - char *envp[] = {NULL}; - - kit_assert (setenv ("KIT_TEST_VAR", "foobar", 1) == 0); - - if (kit_spawn_sync ("/", - 0, - argv, - envp, - NULL, - NULL, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - } - - kit_assert (unlink (path) == 0); - kit_assert (unsetenv ("KIT_TEST_VAR") == 0); - } - - /* check environment is inherited */ - if (kit_file_set_contents (path, 0700, script4b, strlen (script4b))) { - - kit_assert (setenv ("KIT_TEST_VAR", "foobar2", 1) == 0); - - if (kit_spawn_sync ("/", - 0, - argv, - NULL, - NULL, - NULL, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - } - - kit_assert (unlink (path) == 0); - kit_assert (unsetenv ("KIT_TEST_VAR") == 0); - } - - /* check working directory */ - if (kit_file_set_contents (path, 0700, script5, strlen (script5))) { - kit_assert (stat ("/tmp", &statbuf) == 0 && S_ISDIR (statbuf.st_mode)); - if (kit_spawn_sync ("/tmp", - 0, - argv, - NULL, - NULL, - &stdoutp, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - kit_assert (stdoutp != NULL && strcmp (stdoutp, "/tmp\n") == 0); - kit_free (stdoutp); - } - - kit_assert (stat ("/usr", &statbuf) == 0 && S_ISDIR (statbuf.st_mode)); - if (kit_spawn_sync ("/usr", - 0, - argv, - NULL, - NULL, - &stdoutp, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - kit_assert (stdoutp != NULL && strcmp (stdoutp, "/usr\n") == 0); - kit_free (stdoutp); - } - - kit_assert (unlink (path) == 0); - } - - /* check bogus working directory */ - kit_assert (stat ("/org/freedesktop/PolicyKit/bogus-fs-path", &statbuf) != 0); - kit_assert (kit_spawn_sync ("/org/freedesktop/PolicyKit/bogus-fs-path", - 0, - argv, - NULL, - NULL, - NULL, - NULL, - &exit_status) == FALSE && - (errno == ENOENT || errno == ENOMEM)); - - /* check for writing to stdin */ - if (kit_file_set_contents (path, 0700, script6, strlen (script6))) { - if (kit_spawn_sync (NULL, - 0, - argv, - NULL, - "foobar0\nfoobar1", - &stdoutp, - NULL, - &exit_status)) { - kit_assert (WEXITSTATUS (exit_status) == 0); - kit_assert (stdoutp != NULL && strcmp (stdoutp, "foobar0 foobar1") == 0); - kit_free (stdoutp); - } - - kit_assert (unlink (path) == 0); - } - - return TRUE; -} - -KitTest _test_spawn = { - "kit_spawn", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-spawn.h b/src/kit/kit-spawn.h deleted file mode 100644 index 6f40dd9..0000000 --- a/src/kit/kit-spawn.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-spawn.h : Spawn utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_SPAWN_H -#define KIT_SPAWN_H - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -/** - * KitSpawnFlags: - * @KIT_SPAWN_CHILD_INHERITS_STDIN: If not set, child's stdin will be attached to <literal>/dev/null</literal> - * @KIT_SPAWN_STDOUT_TO_DEV_NULL: If set childs output will be sent to <literal>/dev/null</literal> - * @KIT_SPAWN_STDERR_TO_DEV_NULL: If set childs error output will be sent to <literal>/dev/null</literal> - * - * Flags passed to kit_spawn_sync(). - */ -typedef enum { - KIT_SPAWN_CHILD_INHERITS_STDIN = 1 << 0, - KIT_SPAWN_STDOUT_TO_DEV_NULL = 1 << 1, - KIT_SPAWN_STDERR_TO_DEV_NULL = 1 << 2, -} KitSpawnFlags; - - -kit_bool_t kit_spawn_sync (const char *working_directory, - KitSpawnFlags flags, - char **argv, - char **envp, - char *stdinp, - char **stdoutp, - char **stderrp, - int *out_exit_status); - -KIT_END_DECLS - -#endif /* KIT_SPAWN_H */ - - diff --git a/src/kit/kit-string.c b/src/kit/kit-string.c deleted file mode 100644 index 13a563d..0000000 --- a/src/kit/kit-string.c +++ /dev/null @@ -1,1204 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-string.c : String utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <errno.h> - -#include <kit/kit.h> -#include "kit-test.h" - - -/** - * SECTION:kit-string - * @title: String utilities - * @short_description: String utilities - * - * Various string utilities. - **/ - -#ifdef KIT_BUILD_TESTS - -/** - * kit_strdup: - * @s: string - * - * Duplicate a string. Similar to strdup(3). - * - * Returns: Allocated memory or #NULL on OOM. Free with kit_free(). - */ -char * -kit_strdup (const char *s) -{ - char *p; - size_t len; - - len = strlen (s); - - p = kit_malloc (len + 1); - if (p == NULL) - goto out; - - memcpy (p, s, len); - p[len] = '\0'; - -out: - return p; -} - -/** - * kit_strndup: - * @s: string - * @n: size - * - * Duplicate a string but copy at most @n characters. If @s is longer - * than @n, only @n characters are copied, and a terminating null byte - * is added. Similar to strndup(3). - * - * Returns: Allocated memory or #NULL on OOM. Free with kit_free(). - */ -char * -kit_strndup (const char *s, size_t n) -{ - char *p; - size_t len; - - for (len = 0; len < n; len++) { - if (s[len] == '\0') - break; - } - - - p = kit_malloc (len + 1); - if (p == NULL) - goto out; - - memcpy (p, s, len); - p[len] = '\0'; -out: - return p; -} - -#else - -#ifndef HAVE_STRNDUP -static char -*strndup ( const char *s, size_t n) -{ - size_t nAvail; - char *p; - - if ( !s ) - return NULL; - - if ( strlen(s) > n ) - nAvail = n + 1; - else - nAvail = strlen(s) + 1; - p = malloc ( nAvail ); - memcpy ( p, s, nAvail ); - p[nAvail - 1] = '\0'; - - return p; -} -#endif - -char * -kit_strdup (const char *s) -{ - return strdup (s); -} - -char * -kit_strndup (const char *s, size_t n) -{ - return strndup (s, n); -} - -#endif /* KIT_BUILD_TESTS */ - -#ifdef HAVE_SOLARIS -int vasprintf(char **strp, const char *fmt, va_list ap) -{ - int size; - va_list ap2; - char s; - - *strp = NULL; - va_copy(ap2, ap); - size = vsnprintf(&s, 1, fmt, ap2); - va_end(ap2); - *strp = malloc(size + 1); - if (!*strp) - return -1; - vsnprintf(*strp, size + 1, fmt, ap); - - return size; -} -#endif - -/** - * kit_strdup_printf: - * @format: sprintf(3) format string - * @...: the parameters to insert into the format string. - * - * Similar to the standard C sprintf(3) function but safer, since it - * calculates the maximum space required and allocates memory to hold - * the result. The returned string should be freed when no longer - * needed. - * - * Returns: A newly allocated string or #NULL on OOM. Free with kit_free(). - */ -char* -kit_strdup_printf (const char *format, ...) -{ - char *s; - va_list args; - - va_start (args, format); - s = kit_strdup_vprintf (format, args); - va_end (args); - - return s; -} - -/** - * kit_strdup_vprintf: - * @format: printf(3) format string - * @args: list of parameters to insert - * - * Similar to the standard C vsprintf(3) function but safer, since it - * calculates the maximum space required and allocates memory to hold - * the result. The returned string should be freed when no longer - * needed. - * - * Returns: A newly allocated string or #NULL on OOM. Free with kit_free(). - */ -char* -kit_strdup_vprintf (const char *format, va_list args) -{ - char *s; - -#ifdef KIT_BUILD_TESTS - char *p; - vasprintf (&p, format, args); - s = kit_strdup (p); - free (p); -#else - if (vasprintf (&s, format, args) == -1) { - s = NULL; - } -#endif - return s; -} - - -/** - * kit_str_has_prefix: - * @s: string to check - * @prefix: prefix to check for - * - * Determines if a string has a given prefix. - * - * Returns: #TRUE only if @s starts with @prefix - */ -kit_bool_t -kit_str_has_prefix (const char *s, const char *prefix) -{ - size_t s_len; - size_t prefix_len; - - kit_return_val_if_fail (s != NULL, FALSE); - kit_return_val_if_fail (prefix != NULL, FALSE); - - s_len = strlen (s); - prefix_len = strlen (prefix); - if (prefix_len > s_len) - return FALSE; - - return strncmp (s, prefix, prefix_len) == 0; -} - -/** - * kit_str_has_suffix: - * @s: string to check - * @suffix: suffix to check for - * - * Determines if a string has a given suffix. - * - * Returns: #TRUE only if @s ends with @suffix - */ -kit_bool_t -kit_str_has_suffix (const char *s, const char *suffix) -{ - size_t s_len; - size_t suffix_len; - - kit_return_val_if_fail (s != NULL, FALSE); - kit_return_val_if_fail (suffix != NULL, FALSE); - - s_len = strlen (s); - suffix_len = strlen (suffix); - if (suffix_len > s_len) - return FALSE; - - return strncmp (s + s_len - suffix_len, suffix, suffix_len) == 0; -} - -/** - * kit_strsplit: - * @s: string to split - * @delim: delimiter used for splitting - * @num_tokens: return location for number of elements or #NULL - * - * Split a given string into components given a delimiter. - * - * Returns: A #NULL terminated array of strings. Free with kit_strfreev(). Returns #NULL on OOM. - */ -char ** -kit_strsplit (const char *s, char delim, size_t *num_tokens) -{ - int n; - int m; - int num; - char **result; - - kit_return_val_if_fail (s != NULL, NULL); - - result = NULL; - - num = 0; - for (n = 0; s[n] != '\0'; n++) { - if (s[n] == delim) { - num++; - } - } - num++; - - result = kit_new0 (char*, num + 1); - if (result == NULL) - goto oom; - - m = 0; - for (n = 0; n < num; n++) { - int begin; - - begin = m; - - while (s[m] != delim && s[m] != '\0') { - m++; - } - - result[n] = kit_strndup (s + begin, m - begin); - if (result[n] == NULL) - goto oom; - - m++; - } - result[n] = NULL; - - if (num_tokens != NULL) - *num_tokens = num; - - return result; -oom: - kit_strfreev (result); - return NULL; -} - -/** - * kit_strfreev: - * @str_array: string array - * - * Free a #NULL terminated string array. - */ -void -kit_strfreev (char **str_array) -{ - int n; - - if (str_array == NULL) - return; - - for (n = 0; str_array[n] != NULL; n++) - kit_free (str_array[n]); - - kit_free (str_array); -} - -/** - * kit_strv_length: - * @str_array: string array - * - * Compute number of elements in a #NULL terminated string array. - * - * Returns: Number of elements not including the terminating #NULL - */ -size_t -kit_strv_length (char **str_array) -{ - int n; - - kit_return_val_if_fail (str_array != NULL, 0); - - for (n = 0; str_array[n] != NULL; n++) - ; - - return n; -} - -/** - * kit_str_append: - * @s: either %NULL or a string previously allocated on the heap - * @s2: string to append - * - * Append a string to an existing string. - * - * Returns: %NULL on OOM or the new string; possibly at the same - * location as @s. - */ -char * -kit_str_append (char *s, const char *s2) -{ - char *p; - size_t s_len; - size_t s2_len; - - kit_return_val_if_fail (s2 != NULL, NULL); - - if (s != NULL) - s_len = strlen (s); - else - s_len = 0; - s2_len = strlen (s2); - p = (char *) kit_realloc ((void *) s, s_len + s2_len + 1); - if (p == NULL) - goto oom; - s = p; - memcpy ((void *) (s + s_len), s2, s2_len); - s[s_len + s2_len] = '\0'; - - return s; -oom: - return NULL; -} - -static kit_bool_t -_is_reserved (char c) -{ - unsigned int n; - char reserved[] = " !*'();:@&=+$,/?%#[]\n\r\t"; - - for (n = 0; n < sizeof (reserved); n++) { - if (reserved[n] == c) - return TRUE; - } - - return FALSE; -} - -static char -_to_hex (unsigned int nibble) -{ - if (nibble < 10) - return nibble + '0'; - else - return nibble - 10 + 'A'; -} - -/** - * kit_string_percent_encode: - * @buf: return location for output - * @buf_size: size of buffer - * @s: string to encode - * - * Percent encodes a string; each occurence of an ASCII characters in - * the set <literal>" !*'();:@&=+$,/?%#[]\n\r\t"</literal> will be - * replaced by a three character sequence started by the percent sign - * "%" and then the hexidecimal representation of the ASCII character - * in question. - * - * Returns: This function do not write more than @buf_size bytes - * (including the trailing zero). If the output was truncated due to - * this limit then the return value is the number of characters (not - * including the trailing zero) which would have been written to the - * final string if enough space had been available. Thus, a return - * value of @buf_size or more means that the output was truncated. - */ -size_t -kit_string_percent_encode (char *buf, size_t buf_size, const char *s) -{ - size_t len; - unsigned int n; - unsigned int m; - - kit_return_val_if_fail (buf != NULL, 0); - kit_return_val_if_fail (s != NULL, 0); - - len = strlen (s); - - for (n = 0, m = 0; n < len; n++) { - int c = s[n]; - - if (_is_reserved (c)) { - if (m < buf_size) - buf[m] = '%'; - m++; - if (m < buf_size) - buf[m] = _to_hex (c >> 4); - m++; - if (m < buf_size) - buf[m] = _to_hex (c & 0x0f); - m++; - } else { - if (m < buf_size) - buf[m] = c; - m++; - } - } - if (m < buf_size) - buf[m] = '\0'; - - return m; -} - -/** - * kit_string_percent_decode: - * @s: string to modify in place - * - * Percent-decodes a string in place. See kit_string_percent_encode() - * for details on the encoding format. - * - * Returns: %FALSE if string is not properly encoded (and errno will be set to EINVAL) - */ -kit_bool_t -kit_string_percent_decode (char *s) -{ - kit_bool_t ret; - unsigned int n; - unsigned int m; - size_t len; - - kit_return_val_if_fail (s != NULL, FALSE); - - ret = FALSE; - - len = strlen (s); - - for (n = 0, m = 0; n < len; n++) { - int c = s[n]; - - if (c != '%') { - if (_is_reserved (c)) { - errno = EINVAL; - goto out; - } - s[m++] = s[n]; - } else { - int nibble1; - int nibble2; - - if (n + 2 >= len) { - errno = EINVAL; - goto out; - } - - nibble1 = s[n + 1]; - nibble2 = s[n + 2]; - n += 2; - - if (nibble1 >= '0' && nibble1 <= '9') { - nibble1 -= '0'; - } else if (nibble1 >= 'A' && nibble1 <= 'F') { - nibble1 -= 'A' - 10; - } else { - errno = EINVAL; - goto out; - } - - if (nibble2 >= '0' && nibble2 <= '9') { - nibble2 -= '0'; - } else if (nibble2 >= 'A' && nibble2 <= 'F') { - nibble2 -= 'A' - 10; - } else { - errno = EINVAL; - goto out; - } - - s[m++] = (nibble1 << 4) | nibble2; - } - } - s[m] = '\0'; - - ret = TRUE; -out: - return ret; -} - - -/** - * kit_string_entry_parse: - * @entry: line to parse - * @func: callback function - * @user_data: user data to pass to @func - * - * Parse a line of the form - * <literal>key1=val1:key2=val2:key3=val3</literal>. - * - * The given @entry is said not to be wellformed if a) it doesn't - * follow this structure (for example - * <literal>key1=val1:key2:key3=val3</literal> is not well-formed - * because it's missing the '=' character) or the extracted key and - * value strings are not properly percent encoded. - * - * Both the key and value values are run through the - * kit_string_percent_decode() function prior to being passed to - * @func. Normally this function is used to decode strings produced - * with kit_string_entry_create(). - * - * Returns: %TRUE if the line is wellformed and the callback didn't - * short-circuit the iteration. Returns %FALSE on OOM (and errno will - * be set to ENOMEM) or if @entry is not wellformed (and errno will - * be set to EINVAL). - */ -kit_bool_t -kit_string_entry_parse (const char *entry, KitStringEntryParseFunc func, void *user_data) -{ - unsigned int n; - kit_bool_t ret; - char **tokens; - size_t num_tokens; - - kit_return_val_if_fail (entry != NULL, FALSE); - kit_return_val_if_fail (func != NULL, FALSE); - - ret = FALSE; - tokens = NULL; - - tokens = kit_strsplit (entry, ':', &num_tokens); - if (tokens == NULL) { - errno = ENOMEM; - goto out; - } - - for (n = 0; n < num_tokens; n++) { - char *token; - char *p; - - token = tokens[n]; - - p = strchr (token, '='); - if (p == NULL) { - errno = EINVAL; - goto out; - } - - token [p - token] = '\0'; - - p++; - - if (!kit_string_percent_decode (token)) - goto out; - - if (!kit_string_percent_decode (p)) - goto out; - - if (!func (token, p, user_data)) { - goto out; - } - } - - ret = TRUE; - -out: - if (tokens != NULL) - kit_strfreev (tokens); - return ret; -} - -/** - * kit_string_entry_createv: - * @buf: return location for output - * @buf_size: size of buffer - * @kv_pairs: %NULL terminated array of key/value pairs. - * - * Takes an array of key/value pairs and generates a string - * <literal>"k1=v1:k2=v2:...:k_n=v_n"</literal> where - * <literal>k_i</literal> and <literal>v_i</literal> are percent - * encoded representations of the given key/value pairs. - * - * The string can later be parsed with kit_string_entry_parse() to get - * the exact same list of key/value pairs back. - * - * Returns: This function do not write more than @buf_size bytes - * (including the trailing zero). If the output was truncated due to - * this limit then the return value is the number of characters (not - * including the trailing zero) which would have been written to the - * final string if enough space had been available. Thus, a return - * value of @buf_size or more means that the output was truncated. - * - * If an uneven number of strings are given, this function will return - * zero and errno will be set to EINVAL. - */ -size_t -kit_string_entry_createv (char *buf, size_t buf_size, const char *kv_pairs[]) -{ - int n; - unsigned int m; - - for (n = 0, m = 0; kv_pairs[n] != NULL; n+= 2) { - const char *key; - const char *value; - - if (kv_pairs[n + 1] == NULL) { - m = 0; - errno = EINVAL; - goto out; - } - - key = kv_pairs[n]; - value = kv_pairs[n + 1]; - - if (n > 0) { - if (m < buf_size) - buf[m] = ':'; - m++; - } - - m += kit_string_percent_encode (buf + m, buf_size - m > 0 ? buf_size - m : 0, key); - - if (m < buf_size) - buf[m] = '='; - m++; - - m += kit_string_percent_encode (buf + m, buf_size - m > 0 ? buf_size - m : 0, value); - } - -out: - if (m < buf_size) - buf[m] = '\0'; - - return m; -} - -/** - * kit_string_entry_create: - * @buf: return location for output - * @buf_size: size of buffer - * @...: %NULL terminated array of key/value pairs. - * - * See kit_string_entry_create(). - * - * Returns: See kit_string_entry_create(). Up to 64 pairs can be - * passed; if there are more pairs, this function will return zero and - * errno will be set to EOVERFLOW. - */ -size_t -kit_string_entry_create (char *buf, size_t buf_size, ...) -{ - int n; - va_list args; - const char *val; - const char *kv_pairs[64 * 2 + 1]; - size_t ret; - - /* TODO: get rid of the 64 limit... */ - - ret = 0; - - n = 0; - va_start (args, buf_size); - while ((val = va_arg (args, const char *)) != NULL) { - if (n == 64 * 2) { - errno = EOVERFLOW; - goto out; - } - kv_pairs[n++] = val; - } - va_end (args); - kv_pairs[n] = NULL; - - ret = kit_string_entry_createv (buf, buf_size, kv_pairs); -out: - return ret; -} - -/** - * KitString: - * - * String buffer that grows automatically as text is added. - */ -struct _KitString { - char *buf; - size_t cur_len; - size_t buf_len; -}; - -/** - * kit_string_free: - * @s: the #KitString object - * @free_segment: whether to free the string data itself - * @out_segment_size: return location for size of string or %NULL - * - * Free resources used by a #KitString object - * - * Returns: If @free_segment is %TRUE, returns the segment (will - * always be zero terminated), must be freed with kit_free(), - * otherwise %NULL - */ -char * -kit_string_free (KitString *s, kit_bool_t free_segment, size_t *out_segment_size) -{ - char *ret; - - kit_return_val_if_fail (s != NULL, NULL); - - if (out_segment_size != NULL) { - *out_segment_size = s->cur_len; - } - - if (free_segment) { - kit_free (s->buf); - ret = NULL; - } else { - ret = s->buf; - } - kit_free (s); - - return ret; -} - -#define KIT_STRING_BLOCK_SIZE 256 - -/** - * kit_string_new: - * @init: String to initialize with or %NULL - * @len: Initial size of buffer; pass zero to use the default size - * - * Initialize a new #KitString object. - * - * Returns: The new object or %NULL on OOM - */ -KitString * -kit_string_new (const char *init, size_t len) -{ - KitString *s; - - s = kit_new0 (KitString, 1); - if (s == NULL) - goto oom; - - if (len == 0) - len = KIT_STRING_BLOCK_SIZE; - s->buf_len = len; - - if (init == NULL) { - s->buf = kit_new0 (char, s->buf_len); - if (s->buf == NULL) - goto oom; - s->cur_len = 0; - } else { - size_t init_len; - - init_len = strlen (init); - if (init_len + 1 > s->buf_len) - s->buf_len = init_len + 1; - s->buf = kit_new0 (char, s->buf_len); - if (s->buf == NULL) - goto oom; - strncpy (s->buf, init, init_len); - s->cur_len = init_len; - } - - return s; -oom: - if (s != NULL) - kit_string_free (s, TRUE, NULL); - return NULL; -} - -/** - * kit_string_ensure_size: - * @s: String object - * @new_size: The size to check for. - * - * Ensure that the given #KitString object can hold at least @new_size - * characters. - * - * Returns: %TRUE if the given #KitString object can hold at least - * @new_size characters. %FALSE if OOM. - */ -kit_bool_t -kit_string_ensure_size (KitString *s, size_t new_size) -{ - kit_return_val_if_fail (s != NULL, FALSE); - - if (new_size > s->buf_len - 1) { - char *p; - size_t grow_to; - - grow_to = ((new_size / KIT_STRING_BLOCK_SIZE) + 1) * KIT_STRING_BLOCK_SIZE; - - p = kit_realloc (s->buf, grow_to); - if (p == NULL) - goto oom; - /* zero the new block we got */ - s->buf = p; - memset (s->buf + s->buf_len, 0, grow_to - s->buf_len); - s->buf_len = grow_to; - } - - return TRUE; -oom: - return FALSE; -} - -/** - * kit_string_append_c: - * @s: the #KitString object - * @c: character to append - * - * Append a character to a #KitString object. - * - * Returns: %TRUE unless OOM - */ -kit_bool_t -kit_string_append_c (KitString *s, char c) -{ - kit_return_val_if_fail (s != NULL, FALSE); - - if (!kit_string_ensure_size (s, s->cur_len + 1)) - goto oom; - - s->buf[s->cur_len] = c; - s->cur_len += 1; - return TRUE; -oom: - return FALSE; -} - -/** - * kit_string_append: - * @s: the #KitString object - * @str: string to append - * - * Append a string to a #KitString object. - * - * Returns: %TRUE unless OOM - */ -kit_bool_t -kit_string_append (KitString *s, const char *str) -{ - size_t str_len; - - kit_return_val_if_fail (s != NULL, FALSE); - - str_len = strlen (str); - - if (!kit_string_ensure_size (s, s->cur_len + str_len)) - goto oom; - - strncpy (s->buf + s->cur_len, str, str_len); - s->cur_len += str_len; - return TRUE; -oom: - return FALSE; -} - - -#ifdef KIT_BUILD_TESTS - -static kit_bool_t -_ep1 (const char *key, const char *value, void *user_data) -{ - int *n = (int *) user_data; - - if (strcmp (key, "a") == 0 && strcmp (value, "aval") == 0) - *n += 1; - if (strcmp (key, "a") == 0 && strcmp (value, "aval2") == 0) - *n += 1; - if (strcmp (key, "b") == 0 && strcmp (value, "bval") == 0) - *n += 1; - if (strcmp (key, "c") == 0 && strcmp (value, "cval") == 0) - *n += 1; - if (strcmp (key, "some_other_key") == 0 && strcmp (value, "some_value") == 0) - *n += 1; - if (strcmp (key, "escaped;here:right=") == 0 && strcmp (value, "yes! it's ==:crazy!") == 0) - *n += 1; - - return TRUE; -} - -static kit_bool_t -_ep2 (const char *key, const char *value, void *user_data) -{ - int *n = (int *) user_data; - - if (strcmp (key, "b") == 0) - return FALSE; - - *n += 1; - - return TRUE; -} - -static kit_bool_t -_run_test (void) -{ - int num; - char str[] = "Hello world"; - char *p; - char *p2; - char **tokens; - size_t num_tokens; - unsigned int n; - char *bad_strings[] = {"bad:", - "bad=", - "bad%", - "bad%1", - "bad%xy", - "bad%1x", - "bad%Ax", - "bad%2a"}; - char buf[256]; - KitString *s; - - if ((s = kit_string_new (NULL, 3)) != NULL) { - for (n = 0; n < 8; n++) { - if (!kit_string_append_c (s, 'd')) - break; - } - p = kit_string_free (s, FALSE, NULL); - if (n == 8) { - kit_assert (strcmp ("dddddddd", p) == 0); - } - kit_free (p); - } - - /* KitString always makes place for the terminating zero, hence allocate one more byte */ - if ((s = kit_string_new (NULL, 101)) != NULL) { - size_t segment_size; - for (n = 0; n < 100; n++) { - kit_assert (kit_string_append_c (s, n)); - } - p = kit_string_free (s, FALSE, &segment_size); - kit_assert (segment_size == 100); - for (n = 0; n < 100; n++) { - kit_assert (p[n] == (char) n); - } - kit_assert (p[100] == 0); - kit_free (p); - } - - if ((s = kit_string_new (NULL, 0)) != NULL) { - for (n = 0; n < 100; n++) { - if (!kit_string_append (s, "foobar")) - break; - } - p = kit_string_free (s, FALSE, NULL); - if (n == 100) { - kit_assert (strlen (p) == 600); - for (n = 0; n < 100; n++) { - kit_assert (strncmp ("foobar", p + n * 6, 6) == 0); - } - } - kit_free (p); - } - - if ((s = kit_string_new ("fooobar", 3)) != NULL) { - p = kit_string_free (s, FALSE, NULL); - kit_assert (strcmp ("fooobar", p) == 0); - kit_free (p); - } - - if ((s = kit_string_new ("fooobar2", 100)) != NULL) { - p = kit_string_free (s, FALSE, NULL); - kit_assert (strcmp ("fooobar2", p) == 0); - kit_free (p); - } - - - kit_assert (kit_string_percent_encode (buf, sizeof (buf), "Hello World; Nice day!") < sizeof (buf)); - kit_assert (strcmp (buf, "Hello%20World%3B%20Nice%20day%21") == 0); - kit_assert (kit_string_percent_decode (buf)); - kit_assert (strcmp (buf, "Hello World; Nice day!") == 0); - - for (n = 0; n < sizeof (bad_strings) / sizeof (char *); n++) { - if ((p = kit_strdup (bad_strings[n])) != NULL) { - kit_assert (!kit_string_percent_decode (p) && errno == EINVAL); - kit_free (p); - } - } - - kit_assert (kit_string_entry_create (buf, sizeof (buf), - "key1", "val1", - "key2", "val2", - "key3", "val3", - NULL) < sizeof (buf) && - strcmp (buf, "key1=val1:key2=val2:key3=val3") == 0); - - kit_assert (kit_string_entry_create (buf, sizeof (buf), - "key1;", "val1=val1x", - "key2%", "val2!", - NULL) < sizeof (buf) && - strcmp (buf, "key1%3B=val1%3Dval1x:key2%25=val2%21") == 0); - - kit_assert (kit_string_entry_create (buf, sizeof (buf), - "key1", "val1", - "key2", NULL) == 0 && errno == EINVAL); - - kit_assert (kit_string_entry_create (buf, 3, - "key1", "val1", - "key2", "val2", NULL) > 3); - - kit_assert (kit_string_entry_create (buf, sizeof (buf), - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a", - "b", "c", NULL) == 0 && errno == EOVERFLOW); - - kit_assert (!kit_string_entry_parse ("key=val:invalidkeyval:key2=val2", _ep1, &num) && - (errno == EINVAL || errno == ENOMEM)); - kit_assert (!kit_string_entry_parse ("key;=val:key2=val2", _ep1, &num) && - (errno == EINVAL || errno == ENOMEM)); - kit_assert (!kit_string_entry_parse ("key=val:key2=val2;", _ep1, &num) && - (errno == EINVAL || errno == ENOMEM)); - - kit_assert (kit_string_entry_create (buf, sizeof (buf), - "a", "aval", - "a", "aval2", - "b", "bval", - "c", "cval", - "some_other_key", "some_value", - "escaped;here:right=", "yes! it's ==:crazy!", - NULL) < sizeof (buf)); - num = 0; - if (kit_string_entry_parse (buf, _ep1, &num)) { - kit_assert (num == 6); - } else { - kit_assert (errno == ENOMEM); - } - - num = 0; - errno = 0; - kit_assert (!kit_string_entry_parse ("a=0:b=1:c=2", _ep2, &num)); - if (num > 0) - kit_assert (errno == 0); - else - kit_assert (errno == ENOMEM); - - - if ((p = kit_strdup (str)) != NULL) { - kit_assert (strcmp (p, "Hello world") == 0); - kit_free (p); - } - - if ((p = kit_strndup (str, 5)) != NULL) { - kit_assert (strcmp (p, "Hello") == 0); - kit_free (p); - } - - if ((p = kit_strndup (str, 100)) != NULL) { - kit_assert (strcmp (p, "Hello world") == 0); - kit_free (p); - } - - if ((p = kit_strdup_printf ("Hello %d", 5)) != NULL) { - kit_assert (strcmp (p, "Hello 5") == 0); - kit_free (p); - } - - kit_assert ( kit_str_has_suffix ("12345", "45")); - kit_assert ( kit_str_has_suffix ("12345", "12345")); - kit_assert (!kit_str_has_suffix ("12345", "123456")); - - kit_assert ( kit_str_has_prefix ("12345", "12")); - kit_assert ( kit_str_has_prefix ("12345", "12345")); - kit_assert (!kit_str_has_prefix ("12345", "123456")); - - if ((tokens = kit_strsplit ("abc:012:xyz", ':', &num_tokens)) != NULL) { - kit_assert (num_tokens == 3); - kit_assert (kit_strv_length (tokens) == 3); - kit_assert (strcmp (tokens[0], "abc") == 0); - kit_assert (strcmp (tokens[1], "012") == 0); - kit_assert (strcmp (tokens[2], "xyz") == 0); - kit_strfreev (tokens); - } - - if ((tokens = kit_strsplit ("abc012xyz", ':', &num_tokens)) != NULL) { - kit_assert (num_tokens == 1); - kit_assert (kit_strv_length (tokens) == 1); - kit_assert (strcmp (tokens[0], "abc012xyz") == 0); - kit_strfreev (tokens); - } - - if ((tokens = kit_strsplit ("", ':', &num_tokens)) != NULL) { - kit_assert (num_tokens == 1); - kit_assert (kit_strv_length (tokens) == 1); - kit_assert (strcmp (tokens[0], "") == 0); - kit_strfreev (tokens); - } - - if ((p = kit_strdup ("foobar")) != NULL) { - if ((p2 = kit_str_append (p, "_cool")) != NULL) { - p = p2; - - kit_assert (strcmp (p, "foobar_cool") == 0); - } - - kit_free (p); - } - - if ((p = kit_str_append (NULL, "baz")) != NULL) { - kit_assert (strcmp (p, "baz") == 0); - kit_free (p); - } - - return TRUE; -} - -KitTest _test_string = { - "kit_string", - NULL, - NULL, - _run_test -}; - -#endif /* KIT_BUILD_TESTS */ diff --git a/src/kit/kit-string.h b/src/kit/kit-string.h deleted file mode 100644 index 3f58e21..0000000 --- a/src/kit/kit-string.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-string.h : String utilities - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_STRING_H -#define KIT_STRING_H - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -char *kit_strdup (const char *s); -char *kit_strndup (const char *s, size_t n); -#ifdef __sun -char *kit_strdup_printf (const char *format, ...); -#else -char *kit_strdup_printf (const char *format, ...) __attribute__((__format__ (__printf__, 1, 2))); -#endif -char *kit_strdup_vprintf (const char *format, va_list args); -char *kit_str_append (char *s, const char *s2); - -kit_bool_t kit_str_has_prefix (const char *s, const char *prefix); -kit_bool_t kit_str_has_suffix (const char *s, const char *suffix); - -char **kit_strsplit (const char *s, char delim, size_t *num_tokens); - -void kit_strfreev (char **str_array); -size_t kit_strv_length (char **str_array); - -/** - * KitStringEntryParseFunc: - * @key: key of one of the entries - * @value: value of one of the entries - * @user_data: user data passed to kit_string_entry_parse() - * - * Type of callback function to use in kit_string_entry_parse() - * - * Returns: If %FALSE is returned the parsing will be aborted and - * kit_string_entry_parse() will return FALSE. - */ -typedef kit_bool_t (*KitStringEntryParseFunc) (const char *key, const char *value, void *user_data); - -kit_bool_t kit_string_entry_parse (const char *entry, KitStringEntryParseFunc func, void *user_data); - -kit_bool_t kit_string_percent_decode (char *s); -size_t kit_string_percent_encode (char *buf, size_t buf_size, const char *s); - -size_t kit_string_entry_create (char *buf, size_t buf_size, ...); -size_t kit_string_entry_createv (char *buf, size_t buf_size, const char *kv_pairs[]); - - -struct _KitString; -typedef struct _KitString KitString; - -KitString *kit_string_new (const char *init, size_t len); -char *kit_string_free (KitString *s, kit_bool_t free_segment, size_t *out_segment_size); -kit_bool_t kit_string_ensure_size (KitString *s, size_t new_size); -kit_bool_t kit_string_append_c (KitString *s, char c); -kit_bool_t kit_string_append (KitString *s, const char *str); - -KIT_END_DECLS - -#endif /* KIT_STRING_H */ - - diff --git a/src/kit/kit-test-main.c b/src/kit/kit-test-main.c deleted file mode 100644 index ccdcf79..0000000 --- a/src/kit/kit-test-main.c +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-test-main.c : Run test suites for libkit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#include <stdio.h> -#include <stdlib.h> -#include <kit/kit-test.h> - -static KitTest *tests[] = { - &_test_message, - &_test_memory, - &_test_string, - &_test_list, - &_test_hash, - &_test_file, - &_test_spawn, - &_test_entity, -}; - -int -main (int argc, char *argv[]) -{ - if (kit_test_run (tests, sizeof (tests) / sizeof (KitTest*))) - return 0; - else - return 1; -} diff --git a/src/kit/kit-test.c b/src/kit/kit-test.c deleted file mode 100644 index 3f8718f..0000000 --- a/src/kit/kit-test.c +++ /dev/null @@ -1,142 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-test.c : PolicyKit test - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#ifdef HAVE_SOLARIS -#include <sys/types.h> -#endif -#include <kit/kit-test.h> -#include <kit/kit-memory.h> - -/** - * SECTION:kit-test - * @title: Unit testing - * @short_description: Unit testing - * - * Functions used for unit testing. - */ - -/** - * kit_test_run: - * @tests: array of #KitTest objects - * @num_tests: size of @tests array - * - * Runs a number of tests simulating Out Of Memory. Checks for both - * memory and file descriptor leaks. - * - * This function is only available if libkit have been built with - * KIT_BUILD_TESTS. - * - * Returns: %TRUE only if all tests succeed without memory or file descriptor leaks - */ -kit_bool_t -kit_test_run (KitTest **tests, size_t num_tests) -{ - kit_bool_t ret; - unsigned int n; - - /* be optimistic! */ - ret = TRUE; - - printf ("Running %d unit tests\n", num_tests); - for (n = 0; n < num_tests; n++) { - int m; - int total_allocs; - int delta; - int num_fd; - int num_fd_after; - KitTest *test = tests[n]; - - _kit_memory_reset (); - - if (test->setup != NULL) - test->setup (); - - num_fd = _kit_get_num_fd (); - printf ("Running: %s\n", test->name); - if (!test->run ()) { - printf ("Failed\n"); - ret = FALSE; - goto test_done; - } - num_fd_after = _kit_get_num_fd (); - - total_allocs = _kit_memory_get_total_allocations (); - printf (" Unit test made %d allocations in total\n", total_allocs); - - delta = _kit_memory_get_current_allocations (); - if (delta != 0) { - printf (" Unit test leaked %d allocations\n", delta); - _kit_memory_print_outstanding_allocations (); - ret = FALSE; - } - if (num_fd != num_fd_after) { - printf (" Unit test leaked %d file descriptors\n", num_fd_after - num_fd); - ret = FALSE; - } - - for (m = 0; m < total_allocs; m++) { - printf (" Failing allocation %d of %d\n", m + 1, total_allocs); - - _kit_memory_reset (); - _kit_memory_fail_nth_alloc (m); - - num_fd = _kit_get_num_fd (); - if (!test->run ()) { - printf (" Failed\n"); - ret = FALSE; - continue; - } - num_fd_after = _kit_get_num_fd (); - - delta = _kit_memory_get_current_allocations (); - if (delta != 0) { - printf (" Unit test leaked %d allocations:\n", delta); - _kit_memory_print_outstanding_allocations (); - ret = FALSE; - } - if (num_fd != num_fd_after) { - printf (" Unit test leaked %d file descriptors\n", num_fd_after - num_fd); - ret = FALSE; - } - - } - - test_done: - if (test->teardown != NULL) - test->teardown (); - } - - return ret; -} diff --git a/src/kit/kit-test.h b/src/kit/kit-test.h deleted file mode 100644 index a3869c4..0000000 --- a/src/kit/kit-test.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit-test.h : PolicyKit test - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (KIT_COMPILATION) && !defined(_KIT_INSIDE_KIT_H) -#error "Only <kit/kit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef KIT_TEST_H -#define KIT_TEST_H - -#include <kit/kit.h> - -KIT_BEGIN_DECLS - -/** - * KitTest: - * @name: name of the unit test - * @setup: setup function - * @teardown: teardown function - * @run: actual test function. - * - * Test suite abstraction. See kit_test_run() for details. - */ -typedef struct { - const char *name; - void (*setup) (void); - void (*teardown) (void); - kit_bool_t (*run) (void); -} KitTest; - -kit_bool_t kit_test_run (KitTest **tests, size_t num_tests); - -extern KitTest _test_memory; -extern KitTest _test_string; -extern KitTest _test_hash; -extern KitTest _test_list; -extern KitTest _test_file; -extern KitTest _test_spawn; -extern KitTest _test_message; -extern KitTest _test_entity; - -KIT_END_DECLS - -#endif /* KIT_TEST_H */ - - diff --git a/src/kit/kit.h b/src/kit/kit.h deleted file mode 100644 index 1457acf..0000000 --- a/src/kit/kit.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * kit.h : OOM-safe utility library - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifndef KIT_H -#define KIT_H - -/** - * SECTION:kit - * @title: Macros - * @short_description: Macros - * - * Various low-level macros. - **/ - -#ifdef __cplusplus -# define KIT_BEGIN_DECLS extern "C" { -# define KIT_END_DECLS } -#else -/** - * KIT_BEGIN_DECLS: - * - * C++ include header guard. - */ -# define KIT_BEGIN_DECLS -/** - * KIT_END_DECLS: - * - * C++ include header guard. - */ -# define KIT_END_DECLS -#endif - -/** - * kit_bool_t: - * - * A boolean, valid values are #TRUE and #FALSE. - */ -typedef int kit_bool_t; - -#ifndef TRUE -# define TRUE 1 -#endif -#ifndef FALSE -# define FALSE 0 -#endif - -void kit_print_backtrace (void); - -#ifdef HAVE_SOLARIS -#define __PRETTY_FUNCTION__ __func__ -#endif -/** - * kit_assert: - * @expr: expression - * - * Debugging macro to terminate the application if the assertion - * fails. If the assertion fails (i.e. the expression is not true), an - * error message is logged and the application is terminated. - */ -#define kit_assert(expr) \ -do { \ - if (expr) { \ - ; \ - } else { \ - kit_warning ("%s:%d:%s(): %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, #expr); \ - kit_print_backtrace (); \ - exit (1); \ - } \ -} while (0) - -/** - * kit_return_if_fail: - * @expr: expression - * - * Returns from the current function if the expression is not true. If - * the expression evaluates to #FALSE, an error message is logged and - * the function returns. This can only be used in functions which do - * not return a value. - * - * Returns: nothing - */ -#define kit_return_if_fail(expr) \ -do { \ - if (expr) { \ - ; \ - } else { \ - kit_warning ("%s:%d:%s(): %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, #expr); \ - kit_print_backtrace (); \ - return; \ - } \ -} while (0) - -/** - * kit_return_val_if_fail: - * @expr: expression - * @val: the value to return if the expression evaluates does not - * evaluate to #TRUE - * - * Returns from the current function, returning the value @val, if the - * expression is not true. If the expression evaluates to #FALSE, an - * error message is logged and val is returned. - * - * Returns: nothing - */ -#define kit_return_val_if_fail(expr,val) \ -do { \ - if (expr) { \ - ; \ - } else { \ - kit_warning ("%s:%d:%s(): %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, #expr); \ - kit_print_backtrace (); \ - return val; \ - } \ -} while (0) - - - -#define _KIT_INSIDE_KIT_H 1 - -#ifdef HAVE_SOLARIS -#include <sys/types.h> -#endif -#include <kit/kit-memory.h> -#include <kit/kit-string.h> -#include <kit/kit-lib.h> -#include <kit/kit-list.h> -#include <kit/kit-hash.h> -#include <kit/kit-file.h> -#include <kit/kit-spawn.h> -#include <kit/kit-message.h> -#include <kit/kit-test.h> -#include <kit/kit-entity.h> - -#undef _KIT_INSIDE_KIT_H - -#endif /* KIT_H */ - - diff --git a/src/polkit-grant/Makefile.am b/src/polkit-grant/Makefile.am deleted file mode 100644 index 87c821b..0000000 --- a/src/polkit-grant/Makefile.am +++ /dev/null @@ -1,183 +0,0 @@ -## Process this file with automake to produce Makefile.in - -INCLUDES = \ - -I$(top_builddir)/src -I$(top_srcdir)/src \ - -DPACKAGE_LIBEXEC_DIR=\""$(libexecdir)"\" \ - -DPACKAGE_SYSCONF_DIR=\""$(sysconfdir)"\" \ - -DPACKAGE_DATA_DIR=\""$(datadir)"\" \ - -DPACKAGE_BIN_DIR=\""$(bindir)"\" \ - -DPACKAGE_LOCALSTATE_DIR=\""$(localstatedir)"\" \ - -DPACKAGE_LOCALE_DIR=\""$(localedir)"\" \ - -DPACKAGE_LIB_DIR=\""$(libdir)"\" \ - -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT \ - -DPOLKIT_COMPILATION \ - @GLIB_CFLAGS@ @DBUS_CFLAGS@ - -lib_LTLIBRARIES=libpolkit-grant-1.la - -libpolkit_grant_1includedir=$(includedir)/polkit-1/polkit-grant - -libpolkit_grant_1include_HEADERS = \ - polkit-grant.h - -libpolkit_grant_1_la_SOURCES = \ - polkit-grant.h polkit-grant.c - - -if POLKIT_AUTHDB_DUMMY -libpolkit_grant_1_la_SOURCES += polkit-authorization-db-dummy-write.c -endif - -if POLKIT_AUTHDB_DEFAULT -libpolkit_grant_1_la_SOURCES += polkit-authorization-db-write.c -endif - -libpolkit_grant_1_la_LIBADD = @GLIB_LIBS@ @DBUS_LIBS@ $(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la - - -if POLKIT_BUILD_TESTS -libpolkit_grant_1_la_LDFLAGS = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) @R_DYNAMIC_LDFLAG@ -else -libpolkit_grant_1_la_LDFLAGS = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) @R_DYNAMIC_LDFLAG@ \ - -export-dynamic -no-undefined -export-symbols-regex '(^polkit_.*|_polkit_authorization_db_auth_file_add)' -endif - - -# Only if the authdb backend has the capability POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN -# then the backend must supply the /usr/libexec/polkit-grant-helper program.. also remember to -# adjust the PAM stuff in data/Makefile.am -# -if POLKIT_AUTHDB_DEFAULT -libexec_PROGRAMS = polkit-grant-helper-1 - -if POLKIT_AUTHFW_PAM -libexec_PROGRAMS += polkit-grant-helper-pam-1 -endif - -if POLKIT_AUTHFW_SHADOW -libexec_PROGRAMS += polkit-grant-helper-shadow-1 -endif - -libexec_PROGRAMS += polkit-explicit-grant-helper-1 polkit-revoke-helper-1 - -polkit_grant_helper_1_SOURCES = polkit-grant-helper.c -polkit_grant_helper_1_LDADD = @GLIB_LIBS@ @DBUS_LIBS@ $(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la libpolkit-grant-1.la - -if POLKIT_AUTHFW_PAM -polkit_grant_helper_pam_1_SOURCES = polkit-grant-helper-pam.c -polkit_grant_helper_pam_1_LDADD = @AUTH_LIBS@ $(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la -endif - -if POLKIT_AUTHFW_SHADOW -polkit_grant_helper_shadow_1_SOURCES = polkit-grant-helper-shadow.c -polkit_grant_helper_shadow_1_LDADD = @AUTH_LIBS@ -endif - -polkit_explicit_grant_helper_1_SOURCES = polkit-explicit-grant-helper.c -polkit_explicit_grant_helper_1_CFLAGS = @DBUS_CFLAGS@ -polkit_explicit_grant_helper_1_LDADD = $(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la libpolkit-grant-1.la - -polkit_revoke_helper_1_SOURCES = polkit-revoke-helper.c -polkit_revoke_helper_1_CFLAGS = @DBUS_CFLAGS@ -polkit_revoke_helper_1_LDADD = $(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la - -# polkit-grant-helper needs to be setgid polkituser to be able to -# write cookies to /var/lib/PolicyKit and /var/run/PolicyKit -# -# polkit-grant-helper-* need to be setuid root because it's used to -# authenticate not only the invoking user, but possibly also root -# and/or other users. As only polkit-grant-helper will invoke it we -# make it owned by the polkitiuser group and non-executable to the -# world -# -# polkit-explicit-grant-helper needs to be setgid $POLKIT_GROUP to be -# able to edit authorization files in /var/lib/PolicyKit and -# /var/run/PolicyKit -# -# polkit-revoke-helper needs to be setgid $POLKIT_GROUP to be able to -# edit authorization files in /var/lib/PolicyKit and -# /var/run/PolicyKit -# -install-exec-hook: - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-grant-helper-1 - -chmod 2755 $(DESTDIR)$(libexecdir)/polkit-grant-helper-1 -if POLKIT_AUTHFW_PAM - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-grant-helper-pam-1 - -chmod 4754 $(DESTDIR)$(libexecdir)/polkit-grant-helper-pam-1 -endif -if POLKIT_AUTHFW_SHADOW - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-grant-helper-shadow-1 - -chmod 4750 $(DESTDIR)$(libexecdir)/polkit-grant-helper-shadow-1 -endif - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-explicit-grant-helper-1 - -chmod 2755 $(DESTDIR)$(libexecdir)/polkit-explicit-grant-helper-1 - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-revoke-helper-1 - -chmod 2755 $(DESTDIR)$(libexecdir)/polkit-revoke-helper-1 -endif - -## note that TESTS has special meaning (stuff to use in make check) -## so if adding tests not to be run in make check, don't add them to -## TESTS -if KIT_BUILD_TESTS -TESTS_ENVIRONMENT= -TESTS=polkit-grant-test - -check_PROGRAMS=$(TESTS) - -polkit_grant_test_SOURCES= \ - polkit-grant-test.h polkit-grant-test.c - -polkit_grant_test_LDADD=$(top_builddir)/src/polkit-grant/libpolkit-grant-1.la -polkit_grant_test_LDFLAGS= - -if KIT_GCOV_ENABLED -clean-gcov: - rm -f *.gcov .libs/*.gcda - -.PHONY: coverage-report.txt covered-files.txt - -covered-files.txt : - echo $(addprefix src/polkit-grant/,$(filter %.c,$(libpolkit_grant_1_la_SOURCES))) > covered-files.txt -if POLKIT_AUTHDB_DEFAULT - echo src/polkit-grant/polkit-explicit-grant-helper.c >> covered-files.txt - echo src/polkit-grant/polkit-grant-helper.c >> covered-files.txt -if POLKIT_AUTHFW_PAM - echo src/polkit-grant/polkit-grant-helper-pam.c >> covered-files.txt -endif -if POLKIT_AUTHFW_SHADOW - echo src/polkit-grant/polkit-grant-helper-shadow.c >> covered-files.txt -endif - echo src/polkit-grant/polkit-revoke-helper.c >> covered-files.txt -endif - -coverage-report.txt : covered-files.txt clean-gcov all check - gcov $(filter %.c,$(libpolkit_grant_1_la_SOURCES)) -o .libs/ > /dev/null -if POLKIT_AUTHDB_DEFAULT - gcov polkit-explicit-grant-helper.c -o .libs/ > /dev/null - gcov polkit-grant-helper.c -o .libs/ > /dev/null -if POLKIT_AUTHFW_PAM - gcov polkit-grant-helper-pam.c -o .libs/ > /dev/null -endif -if POLKIT_AUTHFW_SHADOW - gcov polkit-grant-helper-shadow.c -o .libs/ > /dev/null -endif - gcov polkit-revoke-helper.c -o .libs/ > /dev/null -endif - $(top_srcdir)/test/create-coverage-report.sh "module polkit-grant" `cat covered-files.txt` > coverage-report.txt - -check-coverage : coverage-report.txt - cat coverage-report.txt -else -coverage-report.txt: - @echo "Need to reconfigure with --enable-gcov" - -check-coverage: - @echo "Need to reconfigure with --enable-gcov" -endif - -else -TESTS= -endif - -clean-local : - rm -f *~ *.bb *.bbg *.da *.gcov .libs/*.da .libs/*.bbg diff --git a/src/polkit-grant/polkit-authorization-db-dummy-write.c b/src/polkit-grant/polkit-authorization-db-dummy-write.c deleted file mode 100644 index ac1fcc5..0000000 --- a/src/polkit-grant/polkit-authorization-db-dummy-write.c +++ /dev/null @@ -1,111 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-db.c : Dummy authorization database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <sys/time.h> -#include <sys/wait.h> -#include <errno.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <pwd.h> - -#include <glib.h> - -#include <polkit/polkit-debug.h> -#include <polkit/polkit-authorization-db.h> -#include <polkit/polkit-utils.h> -#include <polkit/polkit-private.h> - -/* PolKitAuthorizationDB structure is defined in polkit/polkit-private.h */ - -polkit_bool_t -polkit_authorization_db_add_entry_process_one_shot (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_add_entry_process (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_add_entry_session (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_add_entry_always (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_grant_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error) -{ - polkit_error_set_error (error, POLKIT_ERROR_NOT_SUPPORTED, "Not supported"); - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_grant_negative_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error) -{ - polkit_error_set_error (error, POLKIT_ERROR_NOT_SUPPORTED, "Not supported"); - return FALSE; -} diff --git a/src/polkit-grant/polkit-authorization-db-write.c b/src/polkit-grant/polkit-authorization-db-write.c deleted file mode 100644 index fec91a1..0000000 --- a/src/polkit-grant/polkit-authorization-db-write.c +++ /dev/null @@ -1,922 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-db.c : Represents the authorization database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <sys/time.h> -#include <sys/wait.h> -#include <errno.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <pwd.h> - -#include <glib.h> - -#include <polkit/polkit-debug.h> -#include <polkit/polkit-authorization-db.h> -#include <polkit/polkit-utils.h> -#include <polkit/polkit-private.h> - -/** - * SECTION:polkit-authorization-db - **/ - - -static polkit_bool_t -_write_to_fd (int fd, const char *str, ssize_t str_len) -{ - polkit_bool_t ret; - ssize_t written; - - ret = FALSE; - - written = 0; - while (written < str_len) { - ssize_t ret; - ret = write (fd, str + written, str_len - written); - if (ret < 0) { - if (errno == EAGAIN || errno == EINTR) { - continue; - } else { - goto out; - } - } - written += ret; - } - - ret = TRUE; - -out: - return ret; -} - -polkit_bool_t -_polkit_authorization_db_auth_file_add (polkit_bool_t transient, uid_t uid, char *str_to_add) -{ - int fd; - char *contents; - gsize contents_size; - char *path; - char *path_tmp; - GError *error; - polkit_bool_t ret; - struct stat statbuf; - struct passwd *pw; - const char *root; - char *newline = "\n"; - - if (transient) - root = PACKAGE_LOCALSTATE_DIR "/run/polkit-1"; - else - root = PACKAGE_LOCALSTATE_DIR "/lib/polkit-1"; - - ret = FALSE; - path = NULL; - path_tmp = NULL; - contents = NULL; - - pw = getpwuid (uid); - if (pw == NULL) { - g_warning ("cannot lookup user name for uid %d\n", uid); - goto out; - } - - path = g_strdup_printf ("%s/user-%s.auths", root, pw->pw_name); - path_tmp = g_strdup_printf ("%s.XXXXXX", path); - - if (stat (path, &statbuf) != 0 && errno == ENOENT) { - //fprintf (stderr, "path=%s does not exist (egid=%d): %m!\n", path, getegid ()); - - g_free (path_tmp); - path_tmp = path; - path = NULL; - - /* Write a nice blurb if we're creating the file for the first time */ - - contents = g_strdup_printf ( - "# This file lists authorizations for user %s\n" - "%s" - "# \n" - "# File format may change at any time; do not rely on it. To manage\n" - "# authorizations use polkit-auth(1) instead.\n" - "\n", - pw->pw_name, - transient ? "# (these are temporary and will be removed on the next system boot)\n" : ""); - contents_size = strlen (contents); - } else { - error = NULL; - if (!g_file_get_contents (path, &contents, &contents_size, &error)) { - g_warning ("Cannot read authorizations file %s: %s", path, error->message); - g_error_free (error); - goto out; - } - } - - if (path != NULL) { - fd = mkstemp (path_tmp); - if (fd < 0) { - fprintf (stderr, "Cannot create file '%s': %m\n", path_tmp); - goto out; - } - if (fchmod (fd, 0464) != 0) { - fprintf (stderr, "Cannot change mode for '%s' to 0460: %m\n", path_tmp); - close (fd); - unlink (path_tmp); - goto out; - } - } else { - fd = open (path_tmp, O_RDWR|O_CREAT, 0464); - if (fd < 0) { - fprintf (stderr, "Cannot create file '%s': %m\n", path_tmp); - goto out; - } - } - - if (!_write_to_fd (fd, contents, contents_size)) { - g_warning ("Cannot write to temporary authorizations file %s: %m", path_tmp); - close (fd); - if (unlink (path_tmp) != 0) { - g_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - if (!_write_to_fd (fd, str_to_add, strlen (str_to_add))) { - g_warning ("Cannot write to temporary authorizations file %s: %m", path_tmp); - close (fd); - if (unlink (path_tmp) != 0) { - g_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - if (!_write_to_fd (fd, newline, 1)) { - g_warning ("Cannot write to temporary authorizations file %s: %m", path_tmp); - close (fd); - if (unlink (path_tmp) != 0) { - g_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - close (fd); - - if (path != NULL) { - if (rename (path_tmp, path) != 0) { - g_warning ("Cannot rename %s to %s: %m", path_tmp, path); - if (unlink (path_tmp) != 0) { - g_warning ("Cannot unlink %s: %m", path_tmp); - } - goto out; - } - } - - /* trigger a reload */ - if (utimes (PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload", NULL) != 0) { - g_warning ("Error updating access+modification time on file '%s': %m\n", - PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload"); - } - - ret = TRUE; - -out: - if (contents != NULL) - g_free (contents); - if (path != NULL) - g_free (path); - if (path_tmp != NULL) - g_free (path_tmp); - return ret; -} - -/* returns -1 on error */ -static int -_write_constraints (char *buf, size_t buf_size, PolKitAuthorizationConstraint **constraints) -{ - unsigned int n; - unsigned int m; - - kit_return_val_if_fail (constraints != NULL, 0); - - for (n = 0, m = 0; constraints[n] != NULL; n++) { - PolKitAuthorizationConstraint *c; - const char *key; - char value[1024]; - - c = constraints[n]; - - key = "constraint"; - - if (polkit_authorization_constraint_to_string (c, value, sizeof (value)) >= sizeof (value)) { - kit_warning ("Constraint %d is too large!", n); - m = -1; - goto out; - } - - if (m < buf_size) - buf[m] = ':'; - m++; - - m += kit_string_percent_encode (buf + m, buf_size - m > 0 ? buf_size - m : 0, key); - - if (m < buf_size) - buf[m] = '='; - m++; - - m += kit_string_percent_encode (buf + m, buf_size - m > 0 ? buf_size - m : 0, value); - } - - if (m < buf_size) - buf[m] = '\0'; - -out: - return m; -} - -static polkit_bool_t -_add_caller_constraints (char *buf, size_t buf_size, PolKitCaller *caller) -{ - PolKitAuthorizationConstraint *constraints[64]; - int num_constraints; - polkit_bool_t ret; - int num_written; - int n; - - ret = FALSE; - - num_constraints = polkit_authorization_constraint_get_from_caller (caller, constraints, 64); - if (num_constraints == -1) - goto out; - - if (num_constraints >= 64) { - goto out; - } - - num_written = _write_constraints (buf, buf_size, constraints); - if (num_written == -1) { - goto out; - } - - if ((size_t) num_written >= buf_size) { - goto out; - } - - ret = TRUE; - -out: - for (n = 0; n < num_constraints && n < 64 && constraints[n] != NULL; n++) { - polkit_authorization_constraint_unref (constraints[n]); - } - return ret; -} - -/** - * polkit_authorization_db_add_entry_process_one_shot: - * @authdb: the authorization database - * @action: the action - * @caller: the caller - * @user_authenticated_as: the user that was authenticated - * - * Write an entry to the authorization database to indicate that the - * given caller is authorized for the given action a single time. - * - * Note that this function should only be used by - * <literal>libpolkit-grant</literal> or other sufficiently privileged - * processes that deals with managing authorizations. It should never - * be used by mechanisms or applications. The caller must have - * egid=polkituser and umask set so creating files with mode 0460 will - * work. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if an entry was written to the authorization - * database, #FALSE if the caller of this function is not sufficiently - * privileged. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_add_entry_process_one_shot (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - char *action_id; - uid_t caller_uid; - pid_t caller_pid; - polkit_bool_t ret; - polkit_uint64_t pid_start_time; - struct timeval now; - - g_return_val_if_fail (authdb != NULL, FALSE); - g_return_val_if_fail (action != NULL, FALSE); - g_return_val_if_fail (caller != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &action_id)) - return FALSE; - - if (!polkit_caller_get_pid (caller, &caller_pid)) - return FALSE; - - if (!polkit_caller_get_uid (caller, &caller_uid)) - return FALSE; - - pid_start_time = polkit_sysdeps_get_start_time_for_pid (caller_pid); - if (pid_start_time == 0) - return FALSE; - - if (gettimeofday (&now, NULL) != 0) { - g_warning ("Error calling gettimeofday: %m"); - return FALSE; - } - - char pid_buf[32]; - char pid_st_buf[32]; - char now_buf[32]; - char uid_buf[32]; - char auth_buf[1024]; - snprintf (pid_buf, sizeof (pid_buf), "%d", caller_pid); - snprintf (pid_st_buf, sizeof (pid_st_buf), "%Lu", pid_start_time); - snprintf (now_buf, sizeof (now_buf), "%Lu", (polkit_uint64_t) now.tv_sec); - snprintf (uid_buf, sizeof (uid_buf), "%d", user_authenticated_as); - - size_t len; - if ((len = kit_string_entry_create (auth_buf, sizeof (auth_buf), - "scope", "process-one-shot", - "pid", pid_buf, - "pid-start-time", pid_st_buf, - "action-id", action_id, - "when", now_buf, - "auth-as", uid_buf, - NULL)) >= sizeof (auth_buf)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - if (!_add_caller_constraints (auth_buf + len, sizeof (auth_buf) - len, caller)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - ret = _polkit_authorization_db_auth_file_add (TRUE, - caller_uid, - auth_buf); - return ret; -} - -/** - * polkit_authorization_db_add_entry_process: - * @authdb: the authorization database - * @action: the action - * @caller: the caller - * @user_authenticated_as: the user that was authenticated - * - * Write an entry to the authorization database to indicate that the - * given caller is authorized for the given action. - * - * Note that this function should only be used by - * <literal>libpolkit-grant</literal> or other sufficiently privileged - * processes that deals with managing authorizations. It should never - * be used by mechanisms or applications. The caller must have - * egid=polkituser and umask set so creating files with mode 0460 will - * work. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if an entry was written to the authorization - * database, #FALSE if the caller of this function is not sufficiently - * privileged. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_add_entry_process (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - char *action_id; - uid_t caller_uid; - pid_t caller_pid; - polkit_bool_t ret; - polkit_uint64_t pid_start_time; - struct timeval now; - - g_return_val_if_fail (authdb != NULL, FALSE); - g_return_val_if_fail (action != NULL, FALSE); - g_return_val_if_fail (caller != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &action_id)) - return FALSE; - - if (!polkit_caller_get_pid (caller, &caller_pid)) - return FALSE; - - if (!polkit_caller_get_uid (caller, &caller_uid)) - return FALSE; - - pid_start_time = polkit_sysdeps_get_start_time_for_pid (caller_pid); - if (pid_start_time == 0) - return FALSE; - - if (gettimeofday (&now, NULL) != 0) { - g_warning ("Error calling gettimeofday: %m"); - return FALSE; - } - - char pid_buf[32]; - char pid_st_buf[32]; - char now_buf[32]; - char uid_buf[32]; - char auth_buf[1024]; - snprintf (pid_buf, sizeof (pid_buf), "%d", caller_pid); - snprintf (pid_st_buf, sizeof (pid_st_buf), "%Lu", pid_start_time); - snprintf (now_buf, sizeof (now_buf), "%Lu", (polkit_uint64_t) now.tv_sec); - snprintf (uid_buf, sizeof (uid_buf), "%d", user_authenticated_as); - - size_t len; - if ((len = kit_string_entry_create (auth_buf, sizeof (auth_buf), - "scope", "process", - "pid", pid_buf, - "pid-start-time", pid_st_buf, - "action-id", action_id, - "when", now_buf, - "auth-as", uid_buf, - NULL)) >= sizeof (auth_buf)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - if (!_add_caller_constraints (auth_buf + len, sizeof (auth_buf) - len, caller)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - ret = _polkit_authorization_db_auth_file_add (TRUE, - caller_uid, - auth_buf); - return ret; -} - -/** - * polkit_authorization_db_add_entry_session: - * @authdb: the authorization database - * @action: the action - * @caller: the caller - * @user_authenticated_as: the user that was authenticated - * - * Write an entry to the authorization database to indicate that the - * session for the given caller is authorized for the given action for - * the remainer of the session. - * - * Note that this function should only be used by - * <literal>libpolkit-grant</literal> or other sufficiently privileged - * processes that deals with managing authorizations. It should never - * be used by mechanisms or applications. The caller must have - * egid=polkituser and umask set so creating files with mode 0460 will - * work. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if an entry was written to the authorization - * database, #FALSE if the caller of this function is not sufficiently - * privileged. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_add_entry_session (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - uid_t session_uid; - char *action_id; - PolKitSession *session; - char *session_objpath; - polkit_bool_t ret; - struct timeval now; - - g_return_val_if_fail (authdb != NULL, FALSE); - g_return_val_if_fail (action != NULL, FALSE); - g_return_val_if_fail (caller != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &action_id)) - return FALSE; - - if (!polkit_caller_get_ck_session (caller, &session)) - return FALSE; - - if (!polkit_session_get_ck_objref (session, &session_objpath)) - return FALSE; - - if (!polkit_session_get_uid (session, &session_uid)) - return FALSE; - - if (gettimeofday (&now, NULL) != 0) { - g_warning ("Error calling gettimeofday: %m"); - return FALSE; - } - - char now_buf[32]; - char uid_buf[32]; - char auth_buf[1024]; - snprintf (now_buf, sizeof (now_buf), "%Lu", (polkit_uint64_t) now.tv_sec); - snprintf (uid_buf, sizeof (uid_buf), "%d", user_authenticated_as); - - size_t len; - if ((len = kit_string_entry_create (auth_buf, sizeof (auth_buf), - "scope", "session", - "session-id", session_objpath, - "action-id", action_id, - "when", now_buf, - "auth-as", uid_buf, - NULL)) >= sizeof (auth_buf)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - if (!_add_caller_constraints (auth_buf + len, sizeof (auth_buf) - len, caller)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - ret = _polkit_authorization_db_auth_file_add (TRUE, - session_uid, - auth_buf); - return ret; -} - -/** - * polkit_authorization_db_add_entry_always: - * @authdb: the authorization database - * @action: the action - * @caller: the caller - * @user_authenticated_as: the user that was authenticated - * - * Write an entry to the authorization database to indicate that the - * given user is authorized for the given action. - * - * Note that this function should only be used by - * <literal>libpolkit-grant</literal> or other sufficiently privileged - * processes that deals with managing authorizations. It should never - * be used by mechanisms or applications. The caller must have - * egid=polkituser and umask set so creating files with mode 0460 will - * work. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if an entry was written to the authorization - * database, #FALSE if the caller of this function is not sufficiently - * privileged. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_add_entry_always (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as) -{ - uid_t uid; - char *action_id; - polkit_bool_t ret; - struct timeval now; - - g_return_val_if_fail (authdb != NULL, FALSE); - g_return_val_if_fail (action != NULL, FALSE); - g_return_val_if_fail (caller != NULL, FALSE); - - if (!polkit_caller_get_uid (caller, &uid)) - return FALSE; - - if (!polkit_action_get_action_id (action, &action_id)) - return FALSE; - - if (gettimeofday (&now, NULL) != 0) { - g_warning ("Error calling gettimeofday: %m"); - return FALSE; - } - - char now_buf[32]; - char uid_buf[32]; - char auth_buf[1024]; - snprintf (now_buf, sizeof (now_buf), "%Lu", (polkit_uint64_t) now.tv_sec); - snprintf (uid_buf, sizeof (uid_buf), "%d", user_authenticated_as); - - size_t len; - if ((len = kit_string_entry_create (auth_buf, sizeof (auth_buf), - "scope", "always", - "action-id", action_id, - "when", now_buf, - "auth-as", uid_buf, - NULL)) >= sizeof (auth_buf)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - if (!_add_caller_constraints (auth_buf + len, sizeof (auth_buf) - len, caller)) { - g_warning ("authbuf for is too small"); - return FALSE; - } - - ret = _polkit_authorization_db_auth_file_add (FALSE, - uid, - auth_buf); - return ret; -} - - -typedef struct { - char *action_id; - unsigned int _check_constraint_num; - PolKitAuthorizationConstraint **constraints; - - polkit_bool_t is_authorized; - polkit_bool_t is_negative_authorized; -} CheckDataGrant; - -static polkit_bool_t -_check_constraints_for_grant (PolKitAuthorization *auth, PolKitAuthorizationConstraint *authc, void *user_data) -{ - CheckDataGrant *cd = (CheckDataGrant *) user_data; - polkit_bool_t ret; - - ret = FALSE; - - if (cd->constraints [cd->_check_constraint_num] == NULL) - goto no_match; - - if (!polkit_authorization_constraint_equal (authc, cd->constraints[cd->_check_constraint_num])) - goto no_match; - - cd->_check_constraint_num += 1; - return FALSE; - -no_match: - return TRUE; -} - -static polkit_bool_t -_check_auth_for_grant (PolKitAuthorizationDB *authdb, PolKitAuthorization *auth, void *user_data) -{ - uid_t pimp; - polkit_bool_t ret; - polkit_bool_t is_negative; - CheckDataGrant *cd = (CheckDataGrant *) user_data; - - ret = FALSE; - - if (strcmp (polkit_authorization_get_action_id (auth), cd->action_id) != 0) - goto no_match; - - if (!polkit_authorization_was_granted_explicitly (auth, &pimp, &is_negative)) - goto no_match; - - /* This checks that the number of authorizations are the - * same.. as well as that the authorizations are similar one - * by one.. - * - * TODO: FIXME: this relies on the ordering, e.g. we don't - * catch local+active if there is an active+local one already. - */ - cd->_check_constraint_num = 0; - if (polkit_authorization_constraints_foreach (auth, _check_constraints_for_grant, cd) || - cd->constraints [cd->_check_constraint_num] != NULL) - goto no_match; - - if (is_negative) { - cd->is_authorized = FALSE; - cd->is_negative_authorized = TRUE; - /* it only takes a single negative auth to block things so stop iterating */ - ret = TRUE; - } else { - cd->is_authorized = TRUE; - cd->is_negative_authorized = FALSE; - /* keep iterating; we may find negative auths... */ - } - -no_match: - return ret; -} - -static polkit_bool_t -_grant_internal (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error, - polkit_bool_t is_negative) -{ - GError *g_error; - char *helper_argv[6] = {PACKAGE_LIBEXEC_DIR "/polkit-explicit-grant-helper-1", NULL, NULL, NULL, NULL, NULL}; - gboolean ret; - gint exit_status; - char cbuf[1024]; - CheckDataGrant cd; - polkit_bool_t did_exist; - - ret = FALSE; - - g_return_val_if_fail (authdb != NULL, FALSE); - g_return_val_if_fail (action != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &(cd.action_id))) { - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Given action does not have action_id set"); - goto out; - } - - if (constraints == NULL) { - cbuf[0] = '\0'; - } else { - int num_written; - num_written = _write_constraints (cbuf, sizeof (cbuf), constraints); - if (num_written == -1) { - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "one of the given constraints did not fit"); - goto out; - } - - if ((size_t) num_written >= sizeof (cbuf)) { - g_warning ("buffer for auth constraint is too small"); - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "buffer for auth constraint is too small"); - goto out; - } - } - - /* check if we have the auth already */ - cd.constraints = constraints; - cd.is_authorized = FALSE; - cd.is_negative_authorized = FALSE; - polkit_authorization_db_foreach_for_uid (authdb, - uid, - _check_auth_for_grant, - &cd, - error); - - /* happens if caller can't read auths of target user */ - if (error != NULL && polkit_error_is_set (*error)) { - goto out; - } - - did_exist = FALSE; - if (is_negative) { - if (cd.is_negative_authorized) - did_exist = TRUE; - } else { - if (cd.is_authorized) - did_exist = TRUE; - } - - if (did_exist) { - /* so it did exist.. */ - polkit_error_set_error (error, - POLKIT_ERROR_AUTHORIZATION_ALREADY_EXISTS, - "An authorization for uid %d for the action %s with constraint '%s' already exists", - uid, cd.action_id, cbuf); - goto out; - } - - - helper_argv[1] = cd.action_id; - helper_argv[2] = cbuf; - if (is_negative) - helper_argv[3] = "uid-negative"; - else - helper_argv[3] = "uid"; - helper_argv[4] = g_strdup_printf ("%d", uid); - helper_argv[5] = NULL; - - g_error = NULL; - if (!g_spawn_sync (NULL, /* const gchar *working_directory */ - helper_argv, /* gchar **argv */ - NULL, /* gchar **envp */ - 0, /* GSpawnFlags flags */ - NULL, /* GSpawnChildSetupFunc child_setup */ - NULL, /* gpointer user_data */ - NULL, /* gchar **standard_output */ - NULL, /* gchar **standard_error */ - &exit_status, /* gint *exit_status */ - &g_error)) { /* GError **error */ - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Error spawning explicit grant helper: %s", - g_error->message); - g_error_free (g_error); - goto out; - } - - if (!WIFEXITED (exit_status)) { - g_warning ("Explicit grant helper crashed!"); - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Explicit grant helper crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - polkit_error_set_error (error, - POLKIT_ERROR_NOT_AUTHORIZED_TO_GRANT_AUTHORIZATION, - "uid %d is not authorized to grant authorization for action %s to uid %d (requires org.freedesktop.policykit.grant)", - getuid (), cd.action_id, uid); - } else { - ret = TRUE; - } - -out: - g_free (helper_argv[4]); - return ret; -} - -/** - * polkit_authorization_db_grant_to_uid: - * @authdb: authorization database - * @action: action - * @uid: uid to grant to - * @constraints: Either %NULL or a %NULL terminated list of constraint to put on the authorization - * @error: return location for error - * - * Grants an authorization to a user for a specific action. This - * requires the org.freedesktop.policykit.grant authorization. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if the authorization was granted, #FALSE otherwise - * and error will be set - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_grant_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error) -{ - return _grant_internal (authdb, action, uid, constraints, error, FALSE); -} - -/** - * polkit_authorization_db_grant_negative_to_uid: - * @authdb: authorization database - * @action: action - * @uid: uid to grant to - * @constraints: Either %NULL or a %NULL terminated list of constraint to put on the authorization - * @error: return location for error - * - * Grants a negative authorization to a user for a specific action. If - * @uid differs from the calling user, the - * org.freedesktop.policykit.grant authorization is required. In other - * words, users may "grant" negative authorizations to themselves. - * - * A negative authorization is normally used to block users that would - * normally be authorized from an implicit authorization. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE if the authorization was granted, #FALSE otherwise - * and error will be set - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_grant_negative_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error) -{ - return _grant_internal (authdb, action, uid, constraints, error, TRUE); -} diff --git a/src/polkit-grant/polkit-explicit-grant-helper.c b/src/polkit-grant/polkit-explicit-grant-helper.c deleted file mode 100644 index 5609912..0000000 --- a/src/polkit-grant/polkit-explicit-grant-helper.c +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-explicit-grant-helper.c : setgid polkituser explicit grant - * helper for PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/time.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> -#include <fcntl.h> - -#include <polkit/polkit.h> -#include <polkit/polkit-private.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#endif - -int -main (int argc, char *argv[]) -{ - int ret; - gid_t egid; - struct group *group; - uid_t invoking_uid; - char *action_id; - char *endp; - struct timeval now; - - ret = 1; - - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - openlog ("polkit-explicit-grant-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 5) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-explicit-grant-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-explicit-grant-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - - invoking_uid = getuid (); - - /* check that we are setgid polkituser */ - egid = getegid (); - group = getgrgid (egid); - if (group == NULL) { - fprintf (stderr, "polkit-explicit-grant-helper: cannot lookup group info for gid %d\n", egid); - goto out; - } - if (strcmp (group->gr_name, POLKIT_GROUP) != 0) { - fprintf (stderr, "polkit-explicit-grant-helper: needs to be setgid " POLKIT_GROUP "\n"); - goto out; - } - - /*----------------------------------------------------------------------------------------------------*/ - - /* check and validate incoming parameters */ - - /* first one is action_id */ - action_id = argv[1]; - if (!polkit_action_validate_id (action_id)) { - syslog (LOG_NOTICE, "action_id is malformed [uid=%d]", getuid ()); - fprintf (stderr, "polkit-explicit-grant-helper: action_id is malformed. This incident has been logged.\n"); - goto out; - } - - char *authc_str; - size_t authc_str_len; - - /* second is the textual form of the auth constraint */ - authc_str = argv[2]; - authc_str_len = strlen (authc_str); - -#define TARGET_UID 0 - int target; - uid_t target_uid = -1; - polkit_bool_t is_negative; - - is_negative = FALSE; - - /* (third, fourth) is one of: ("uid", uid), ("uid-negative", uid) */ - if (strcmp (argv[3], "uid") == 0 || strcmp (argv[3], "uid-negative") == 0) { - - if (strcmp (argv[3], "uid") != 0) { - is_negative = TRUE; - } - - target = TARGET_UID; - target_uid = strtol (argv[4], &endp, 10); - if (*endp != '\0') { - syslog (LOG_NOTICE, "target uid is malformed [uid=%d]", getuid ()); - fprintf (stderr, "polkit-explicit-grant-helper: target uid is malformed. This incident has been logged.\n"); - goto out; - } - } else { - syslog (LOG_NOTICE, "target type is malformed [uid=%d]", getuid ()); - fprintf (stderr, "polkit-explicit-grant-helper: target type is malformed. This incident has been logged.\n"); - goto out; - } - - - //fprintf (stderr, "action_id=%s constraint=%s uid=%d\n", action_id, authc_str, target_uid); - - /* OK, we're done parsing ... check if the user is authorized */ - - if (invoking_uid != 0) { - - if (is_negative && (invoking_uid == target_uid)) { - /* it's fine to grant negative-auths to one self... */ - } else { - pid_t ppid; - - ppid = getppid (); - if (ppid == 1) - goto out; - - if (polkit_check_auth (ppid, "org.freedesktop.policykit.grant", NULL) == 0) { - goto out; - } - } - } - - /* he is.. proceed to add the grant */ - - umask (002); - - if (gettimeofday (&now, NULL) != 0) { - fprintf (stderr, "polkit-explicit-grant-helper: error calling gettimeofday: %m"); - return FALSE; - } - - char now_buf[32]; - char uid_buf[32]; - char auth_buf[1024]; - snprintf (now_buf, sizeof (now_buf), "%Lu", (polkit_uint64_t) now.tv_sec); - snprintf (uid_buf, sizeof (uid_buf), "%d", invoking_uid); - - size_t len; - if ((len = kit_string_entry_create (auth_buf, sizeof (auth_buf), - "scope", is_negative ? "grant-negative" : "grant", - "action-id", action_id, - "when", now_buf, - "granted-by", uid_buf, - NULL)) >= sizeof (auth_buf)) { - kit_warning ("polkit-explicit-grant-helper: authbuf is too small"); - goto out; - } - if (authc_str_len > 0) { - if (sizeof (auth_buf) - len < authc_str_len + 1) { - kit_warning ("polkit-explicit-grant-helper: authbuf is too small"); - goto out; - } - strncpy (auth_buf + len, authc_str, authc_str_len + 1); - } - - if (_polkit_authorization_db_auth_file_add (FALSE, - target_uid, - auth_buf)) { - ret = 0; - } - -out: - - return ret; -} - diff --git a/src/polkit-grant/polkit-grant-helper-pam.c b/src/polkit-grant/polkit-grant-helper-pam.c deleted file mode 100644 index 2596595..0000000 --- a/src/polkit-grant/polkit-grant-helper-pam.c +++ /dev/null @@ -1,247 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant-helper-pam.c : setuid root pam grant helper for PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/* TODO: FIXME: XXX: this code needs security review before it can be released! */ -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <syslog.h> -#include <security/pam_appl.h> - -#include <kit/kit.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#endif - -/* Development aid: define PGH_DEBUG to get debugging output. Do _NOT_ - * enable this in production builds; it may leak passwords and other - * sensitive information. - */ -#undef PGH_DEBUG -/* #define PGH_DEBUG */ - -static int conversation_function (int n, const struct pam_message **msg, struct pam_response **resp, void *data); - -int -main (int argc, char *argv[]) -{ - int rc; - char user_to_auth[256]; - struct pam_conv pam_conversation; - pam_handle_t *pam_h; - const void *authed_user; - - rc = 0; - pam_h = NULL; - - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto error; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - /* check that we are setuid root */ - if (geteuid () != 0) { - fprintf (stderr, "polkit-grant-helper-pam: needs to be setuid root\n"); - goto error; - } - - openlog ("polkit-grant-helper-pam-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 1) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper-pam: wrong number of arguments. This incident has been logged.\n"); - goto error; - } - - if (getuid () != 0) { - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper-pam: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto error; - } - } - - /* get user to auth */ - if (fgets (user_to_auth, sizeof user_to_auth, stdin) == NULL) - goto error; - if (strlen (user_to_auth) > 0 && user_to_auth[strlen (user_to_auth) - 1] == '\n') - user_to_auth[strlen (user_to_auth) - 1] = '\0'; - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper-pam: user to auth is '%s'.\n", user_to_auth); -#endif /* PGH_DEBUG */ - - pam_conversation.conv = conversation_function; - pam_conversation.appdata_ptr = NULL; - - /* start the pam stack */ - rc = pam_start ("polkit", - user_to_auth, - &pam_conversation, - &pam_h); - if (rc != PAM_SUCCESS) { - fprintf (stderr, "polkit-grant-helper-pam: pam_start failed: %s\n", pam_strerror (pam_h, rc)); - goto error; - } - - /* set the requesting user */ - rc = pam_set_item (pam_h, PAM_RUSER, user_to_auth); - if (rc != PAM_SUCCESS) { - fprintf (stderr, "polkit-grant-helper-pam: pam_set_item failed: %s\n", pam_strerror (pam_h, rc)); - goto error; - } - - /* is user really user? */ - rc = pam_authenticate (pam_h, 0); - if (rc != PAM_SUCCESS) { - fprintf (stderr, "polkit-grant-helper-pam: pam_authenticated failed: %s\n", pam_strerror (pam_h, rc)); - goto error; - } - - /* permitted access? */ - rc = pam_acct_mgmt (pam_h, 0); - if (rc != PAM_SUCCESS) { - fprintf (stderr, "polkit-grant-helper-pam: pam_acct_mgmt failed: %s\n", pam_strerror (pam_h, rc)); - goto error; - } - - /* did we auth the right user? */ - rc = pam_get_item (pam_h, PAM_USER, &authed_user); - if (rc != PAM_SUCCESS) { - fprintf (stderr, "polkit-grant-helper-pam: pam_get_item failed: %s\n", pam_strerror (pam_h, rc)); - goto error; - } - - if (strcmp (authed_user, user_to_auth) != 0) { - fprintf (stderr, "polkit-grant-helper-pam: Tried to auth user '%s' but we got auth for user '%s' instead", - user_to_auth, (const char *) authed_user); - goto error; - } - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper-pam: successfully authenticated user '%s'.\n", user_to_auth); -#endif /* PGH_DEBUG */ - - fprintf (stdout, "SUCCESS\n"); - fflush (stdout); - - pam_end (pam_h, rc); - return 0; -error: - if (pam_h != NULL) - pam_end (pam_h, rc); - - fprintf (stdout, "FAILURE\n"); - fflush (stdout); - return 1; -} - -static int -conversation_function (int n, const struct pam_message **msg, struct pam_response **resp, void *data) -{ - struct pam_response *aresp; - char buf[PAM_MAX_RESP_SIZE]; - int i; - - data = data; - if (n <= 0 || n > PAM_MAX_NUM_MSG) - return PAM_CONV_ERR; - - if ((aresp = calloc(n, sizeof *aresp)) == NULL) - return PAM_BUF_ERR; - - for (i = 0; i < n; ++i) { - aresp[i].resp_retcode = 0; - aresp[i].resp = NULL; - switch (msg[i]->msg_style) { - case PAM_PROMPT_ECHO_OFF: - fprintf (stdout, "PAM_PROMPT_ECHO_OFF "); - goto conv1; - case PAM_PROMPT_ECHO_ON: - fprintf (stdout, "PAM_PROMPT_ECHO_ON "); - conv1: - fputs (msg[i]->msg, stdout); - if (strlen (msg[i]->msg) > 0 && - msg[i]->msg[strlen (msg[i]->msg) - 1] != '\n') - fputc ('\n', stdout); - fflush (stdout); - - if (fgets (buf, sizeof buf, stdin) == NULL) - goto error; - if (strlen (buf) > 0 && - buf[strlen (buf) - 1] == '\n') - buf[strlen (buf) - 1] = '\0'; - - aresp[i].resp = strdup (buf); - if (aresp[i].resp == NULL) - goto error; - break; - - case PAM_ERROR_MSG: - fprintf (stdout, "PAM_ERROR_MSG "); - goto conv2; - - case PAM_TEXT_INFO: - fprintf (stdout, "PAM_TEXT_INFO "); - conv2: - fputs (msg[i]->msg, stdout); - if (strlen (msg[i]->msg) > 0 && - msg[i]->msg[strlen (msg[i]->msg) - 1] != '\n') - fputc ('\n', stdout); - fflush (stdout); - break; - default: - goto error; - } - } - *resp = aresp; - return PAM_SUCCESS; - -error: - for (i = 0; i < n; ++i) { - if (aresp[i].resp != NULL) { - memset (aresp[i].resp, 0, strlen(aresp[i].resp)); - free (aresp[i].resp); - } - } - memset (aresp, 0, n * sizeof *aresp); - *resp = NULL; - return PAM_CONV_ERR; -} diff --git a/src/polkit-grant/polkit-grant-helper-shadow.c b/src/polkit-grant/polkit-grant-helper-shadow.c deleted file mode 100644 index d9d3ef1..0000000 --- a/src/polkit-grant/polkit-grant-helper-shadow.c +++ /dev/null @@ -1,148 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant-helper-shadow.c : setuid root shadow helper for PolicyKit - * - * Copyright (C) 2007 Piter PUNK, <piterpunk@slackware.com> - * - * Based on polkit-grant-helper-pam.c : - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <syslog.h> -#include <shadow.h> -#include <grp.h> -#include <pwd.h> - -/* Development aid: define PGH_DEBUG to get debugging output. Do _NOT_ - * enable this in production builds; it may leak passwords and other - * sensitive information. - */ -#undef PGH_DEBUG -/* #define PGH_DEBUG */ - -extern char *crypt (); -static int do_auth (const char *user_to_auth); - -int main (int argc, char *argv[]) -{ - char user_to_auth[256]; - - /* clear the entire environment to avoid attacks with - * libraries honoring environment variables */ - if (clearenv () != 0) - goto error; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - /* check that we are setuid root */ - if (geteuid () != 0) { - fprintf (stderr, "polkit-grant-helper-shadow: needs to be setuid root\n"); - goto error; - } - - openlog ("polkit-grant-helper-shadow", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 1) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper-shadow: wrong number of arguments. This incident has been logged.\n"); - goto error; - } - - if (getuid () != 0) { - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper-shadow: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto error; - } - } - - /* get user to auth */ - if (fgets (user_to_auth, sizeof (user_to_auth), stdin) == NULL) - goto error; - if (strlen (user_to_auth) > 0 && user_to_auth[strlen (user_to_auth) - 1] == '\n') - user_to_auth[strlen(user_to_auth) - 1] = '\0'; - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper-shadow: user to auth is '%s'.\n", user_to_auth); -#endif /* PGH_DEBUG */ - - if(!do_auth (user_to_auth)) { - syslog (LOG_NOTICE, "authentication failure [uid=%d] trying to authenticate '%s'", getuid (), user_to_auth); - fprintf (stderr, "polkit-grant-helper-shadow: authentication failure. This incident has been logged.\n"); - goto error; - } - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper-shadow: successfully authenticated user '%s'.\n", user_to_auth); -#endif /* PGH_DEBUG */ - - fprintf (stdout, "SUCCESS\n"); - fflush (stdout); - return 0; - -error: - sleep (2); /* Discourage brute force attackers */ - fprintf (stdout, "FAILURE\n"); - fflush (stdout); - return 1; -} -/* - * This is the shadow do_auth function. It receives - * only the name of user (user_to_auth). Waits for - * password in stdin and auth the user. It return success - * if the user can be authenticated and unsuccess when - * user can't be authenticated. - */ -int do_auth (const char *user_to_auth) -{ - struct spwd *shadow; - char password[256]; - - if ((shadow = getspnam (user_to_auth)) == NULL) - goto error; - - if (fgets (password, sizeof (password), stdin) == NULL) - goto error; - - if (strlen (password) > 0 && - password[strlen (password) - 1] == '\n') - password[strlen (password) - 1] = '\0'; - - if (strcmp (shadow->sp_pwdp, crypt (password, shadow->sp_pwdp)) != 0) - goto error; - - return 1; - -error: - return 0; -} diff --git a/src/polkit-grant/polkit-grant-helper.c b/src/polkit-grant/polkit-grant-helper.c deleted file mode 100644 index ff4b03f..0000000 --- a/src/polkit-grant/polkit-grant-helper.c +++ /dev/null @@ -1,816 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant-helper.c : setgid polkituser grant helper for PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/* TODO: FIXME: XXX: this code needs security review before it can be released! */ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> - -#ifdef POLKIT_AUTHFW_PAM -#include <security/pam_appl.h> -#endif - -#ifdef POLKIT_AUTHFW_SHADOW -#include <shadow.h> -#endif - -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> - -#include <glib.h> - -#include <kit/kit.h> - -#include <polkit/polkit.h> -// #include <polkit/polkit-grant-database.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#endif - -/* Development aid: define PGH_DEBUG to get debugging output. Do _NOT_ - * enable this in production builds; it may leak passwords and other - * sensitive information. - */ -#undef PGH_DEBUG -/* #define PGH_DEBUG */ - -/* synopsis: polkit-grant-helper <pid> <action-name> - * - * <pid> : process id of caller to grant privilege to - * <action-name> : the PolicyKit action - * - * Error/debug messages goes to stderr. Interaction with the program - * launching this helper happens via stdin/stdout. A rough high-level - * interaction diagram looks like this (120 character width): - * - * Program using - * libpolkit-grant polkit-grant-helper polkit-grant-helper-pam - * ------------- ------------------- ----------------------- - * - * Spawn polkit-grant-helper - * with args <pid>, <action-name> --> - * - * Create PolKitCaller object - * from <pid>. Involves querying - * ConsoleKit over the system - * message-bus. Verify that - * the caller qualifies for - * for authentication to gain - * the right to do the Action. - * - * <-- Tell libpolkit-grant about grant details, e.g. - * {self,admin}_{,keep_session,keep_always} + - * what users can authenticate using stdout - * - * Receive grant details on stdin. - * Caller prepares UI dialog depending - * on grant details. - * - * if admin_users is not empty, wait for - * user name of admin user to auth on stdin - * - * if admin_users is not empty, write - * user name of admin user to auth on stdout --> - * - * - * verify that given username is - * in admin_users - * - * - * Spawn polkit-grant-helper-pam - * with no args --> - * - * Write username to auth as - * on stdout --> - * - * Receive username on stdin. - * Start the PAM stack - * auth_in_progess: - * Write a PAM request on stdout, one off - * - PAM_PROMPT_ECHO_OFF - * - PAM_PROMPT_ECHO_ON - * - PAM_ERROR_MSG - * - PAM_TEXT_INFO - * - * Receive PAM request on stdin. - * Send it to libpolkit-grant on stdout - * - * Receive PAM request on stdin. - * Program deals with it. - * Write reply on stdout - * - * Receive PAM reply on stdin - * Send PAM reply on stdout - * - * Deal with PAM reply on stdin. - * Now either - * - GOTO auth_in_progress; or - * - Write SUCCESS|FAILURE on stdout and then - * die - * - * Receive either SUCCESS or - * FAILURE on stdin. If FAILURE - * is received, then die with exit - * code 1. If SUCCESS, leave a cookie - * in /var/{lib,run}/polkit-1 indicating - * the grant was successful and die with - * exit code 0 - * - * - * If auth fails, we exit with code 1. - * If input is not valid we exit with code 2. - * If any other error occur we exit with code 3 - * If privilege was granted, we exit code 0. - */ - - -/** - * do_auth: - * - * the authentication itself is done via a setuid root helper; this is - * to make the code running as uid 0 easier to audit. - * - */ -static polkit_bool_t -do_auth (const char *user_to_auth, gboolean *empty_conversation) -{ - int helper_pid; - int helper_stdin; - int helper_stdout; - GError *g_error; -#ifdef POLKIT_AUTHFW_PAM - char *helper_argv[2] = {PACKAGE_LIBEXEC_DIR "/polkit-grant-helper-pam-1", NULL}; -#endif -#ifdef POLKIT_AUTHFW_SHADOW - char *helper_argv[2] = {PACKAGE_LIBEXEC_DIR "/polkit-grant-helper-shadow-1", NULL}; -#endif - char buf[256]; - FILE *child_stdin; - FILE *child_stdout; - gboolean ret; - - child_stdin = NULL; - child_stdout = NULL; - ret = FALSE; - *empty_conversation = TRUE; - - g_error = NULL; - if (!g_spawn_async_with_pipes (NULL, - (char **) helper_argv, - NULL, - 0, - NULL, - NULL, - &helper_pid, - &helper_stdin, - &helper_stdout, - NULL, - &g_error)) { - fprintf (stderr, "polkit-grant-helper: cannot spawn helper: %s\n", g_error->message); - g_error_free (g_error); - g_free (helper_argv[1]); - goto out; - } - - child_stdin = fdopen (helper_stdin, "w"); - if (child_stdin == NULL) { - fprintf (stderr, "polkit-grant-helper: fdopen (helper_stdin) failed: %s\n", strerror (errno)); - goto out; - } - child_stdout = fdopen (helper_stdout, "r"); - if (child_stdout == NULL) { - fprintf (stderr, "polkit-grant-helper: fdopen (helper_stdout) failed: %s\n", strerror (errno)); - goto out; - } - - /* First, tell the pam helper what user we wish to auth */ - fprintf (child_stdin, "%s\n", user_to_auth); - fflush (child_stdin); - - /* now act as middle man between our parent and our child */ - - while (TRUE) { - /* read from child */ - if (fgets (buf, sizeof buf, child_stdout) == NULL) - goto out; -#ifdef PGH_DEBUG - fprintf (stderr, "received: '%s' from child; sending to parent\n", buf); -#endif /* PGH_DEBUG */ - /* see if we're done? */ - if (strcmp (buf, "SUCCESS\n") == 0) { - ret = TRUE; - goto out; - } - if (strcmp (buf, "FAILURE\n") == 0) { - goto out; - } - - *empty_conversation = FALSE; - - /* send to parent */ - fprintf (stdout, "%s", buf); - fflush (stdout); - - /* read from parent */ - if (fgets (buf, sizeof buf, stdin) == NULL) - goto out; - -#ifdef PGH_DEBUG - fprintf (stderr, "received: '%s' from parent; sending to child\n", buf); -#endif /* PGH_DEBUG */ - /* send to child */ - fprintf (child_stdin, "%s", buf); - fflush (child_stdin); - } - -out: - if (child_stdin != NULL) - fclose (child_stdin); - if (child_stdout != NULL) - fclose (child_stdout); - return ret; -} - -/** - * verify_with_polkit: - * @caller: the caller - * @action: the action - * @out_result: return location for result AKA how the user can auth - * @out_admin_users: return location for a NULL-terminated array of - * strings that can be user to auth as admin. Is set to NULL if the - * super user (e.g. uid 0) should be user to auth as admin. - * - * Verify that the given caller can authenticate to gain a privilege - * to do the given action. If the authentication requires - * administrator privileges, also return a list of users that can be - * used to do this cf. the <define_admin_auth/> element in the - * configuration file; see the PolicyKit.conf(5) manual page for - * details. - * - * Returns: #TRUE if, and only if, the given caller can authenticate to - * gain a privilege to do the given action. - */ -static polkit_bool_t -verify_with_polkit (PolKitContext *pol_ctx, - PolKitCaller *caller, - PolKitAction *action, - PolKitResult *out_result, - char ***out_admin_users) -{ - PolKitError *pk_error; - - pk_error = NULL; - *out_result = polkit_context_is_caller_authorized (pol_ctx, action, caller, FALSE, &pk_error); - if (polkit_error_is_set (pk_error)) { - fprintf (stderr, "polkit-grant-helper: cannot determine if caller is authorized: %s: %s\n", - polkit_error_get_error_name (pk_error), - polkit_error_get_error_message (pk_error)); - polkit_error_free (pk_error); - goto error; - } - - if (*out_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT && - *out_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH && - *out_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION && - *out_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS && - *out_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT && - *out_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH && - *out_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION && - *out_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS) { - fprintf (stderr, "polkit-grant-helper: given auth type (%d -> %s) is bogus\n", - *out_result, polkit_result_to_string_representation (*out_result)); - goto error; - } - - *out_admin_users = NULL; - - /* for admin auth, get a list of users that can be used - this is basically evaluating the - * <define_admin_auth/> directives in the config file... - */ - if (*out_result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT || - *out_result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH || - *out_result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION || - *out_result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS) { - /* TODO: need to revisit this and return list of users that can auth */ - *out_admin_users = NULL; - } - - /* TODO: we should probably clean up */ - - return TRUE; -error: - return FALSE; -} - -static polkit_bool_t -get_and_validate_override_details (PolKitResult *result) -{ - char buf[256]; - char *textual_result; - PolKitResult desired_result; - - if (fgets (buf, sizeof buf, stdin) == NULL) - goto error; - if (strlen (buf) > 0 && - buf[strlen (buf) - 1] == '\n') - buf[strlen (buf) - 1] = '\0'; - - if (strncmp (buf, - "POLKIT_GRANT_CALLER_PASS_OVERRIDE_GRANT_TYPE ", - sizeof "POLKIT_GRANT_CALLER_PASS_OVERRIDE_GRANT_TYPE " - 1) != 0) { - goto error; - } - textual_result = buf + sizeof "POLKIT_GRANT_CALLER_PASS_OVERRIDE_GRANT_TYPE " - 1; - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: caller said '%s'\n", textual_result); -#endif /* PGH_DEBUG */ - - if (!polkit_result_from_string_representation (textual_result, &desired_result)) - goto error; - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: testing for voluntarily downgrade from '%s' to '%s'\n", - polkit_result_to_string_representation (*result), - polkit_result_to_string_representation (desired_result)); -#endif /* PGH_DEBUG */ - - /* See the huge comment in main() below... - * - * it comes down to this... users can only choose a more restricted granting type... - */ - switch (*result) { - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT: - if (desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH: - if (desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION: - if (desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS: - if (desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION && - desired_result != POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS) - goto error; - break; - - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT: - if (desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH: - if (desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION: - if (desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION) - goto error; - break; - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS: - if (desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION && - desired_result != POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS) - goto error; - break; - - default: - /* we should never reach this */ - goto error; - } - -#ifdef PGH_DEBUG - if (*result != desired_result) { - fprintf (stderr, "polkit-grant-helper: voluntarily downgrading from '%s' to '%s'\n", - polkit_result_to_string_representation (*result), - polkit_result_to_string_representation (desired_result)); - } -#endif /* PGH_DEBUG */ - - *result = desired_result; - - return TRUE; -error: - return FALSE; -} - -int -main (int argc, char *argv[]) -{ - int ret; - uid_t invoking_user_id; - pid_t caller_pid; - gid_t egid; - struct group *group; - char *endp; - const char *invoking_user_name; - const char *action_name; - PolKitResult result; - PolKitResult orig_result; - const char *user_to_auth; - uid_t uid_of_user_to_auth; - char *session_objpath; - struct passwd *pw; - polkit_bool_t dbres; - char **admin_users; - DBusError error; - DBusConnection *bus; - PolKitContext *context; - PolKitAction *action; - PolKitCaller *caller; - uid_t caller_uid; - PolKitSession *session; - gboolean empty_conversation; - char buf[256]; - - ret = 3; - - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - openlog ("polkit-grant-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 3) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-grant-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - - /* check user */ - invoking_user_id = getuid (); - if (invoking_user_id == 0) { - fprintf (stderr, "polkit-grant-helper: it only makes sense to run polkit-grant-helper as non-root\n"); - goto out; - } - - /* check that we are setgid polkituser */ - egid = getegid (); - group = getgrgid (egid); - if (group == NULL) { - fprintf (stderr, "polkit-grant-helper: cannot lookup group info for gid %d\n", egid); - goto out; - } - if (strcmp (group->gr_name, POLKIT_GROUP) != 0) { - fprintf (stderr, "polkit-grant-helper: needs to be setgid " POLKIT_GROUP "\n"); - goto out; - } - - pw = getpwuid (invoking_user_id); - if (pw == NULL) { - fprintf (stderr, "polkit-grant-helper: cannot lookup passwd info for uid %d\n", invoking_user_id); - goto out; - } - invoking_user_name = strdup (pw->pw_name); - if (invoking_user_name == NULL) { - fprintf (stderr, "polkit-grant-helper: OOM allocating memory for invoking user name\n"); - goto out; - } - - caller_pid = strtol (argv[1], &endp, 10); - if (endp == NULL || endp == argv[1] || *endp != '\0') { - fprintf (stderr, "polkit-grant-helper: cannot parse pid\n"); - goto out; - } - action_name = argv[2]; - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: invoking user = %d ('%s')\n", invoking_user_id, invoking_user_name); - fprintf (stderr, "polkit-grant-helper: caller_pid = %d\n", caller_pid); - fprintf (stderr, "polkit-grant-helper: action_name = '%s'\n", action_name); -#endif /* PGH_DEBUG */ - - ret = 2; - - context = polkit_context_new (); - if (!polkit_context_init (context, NULL)) { - fprintf (stderr, "polkit-grant-helper: cannot initialize polkit\n"); - goto out; - } - - action = polkit_action_new (); - polkit_action_set_action_id (action, action_name); - - dbus_error_init (&error); - bus = dbus_bus_get (DBUS_BUS_SYSTEM, &error); - if (bus == NULL) { - fprintf (stderr, "polkit-grant-helper: cannot connect to system bus: %s: %s\n", - error.name, error.message); - dbus_error_free (&error); - goto out; - } - - caller = polkit_caller_new_from_pid (bus, caller_pid, &error); - if (caller == NULL) { - fprintf (stderr, "polkit-grant-helper: cannot get caller from pid: %s: %s\n", - error.name, error.message); - goto out; - } - if (!polkit_caller_get_uid (caller, &caller_uid)) { - fprintf (stderr, "polkit-grant-helper: no uid for caller\n"); - goto out; - } - - /* This user does not have to be in a session.. for example, one might - * use <allow_any>auth_admin</allow_any>... - */ - session = NULL; - session_objpath = NULL; - if (polkit_caller_get_ck_session (caller, &session) && session != NULL) { - if (!polkit_session_get_ck_objref (session, &session_objpath)) { - session = NULL; - session_objpath = NULL; - } - } - - /* Use libpolkit to figure out if the caller can really auth to do the action - */ - if (!verify_with_polkit (context, caller, action, &result, &admin_users)) - goto out; - -#ifdef PGH_DEBUG - if (admin_users != NULL) { - int n; - fprintf (stderr, "polkit-grant-helper: admin_users: "); - for (n = 0; admin_users[n] != NULL; n++) - fprintf (stderr, "'%s' ", admin_users[n]); - fprintf (stderr, "\n"); - } -#endif /* PGH_DEBUG */ - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: polkit result = '%s'\n", - polkit_result_to_string_representation (result)); - fprintf (stderr, "polkit-grant-helper: session_objpath = '%s'\n", session_objpath); -#endif /* PGH_DEBUG */ - - /* tell the caller about the grant details; e.g. whether - * it's auth_self_keep_always or auth_self etc. - */ - fprintf (stdout, "POLKIT_GRANT_HELPER_TELL_TYPE %s\n", - polkit_result_to_string_representation (result)); - fflush (stdout); - - /* if admin auth is required, tell caller about possible users */ - if (admin_users != NULL) { - int n; - fprintf (stdout, "POLKIT_GRANT_HELPER_TELL_ADMIN_USERS"); - for (n = 0; admin_users[n] != NULL; n++) - fprintf (stdout, " %s", admin_users[n]); - fprintf (stdout, "\n"); - fflush (stdout); - } - - - /* wait for libpolkit-grant to tell us what user to use */ - if (admin_users != NULL) { - int n; - -#ifdef PGH_DEBUG - fprintf (stderr, "waiting for admin user name...\n"); -#endif /* PGH_DEBUG */ - - /* read from parent */ - if (fgets (buf, sizeof buf, stdin) == NULL) - goto out; - if (strlen (buf) > 0 && buf[strlen (buf) - 1] == '\n') - buf[strlen (buf) - 1] = '\0'; - - if (strncmp (buf, - "POLKIT_GRANT_CALLER_SELECT_ADMIN_USER ", - sizeof "POLKIT_GRANT_CALLER_SELECT_ADMIN_USER " - 1) != 0) { - goto out; - } - - user_to_auth = buf + sizeof "POLKIT_GRANT_CALLER_SELECT_ADMIN_USER " - 1; -#ifdef PGH_DEBUG - fprintf (stderr, "libpolkit-grant wants to auth as '%s'\n", user_to_auth); -#endif /* PGH_DEBUG */ - - /* now sanity check that returned user is actually in admin_users */ - for (n = 0; admin_users[n] != NULL; n++) { - if (strcmp (admin_users[n], user_to_auth) == 0) - break; - } - if (admin_users[n] == NULL) { - ret = 2; - goto out; - } - - } else { - /* figure out what user to auth */ - if (result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT || - result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH || - result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION || - result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS) { - user_to_auth = "root"; - } else { - user_to_auth = invoking_user_name; - } - } - - if (strcmp (user_to_auth, "root") == 0) { - uid_of_user_to_auth = 0; - } else { - struct passwd *passwd; - - passwd = getpwnam (user_to_auth); - if (passwd == NULL) { - fprintf (stderr, "polkit-grant-helper: can not look up uid for user '%s'\n", user_to_auth); - goto out; - } - uid_of_user_to_auth = passwd->pw_uid; - } - - ret = 1; - - /* Start authentication */ - if (!do_auth (user_to_auth, &empty_conversation)) { - goto out; - } - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: empty_conversation=%d\n", empty_conversation); -#endif /* PGH_DEBUG */ - - /* Ask caller if he want to slim down grant type... e.g. he - * might want to go from auth_self_keep_always to - * auth_self_keep_session.. - * - * See docs for the PolKitGrantOverrideGrantType callback type - * for use cases; it's in polkit-grant/polkit-grant.h - */ - fprintf (stdout, "POLKIT_GRANT_HELPER_ASK_OVERRIDE_GRANT_TYPE %s\n", - polkit_result_to_string_representation (result)); - fflush (stdout); - - orig_result = result; - if (!get_and_validate_override_details (&result)) { - /* if this fails it means bogus input from user */ - ret = 2; - goto out; - } - - if (empty_conversation && orig_result == result) { - /* If the conversation was empty it means the user probably never - * saw the an auth dialog.. specifically it means he never was able - * to change the scope of the from e.g. 'always' to 'session' or - * 'process'. In fact, it means he was never aware any authorization - * was granted. - * - * So to avoid surprises for people who do reckless things like play - * around with disabling passwords on their system, make an executive - * decision to downgrade the scope... - * - * See RH #401811 for details of one user that was caught by this. - */ - - if (result == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS) { - result = POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION; - } else if (result == POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS) { - result = POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION; - } - } - - -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: adding grant: action_id=%s session_id=%s pid=%d result='%s'\n", - action_name, session_objpath, caller_pid, polkit_result_to_string_representation (result)); -#endif /* PGH_DEBUG */ - - /* make sure write permissions for group is honored */ - umask (002); - - switch (result) { - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT: - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT: - dbres = polkit_authorization_db_add_entry_process_one_shot (polkit_context_get_authorization_db (context), - action, - caller, - uid_of_user_to_auth); - if (dbres) { - syslog (LOG_INFO, "granted one shot authorization for %s to pid %d [uid=%d] [auth=%s]", - action_name, caller_pid, invoking_user_id, user_to_auth); - } - break; - - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH: - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH: - dbres = polkit_authorization_db_add_entry_process (polkit_context_get_authorization_db (context), - action, - caller, - uid_of_user_to_auth); - if (dbres) { - syslog (LOG_INFO, "granted authorization for %s to pid %d [uid=%d] [auth=%s]", - action_name, caller_pid, invoking_user_id, user_to_auth); - } - break; - - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION: - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION: - if (session == NULL || session_objpath == NULL) { - fprintf (stderr, "polkit-grant-helper: cannot grant to session when not in a session\n"); - ret = 2; - goto out; - } - dbres = polkit_authorization_db_add_entry_session (polkit_context_get_authorization_db (context), - action, - caller, - uid_of_user_to_auth); - - if (dbres) { - syslog (LOG_INFO, "granted authorization for %s to session %s [uid=%d] [auth=%s]", - action_name, session_objpath, invoking_user_id, user_to_auth); - } - break; - - case POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS: - case POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS: - dbres = polkit_authorization_db_add_entry_always (polkit_context_get_authorization_db (context), - action, - caller, - uid_of_user_to_auth); - if (dbres) { - syslog (LOG_INFO, "granted authorization for %s to uid %d [auth=%s]", - action_name, caller_uid, user_to_auth); - } - break; - - default: - /* should never happen */ - goto out; - } - - if (!dbres) { - fprintf (stderr, "polkit-grant-helper: failed to write to grantdb\n"); - goto out; - } - - ret = 0; -out: -#ifdef PGH_DEBUG - fprintf (stderr, "polkit-grant-helper: exiting with code %d\n", ret); -#endif /* PGH_DEBUG */ - return ret; -} diff --git a/src/polkit-grant/polkit-grant-test.c b/src/polkit-grant/polkit-grant-test.c deleted file mode 100644 index 8867769..0000000 --- a/src/polkit-grant/polkit-grant-test.c +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant-test.c : polkit-grant tests - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#include <stdio.h> -#include <stdlib.h> -#include <syslog.h> -#include <polkit/polkit-private.h> -#include <polkit-grant/polkit-grant-test.h> - -#define MAX_TESTS 64 - -/** - * SECTION:polkit-grant-test - * @short_description: Testing code for libpolkit-grant - * - * Testing code for libpolkit-grant - */ - -static KitTest *tests[] = { - &_test_polkit_grant, -}; - -int -main (int argc, char *argv[]) -{ - /* Some of the code will log to syslog because .policy files - * etc. may be malformed. Since this will open a socket to the - * system logger preempt this so the fd-leak checking don't - * freak out. - */ - syslog (LOG_INFO, "libpolkit-grant: initiating test; bogus alerts may be written to syslog"); - - if (kit_test_run (tests, sizeof (tests) / sizeof (KitTest*))) - return 0; - else - return 1; -} diff --git a/src/polkit-grant/polkit-grant-test.h b/src/polkit-grant/polkit-grant-test.h deleted file mode 100644 index dfb9a61..0000000 --- a/src/polkit-grant/polkit-grant-test.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant-test.h : polkit-grant tests - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) -#error "polkit-dbus-test.h is a private file" -#endif - -#ifndef POLKIT_GRANT_TEST_H -#define POLKIT_GRANT_TEST_H - -#include <kit/kit.h> - -POLKIT_BEGIN_DECLS - -extern KitTest _test_polkit_grant; - -POLKIT_END_DECLS - -#endif /* POLKIT_GRANT_TEST_H */ - - diff --git a/src/polkit-grant/polkit-grant.c b/src/polkit-grant/polkit-grant.c deleted file mode 100644 index ad4c98f..0000000 --- a/src/polkit-grant/polkit-grant.c +++ /dev/null @@ -1,564 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant.c : library for obtaining privileges - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <errno.h> -#include <sys/types.h> -#include <unistd.h> -#include <sys/wait.h> -#include <signal.h> - -#include <glib.h> -#include "polkit-grant.h" -#include "polkit-grant-test.h" - -/** - * SECTION:polkit-grant - * @title: Authorizations and Authentication - * @short_description: Obtain authorizations through - * authentication. - * - * These functions are used to obtain authorizations for a user that - * is able to successfully authenticate. It is only useful for people - * writing user interfaces that interfaces with the end user. - * - * All of these functions are in the - * <literal>libpolkit-grant</literal> library. - **/ - -/** - * PolKitGrant: - * - * Objects of this class are used to obtain authorizations for a user - * that is able to successfully authenticate. It is only useful for - * people writing user interfaces that interfaces with the end user. - * - * All of these functions are in the - * <literal>libpolkit-grant</literal> library. - **/ -struct _PolKitGrant -{ - int refcount; - - PolKitGrantAddIOWatch func_add_io_watch; - PolKitGrantAddChildWatch func_add_child_watch; - PolKitGrantRemoveWatch func_remove_watch; - PolKitGrantType func_type; - PolKitGrantSelectAdminUser func_select_admin_user; - PolKitGrantConversationPromptEchoOff func_prompt_echo_off; - PolKitGrantConversationPromptEchoOn func_prompt_echo_on; - PolKitGrantConversationErrorMessage func_error_message; - PolKitGrantConversationTextInfo func_text_info; - PolKitGrantOverrideGrantType func_override_grant_type; - PolKitGrantDone func_done; - void *user_data; - - int child_stdin; - int child_stdout; - GPid child_pid; - FILE *child_stdout_f; - - int child_watch_id; - int io_watch_id; - - gboolean success; - gboolean helper_is_running; -}; - -/** - * polkit_grant_new: - * - * Creates a #PolKitGrant object. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: the new object or #NULL if the authorization backend - * doesn't support obtaining authorizations through authentication. - **/ -PolKitGrant * -polkit_grant_new (void) -{ - PolKitGrant *polkit_grant; - - if (! (polkit_authorization_db_get_capabilities () & POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN)) - return NULL; - - polkit_grant = g_new0 (PolKitGrant, 1); - polkit_grant->refcount = 1; - return polkit_grant; -} - -/** - * polkit_grant_ref: - * @polkit_grant: the object - * - * Increase reference count. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: the object. - **/ -PolKitGrant * -polkit_grant_ref (PolKitGrant *polkit_grant) -{ - g_return_val_if_fail (polkit_grant != NULL, NULL); - - polkit_grant->refcount++; - return polkit_grant; -} - -/** - * polkit_grant_unref: - * @polkit_grant: the object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - * - * This function is in <literal>libpolkit-grant</literal>. - **/ -void -polkit_grant_unref (PolKitGrant *polkit_grant) -{ - g_return_if_fail (polkit_grant != NULL); - - polkit_grant->refcount--; - if (polkit_grant->refcount > 0) - return; - - if (polkit_grant->io_watch_id > 0) { - polkit_grant->func_remove_watch (polkit_grant, polkit_grant->io_watch_id); - } - if (polkit_grant->child_watch_id > 0) { - polkit_grant->func_remove_watch (polkit_grant, polkit_grant->child_watch_id); - } - if (polkit_grant->child_pid > 0) { - int status; - kill (polkit_grant->child_pid, SIGTERM); - waitpid (polkit_grant->child_pid, &status, 0); - } - if (polkit_grant->child_stdout_f != NULL) { - fclose (polkit_grant->child_stdout_f); - } - if (polkit_grant->child_stdout >= 0) { - close (polkit_grant->child_stdout); - } - if (polkit_grant->child_stdin >= 0) { - close (polkit_grant->child_stdin); - } - - g_free (polkit_grant); -} - -/** - * polkit_grant_set_functions: - * @polkit_grant: the object - * @func_add_io_watch: Callback function - * @func_add_child_watch: Callback function - * @func_remove_watch: Callback function - * @func_type: Callback function - * @func_select_admin_user: Callback function - * @func_prompt_echo_off: Callback function - * @func_prompt_echo_on: Callback function - * @func_error_message: Callback function - * @func_text_info: Callback function - * @func_override_grant_type: Callback function - * @func_done: Callback function - * @user_data: User data that will be passed to the callback functions. - * - * Set callback functions used for authentication. - * - * This function is in <literal>libpolkit-grant</literal>. - **/ -void -polkit_grant_set_functions (PolKitGrant *polkit_grant, - PolKitGrantAddIOWatch func_add_io_watch, - PolKitGrantAddChildWatch func_add_child_watch, - PolKitGrantRemoveWatch func_remove_watch, - PolKitGrantType func_type, - PolKitGrantSelectAdminUser func_select_admin_user, - PolKitGrantConversationPromptEchoOff func_prompt_echo_off, - PolKitGrantConversationPromptEchoOn func_prompt_echo_on, - PolKitGrantConversationErrorMessage func_error_message, - PolKitGrantConversationTextInfo func_text_info, - PolKitGrantOverrideGrantType func_override_grant_type, - PolKitGrantDone func_done, - void *user_data) -{ - g_return_if_fail (polkit_grant != NULL); - g_return_if_fail (func_add_io_watch != NULL); - g_return_if_fail (func_add_child_watch != NULL); - g_return_if_fail (func_remove_watch != NULL); - g_return_if_fail (func_type != NULL); - g_return_if_fail (func_select_admin_user != NULL); - g_return_if_fail (func_prompt_echo_off != NULL); - g_return_if_fail (func_prompt_echo_on != NULL); - g_return_if_fail (func_error_message != NULL); - g_return_if_fail (func_text_info != NULL); - g_return_if_fail (func_override_grant_type != NULL); - polkit_grant->func_add_io_watch = func_add_io_watch; - polkit_grant->func_add_child_watch = func_add_child_watch; - polkit_grant->func_remove_watch = func_remove_watch; - polkit_grant->func_type = func_type; - polkit_grant->func_select_admin_user = func_select_admin_user; - polkit_grant->func_prompt_echo_off = func_prompt_echo_off; - polkit_grant->func_prompt_echo_on = func_prompt_echo_on; - polkit_grant->func_error_message = func_error_message; - polkit_grant->func_text_info = func_text_info; - polkit_grant->func_override_grant_type = func_override_grant_type; - polkit_grant->func_done = func_done; - polkit_grant->user_data = user_data; -} - - -/** - * polkit_grant_child_func: - * @polkit_grant: the object - * @pid: pid of the child - * @exit_code: exit code of the child - * - * Method that the application must call when a child process - * registered with the supplied function of type - * #PolKitGrantAddChildWatch terminates. - * - * This function is in <literal>libpolkit-grant</literal>. - **/ -void -polkit_grant_child_func (PolKitGrant *polkit_grant, pid_t pid, int exit_code) -{ - int status; - polkit_bool_t input_was_bogus; - - g_return_if_fail (polkit_grant != NULL); - g_return_if_fail (polkit_grant->helper_is_running); - - /* g_debug ("pid %d terminated", pid); */ - waitpid (pid, &status, 0); - - if (exit_code >= 2) - input_was_bogus = TRUE; - else - input_was_bogus = FALSE; - - polkit_grant->success = (exit_code == 0); - polkit_grant->helper_is_running = FALSE; - polkit_grant->func_done (polkit_grant, polkit_grant->success, input_was_bogus, polkit_grant->user_data); -} - - -/** - * polkit_grant_io_func: - * @polkit_grant: the object - * @fd: the file descriptor passed to the supplied function of type #PolKitGrantAddIOWatch. - * - * Method that the application must call when there is data to read - * from a file descriptor registered with the supplied function of - * type #PolKitGrantAddIOWatch. - * - * This function is in <literal>libpolkit-grant</literal>. - **/ -void -polkit_grant_io_func (PolKitGrant *polkit_grant, int fd) -{ - char *line = NULL; - size_t line_len = 0; - char *id; - size_t id_len; - char *response; - char *response_prefix; - - g_return_if_fail (polkit_grant != NULL); - g_return_if_fail (polkit_grant->helper_is_running); - - while (kit_getline (&line, &line_len, polkit_grant->child_stdout_f) != -1) { - if (strlen (line) > 0 && - line[strlen (line) - 1] == '\n') - line[strlen (line) - 1] = '\0'; - - response = NULL; - response_prefix = NULL; - - id = "PAM_PROMPT_ECHO_OFF "; - if (g_str_has_prefix (line, id)) { - id_len = strlen (id); - response_prefix = ""; - response = polkit_grant->func_prompt_echo_off (polkit_grant, - line + id_len, - polkit_grant->user_data); - goto processed; - } - - id = "PAM_PROMPT_ECHO_ON "; - if (g_str_has_prefix (line, id)) { - id_len = strlen (id); - response_prefix = ""; - response = polkit_grant->func_prompt_echo_on (polkit_grant, - line + id_len, - polkit_grant->user_data); - goto processed; - } - - id = "PAM_ERROR_MSG "; - if (g_str_has_prefix (line, id)) { - id_len = strlen (id); - polkit_grant->func_error_message (polkit_grant, - line + id_len, - polkit_grant->user_data); - goto processed; - } - - id = "PAM_TEXT_INFO "; - if (g_str_has_prefix (line, id)) { - id_len = strlen (id); - polkit_grant->func_text_info (polkit_grant, - line + id_len, - polkit_grant->user_data); - goto processed; - } - - id = "POLKIT_GRANT_HELPER_TELL_TYPE "; - if (g_str_has_prefix (line, id)) { - PolKitResult result; - char *result_textual; - - id_len = strlen (id); - result_textual = line + id_len; - if (!polkit_result_from_string_representation (result_textual, &result)) { - /* TODO: danger will robinson */ - } - - polkit_grant->func_type (polkit_grant, - result, - polkit_grant->user_data); - goto processed; - } - - id = "POLKIT_GRANT_HELPER_TELL_ADMIN_USERS "; - if (g_str_has_prefix (line, id)) { - char **admin_users; - - id_len = strlen (id); - admin_users = g_strsplit (line + id_len, " ", 0); - - response_prefix = "POLKIT_GRANT_CALLER_SELECT_ADMIN_USER "; - response = polkit_grant->func_select_admin_user (polkit_grant, - admin_users, - polkit_grant->user_data); - g_strfreev (admin_users); - - goto processed; - } - - id = "POLKIT_GRANT_HELPER_ASK_OVERRIDE_GRANT_TYPE "; - if (g_str_has_prefix (line, id)) { - PolKitResult override; - PolKitResult result; - id_len = strlen (id); - if (!polkit_result_from_string_representation (line + id_len, &result)) { - /* TODO: danger will robinson */ - } - override = polkit_grant->func_override_grant_type (polkit_grant, - result, - polkit_grant->user_data); - response_prefix = "POLKIT_GRANT_CALLER_PASS_OVERRIDE_GRANT_TYPE "; - response = g_strdup (polkit_result_to_string_representation (override)); - goto processed; - } - - processed: - if (response != NULL && response_prefix != NULL) { - char *buf; - gboolean add_newline; - - /* add a newline if there isn't one already... */ - add_newline = FALSE; - if (response[strlen (response) - 1] != '\n') { - add_newline = TRUE; - } - buf = g_strdup_printf ("%s%s%c", - response_prefix, - response, - add_newline ? '\n' : '\0'); - write (polkit_grant->child_stdin, buf, strlen (buf)); - g_free (buf); - free (response); - } - } - - if (line != NULL) - free (line); - - polkit_grant->func_remove_watch (polkit_grant, polkit_grant->io_watch_id); -} - -/** - * polkit_grant_cancel_auth: - * @polkit_grant: the object - * - * Cancel an authentication in progress - * - * This function is in <literal>libpolkit-grant</literal>. - **/ -void -polkit_grant_cancel_auth (PolKitGrant *polkit_grant) -{ - GPid pid; - g_return_if_fail (polkit_grant != NULL); - g_return_if_fail (polkit_grant->helper_is_running); - - pid = polkit_grant->child_pid; - polkit_grant->child_pid = 0; - if (pid > 0) { - int status; - kill (pid, SIGTERM); - waitpid (pid, &status, 0); - polkit_grant->helper_is_running = FALSE; - } - polkit_grant->func_done (polkit_grant, FALSE, FALSE, polkit_grant->user_data); -} - -/** - * polkit_grant_initiate_auth: - * @polkit_grant: the object - * @action: Action requested by caller - * @caller: Caller in question - * - * Initiate authentication to obtain the privilege for the given - * @caller to perform the specified @action. The caller of this method - * must have setup callback functions using the method - * polkit_grant_set_functions() prior to calling this method. - * - * Implementation-wise, this class uses a secure (e.g. as in that it - * checks all information and fundamenally don't trust the caller; - * e.g. the #PolKitGrant class) setgid helper that does all the heavy - * lifting. - * - * The caller of this method must iterate the mainloop context in - * order for authentication to make progress. - * - * This function is in <literal>libpolkit-grant</literal>. - * - * Returns: #TRUE only if authentication have been initiated. - **/ -polkit_bool_t -polkit_grant_initiate_auth (PolKitGrant *polkit_grant, - PolKitAction *action, - PolKitCaller *caller) -{ - pid_t pid; - char *action_id; - GError *g_error; - char *helper_argv[4]; - - g_return_val_if_fail (polkit_grant != NULL, FALSE); - /* check that callback functions have been properly set up */ - g_return_val_if_fail (polkit_grant->func_done != NULL, FALSE); - - if (!polkit_caller_get_pid (caller, &pid)) - goto error; - - if (!polkit_action_get_action_id (action, &action_id)) - goto error; - - /* TODO: verify incoming args */ - - /* helper_argv[0] = "/home/davidz/Hacking/PolicyKit/polkit-grant/.libs/polkit-grant-helper-1"; */ - helper_argv[0] = PACKAGE_LIBEXEC_DIR "/polkit-grant-helper-1"; - helper_argv[1] = g_strdup_printf ("%d", pid); - helper_argv[2] = action_id; - helper_argv[3] = NULL; - - polkit_grant->child_stdin = -1; - polkit_grant->child_stdout = -1; - - g_error = NULL; - if (!g_spawn_async_with_pipes (NULL, - (char **) helper_argv, - NULL, - G_SPAWN_DO_NOT_REAP_CHILD | - 0,//G_SPAWN_STDERR_TO_DEV_NULL, - NULL, - NULL, - &polkit_grant->child_pid, - &polkit_grant->child_stdin, - &polkit_grant->child_stdout, - NULL, - &g_error)) { - fprintf (stderr, "Cannot spawn helper: %s.\n", g_error->message); - g_error_free (g_error); - g_free (helper_argv[1]); - goto error; - } - g_free (helper_argv[1]); - - polkit_grant->child_watch_id = polkit_grant->func_add_child_watch (polkit_grant, polkit_grant->child_pid); - if (polkit_grant->child_watch_id == 0) - goto error; - - polkit_grant->io_watch_id = polkit_grant->func_add_io_watch (polkit_grant, polkit_grant->child_stdout); - if (polkit_grant->io_watch_id == 0) - goto error; - - /* so we can use getline... */ - polkit_grant->child_stdout_f = fdopen (polkit_grant->child_stdout, "r"); - if (polkit_grant->child_stdout_f == NULL) - goto error; - - polkit_grant->success = FALSE; - - polkit_grant->helper_is_running = TRUE; - - return TRUE; -error: - return FALSE; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_polkit_grant = { - "polkit_grant", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit-grant/polkit-grant.h b/src/polkit-grant/polkit-grant.h deleted file mode 100644 index 0e6e19a..0000000 --- a/src/polkit-grant/polkit-grant.h +++ /dev/null @@ -1,373 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-grant.h : library for obtaining privileges - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifndef POLKIT_GRANT_H -#define POLKIT_GRANT_H - -#include <polkit/polkit.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitGrant; -typedef struct _PolKitGrant PolKitGrant; - -/** - * PolKitGrantType: - * @polkit_grant: the grant object - * @grant_type: the current type of what privilege to obtain - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that describes to what extent the - * privilege can be obtained; e.g. whether the user can keep it - * (e.g. forever, for the session or not keep it at all). - * - * See also #PolKitGrantOverrideGrantType for discussion on the type - * of user interfaces one should put up depending on the value of - * @grant_type. - **/ -typedef void (*PolKitGrantType) (PolKitGrant *polkit_grant, - PolKitResult grant_type, - void *user_data); - -/** - * PolKitGrantSelectAdminUser: - * @polkit_grant: the grant object - * @admin_users: a NULL-terminated array of users that can be used for - * authentication for admin grants. - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that describes the possible users that - * can be chosen for authentication when administrator privileges are - * required. - * - * Returns: the chosen user; must be allocated with malloc(3) and will - * be freed by the #PolKitGrant class. - **/ -typedef char* (*PolKitGrantSelectAdminUser) (PolKitGrant *polkit_grant, - char **admin_users, - void *user_data); - - -/** - * PolKitGrantConversationPromptEchoOff: - * @polkit_grant: the grant object - * @prompt: prompt passed by the authentication layer; do not free this string - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that is invoked when the authentication - * layer needs to ask the user a secret and the UI should NOT echo what - * the user types on the screen. - * - * Returns: the answer obtained from the user; must be allocated with - * malloc(3) and will be freed by the #PolKitGrant class. - **/ -typedef char* (*PolKitGrantConversationPromptEchoOff) (PolKitGrant *polkit_grant, - const char *prompt, - void *user_data); - -/** - * PolKitGrantConversationPromptEchoOn: - * @polkit_grant: the grant object - * @prompt: prompt passed by the authentication layer; do not free this string - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that is invoked when the authentication - * layer needs to ask the user a secret and the UI should echo what - * the user types on the screen. - * - * Returns: the answer obtained from the user; must be allocated with - * malloc(3) and will be freed by the #PolKitGrant class. - **/ -typedef char* (*PolKitGrantConversationPromptEchoOn) (PolKitGrant *polkit_grant, - const char *prompt, - void *user_data); - -/** - * PolKitGrantConversationErrorMessage: - * @polkit_grant: the grant object - * @error_message: error message passed by the authentication layer; do not free this string - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that is invoked when the authentication - * layer produces an error message that should be displayed in the UI. - **/ -typedef void (*PolKitGrantConversationErrorMessage) (PolKitGrant *polkit_grant, - const char *error_message, - void *user_data); - -/** - * PolKitGrantConversationTextInfo: - * @polkit_grant: the grant object - * @text_info: information passed by the authentication layer; do not free this string - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that is invoked when the authentication - * layer produces an informational message that should be displayed in - * the UI. - **/ -typedef void (*PolKitGrantConversationTextInfo) (PolKitGrant *polkit_grant, - const char *text_info, - void *user_data); - -/** - * PolKitGrantOverrideGrantType: - * @polkit_grant: the grant object - * @grant_type: the current type of what privilege to obtain; this is - * the same value as passed to the callback of type #PolKitGrantType. - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * Type for callback function that enables the UI to request a lesser - * privilege than is obtainable. This callback is invoked when the - * user have successfully authenticated but before the privilege is - * granted. - * - * Basically, this callback enables a program to provide an user - * interface like this: - * - * <programlisting> - * +------------------------------------------------------------+ - * | You need to authenticate to access the volume 'Frobnicator | - * | Adventures Vol 2' | - * | | - * | Password: [_________________] | - * | | - * [ [x] Remember this decision | - * | [ ] for this session | - * | [*] for this and future sessions | - * | | - * | [Cancel] [Authenticate] | - * +------------------------------------------------------------+ - * </programlisting> - * - * This dialog assumes that @grant_type passed was - * #POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS. By ticking the - * check boxes in the dialog, the user can override this to either - * #POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION or - * #POLKIT_RESULT_ONLY_VIA_SELF_AUTH. Thus, the user can - * voluntarily choose to obtain a lesser privilege. - * - * Another example, would be that the @grant_type passed was - * #POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION. Then the dialog - * should look like this: - * - * <programlisting> - * +------------------------------------------------------------+ - * | You need to authenticate to access the volume 'Frobnicator | - * | Adventures Vol 2' | - * | | - * | Password: [_________________] | - * | | - * [ [x] Remember this decision for the rest of the session | - * | | - * | [Cancel] [Authenticate] | - * +------------------------------------------------------------+ - * </programlisting> - * - * Finally, if the @grant_type value passed is - * e.g. #POLKIT_RESULT_ONLY_VIA_SELF_AUTH, there are no options to - * click.: - * - * <programlisting> - * +------------------------------------------------------------+ - * | You need to authenticate to access the volume 'Frobnicator | - * | Adventures Vol 2' | - * | | - * | Password: [_________________] | - * | | - * | [Cancel] [Authenticate] | - * +------------------------------------------------------------+ - * </programlisting> - * - * Of course, these examples also applies to - * #POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH and friends. - * - * Returns: the desired type of what privilege to obtain; note that it - * won't work asking for more privileges than what @grant_type - * specifies; the passed value is properly checked in the secure - * setgid granting helper mentioned in - * polkit_grant_initiate_auth(). - **/ -typedef PolKitResult (*PolKitGrantOverrideGrantType) (PolKitGrant *polkit_grant, - PolKitResult grant_type, - void *user_data); - -/** - * PolKitGrantDone: - * @polkit_grant: the grant object - * @gained_privilege: whether the privilege was obtained - * @invalid_data: whether the input data was bogus (not including bad passwords) - * @user_data: user data pointed as passed into polkit_grant_set_functions() - * - * This function is called when the granting process ends; either if - * successful or if it was canceled using - * e.g. polkit_grant_cancel_auth(). - **/ -typedef void (*PolKitGrantDone) (PolKitGrant *polkit_grant, - polkit_bool_t gained_privilege, - polkit_bool_t invalid_data, - void *user_data); - -/** - * PolKitGrantAddChildWatch: - * @polkit_grant: the grant object - * @pid: the child pid to watch - * - * Type for function supplied by the application to integrate a watch - * on a child process into the applications main loop. The - * application must call polkit_grant_child_func() when the - * child dies - * - * For glib mainloop, the function will typically look like this: - * - * <programlisting> - * static void - * child_watch_func (GPid pid, - * gint status, - * gpointer user_data) - * { - * PolKitGrant *polkit_grant = user_data; - * polkit_grant_child_func (polkit_grant, pid, WEXITSTATUS (status)); - * } - * - * static int - * add_child_watch (PolKitGrant *polkit_grant, pid_t pid) - * { - * return g_child_watch_add (pid, child_watch_func, polkit_grant); - * } - * </programlisting> - * - * Returns: 0 if the watch couldn't be set up; otherwise an unique - * identifier for the watch. - **/ -typedef int (*PolKitGrantAddChildWatch) (PolKitGrant *polkit_grant, - pid_t pid); - -/** - * PolKitGrantAddIOWatch: - * @polkit_grant: the grant object - * @fd: the file descriptor to watch - * - * Type for function supplied by the application to integrate a watch - * on a file descriptor into the applications main loop. The - * application must call polkit_grant_io_func() when there is data - * to read from the file descriptor. - * - * For glib mainloop, the function will typically look like this: - * - * <programlisting> - * static gboolean - * io_watch_have_data (GIOChannel *channel, GIOCondition condition, gpointer user_data) - * { - * int fd; - * PolKitGrant *polkit_grant = user_data; - * fd = g_io_channel_unix_get_fd (channel); - * polkit_grant_io_func (polkit_grant, fd); - * return TRUE; - * } - * - * static int - * add_io_watch (PolKitGrant *polkit_grant, int fd) - * { - * guint id = 0; - * GIOChannel *channel; - * channel = g_io_channel_unix_new (fd); - * if (channel == NULL) - * goto out; - * id = g_io_add_watch (channel, G_IO_IN, io_watch_have_data, polkit_grant); - * if (id == 0) { - * g_io_channel_unref (channel); - * goto out; - * } - * g_io_channel_unref (channel); - * out: - * return id; - * } - * </programlisting> - * - * Returns: 0 if the watch couldn't be set up; otherwise an unique - * identifier for the watch. - **/ -typedef int (*PolKitGrantAddIOWatch) (PolKitGrant *polkit_grant, - int fd); - -/** - * PolKitGrantRemoveWatch: - * @polkit_grant: the grant object - * @watch_id: the id obtained from using the supplied function - * of type #PolKitGrantAddIOWatch or #PolKitGrantAddChildWatch. - * - * Type for function supplied by the application to remove a watch set - * up via the supplied function of type #PolKitGrantAddIOWatch or type - * #PolKitGrantAddChildWatch. - * - * For glib mainloop, the function will typically look like this: - * - * <programlisting> - * static void - * remove_watch (PolKitGrant *polkit_auth, int watch_id) - * { - * g_source_remove (watch_id); - * } - * </programlisting> - * - **/ -typedef void (*PolKitGrantRemoveWatch) (PolKitGrant *polkit_grant, - int watch_id); - -PolKitGrant *polkit_grant_new (void); -PolKitGrant *polkit_grant_ref (PolKitGrant *polkit_grant); -void polkit_grant_unref (PolKitGrant *polkit_grant); -void polkit_grant_set_functions (PolKitGrant *polkit_grant, - PolKitGrantAddIOWatch func_add_io_watch, - PolKitGrantAddChildWatch func_add_child_watch, - PolKitGrantRemoveWatch func_remove_watch, - PolKitGrantType func_type, - PolKitGrantSelectAdminUser func_select_admin_user, - PolKitGrantConversationPromptEchoOff func_prompt_echo_off, - PolKitGrantConversationPromptEchoOn func_prompt_echo_on, - PolKitGrantConversationErrorMessage func_error_message, - PolKitGrantConversationTextInfo func_text_info, - PolKitGrantOverrideGrantType func_override_grant_type, - PolKitGrantDone func_done, - void *user_data); - -polkit_bool_t polkit_grant_initiate_auth (PolKitGrant *polkit_grant, - PolKitAction *action, - PolKitCaller *caller); - -void polkit_grant_cancel_auth (PolKitGrant *polkit_grant); - -void polkit_grant_io_func (PolKitGrant *polkit_grant, int fd); -void polkit_grant_child_func (PolKitGrant *polkit_grant, pid_t pid, int exit_code); - -POLKIT_END_DECLS - -#endif /* POLKIT_GRANT_H */ - - diff --git a/src/polkit-grant/polkit-revoke-helper.c b/src/polkit-grant/polkit-revoke-helper.c deleted file mode 100644 index 3b79813..0000000 --- a/src/polkit-grant/polkit-revoke-helper.c +++ /dev/null @@ -1,362 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-revoke-helper.c : setgid polkituser revoke helper for PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/time.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> -#include <fcntl.h> - -#include <polkit/polkit.h> -#include <polkit/polkit-private.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#endif - -static int -_write_to_fd (int fd, const char *str, ssize_t str_len) -{ - int ret; - ssize_t written; - - ret = 0; - - written = 0; - while (written < str_len) { - ssize_t ret; - ret = write (fd, str + written, str_len - written); - if (ret < 0) { - if (errno == EAGAIN || errno == EINTR) { - continue; - } else { - goto out; - } - } - written += ret; - } - - ret = 1; - -out: - return ret; -} - -int -main (int argc, char *argv[]) -{ - int ret; - gid_t egid; - struct group *group; - uid_t invoking_uid; - char *entry_to_remove; - char *scope; - uid_t uid_to_revoke; - char *endp; - FILE *f; - int fd; - char path[256]; - char path_tmp[256]; - char line[512]; - char *root; - char *target_type; - char *target_value; - struct passwd *pw; - polkit_bool_t is_one_shot; - polkit_bool_t not_granted_by_self; - char **tokens; - size_t num_tokens; - - ret = 1; - -#ifndef POLKIT_BUILD_TESTS - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); -#endif - - openlog ("polkit-revoke-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 4) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-revoke-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-revoke-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - - invoking_uid = getuid (); - - /* check that we are setgid polkituser */ -#ifdef POLKIT_BUILD_TESTS - char *pretend; - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_UID")) != NULL) { - invoking_uid = atoi (pretend); - goto skip_check; - } -#endif - egid = getegid (); - group = getgrgid (egid); - if (group == NULL) { - fprintf (stderr, "polkit-revoke-helper: cannot lookup group info for gid %d\n", egid); - goto out; - } - if (strcmp (group->gr_name, POLKIT_GROUP) != 0) { - fprintf (stderr, "polkit-revoke-helper: needs to be setgid " POLKIT_GROUP "\n"); - goto out; - } -#ifdef POLKIT_BUILD_TESTS -skip_check: -#endif - - entry_to_remove = argv[1]; - target_type = argv[2]; - target_value = argv[3]; - - /*----------------------------------------------------------------------------------------------------*/ - - /* paranoia: we have to validate the entry_to_remove argument - * and determine if the process who invoked us is sufficiently - * privileged. - * - * As we're setuid root we don't want to pull in libpolkit and - * as we only need to parse the first two entries... we do it - * right here - */ - - tokens = kit_strsplit (entry_to_remove, ':', &num_tokens); - if (tokens == NULL || num_tokens < 2) { - fprintf (stderr, "polkit-revoke-helper: entry_to_remove malformed\n"); - goto out; - } - - scope = tokens[0]; - - if (strcmp (target_type, "uid") == 0) { - uid_to_revoke = strtol (target_value, &endp, 10); - if (*endp != '\0') { - fprintf (stderr, "polkit-revoke-helper: cannot parse uid\n"); - goto out; - } - } else { - fprintf (stderr, "polkit-revoke-helper: unknown target type\n"); - goto out; - } - - /* OK, we're done parsing ... */ - - not_granted_by_self = FALSE; - -#ifdef POLKIT_BUILD_TESTS - char *test_dir; - char dir_run[256]; - char dir_lib[256]; - - if ((test_dir = getenv ("POLKIT_TEST_LOCALSTATE_DIR")) == NULL) { - test_dir = PACKAGE_LOCALSTATE_DIR; - } - kit_assert ((size_t) snprintf (dir_run, sizeof (dir_run), "%s/run/polkit-1", test_dir) < sizeof (dir_run)); - kit_assert ((size_t) snprintf (dir_lib, sizeof (dir_lib), "%s/lib/polkit-1", test_dir) < sizeof (dir_lib)); - -#else - char *dir_run = PACKAGE_LOCALSTATE_DIR "/run/polkit-1"; - char *dir_lib = PACKAGE_LOCALSTATE_DIR "/lib/polkit-1"; -#endif - - - is_one_shot = FALSE; - if (strcmp (scope, "scope=process") == 0) { - root = dir_run; - } else if (strcmp (scope, "scope=process-one-shot") == 0) { - root = dir_run; - is_one_shot = TRUE; - } else if (strcmp (scope, "scope=session") == 0) { - root = dir_run; - } else if (strcmp (scope, "scope=always") == 0) { - root = dir_lib; - } else if (strcmp (scope, "scope=grant") == 0 || - strcmp (scope, "scope=grant-negative") == 0) { - unsigned int n; - - root = dir_lib; - - for (n = 1; n < num_tokens; n++) { - if (strncmp (tokens[n], "granted-by=", sizeof ("granted-by=") - 1) == 0) { - uid_t granted_by; - granted_by = strtol (tokens[n] + sizeof ("granted-by=") - 1, &endp, 10); - if (*endp != '\0') { - fprintf (stderr, "polkit-revoke-helper: cannot parse granted-by uid\n"); - goto out; - } - - if (granted_by != invoking_uid) - not_granted_by_self = TRUE; - - goto parsed_granted_by; - } - } - - fprintf (stderr, "polkit-revoke-helper: cannot find key granted-by\n"); - - goto out; - parsed_granted_by: - ; - } else { - fprintf (stderr, "polkit-revoke-helper: unknown scope '%s'\n", scope); - goto out; - } - - - if (invoking_uid != 0) { - /* Check that the caller is privileged to do this... basically, callers can only - * revoke auths granted by themselves... - */ - if (not_granted_by_self) { - pid_t ppid; - - ppid = getppid (); - if (ppid == 1) - goto out; - - if (polkit_check_auth (ppid, "org.freedesktop.policykit.revoke", NULL) == 0) { - goto out; - } - } - } - - pw = kit_getpwuid (uid_to_revoke); - if (pw == NULL) { - fprintf (stderr, "polkit-revoke-helper: cannot lookup user name for uid %d\n", uid_to_revoke); - goto out; - } - - if (snprintf (path, sizeof (path), "%s/user-%s.auths", root, pw->pw_name) >= (int) sizeof (path)) { - fprintf (stderr, "polkit-revoke-helper: string was truncated (1)\n"); - goto out; - } - if (snprintf (path_tmp, sizeof (path_tmp), "%s/user-%s.auths.XXXXXX", root, pw->pw_name) >= (int) sizeof (path)) { - fprintf (stderr, "polkit-revoke-helper: string was truncated (2)\n"); - goto out; - } - - f = fopen (path, "r"); - if (f == NULL) { - fprintf (stderr, "Cannot open file '%s': %m\n", path); - goto out; - } - - fd = mkstemp (path_tmp); - if (fd < 0) { - fprintf (stderr, "Cannot create file '%s': %m\n", path_tmp); - goto out; - } - if (fchmod (fd, 0464) != 0) { - fprintf (stderr, "Cannot change mode for '%s' to 0460: %m\n", path_tmp); - close (fd); - unlink (path_tmp); - goto out; - } - - - /* read one line at a time */ - while (fgets (line, sizeof (line), f) != NULL) { - size_t line_len; - - line_len = strlen (line); - if (line_len > 1 && line[line_len - 1] == '\n') { - if (strncmp (line, entry_to_remove, line_len - 1) == 0) { - /* woho, found it */ - continue; - } - } - - /* otherwise, just write the line to the temporary file */ - if (!_write_to_fd (fd, line, line_len)) { - fprintf (stderr, "Error write to file '%s': %m\n", path_tmp); - close (fd); - unlink (path_tmp); - goto out; - } - } - - fclose (f); - close (fd); - - if (rename (path_tmp, path) != 0) { - fprintf (stderr, "Error renaming %s to %s: %m\n", path_tmp, path); - unlink (path_tmp); - goto out; - } - - /* we're good now (if triggering a reload fails, so be it, we - * still did what the caller asked...) - */ - ret = 0; - -#ifdef POLKIT_BUILD_TESTS - if (test_dir != NULL) - goto no_reload; -#endif - /* trigger a reload */ - if (utimes (PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload", NULL) != 0) { - fprintf (stderr, "Error updating access+modification time on file '%s': %m\n", - PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload"); - } -#ifdef POLKIT_BUILD_TESTS -no_reload: -#endif - -out: - - return ret; -} - diff --git a/src/polkit/.gitignore b/src/polkit/.gitignore deleted file mode 100644 index 764d994..0000000 --- a/src/polkit/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.deps -.libs -*.la -*.lo -*.o -Makefile -Makefile.in -polkit-interface-manager-glue.h -polkit-interface-session-glue.h diff --git a/src/polkit/Makefile.am b/src/polkit/Makefile.am deleted file mode 100644 index ad07c9e..0000000 --- a/src/polkit/Makefile.am +++ /dev/null @@ -1,190 +0,0 @@ -## Process this file with automake to produce Makefile.in - -INCLUDES = \ - -I$(top_builddir)/src -I$(top_srcdir)/src \ - -DPACKAGE_LIBEXEC_DIR=\""$(libexecdir)"\" \ - -DPACKAGE_SYSCONF_DIR=\""$(sysconfdir)"\" \ - -DPACKAGE_DATA_DIR=\""$(datadir)"\" \ - -DPACKAGE_BIN_DIR=\""$(bindir)"\" \ - -DPACKAGE_LOCALSTATE_DIR=\""$(localstatedir)"\" \ - -DPACKAGE_LOCALE_DIR=\""$(localedir)"\" \ - -DPACKAGE_LIB_DIR=\""$(libdir)"\" \ - -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT \ - -DPOLKIT_COMPILATION \ - -DTEST_DATA_DIR=\"$(top_srcdir)/test/\" \ - -DTEST_BUILD_DIR=\"$(top_builddir)\" \ - @DBUS_CFLAGS@ - - -lib_LTLIBRARIES=libpolkit-1.la - -libpolkit_1includedir=$(includedir)/polkit-1/polkit - -libpolkit_1include_HEADERS = \ - polkit.h \ - polkit-sysdeps.h \ - polkit-types.h \ - polkit-error.h \ - polkit-result.h \ - polkit-context.h \ - polkit-action.h \ - polkit-seat.h \ - polkit-session.h \ - polkit-caller.h \ - polkit-action-description.h \ - polkit-implicit-authorization.h \ - polkit-authorization.h \ - polkit-authorization-constraint.h \ - polkit-authorization-db.h \ - polkit-tracker.h \ - polkit-simple.h - -libpolkit_1_la_SOURCES = \ - polkit.h \ - polkit-private.h \ - polkit-types.h \ - polkit-sysdeps.h polkit-sysdeps.c \ - polkit-error.h polkit-error.c \ - polkit-result.h polkit-result.c \ - polkit-context.h polkit-context.c \ - polkit-action.h polkit-action.c \ - polkit-seat.h polkit-seat.c \ - polkit-session.h polkit-session.c \ - polkit-caller.h polkit-caller.c \ - polkit-action-description.h polkit-action-description.c \ - polkit-implicit-authorization.h polkit-implicit-authorization.c \ - polkit-debug.h polkit-debug.c \ - polkit-utils.h polkit-utils.c \ - polkit-authorization.h polkit-authorization.c \ - polkit-authorization-constraint.h polkit-authorization-constraint.c \ - polkit-authorization-db.h \ - polkit-tracker.h polkit-tracker.c \ - polkit-simple.h polkit-simple.c - -if POLKIT_AUTHDB_DUMMY -libpolkit_1_la_SOURCES += \ - polkit-authorization-db-dummy.c -endif - -if POLKIT_AUTHDB_DEFAULT -libpolkit_1_la_SOURCES += \ - polkit-authorization-db.c -endif - -libpolkit_1_la_LIBADD = @DBUS_LIBS@ @EXPAT_LIBS@ $(top_builddir)/src/kit/libkit.la $(SELINUX_LIBS) - -if POLKIT_BUILD_TESTS -libpolkit_1_la_LDFLAGS = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) @R_DYNAMIC_LDFLAG@ -else -libpolkit_1_la_LDFLAGS = -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE) @R_DYNAMIC_LDFLAG@ \ - -export-dynamic -no-undefined -export-symbols-regex '(^polkit_.*|_pk_validate_unique_bus_name)' -endif - -## note that TESTS has special meaning (stuff to use in make check) -## so if adding tests not to be run in make check, don't add them to -## TESTS -if POLKIT_BUILD_TESTS -TESTS_ENVIRONMENT= -TESTS=polkit-test - -check_PROGRAMS=$(TESTS) - -polkit_test_SOURCES= \ - polkit-test.h polkit-test.c - -polkit_test_LDADD=$(top_builddir)/src/kit/libkit.la $(top_builddir)/src/polkit/libpolkit-1.la -polkit_test_LDFLAGS= - -if POLKIT_GCOV_ENABLED -clean-gcov: - rm -f *.gcov .libs/*.gcda *.gcda - -.PHONY: coverage-report.txt covered-files.txt - -covered-files.txt : - echo $(addprefix src/polkit/,$(filter %.c,$(libpolkit_1_la_SOURCES))) > covered-files.txt - -coverage-report.txt : covered-files.txt clean-gcov all check - gcov $(filter %.c,$(libpolkit_1_la_SOURCES)) -o .libs/ > /dev/null - $(top_srcdir)/test/create-coverage-report.sh "module polkit" `cat covered-files.txt` > coverage-report.txt - -check-coverage : coverage-report.txt - cat coverage-report.txt -else -coverage-report.txt: - @echo "Need to reconfigure with --enable-gcov" - -check-coverage: - @echo "Need to reconfigure with --enable-gcov" -endif - -else -TESTS= -endif - -clean-local : - rm -f *~ $(BUILT_SOURCES) *.bb *.bbg *.da *.gcov .libs/*.da .libs/*.bbg - -libexec_PROGRAMS = polkit-resolve-exe-helper-1 - -polkit_resolve_exe_helper_1_SOURCES = polkit-resolve-exe-helper.c -polkit_resolve_exe_helper_1_CFLAGS = @DBUS_CFLAGS@ -polkit_resolve_exe_helper_1_LDADD = $(top_builddir)/src/kit/libkit.la libpolkit-1.la - -if POLKIT_AUTHDB_DEFAULT -libexec_PROGRAMS += polkit-read-auth-helper-1 polkit-set-default-helper-1 - -polkit_read_auth_helper_1_SOURCES = polkit-read-auth-helper.c -polkit_read_auth_helper_1_CFLAGS = @DBUS_CFLAGS@ -polkit_read_auth_helper_1_LDADD = $(top_builddir)/src/kit/libkit.la libpolkit-1.la - -polkit_set_default_helper_1_SOURCES = polkit-set-default-helper.c -polkit_set_default_helper_1_CFLAGS = @DBUS_CFLAGS@ -polkit_set_default_helper_1_LDADD = $(top_builddir)/src/kit/libkit.la libpolkit-1.la - -# The directories /var/lib/polkit-1 and /var/run/polkit-1 is where -# authorizations are stored. They must not be world readable (the -# polkit-auth-read-helper is used to read it) and the $POLKIT_GROUP -# group needs to be able to write files there. -# -# The directory /var/lib/polkit-public-1 is used for storing world-readable -# information. Only $POLKIT_USER may write to it. -# -# The /var/lib/misc/polkit-1.reload file is used for triggering that -# authorizations have changed; it needs to be world readable and -# writeable for user $POLKIT_USER and group $POLKIT_GROUP (FHS 2.3 suggests -# that location) -# -# polkit-read-auth-helper needs to be setgid $POLKIT_GROUP to be able -# to read authorization files in /var/lib/polkit-1 and -# /var/run/polkit-1 -# -# polkit-set-default-helper needs to be setuid $POLKIT_USER to be able -# to write .defaults-override files in /var/lib/polkit-public-1 -# -# polkit-resolve-exe-helper needs to be setuid root to be able to resolve -# /proc/$pid/exe symlinks. -# -install-exec-hook: - mkdir -p $(DESTDIR)$(localstatedir)/lib/misc - touch $(DESTDIR)$(localstatedir)/lib/misc/polkit-1.reload - -chown $(POLKIT_USER):$(POLKIT_GROUP) $(DESTDIR)$(localstatedir)/lib/misc/polkit-1.reload - -chmod 664 $(DESTDIR)$(localstatedir)/lib/misc/polkit-1.reload - mkdir -p $(DESTDIR)$(localstatedir)/lib/polkit-public-1 - mkdir -p $(DESTDIR)$(localstatedir)/lib/polkit-1 - mkdir -p $(DESTDIR)$(localstatedir)/run/polkit-1 - -chown $(POLKIT_USER) $(DESTDIR)$(localstatedir)/lib/polkit-public-1 - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(localstatedir)/lib/polkit-1 - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(localstatedir)/run/polkit-1 - -chmod 755 $(DESTDIR)$(localstatedir)/lib/polkit-public-1 - -chmod 770 $(DESTDIR)$(localstatedir)/lib/polkit-1 - -chmod 770 $(DESTDIR)$(localstatedir)/run/polkit-1 - -chgrp $(POLKIT_GROUP) $(DESTDIR)$(libexecdir)/polkit-read-auth-helper-1 - -chmod 2755 $(DESTDIR)$(libexecdir)/polkit-read-auth-helper-1 - -chown $(POLKIT_USER) $(DESTDIR)$(libexecdir)/polkit-set-default-helper-1 - -chmod 4755 $(DESTDIR)$(libexecdir)/polkit-set-default-helper-1 - -chmod 4755 $(DESTDIR)$(libexecdir)/polkit-resolve-exe-helper-1 -else -install-exec-hook: - -chmod 4755 $(DESTDIR)$(libexecdir)/polkit-resolve-exe-helper -endif diff --git a/src/polkit/polkit-action-description.c b/src/polkit/polkit-action-description.c deleted file mode 100644 index 7f26ee8..0000000 --- a/src/polkit/polkit-action-description.c +++ /dev/null @@ -1,1398 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-action-description.c : Description of an action - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-error.h" -#include "polkit-result.h" -#include "polkit-action-description.h" -#include "polkit-authorization-db.h" -#include "polkit-private.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-action-description - * @title: Action Description - * @short_description: Represents a declared action in a policy file. - * - * This class is used to represent a entries in policy files. - **/ - -/** - * PolKitActionDescription: - * - * Objects of this class are used to record information about a - * policy. - **/ -struct _PolKitActionDescription -{ - int refcount; - char *action; - PolKitImplicitAuthorization *implicit_authorization_factory; - PolKitImplicitAuthorization *implicit_authorization; - - char *policy_description; - char *policy_message; - char *vendor; - char *vendor_url; - char *icon_name; - KitHash *annotations; -}; - - -/* NOTE: we take ownership of the annotations object */ -PolKitActionDescription * -_polkit_action_description_new (const char *action_id, - const char *vendor, - const char *vendor_url, - const char *icon_name, - PolKitResult implicit_authorization_allow_any, - PolKitResult implicit_authorization_allow_inactive, - PolKitResult implicit_authorization_allow_active, - KitHash *annotations) -{ - char *path; - char *contents; - size_t contents_size; - PolKitActionDescription *pfe; - - path = NULL; - contents = NULL; - - kit_return_val_if_fail (action_id != NULL && polkit_action_validate_id (action_id), NULL); - - pfe = kit_new0 (PolKitActionDescription, 1); - if (pfe == NULL) - goto error; - pfe->refcount = 1; - pfe->action = kit_strdup (action_id); - if (pfe->action == NULL) - goto error; - - pfe->vendor = NULL; - pfe->vendor_url = NULL; - pfe->icon_name = NULL; - if (vendor != NULL && (pfe->vendor = kit_strdup (vendor)) == NULL) - goto error; - if (vendor_url != NULL && (pfe->vendor_url = kit_strdup (vendor_url)) == NULL) - goto error; - if (icon_name != NULL && (pfe->icon_name = kit_strdup (icon_name)) == NULL) - goto error; - - if (! (polkit_authorization_db_get_capabilities () & POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN)) { - /* if we don't support obtaining authorizations - * through authenticating, then make the implicit_authorization - * reflect this ...*/ - implicit_authorization_allow_any = POLKIT_RESULT_NO; - implicit_authorization_allow_inactive = POLKIT_RESULT_NO; - implicit_authorization_allow_active = POLKIT_RESULT_NO; - } - - pfe->implicit_authorization_factory = _polkit_implicit_authorization_new (implicit_authorization_allow_any, - implicit_authorization_allow_inactive, - implicit_authorization_allow_active); - if (pfe->implicit_authorization_factory == NULL) - goto error; - - pfe->implicit_authorization = polkit_implicit_authorization_clone (pfe->implicit_authorization_factory); - if (pfe->implicit_authorization == NULL) - goto error; - -#ifdef POLKIT_AUTHDB_DEFAULT - /* read override file */ - path = kit_strdup_printf (PACKAGE_LOCALSTATE_DIR "/lib/polkit-public-1/%s.defaults-override", action_id); - if (path == NULL) - goto error; - if (!kit_file_get_contents (path, &contents, &contents_size)) { - /* it's not a failure if the file doesn't exist */ - if (errno != ENOENT) - goto error; - - errno = 0; - contents = NULL; - } - - if (contents != NULL) { - char **tokens; - size_t num_tokens; - PolKitResult any; - PolKitResult inactive; - PolKitResult active; - - tokens = kit_strsplit (contents, ':', &num_tokens); - if (num_tokens != 3) - goto error; - - if (!polkit_result_from_string_representation (tokens[0], &any)) { - goto error; - } - if (!polkit_result_from_string_representation (tokens[1], &inactive)) { - goto error; - } - if (!polkit_result_from_string_representation (tokens[2], &active)) { - goto error; - } - - polkit_implicit_authorization_set_allow_any (pfe->implicit_authorization, any); - polkit_implicit_authorization_set_allow_inactive (pfe->implicit_authorization, inactive); - polkit_implicit_authorization_set_allow_active (pfe->implicit_authorization, active); - } -#endif - - pfe->annotations = annotations; - - kit_free (path); - kit_free (contents); - - return pfe; -error: - kit_free (path); - kit_free (contents); - if (pfe != NULL) - polkit_action_description_unref (pfe); - return NULL; -} - -polkit_bool_t -_polkit_action_description_set_descriptions (PolKitActionDescription *pfe, - const char *policy_description, - const char *policy_message) -{ - kit_return_val_if_fail (pfe != NULL, FALSE); - - if (pfe->policy_description != NULL) - kit_free (pfe->policy_description); - if (pfe->policy_message != NULL) - kit_free (pfe->policy_message); - - pfe->policy_description = kit_strdup (policy_description); - pfe->policy_message = kit_strdup (policy_message); - - if (policy_description != NULL && pfe->policy_description == NULL) - return FALSE; - - if (policy_message != NULL && pfe->policy_message == NULL) - return FALSE; - - return TRUE; -} - -/** - * polkit_action_description_get_action_description: - * @action_description: the object - * - * Get the description of the action that this policy entry describes. This - * is intended to be used in policy editors, for example "Mount internal - * volumes". Contrast with polkit_action_description_get_action_message(). The - * textual string will be returned in the current locale. - * - * Note, if polkit_context_set_load_descriptions() on the - * #PolKitContext object used to get this object wasn't called, this - * method will return #NULL. - * - * Returns: string or #NULL if descriptions are not loaded - caller shall not free this string - **/ -const char * -polkit_action_description_get_action_description (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->policy_description; -} - -/** - * polkit_action_description_get_action_message: - * @action_description: the object - * - * Get the message describing the action that this policy entry - * describes. This is to be used in dialogs, for example "System - * Policy prevents mounting this volume". Contrast with - * polkit_action_description_get_action_description(). The textual string - * will be returned in the current locale. - * - * Note, if polkit_context_set_load_descriptions() on the - * #PolKitContext object used to get this object wasn't called, this - * method will return #NULL. - * - * Returns: string or #NULL if descriptions are not loaded - caller shall not free this string - **/ -const char * -polkit_action_description_get_action_message (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->policy_message; -} - -/** - * polkit_action_description_get_action_vendor: - * @action_description: the object - * - * Get the name of the vendor of this action. - * - * Note, if polkit_context_set_load_descriptions() on the - * #PolKitContext object used to get this object wasn't called, this - * method will return #NULL. - * - * Returns: string or #NULL if descriptions are not loaded or vendor - * tag isn't set - caller shall not free this string - * - * Since: 0.7 - */ -const char * -polkit_action_description_get_action_vendor (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->vendor; -} - -/** - * polkit_action_description_get_action_vendor_url: - * @action_description: the object - * - * Get the URL of the vendor of this action. - * - * Note, if polkit_context_set_load_descriptions() on the - * #PolKitContext object used to get this object wasn't called, this - * method will return #NULL. - * - * Returns: string or #NULL if descriptions are not loaded or vendor - * url isn't set - caller shall not free this string - * - * Since: 0.7 - */ -const char * -polkit_action_description_get_action_vendor_url (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->vendor_url; -} - -/** - * polkit_action_description_get_action_icon_name: - * @action_description: the object - * - * Get the name of the icon that represents the action. This name - * conforms to the freedesktop.org icon naming specification. - * - * Note, if polkit_context_set_load_descriptions() on the - * #PolKitContext object used to get this object wasn't called, this - * method will return #NULL. - * - * Returns: string or #NULL if descriptions are not loaded or icon - * tag isn't set - caller shall not free this string - * - * Since: 0.7 - */ -const char * -polkit_action_description_get_action_icon_name (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->icon_name; -} - - -/** - * polkit_action_description_ref: - * @action_description: the policy file object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitActionDescription * -polkit_action_description_ref (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, action_description); - action_description->refcount++; - return action_description; -} - -/** - * polkit_action_description_unref: - * @action_description: the policy file object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_action_description_unref (PolKitActionDescription *action_description) -{ - kit_return_if_fail (action_description != NULL); - action_description->refcount--; - if (action_description->refcount > 0) - return; - - kit_free (action_description->action); - - if (action_description->implicit_authorization_factory != NULL) - polkit_implicit_authorization_unref (action_description->implicit_authorization_factory); - - if (action_description->implicit_authorization != NULL) - polkit_implicit_authorization_unref (action_description->implicit_authorization); - - if (action_description->annotations != NULL) - kit_hash_unref (action_description->annotations); - - kit_free (action_description->policy_description); - kit_free (action_description->policy_message); - kit_free (action_description->vendor); - kit_free (action_description->vendor_url); - kit_free (action_description->icon_name); - - kit_free (action_description); -} - -/** - * polkit_action_description_debug: - * @action_description: the entry - * - * Print debug information about object - **/ -void -polkit_action_description_debug (PolKitActionDescription *action_description) -{ - kit_return_if_fail (action_description != NULL); - polkit_debug ("PolKitActionDescription: refcount=%d action=%s", - action_description->refcount, - action_description->action); - polkit_implicit_authorization_debug (action_description->implicit_authorization); -} - -/** - * polkit_action_description_get_id: - * @action_description: the file entry - * - * Get the action identifier. - * - * Returns: A string - caller shall not free this string. - **/ -const char * -polkit_action_description_get_id (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->action; -} - -/** - * polkit_action_description_get_implicit_authorization: - * @action_description: the file entry - * - * Get the the default policy for this policy. - * - * Returns: A #PolKitImplicitAuthorization object - caller shall not unref or modify this object. - **/ -PolKitImplicitAuthorization * -polkit_action_description_get_implicit_authorization (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->implicit_authorization; -} - -/** - * polkit_action_description_get_implicit_authorization_factory: - * @action_description: the file entry - * - * Get the factory defaults for the entry. This may be different that - * what polkit_action_description_get_implicit_authorization() returns if the function - * polkit_action_description_set_implicit_authorization() have been used to change the - * defaults. - * - * Returns: A #PolKitImplicitAuthorization object - caller shall not unref or modify this object. - * - * Since: 0.7 - */ -PolKitImplicitAuthorization * -polkit_action_description_get_implicit_authorization_factory (PolKitActionDescription *action_description) -{ - kit_return_val_if_fail (action_description != NULL, NULL); - return action_description->implicit_authorization_factory; -} - -/** - * polkit_action_description_set_implicit_authorization: - * @action_description: the file entry - * @implicit_authorization: the new defaults to set - * @error: return location for error or #NULL - * - * Set new defaults for a given policy file entry; subsequent calls to - * polkit_policy_file_get_default() will return these values. Note - * that the old defaults are not modified; they are still available via - * polkit_action_description_get_default_factory(). - * - * This operation requires the - * org.freedesktop.policykit.modify-defaults authorization and will - * fail if the caller lacks it. - * - * Returns: %TRUE if the given defaults was set; %FALSE if @error is set. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_action_description_set_implicit_authorization (PolKitActionDescription *action_description, - PolKitImplicitAuthorization *implicit_authorization, - PolKitError **error) -{ - polkit_bool_t ret; - - ret = FALSE; - - kit_return_val_if_fail (action_description != NULL, FALSE); - kit_return_val_if_fail (implicit_authorization != NULL, FALSE); - -#ifndef POLKIT_AUTHDB_DEFAULT - polkit_error_set_error (error, POLKIT_ERROR_NOT_SUPPORTED, "Not supported"); -#else - char *helper_argv[7] = {PACKAGE_LIBEXEC_DIR "/polkit-set-default-helper-1", - NULL, /* arg1: action_id */ - NULL, /* arg2: "clear" or "set" */ - NULL, /* arg3: result_any */ - NULL, /* arg4: result_inactive */ - NULL, /* arg5: result_active */ - NULL}; - int exit_status; - PolKitResult any; - PolKitResult inactive; - PolKitResult active; - - if (polkit_implicit_authorization_equals (action_description->implicit_authorization, implicit_authorization)) { - /* no point in doing extra work.. */ - ret = TRUE; - goto out; - } - - any = polkit_implicit_authorization_get_allow_any (implicit_authorization); - inactive = polkit_implicit_authorization_get_allow_inactive (implicit_authorization); - active = polkit_implicit_authorization_get_allow_active (implicit_authorization); - - helper_argv[1] = action_description->action; - - if (polkit_implicit_authorization_equals (action_description->implicit_authorization_factory, implicit_authorization)) { - helper_argv[2] = "clear"; - helper_argv[3] = NULL; - } else { - helper_argv[2] = "set"; - helper_argv[3] = (char *) polkit_result_to_string_representation (any); - helper_argv[4] = (char *) polkit_result_to_string_representation (inactive); - helper_argv[5] = (char *) polkit_result_to_string_representation (active); - helper_argv[6] = NULL; - } - - if (!kit_spawn_sync (NULL, /* const char *working_directory */ - 0, /* flags */ - helper_argv, /* char **argv */ - NULL, /* char **envp */ - NULL, /* char *stdin */ - NULL, /* char **stdout */ - NULL, /* char **stderr */ - &exit_status)) { /* int *exit_status */ - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Error spawning set-default helper: %m"); - goto out; - } - - if (!WIFEXITED (exit_status)) { - kit_warning ("Set-default helper crashed!"); - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "set-default helper crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - polkit_error_set_error (error, - POLKIT_ERROR_NOT_AUTHORIZED_TO_MODIFY_DEFAULTS, - "uid %d is not authorized to modify defaults for implicit authorization for action %s (requires org.freedesktop.policykit.modify-defaults)", - getuid (), action_description->action); - } else { - ret = TRUE; - } -out: -#endif /* POLKIT_AUTHDB_DEFAULT */ - return ret; -} - - -typedef struct { - PolKitActionDescription *pfe; - PolKitActionDescriptionAnnotationsForeachFunc cb; - void *user_data; -} _AnnotationsClosure; - -static polkit_bool_t -_annotations_cb (void *key, - void *value, - void *user_data, - KitHash *hash) -{ - _AnnotationsClosure *closure = user_data; - return closure->cb (closure->pfe, (const char *) key, (const char *) value, closure->user_data); -} - -/** - * polkit_action_description_annotations_foreach: - * @action_description: the policy file entry - * @cb: callback function - * @user_data: user data to pass to the callback function - * - * Iterate over all annotations on the policy file entry. - * - * Returns: #TRUE only if the iteration was short-circuited - */ -polkit_bool_t -polkit_action_description_annotations_foreach (PolKitActionDescription *action_description, - PolKitActionDescriptionAnnotationsForeachFunc cb, - void *user_data) -{ - _AnnotationsClosure closure; - - kit_return_val_if_fail (action_description != NULL, FALSE); - if (action_description->annotations == NULL) - return FALSE; - - closure.pfe = action_description; - closure.cb = cb; - closure.user_data = user_data; - - return kit_hash_foreach (action_description->annotations, - _annotations_cb, - &closure); -} - -/** - * polkit_action_description_get_annotation: - * @action_description: the policy file entry - * @key: the key of the annotation - * - * Look of the value of a given annotation. - * - * Returns: The value of the annotation or #NULL if not found. - */ -const char * -polkit_action_description_get_annotation (PolKitActionDescription *action_description, - const char *key) -{ - const char *value; - kit_return_val_if_fail (action_description != NULL, NULL); - kit_return_val_if_fail (key != NULL, NULL); - - value = NULL; - if (action_description->annotations != NULL) { - value = kit_hash_lookup (action_description->annotations, (void *) key, NULL); - } - return value; -} - - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_pfe_cb (PolKitActionDescription *pfe, - const char *key, - const char *value, - void *user_data) -{ - int *count = (int *) user_data; - - if (strcmp (key, "a1") == 0 && strcmp (value, "v1") == 0) - *count += 1; - else if (strcmp (key, "a2") == 0 && strcmp (value, "v2") == 0) - *count += 1; - - return FALSE; -} - -static polkit_bool_t -_pfe_cb2 (PolKitActionDescription *pfe, - const char *key, - const char *value, - void *user_data) -{ - int *count = (int *) user_data; - *count += 1; - - return FALSE; -} - - -static polkit_bool_t -_run_test (void) -{ - PolKitActionDescription *pfe; - PolKitImplicitAuthorization *d; - KitHash *a; - int count; - - a = NULL; - pfe = NULL; - - if ((a = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - NULL, NULL, - NULL, NULL)) == NULL) - goto oom; - - if (!kit_hash_insert (a, "a1", "v1")) - goto oom; - - if (!kit_hash_insert (a, "a2", "v2")) - goto oom; - - if ((pfe = _polkit_action_description_new ("org.example-action", - NULL, - NULL, - NULL, - POLKIT_RESULT_NO, - POLKIT_RESULT_ONLY_VIA_SELF_AUTH, - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH, - a)) == NULL) - goto oom; - /* _file_entry_new assumes ownership of the passed a variable */ - a = NULL; - - kit_assert (strcmp (polkit_action_description_get_id (pfe), "org.example-action") == 0); - - if (_polkit_action_description_set_descriptions (pfe, - "the desc", - "the msg")) { - kit_assert (strcmp (polkit_action_description_get_action_description (pfe), "the desc") == 0); - kit_assert (strcmp (polkit_action_description_get_action_message (pfe), "the msg") == 0); - } - - if (_polkit_action_description_set_descriptions (pfe, - "the desc2", - "the msg2")) { - kit_assert (strcmp (polkit_action_description_get_action_description (pfe), "the desc2") == 0); - kit_assert (strcmp (polkit_action_description_get_action_message (pfe), "the msg2") == 0); - } - - kit_assert ((d = polkit_action_description_get_default (pfe)) != NULL); - -#ifdef POLKIT_AUTHDB_DEFAULT - kit_assert (polkit_implicit_authorization_get_allow_any (d) == POLKIT_RESULT_NO); - kit_assert (polkit_implicit_authorization_get_allow_inactive (d) == POLKIT_RESULT_ONLY_VIA_SELF_AUTH); - kit_assert (polkit_implicit_authorization_get_allow_active (d) == POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH); -#endif - - polkit_action_description_ref (pfe); - polkit_action_description_unref (pfe); - polkit_action_description_debug (pfe); - - kit_assert (strcmp (polkit_action_description_get_annotation (pfe, "a1"), "v1") == 0); - kit_assert (strcmp (polkit_action_description_get_annotation (pfe, "a2"), "v2") == 0); - kit_assert (polkit_action_description_get_annotation (pfe, "a3") == NULL); - - count = 0; - polkit_action_description_annotations_foreach (pfe, _pfe_cb, &count); - kit_assert (count == 2); - - polkit_action_description_unref (pfe); - if ((pfe = _polkit_action_description_new ("org.example-action-2", - NULL, - NULL, - NULL, - POLKIT_RESULT_NO, - POLKIT_RESULT_ONLY_VIA_SELF_AUTH, - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH, - NULL)) == NULL) - goto oom; - count = 0; - polkit_action_description_annotations_foreach (pfe, _pfe_cb2, &count); - kit_assert (count == 0); - _pfe_cb2 (pfe, NULL, NULL, &count); /* want to get coverage of _pfe_cb2 */ - kit_assert (count == 1); - -oom: - if (pfe != NULL) - polkit_action_description_unref (pfe); - - if (a != NULL) - kit_hash_unref (a); - - return TRUE; -} - -KitTest _test_action_description = { - "polkit_action_description", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ - - - -#include <expat.h> -#include "polkit-context.h" - -enum { - STATE_NONE, - STATE_UNKNOWN_TAG, - STATE_IN_POLICY_CONFIG, - STATE_IN_POLICY_VENDOR, - STATE_IN_POLICY_VENDOR_URL, - STATE_IN_POLICY_ICON_NAME, - STATE_IN_ACTION, - STATE_IN_ACTION_DESCRIPTION, - STATE_IN_ACTION_MESSAGE, - STATE_IN_ACTION_VENDOR, - STATE_IN_ACTION_VENDOR_URL, - STATE_IN_ACTION_ICON_NAME, - STATE_IN_DEFAULTS, - STATE_IN_DEFAULTS_ALLOW_ANY, - STATE_IN_DEFAULTS_ALLOW_INACTIVE, - STATE_IN_DEFAULTS_ALLOW_ACTIVE, - STATE_IN_ANNOTATE -}; - -#define PARSER_MAX_DEPTH 32 - -typedef struct { - XML_Parser parser; - int state; - int state_stack[PARSER_MAX_DEPTH]; - int stack_depth; - - const char *path; - - char *global_vendor; - char *global_vendor_url; - char *global_icon_name; - - char *action_id; - char *vendor; - char *vendor_url; - char *icon_name; - - PolKitResult defaults_allow_any; - PolKitResult defaults_allow_inactive; - PolKitResult defaults_allow_active; - - KitHash *policy_descriptions; - KitHash *policy_messages; - - char *policy_description_nolang; - char *policy_message_nolang; - - /* the language according to $LANG (e.g. en_US, da_DK, fr, en_CA minus the encoding) */ - char *lang; - - /* the value of xml:lang for the thing we're reading in _cdata() */ - char *elem_lang; - - char *annotate_key; - KitHash *annotations; - - polkit_bool_t is_oom; - - PolKitActionDescriptionForeachFunc cb; - void *user_data; -} ParserData; - -static void -pd_unref_action_data (ParserData *pd) -{ - kit_free (pd->action_id); - pd->action_id = NULL; - - kit_free (pd->vendor); - pd->vendor = NULL; - kit_free (pd->vendor_url); - pd->vendor_url = NULL; - kit_free (pd->icon_name); - pd->icon_name = NULL; - - kit_free (pd->policy_description_nolang); - pd->policy_description_nolang = NULL; - kit_free (pd->policy_message_nolang); - pd->policy_message_nolang = NULL; - if (pd->policy_descriptions != NULL) { - kit_hash_unref (pd->policy_descriptions); - pd->policy_descriptions = NULL; - } - if (pd->policy_messages != NULL) { - kit_hash_unref (pd->policy_messages); - pd->policy_messages = NULL; - } - kit_free (pd->annotate_key); - pd->annotate_key = NULL; - if (pd->annotations != NULL) { - kit_hash_unref (pd->annotations); - pd->annotations = NULL; - } - kit_free (pd->elem_lang); - pd->elem_lang = NULL; -} - -static void -pd_unref_data (ParserData *pd) -{ - pd_unref_action_data (pd); - kit_free (pd->lang); - pd->lang = NULL; - - kit_free (pd->global_vendor); - pd->global_vendor = NULL; - kit_free (pd->global_vendor_url); - pd->global_vendor_url = NULL; - kit_free (pd->global_icon_name); - pd->global_icon_name = NULL; -} - -static void -_start (void *data, const char *el, const char **attr) -{ - int state; - int num_attr; - ParserData *pd = data; - - for (num_attr = 0; attr[num_attr] != NULL; num_attr++) - ; - - state = STATE_NONE; - - switch (pd->state) { - case STATE_NONE: - if (strcmp (el, "policyconfig") == 0) { - state = STATE_IN_POLICY_CONFIG; - } - break; - case STATE_IN_POLICY_CONFIG: - if (strcmp (el, "action") == 0) { - if (num_attr != 2 || strcmp (attr[0], "id") != 0) - goto error; - state = STATE_IN_ACTION; - - if (!polkit_action_validate_id (attr[1])) - goto error; - - pd_unref_action_data (pd); - pd->action_id = kit_strdup (attr[1]); - if (pd->action_id == NULL) - goto oom; - pd->policy_descriptions = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - kit_hash_str_copy, kit_hash_str_copy, - kit_free, kit_free); - pd->policy_messages = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - kit_hash_str_copy, kit_hash_str_copy, - kit_free, kit_free); - - /* initialize defaults */ - pd->defaults_allow_any = POLKIT_RESULT_NO; - pd->defaults_allow_inactive = POLKIT_RESULT_NO; - pd->defaults_allow_active = POLKIT_RESULT_NO; - } else if (strcmp (el, "vendor") == 0 && num_attr == 0) { - state = STATE_IN_POLICY_VENDOR; - } else if (strcmp (el, "vendor_url") == 0 && num_attr == 0) { - state = STATE_IN_POLICY_VENDOR_URL; - } else if (strcmp (el, "icon_name") == 0 && num_attr == 0) { - state = STATE_IN_POLICY_ICON_NAME; - } - break; - case STATE_IN_ACTION: - if (strcmp (el, "defaults") == 0) { - state = STATE_IN_DEFAULTS; - } else if (strcmp (el, "description") == 0) { - if (num_attr == 2 && strcmp (attr[0], "xml:lang") == 0) { - pd->elem_lang = kit_strdup (attr[1]); - if (pd->elem_lang == NULL) - goto oom; - } - state = STATE_IN_ACTION_DESCRIPTION; - } else if (strcmp (el, "message") == 0) { - if (num_attr == 2 && strcmp (attr[0], "xml:lang") == 0) { - pd->elem_lang = kit_strdup (attr[1]); - if (pd->elem_lang == NULL) - goto oom; - } - state = STATE_IN_ACTION_MESSAGE; - } else if (strcmp (el, "vendor") == 0 && num_attr == 0) { - state = STATE_IN_ACTION_VENDOR; - } else if (strcmp (el, "vendor_url") == 0 && num_attr == 0) { - state = STATE_IN_ACTION_VENDOR_URL; - } else if (strcmp (el, "icon_name") == 0 && num_attr == 0) { - state = STATE_IN_ACTION_ICON_NAME; - } else if (strcmp (el, "annotate") == 0) { - if (num_attr != 2 || strcmp (attr[0], "key") != 0) - goto error; - state = STATE_IN_ANNOTATE; - - kit_free (pd->annotate_key); - pd->annotate_key = kit_strdup (attr[1]); - if (pd->annotate_key == NULL) - goto oom; - } - break; - case STATE_IN_DEFAULTS: - if (strcmp (el, "allow_any") == 0) - state = STATE_IN_DEFAULTS_ALLOW_ANY; - else if (strcmp (el, "allow_inactive") == 0) - state = STATE_IN_DEFAULTS_ALLOW_INACTIVE; - else if (strcmp (el, "allow_active") == 0) - state = STATE_IN_DEFAULTS_ALLOW_ACTIVE; - break; - default: - break; - } - - if (state == STATE_NONE) { - //kit_warning ("skipping unknown tag <%s> at line %d of %s", - // el, (int) XML_GetCurrentLineNumber (pd->parser), pd->path); - state = STATE_UNKNOWN_TAG; - } - - pd->state = state; - pd->state_stack[pd->stack_depth] = pd->state; - pd->stack_depth++; - return; -oom: - pd->is_oom = TRUE; -error: - XML_StopParser (pd->parser, FALSE); -} - -static polkit_bool_t -_validate_icon_name (const char *icon_name) -{ - unsigned int n; - polkit_bool_t ret; - size_t len; - - ret = FALSE; - - len = strlen (icon_name); - - /* check for common suffixes */ - if (kit_str_has_suffix (icon_name, ".png")) - goto out; - if (kit_str_has_suffix (icon_name, ".jpg")) - goto out; - - /* icon name cannot be a path */ - for (n = 0; n < len; n++) { - if (icon_name [n] == '/') { - goto out; - } - } - - ret = TRUE; - -out: - return ret; -} - -static void -_cdata (void *data, const char *s, int len) -{ - char *str; - ParserData *pd = data; - - str = kit_strndup (s, len); - if (str == NULL) - goto oom; - - switch (pd->state) { - - case STATE_IN_ACTION_DESCRIPTION: - if (pd->elem_lang == NULL) { - kit_free (pd->policy_description_nolang); - pd->policy_description_nolang = str; - str = NULL; - } else { - if (!kit_hash_insert (pd->policy_descriptions, pd->elem_lang, str)) - goto oom; - } - break; - - case STATE_IN_ACTION_MESSAGE: - if (pd->elem_lang == NULL) { - kit_free (pd->policy_message_nolang); - pd->policy_message_nolang = str; - str = NULL; - } else { - if (!kit_hash_insert (pd->policy_messages, pd->elem_lang, str)) - goto oom; - } - break; - - case STATE_IN_POLICY_VENDOR: - kit_free (pd->global_vendor); - pd->global_vendor = str; - str = NULL; - break; - - case STATE_IN_POLICY_VENDOR_URL: - kit_free (pd->global_vendor_url); - pd->global_vendor_url = str; - str = NULL; - break; - - case STATE_IN_POLICY_ICON_NAME: - if (! _validate_icon_name (str)) { - kit_warning ("Icon name '%s' is invalid", str); - goto error; - } - - kit_free (pd->global_icon_name); - pd->global_icon_name = str; - str = NULL; - break; - - case STATE_IN_ACTION_VENDOR: - kit_free (pd->vendor); - pd->vendor = str; - str = NULL; - break; - - case STATE_IN_ACTION_VENDOR_URL: - kit_free (pd->vendor_url); - pd->vendor_url = str; - str = NULL; - break; - - case STATE_IN_ACTION_ICON_NAME: - if (! _validate_icon_name (str)) { - kit_warning ("Icon name '%s' is invalid", str); - goto error; - } - - kit_free (pd->icon_name); - pd->icon_name = str; - str = NULL; - break; - - case STATE_IN_DEFAULTS_ALLOW_ANY: - if (!polkit_result_from_string_representation (str, &pd->defaults_allow_any)) - goto error; - break; - case STATE_IN_DEFAULTS_ALLOW_INACTIVE: - if (!polkit_result_from_string_representation (str, &pd->defaults_allow_inactive)) - goto error; - break; - case STATE_IN_DEFAULTS_ALLOW_ACTIVE: - if (!polkit_result_from_string_representation (str, &pd->defaults_allow_active)) - goto error; - break; - - case STATE_IN_ANNOTATE: - if (pd->annotations == NULL) { - pd->annotations = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - kit_hash_str_copy, kit_hash_str_copy, - kit_free, kit_free); - if (pd->annotations == NULL) - goto oom; - } - if (!kit_hash_insert (pd->annotations, pd->annotate_key, str)) - goto oom; - break; - - default: - break; - } - kit_free (str); - return; -oom: - pd->is_oom = TRUE; -error: - kit_free (str); - XML_StopParser (pd->parser, FALSE); -} - -/** - * _localize: - * @translations: a mapping from xml:lang to the value, e.g. 'da' -> 'Smadre', 'en_CA' -> 'Punch, Aye!' - * @untranslated: the untranslated value, e.g. 'Punch' - * @lang: the locale we're interested in, e.g. 'da_DK', 'da', 'en_CA', 'en_US'; basically just $LANG - * with the encoding cut off. Maybe be NULL. - * - * Pick the correct translation to use. - * - * Returns: the localized string to use - */ -static const char * -_localize (KitHash *translations, const char *untranslated, const char *lang) -{ - const char *result; - char lang2[256]; - int n; - - if (lang == NULL) { - result = untranslated; - goto out; - } - - /* first see if we have the translation */ - result = (const char *) kit_hash_lookup (translations, (void *) lang, NULL); - if (result != NULL) - goto out; - - /* we could have a translation for 'da' but lang=='da_DK'; cut off the last part and try again */ - strncpy (lang2, lang, sizeof (lang2)); - for (n = 0; lang2[n] != '\0'; n++) { - if (lang2[n] == '_') { - lang2[n] = '\0'; - break; - } - } - result = (const char *) kit_hash_lookup (translations, (void *) lang2, NULL); - if (result != NULL) - goto out; - - /* fall back to untranslated */ - result = untranslated; -out: - return result; -} - -static void -_end (void *data, const char *el) -{ - ParserData *pd = data; - - kit_free (pd->elem_lang); - pd->elem_lang = NULL; - - switch (pd->state) { - case STATE_IN_ACTION: - { - const char *policy_description; - const char *policy_message; - PolKitActionDescription *pfe; - char *vendor; - char *vendor_url; - char *icon_name; - - vendor = pd->vendor; - if (vendor == NULL) - vendor = pd->global_vendor; - - vendor_url = pd->vendor_url; - if (vendor_url == NULL) - vendor_url = pd->global_vendor_url; - - icon_name = pd->icon_name; - if (icon_name == NULL) - icon_name = pd->global_icon_name; - - /* NOTE: caller takes ownership of the annotations object */ - pfe = _polkit_action_description_new (pd->action_id, - vendor, - vendor_url, - icon_name, - pd->defaults_allow_any, - pd->defaults_allow_inactive, - pd->defaults_allow_active, - pd->annotations); - if (pfe == NULL) - goto oom; - pd->annotations = NULL; - - policy_description = _localize (pd->policy_descriptions, pd->policy_description_nolang, pd->lang); - policy_message = _localize (pd->policy_messages, pd->policy_message_nolang, pd->lang); - - if (!_polkit_action_description_set_descriptions (pfe, - policy_description, - policy_message)) { - polkit_action_description_unref (pfe); - goto oom; - } - - if (pd->cb (pfe, pd->user_data)) { - /* TODO: short-circuit */ - } - - /* and now throw it all away! (eh, don't worry, the user have probably reffed it!) */ - polkit_action_description_unref (pfe); - break; - } - default: - break; - } - - --pd->stack_depth; - if (pd->stack_depth < 0 || pd->stack_depth >= PARSER_MAX_DEPTH) { - polkit_debug ("reached max depth?"); - goto error; - } - if (pd->stack_depth > 0) - pd->state = pd->state_stack[pd->stack_depth - 1]; - else - pd->state = STATE_NONE; - - return; -oom: - pd->is_oom = 1; -error: - XML_StopParser (pd->parser, FALSE); -} - - -/** - * polkit_action_description_get_from_file: - * @path: path to file, e.g. <literal>/usr/share/polkit-1/actions/org.freedesktop.policykit.policy</literal> - * @cb: callback function - * @user_data: user data - * @error: return location for error - * - * Load a .policy file and iterate over all entries. - * - * Returns: #TRUE if @cb short-circuited the iteration. If there was - * an error parsing @file, then @error will be set. - **/ -polkit_bool_t -polkit_action_description_get_from_file (const char *path, - PolKitActionDescriptionForeachFunc cb, - void *user_data, - PolKitError **error) -{ - ParserData pd; - int xml_res; - char *lang; - char *buf; - size_t buflen; - - buf = NULL; - - /* clear parser data */ - memset (&pd, 0, sizeof (ParserData)); - - if (!kit_str_has_suffix (path, ".policy")) { - polkit_error_set_error (error, - POLKIT_ERROR_POLICY_FILE_INVALID, - "Policy files must have extension .policy; file '%s' doesn't", path); - goto error; - } - - if (!kit_file_get_contents (path, &buf, &buflen)) { - if (errno == ENOMEM) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, - "Cannot load PolicyKit policy file at '%s': %s", - path, - "No memory for parser"); - } else { - polkit_error_set_error (error, POLKIT_ERROR_POLICY_FILE_INVALID, - "Cannot load PolicyKit policy file at '%s': %m", - path); - } - goto error; - } - - pd.path = path; - pd.cb = cb; - pd.user_data = user_data; - -/* #ifdef POLKIT_BUILD_TESTS - TODO: expat appears to leak on certain OOM paths -*/ -#if 0 - XML_Memory_Handling_Suite memsuite = {p_malloc, p_realloc, kit_free}; - pd.parser = XML_ParserCreate_MM (NULL, &memsuite, NULL); -#else - pd.parser = XML_ParserCreate (NULL); -#endif - pd.stack_depth = 0; - if (pd.parser == NULL) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, - "Cannot load PolicyKit policy file at '%s': %s", - path, - "No memory for parser"); - goto error; - } - XML_SetUserData (pd.parser, &pd); - XML_SetElementHandler (pd.parser, _start, _end); - XML_SetCharacterDataHandler (pd.parser, _cdata); - - /* init parser data */ - pd.state = STATE_NONE; - lang = getenv ("LANG"); - if (lang != NULL) { - int n; - pd.lang = kit_strdup (lang); - if (pd.lang == NULL) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, - "Cannot load PolicyKit policy file at '%s': No memory for lang", - path); - goto error; - } - for (n = 0; pd.lang[n] != '\0'; n++) { - if (pd.lang[n] == '.') { - pd.lang[n] = '\0'; - break; - } - } - } - - xml_res = XML_Parse (pd.parser, buf, buflen, 1); - - if (xml_res == 0) { - if (XML_GetErrorCode (pd.parser) == XML_ERROR_NO_MEMORY) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, - "Out of memory parsing %s", - path); - } else if (pd.is_oom) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, - "Out of memory parsing %s", - path); - } else { - polkit_error_set_error (error, POLKIT_ERROR_POLICY_FILE_INVALID, - "%s:%d: parse error: %s", - path, - (int) XML_GetCurrentLineNumber (pd.parser), - XML_ErrorString (XML_GetErrorCode (pd.parser))); - } - XML_ParserFree (pd.parser); - goto error; - } - - XML_ParserFree (pd.parser); - kit_free (buf); - pd_unref_data (&pd); - - return FALSE; /* TODO */ -error: - pd_unref_data (&pd); - kit_free (buf); - return FALSE; /* TODO */ -} diff --git a/src/polkit/polkit-action-description.h b/src/polkit/polkit-action-description.h deleted file mode 100644 index e95865c..0000000 --- a/src/polkit/polkit-action-description.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-policy-file-entry.h : entries in policy files - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_ACTION_DESCRIPTION_H -#define POLKIT_ACTION_DESCRIPTION_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-implicit-authorization.h> -#include <polkit/polkit-error.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitActionDescription; -typedef struct _PolKitActionDescription PolKitActionDescription; - -/** - * PolKitActionDescriptionAnnotationsForeachFunc: - * @action_description: the policy file entry - * @key: key of the annotation - * @value: corrosponding value of the annotation - * @user_data: user data passed to polkit_action_description_annotations_foreach() - * - * Callback function for polkit_action_description_annotations_foreach(). - * - * Returns: Pass #TRUE to short-circuit, e.g. stop the iteration - **/ -typedef polkit_bool_t (*PolKitActionDescriptionAnnotationsForeachFunc) (PolKitActionDescription *action_description, - const char *key, - const char *value, - void *user_data); - -PolKitActionDescription *polkit_action_description_ref (PolKitActionDescription *action_description); -void polkit_action_description_unref (PolKitActionDescription *action_description); -void polkit_action_description_debug (PolKitActionDescription *action_description); - -const char *polkit_action_description_get_id (PolKitActionDescription *action_description); -PolKitImplicitAuthorization *polkit_action_description_get_implicit_authorization (PolKitActionDescription *action_description); - -const char *polkit_action_description_get_action_description (PolKitActionDescription *action_description); -const char *polkit_action_description_get_action_message (PolKitActionDescription *action_description); - -const char *polkit_action_description_get_action_vendor (PolKitActionDescription *action_description); -const char *polkit_action_description_get_action_vendor_url (PolKitActionDescription *action_description); -const char *polkit_action_description_get_action_icon_name (PolKitActionDescription *action_description); - -polkit_bool_t polkit_action_description_annotations_foreach (PolKitActionDescription *action_description, - PolKitActionDescriptionAnnotationsForeachFunc cb, - void *user_data); -const char *polkit_action_description_get_annotation (PolKitActionDescription *action_description, - const char *key); - -PolKitImplicitAuthorization *polkit_action_description_get_implicit_authorization_factory (PolKitActionDescription *action_description); -polkit_bool_t polkit_action_description_set_implicit_authorization (PolKitActionDescription *action_description, - PolKitImplicitAuthorization *implicit_authorzation, - PolKitError **error); - -POLKIT_END_DECLS - -#endif /* POLKIT_ACTION_DESCRIPTION_H */ - - diff --git a/src/polkit/polkit-action.c b/src/polkit/polkit-action.c deleted file mode 100644 index 01c054d..0000000 --- a/src/polkit/polkit-action.c +++ /dev/null @@ -1,398 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-action.c : action - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> -#include <ctype.h> - -#include "polkit-debug.h" -#include "polkit-action.h" -#include "polkit-utils.h" -#include "polkit-utils.h" -#include "polkit-private.h" -#include "polkit-test.h" - -/** - * SECTION:polkit-action - * @title: Actions - * @short_description: Models what a caller is attempting to do. - * - * This class is used to represent a PolicyKit action. - **/ - -/** - * PolKitAction: - * - * Objects of this class are used to record information about an action. - **/ -struct _PolKitAction -{ - int refcount; - char *id; -}; - -/** - * polkit_action_new: - * - * Create a new #PolKitAction object. - * - * Returns: the new object - **/ -PolKitAction * -polkit_action_new (void) -{ - PolKitAction *action; - action = kit_new0 (PolKitAction, 1); - if (action == NULL) - goto out; - action->refcount = 1; -out: - return action; -} - -/** - * polkit_action_to_string_representation: - * @action: the action object - * - * Serializes @action into a textual form that can be transferred from - * process to process or saved on disk. Use - * polkit_action_new_from_string_representation() to deserialize it. - * - * Returns: A string representation of @action or #NULL if the action - * is not valid. String is valid until @action is freed. - * - * Since: 0.8 - */ -const char * -polkit_action_to_string_representation (PolKitAction *action) -{ - kit_return_val_if_fail (action != NULL, NULL); - kit_return_val_if_fail (polkit_action_validate_id (action->id), NULL); - return action->id; -} - -/** - * polkit_action_new_from_string_representation: - * @str: textual representation of an action; typically obtained from - * polkit_action_to_string_representation() - * - * Creates a new #PolKitAction object from a textual representation. - * - * Returns: A new #PolKitAction object or #NULL if OOM or if the - * representation isn't valid. Caller must free this object with - * polkit_action_unref(). - * - * Since: 0.8 - */ -PolKitAction * -polkit_action_new_from_string_representation (const char *str) -{ - PolKitAction *action; - - kit_return_val_if_fail (str != NULL, NULL); - - action = polkit_action_new (); - if (action == NULL) - goto out; - - if (!polkit_action_set_action_id (action, str)) { - polkit_action_unref (action); - action = NULL; - } -out: - return action; -} - -/** - * polkit_action_equal: - * @a: first action - * @b: second action - * - * Test if @a and @b refer to the same action. - * - * Returns: #TRUE iff @a and @b refer to the same action. - * - * Since: 0.8 - */ -polkit_bool_t -polkit_action_equal (PolKitAction *a, PolKitAction *b) -{ - kit_return_val_if_fail (a != NULL && polkit_action_validate (a), FALSE); - kit_return_val_if_fail (b != NULL && polkit_action_validate (b), FALSE); - - return strcmp (a->id, b->id) == 0; -} - - -/** - * polkit_action_ref: - * @action: the action object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitAction * -polkit_action_ref (PolKitAction *action) -{ - kit_return_val_if_fail (action != NULL, action); - action->refcount++; - return action; -} - -/** - * polkit_action_unref: - * @action: the action object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_action_unref (PolKitAction *action) -{ - kit_return_if_fail (action != NULL); - action->refcount--; - if (action->refcount > 0) - return; - kit_free (action->id); - kit_free (action); -} - -/** - * polkit_action_set_action_id: - * @action: the action object - * @action_id: action identifier - * - * Set the action identifier - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_action_set_action_id (PolKitAction *action, const char *action_id) -{ - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (polkit_action_validate_id (action_id), FALSE); - if (action->id != NULL) - kit_free (action->id); - action->id = kit_strdup (action_id); - if (action->id == NULL) - return FALSE; - - return TRUE; -} - -/** - * polkit_action_get_action_id: - * @action: the action object - * @out_action_id: Returns the action identifier. The caller shall not free this string. - * - * Get the action identifier. - * - * Returns: TRUE iff the value was returned. - **/ -polkit_bool_t -polkit_action_get_action_id (PolKitAction *action, char **out_action_id) -{ - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (out_action_id != NULL, FALSE); - if (action->id == NULL) - return FALSE; - *out_action_id = action->id; - return TRUE; -} - -/** - * polkit_action_debug: - * @action: the object - * - * Print debug details - **/ -void -polkit_action_debug (PolKitAction *action) -{ - kit_return_if_fail (action != NULL); - polkit_debug ("PolKitAction: refcount=%d id=%s", action->refcount, action->id); -} - -/** - * polkit_action_validate_id: - * @action_id: the action identifier to validate - * - * Validate whether an action identifier is well formed. To be well - * formed, an action identifier needs to start with a lower case ASCII - * character and can only contain the characters "[a-z][0-9].-". It - * must be less than or equal 256 bytes in length including the - * terminating NUL character. - * - * Returns: #TRUE iff the action identifier is well formed - **/ -polkit_bool_t -polkit_action_validate_id (const char *action_id) -{ - int n; - - kit_return_val_if_fail (action_id != NULL, FALSE); - - /* validate that the form of the action identifier is correct */ - if (!islower (action_id[0])) - goto malformed; - - for (n = 1; action_id[n] != '\0'; n++) { - if (n >= 255) - goto malformed; - - if (! (islower (action_id[n]) || - isdigit (action_id[n]) || - action_id[n] == '.' || - action_id[n] == '-')) - goto malformed; - } - - return TRUE; - -malformed: - return FALSE; -} - -/** - * polkit_action_validate: - * @action: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - **/ -polkit_bool_t -polkit_action_validate (PolKitAction *action) -{ - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (action->id != NULL, FALSE); - - return polkit_action_validate_id (action->id); -} - - - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - PolKitAction *a; - char *s; - int n; - char *valid_action_ids[] = {"org.example.action", - "org.example.action-foo", - "org.example.action-foo.42", - "org.example.42-.foo", - "t0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd", - NULL}; - char *invalid_action_ids[] = {"1org.example.action", - ".org.example.action", - "-org.example.action", - "org.example.action_foo", - "org.example.something.that.is.too.long.0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - NULL}; - - for (n = 0; valid_action_ids[n] != NULL; n++) { - kit_assert (polkit_action_validate_id (valid_action_ids[n])); - } - - for (n = 0; invalid_action_ids[n] != NULL; n++) { - kit_assert (! polkit_action_validate_id (invalid_action_ids[n])); - } - - a = polkit_action_new (); - if (a == NULL) { - /* OOM */ - } else { - - kit_assert (! polkit_action_get_action_id (a, &s)); - - if (!polkit_action_set_action_id (a, "org.example.action")) { - /* OOM */ - } else { - kit_assert (polkit_action_validate (a)); - polkit_action_ref (a); - kit_assert (polkit_action_validate (a)); - polkit_action_unref (a); - kit_assert (polkit_action_validate (a)); - - if (!polkit_action_set_action_id (a, "org.example.action2")) { - /* OOM */ - } else { - kit_assert (polkit_action_validate (a)); - kit_assert (polkit_action_get_action_id (a, &s)); - kit_assert (strcmp (s, "org.example.action2") == 0); - polkit_action_debug (a); - } - } - - polkit_action_unref (a); - } - - a = polkit_action_new (); - if (a != NULL) { - if (polkit_action_set_action_id (a, "org.example.foo")) { - const char *action_str; - PolKitAction *a2; - - action_str = polkit_action_to_string_representation (a); - kit_assert (action_str != NULL); - a2 = polkit_action_new_from_string_representation (action_str); - if (a2 != NULL) { - kit_assert (polkit_action_equal (a, a2)); - polkit_action_unref (a2); - } - } - polkit_action_unref (a); - } - - return TRUE; -} - -KitTest _test_action = { - "polkit_action", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-action.h b/src/polkit/polkit-action.h deleted file mode 100644 index be2e807..0000000 --- a/src/polkit/polkit-action.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-action.h : actions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_ACTION_H -#define POLKIT_ACTION_H - -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitAction; -typedef struct _PolKitAction PolKitAction; - -PolKitAction *polkit_action_new (void); -PolKitAction *polkit_action_ref (PolKitAction *action); -void polkit_action_unref (PolKitAction *action); -polkit_bool_t polkit_action_set_action_id (PolKitAction *action, const char *action_id); -polkit_bool_t polkit_action_get_action_id (PolKitAction *action, char **out_action_id); - -void polkit_action_debug (PolKitAction *action); -polkit_bool_t polkit_action_validate (PolKitAction *action); - -polkit_bool_t polkit_action_validate_id (const char *action_id); - -polkit_bool_t polkit_action_equal (PolKitAction *a, PolKitAction *b); - -const char *polkit_action_to_string_representation (PolKitAction *action); -PolKitAction *polkit_action_new_from_string_representation (const char *str); - -POLKIT_END_DECLS - -#endif /* POLKIT_ACTION_H */ - - diff --git a/src/polkit/polkit-authorization-constraint.c b/src/polkit/polkit-authorization-constraint.c deleted file mode 100644 index b12d467..0000000 --- a/src/polkit/polkit-authorization-constraint.c +++ /dev/null @@ -1,1001 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-constraint.c : Conditions that must be - * satisfied in order for an authorization to apply - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> -#include <limits.h> - -#include "polkit-debug.h" -#include "polkit-authorization-constraint.h" -#include "polkit-utils.h" -#include "polkit-private.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-authorization-constraint - * @title: Authorization Constraints - * @short_description: Conditions that must be satisfied in - * order for an authorization to apply - * - * This class is used to represent conditions that must be satisfied - * in order for an authorization to apply - * - * Since: 0.7 - **/ - -/** - * PolKitAuthorizationConstraint: - * - * Instances of this class are used to represent conditions that must - * be satisfied in order for an authorization to apply. - * - * Since: 0.7 - **/ -struct _PolKitAuthorizationConstraint -{ - int refcount; - PolKitAuthorizationConstraintType type; - - union { - struct { - char *path; - } exe; - struct { - char *context; - } selinux_context; - } data; -}; - -static PolKitAuthorizationConstraint _local_constraint = {-1, - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL}; - -static PolKitAuthorizationConstraint _active_constraint = {-1, - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE}; - -static PolKitAuthorizationConstraint * -_polkit_authorization_constraint_new (void) -{ - PolKitAuthorizationConstraint *authc; - authc = kit_new0 (PolKitAuthorizationConstraint, 1); - if (authc == NULL) - goto oom; - authc->refcount = 1; -oom: - return authc; -} - -/** - * polkit_authorization_constraint_ref: - * @authc: the object - * - * Increase reference count. - * - * Returns: the object - * - * Since: 0.7 - **/ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_ref (PolKitAuthorizationConstraint *authc) -{ - kit_return_val_if_fail (authc != NULL, authc); - if (authc->refcount == -1) - return authc; - authc->refcount++; - return authc; -} - -/** - * polkit_authorization_constraint_unref: - * @authc: the authorization_constraint object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - * - * Since: 0.7 - **/ -void -polkit_authorization_constraint_unref (PolKitAuthorizationConstraint *authc) -{ - kit_return_if_fail (authc != NULL); - if (authc->refcount == -1) - return; - authc->refcount--; - if (authc->refcount > 0) - return; - - switch (authc->type) { - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL: - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE: - break; - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE: - kit_free (authc->data.exe.path); - break; - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT: - kit_free (authc->data.selinux_context.context); - break; - } - - kit_free (authc); -} - -/** - * polkit_authorization_constraint_debug: - * @authc: the object - * - * Print debug details - * - * Since: 0.7 - **/ -void -polkit_authorization_constraint_debug (PolKitAuthorizationConstraint *authc) -{ - kit_return_if_fail (authc != NULL); - polkit_debug ("PolKitAuthorizationConstraint: refcount=%d type=%d", authc->refcount, authc->type); -} - -/** - * polkit_authorization_constraint_validate: - * @authc: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - * - * Since: 0.7 - **/ -polkit_bool_t -polkit_authorization_constraint_validate (PolKitAuthorizationConstraint *authc) -{ - kit_return_val_if_fail (authc != NULL, FALSE); - - return TRUE; -} - -/** - * polkit_authorization_constraint_check_session: - * @authc: the object - * @session: the session - * - * Determine if the given session satisfies the conditions imposed by - * the given constraint. - * - * Returns: #TRUE if, and only if, the given session satisfies the - * conditions imposed by the given constraint. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_constraint_check_session (PolKitAuthorizationConstraint *authc, - PolKitSession *session) -{ - polkit_bool_t ret; - polkit_bool_t is_active; - polkit_bool_t is_local; - - kit_return_val_if_fail (authc != NULL, FALSE); - kit_return_val_if_fail (session != NULL, FALSE); - - ret = FALSE; - - polkit_session_get_ck_is_local (session, &is_local); - polkit_session_get_ck_is_active (session, &is_active); - - if (authc->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL) { - if (!is_local) - goto out; - } - - if (authc->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE) { - if (!is_active) - goto out; - } - - ret = TRUE; -out: - return ret; -} - -/** - * polkit_authorization_constraint_check_caller: - * @authc: the object - * @caller: the caller - * - * Determine if the given caller satisfies the conditions imposed by - * the given constraint - * - * Returns: #TRUE if, and only if, the given caller satisfies the - * conditions imposed by the given constraint. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_constraint_check_caller (PolKitAuthorizationConstraint *authc, - PolKitCaller *caller) -{ - int n; - pid_t pid; - char *selinux_context; - char buf[PATH_MAX]; - polkit_bool_t ret; - PolKitSession *session; - - kit_return_val_if_fail (authc != NULL, FALSE); - kit_return_val_if_fail (caller != NULL, FALSE); - - ret = FALSE; - - /* caller may not be in a session */ - - switch (authc->type) { - /* explicit fallthrough */ - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL: - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE: - if (polkit_caller_get_ck_session (caller, &session) && session != NULL) { - ret = polkit_authorization_constraint_check_session (authc, session); - } - break; - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE: - if (polkit_caller_get_pid (caller, &pid)) { - - /* we may be running unprivileged.. so optionally use the helper. Requires the calling - * process (this one) to have the org.freedesktop.policykit.read authorization. - * - * An example of this is HAL (running as user 'haldaemon'). - */ - n = polkit_sysdeps_get_exe_for_pid_with_helper (pid, buf, sizeof (buf)); - - if (n != -1 && n < (int) sizeof (buf)) { - if (strcmp (authc->data.exe.path, buf) == 0) { - ret = TRUE; - } - } - } - - break; - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT: - if (polkit_caller_get_selinux_context (caller, &selinux_context) && selinux_context != NULL) { - if (strcmp (authc->data.selinux_context.context, selinux_context) == 0) { - ret = TRUE; - } - } else { - /* if SELinux context is not set then SELinux is not enabled (or the - * caller made a mistake and didn't set it); thus, the authorization can - * never apply - */ - ret = TRUE; - } - break; - } - - return ret; -} - -/** - * polkit_authorization_constraint_type: - * @authc: the object - * - * Describe the constraint; this is only useful when inspecting an - * authorization to present information to the user (e.g. as - * polkit-auth(1) does). - * - * Returns: type from #PolKitAuthorizationConstraintType - * - * Since: 0.7 - */ -PolKitAuthorizationConstraintType -polkit_authorization_constraint_type (PolKitAuthorizationConstraint *authc) -{ - kit_return_val_if_fail (authc != NULL, FALSE); - return authc->type; -} - -/** - * polkit_authorization_constraint_get_exe: - * @authc: the object - * - * Get the exe path for the constraint. - * - * Returns: The exe path or #NULL if type isn't - * #POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE. Caller shall not - * free this string. - * - * Since: 0.8 - */ -const char * -polkit_authorization_constraint_get_exe (PolKitAuthorizationConstraint *authc) -{ - kit_return_val_if_fail (authc != NULL, NULL); - kit_return_val_if_fail (authc->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE, NULL); - - return authc->data.exe.path; -} - -/** - * polkit_authorization_constraint_get_selinux_context: - * @authc: the object - * - * Get the SELinux context for the constraint. - * - * Returns: The selinux context or #NULL if type isn't - * #POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT. Caller - * shall not free this string. - * - * Since: 0.8 - */ -const char * -polkit_authorization_constraint_get_selinux_context (PolKitAuthorizationConstraint *authc) -{ - kit_return_val_if_fail (authc != NULL, NULL); - kit_return_val_if_fail (authc->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT, NULL); - - return authc->data.selinux_context.context; -} - -/** - * polkit_authorization_constraint_get_require_local: - * - * Get a #PolKitAuthorizationConstraint object that represents the - * constraint that the session or caller must be local. - * - * Returns: the constraint - * - * Since: 0.7 - */ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_get_require_local (void) -{ - return &_local_constraint; -} - -/** - * polkit_authorization_constraint_get_require_active: - * - * Get a #PolKitAuthorizationConstraint object that represents the - * constraint that the session or caller must be active. - * - * Returns: the constraint - * - * Since: 0.7 - */ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_get_require_active (void) -{ - return &_active_constraint; -} - -/** - * polkit_authorization_constraint_get_require_exe: - * @path: path to program - * - * Get a #PolKitAuthorizationConstraint object that represents the - * constraint that the caller must be a specific program - * - * Returns: the constraint or #NULL on OOM - * - * Since: 0.8 - */ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_get_require_exe (const char *path) -{ - PolKitAuthorizationConstraint *authc; - - kit_return_val_if_fail (path != NULL, NULL); - - authc = _polkit_authorization_constraint_new (); - if (authc == NULL) - goto out; - authc->type = POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE; - authc->data.exe.path = kit_strdup (path); - if (authc->data.exe.path == NULL) { - polkit_authorization_constraint_unref (authc); - authc = NULL; - } - -out: - return authc; -} - -/** - * polkit_authorization_constraint_get_require_selinux_context: - * @context: SELinux context - * - * Get a #PolKitAuthorizationConstraint object that represents the - * constraint that the caller must be in a specific SELinux context. - * - * Returns: the constraint or #NULL on OOM - * - * Since: 0.8 - */ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_get_require_selinux_context (const char *context) -{ - PolKitAuthorizationConstraint *authc; - - kit_return_val_if_fail (context != NULL, NULL); - - authc = _polkit_authorization_constraint_new (); - if (authc == NULL) - goto out; - authc->type = POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT; - authc->data.selinux_context.context = kit_strdup (context); - if (authc->data.selinux_context.context == NULL) { - polkit_authorization_constraint_unref (authc); - authc = NULL; - } - -out: - return authc; -} - -/** - * polkit_authorization_constraint_to_string: - * @authc: the object - * @out_buf: buffer to store the string representation in - * @buf_size: size of buffer - * - * Get a textual representation of the constraint; this is only useful - * for serializing; it's a machine, not human, readable string. - * - * Returns: Number of characters written (not including trailing - * '\0'). If the output was truncated due to the buffer being too - * small, buf_size will be returned. Thus, a return value of buf_size - * or more indicates that the output was truncated (see snprintf(3)) - * or an error occured. - * - * Since: 0.7 - */ -size_t -polkit_authorization_constraint_to_string (PolKitAuthorizationConstraint *authc, char *out_buf, size_t buf_size) -{ - kit_return_val_if_fail (authc != NULL, buf_size); - - switch (authc->type) { - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL: - return snprintf (out_buf, buf_size, "local"); - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE: - return snprintf (out_buf, buf_size, "active"); - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE: - return snprintf (out_buf, buf_size, "exe:%s", authc->data.exe.path); - - case POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT: - return snprintf (out_buf, buf_size, "selinux_context:%s", authc->data.selinux_context.context); - } - - return 0; -} - -/** - * polkit_authorization_constraint_from_string: - * @str: textual representation of constraint - * - * Construct a constraint from a textual representation as returned by - * polkit_authorization_constraint_to_string(). - * - * Returns: the constraint or #NULL if the string coulnd't be parsed. - */ -PolKitAuthorizationConstraint * -polkit_authorization_constraint_from_string (const char *str) -{ - PolKitAuthorizationConstraint *ret; - - kit_return_val_if_fail (str != NULL, NULL); - - ret = NULL; - - if (strcmp (str, "local") == 0) { - ret = polkit_authorization_constraint_get_require_local (); - goto out; - } else if (strcmp (str, "active") == 0) { - ret = polkit_authorization_constraint_get_require_active (); - goto out; - } else if (strncmp (str, "exe:", 4) == 0 && strlen (str) > 4) { - ret = polkit_authorization_constraint_get_require_exe (str + 4); - goto out; - } else if (strncmp (str, "selinux_context:", 16) == 0 && strlen (str) > 16) { - ret = polkit_authorization_constraint_get_require_selinux_context (str + 16); - goto out; - } - -out: - return ret; -} - -/** - * polkit_authorization_constraint_get_from_caller: - * @caller: caller - * @out_array: return location for constraints - * @array_size: size of the passed array - * - * Given a caller, return the set of most restrictive constraints - * possible. For example, if the caller is local and active, a set - * constraints requiring this will be returned. - * - * This function is typically used when the caller obtains an - * authorization through authentication; the goal is to put - * constraints on the authorization such that it's only valid when the - * caller is in the context as where she obtained it. - * - * The caller must unref all the created objects using - * polkit_authorization_constraint_unref(). - * - * Returns: If OOM -1 is returned. This function do not create more - * than @array_size constraints (including the trailing %NULL). If the - * output was truncated due to this limit then the return value is the - * number of objects (not including the trailing %NULL) which would - * have been written to the final array if enough space had been - * available. Thus, a return value of @array_size or more means that - * the output was truncated. - * - * Since: 0.7 - */ -int -polkit_authorization_constraint_get_from_caller (PolKitCaller *caller, - PolKitAuthorizationConstraint **out_array, - size_t array_size) -{ - pid_t pid; - char *selinux_context; - int ret; - polkit_bool_t is_local; - polkit_bool_t is_active; - PolKitSession *session; - char path[PATH_MAX]; - int n; - - kit_return_val_if_fail (caller != NULL, 0); - kit_return_val_if_fail (out_array != NULL, 0); - - ret = 0; - - if (!polkit_caller_get_ck_session (caller, &session) || session == NULL) { - goto out; - } - - polkit_session_get_ck_is_local (session, &is_local); - polkit_session_get_ck_is_active (session, &is_active); - - if (is_local) { - if (ret < (int) array_size) - out_array[ret] = polkit_authorization_constraint_get_require_local (); - ret++; - } - - if (is_active) { - if (ret < (int) array_size) - out_array[ret] = polkit_authorization_constraint_get_require_active (); - ret++; - } - - /* constrain to callers program */ - if (polkit_caller_get_pid (caller, &pid)) { - /* So the program to receive a constraint may besetuid root... so we may need some - * help to get the exepath.. Therefore use _with_helper(). - * - * This works because this function is normally only called from polkit-grant-helper which - * is setgid polkituser.. this means that _with_helper will succeed. - * - * An example of this is pulseaudio... - */ - n = polkit_sysdeps_get_exe_for_pid_with_helper (pid, path, sizeof (path)); - if (n != -1 && n < (int) sizeof (path)) { - PolKitAuthorizationConstraint *c; - - c = polkit_authorization_constraint_get_require_exe (path); - if (c == NULL) - goto oom; - - if (ret < (int) array_size) - out_array[ret] = c; - - ret++; - } - } - - /* constrain to callers SELinux context */ - if (polkit_caller_get_selinux_context (caller, &selinux_context) && selinux_context != NULL) { - PolKitAuthorizationConstraint *c; - - c = polkit_authorization_constraint_get_require_selinux_context (selinux_context); - if (c == NULL) - goto oom; - - if (ret < (int) array_size) - out_array[ret] = c; - - ret++; - } - -out: - if (ret < (int) array_size) - out_array[ret] = NULL; - - return ret; - -oom: - for (n = 0; n < ret; n++) { - polkit_authorization_constraint_unref (out_array[n]); - } - return -1; -} - -/** - * polkit_authorization_constraint_equal: - * @a: first constraint - * @b: first constraint - * - * Determines if two constraints are equal - * - * Returns: #TRUE only if the given constraints are equal - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_constraint_equal (PolKitAuthorizationConstraint *a, PolKitAuthorizationConstraint *b) -{ - polkit_bool_t ret; - - kit_return_val_if_fail (a != NULL, FALSE); - kit_return_val_if_fail (b != NULL, FALSE); - - ret = FALSE; - - if (a->type != b->type) - goto out; - - if (a->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE) { - if (strcmp (a->data.exe.path, b->data.exe.path) != 0) - goto out; - } else if (a->type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT) { - if (strcmp (a->data.selinux_context.context, b->data.selinux_context.context) != 0) - goto out; - } - - ret = TRUE; - -out: - return ret; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_tst1 (PolKitSession *s, PolKitAuthorizationConstraint *ac, polkit_bool_t *out_result) -{ - polkit_bool_t oom; - PolKitCaller *c; - - oom = TRUE; - - if (s == NULL) - goto out; - - *out_result = polkit_authorization_constraint_check_session (ac, s); - - if ((c = polkit_caller_new ()) != NULL) { - /* we know that the ac's passed always will be REQUIRE_ACTIVE or REQUIRE_LOCAL */ - kit_assert (polkit_authorization_constraint_check_caller (ac, c) == FALSE); - - kit_assert (polkit_caller_set_ck_session (c, s)); - kit_assert (*out_result == polkit_authorization_constraint_check_caller (ac, c)); - polkit_caller_unref (c); - } - - oom = FALSE; - -out: - return oom; -} - -static void -_tst2 (PolKitAuthorizationConstraint *ac) -{ - char buf[256]; - PolKitAuthorizationConstraint *ac2; - - /* not enough space */ - kit_assert (polkit_authorization_constraint_to_string (ac, buf, 2) >= 2); - - kit_assert (polkit_authorization_constraint_to_string (ac, buf, sizeof (buf)) < sizeof (buf)); - if ((ac2 = polkit_authorization_constraint_from_string (buf)) != NULL) { - kit_assert (polkit_authorization_constraint_equal (ac, ac2) == TRUE); - polkit_authorization_constraint_unref (ac2); - } -} - -#if 0 -static polkit_bool_t -_tst3 (PolKitSession *s, PolKitAuthorizationConstraint *compare_to, polkit_bool_t *ret) -{ - PolKitAuthorizationConstraint *ac; - polkit_bool_t is_oom; - PolKitCaller *c; - - is_oom = TRUE; - - if (s == NULL) - goto out; - - if ((c = polkit_caller_new ()) != NULL) { - ac = polkit_authorization_constraint_get_from_caller (c); - kit_assert (polkit_authorization_constraint_equal (ac, polkit_authorization_constraint_get_null ())); - - - kit_assert (polkit_caller_set_ck_session (c, s)); - - ac = polkit_authorization_constraint_get_from_caller (c); - - *ret = polkit_authorization_constraint_equal (ac, compare_to); - - polkit_caller_unref (c); - polkit_authorization_constraint_unref (ac); - - is_oom = FALSE; - } - - -out: - return is_oom; -} -#endif - -static polkit_bool_t -_run_test (void) -{ - PolKitAuthorizationConstraint *ac; - PolKitAuthorizationConstraint *ac2; - PolKitAuthorizationConstraintType type; - PolKitSession *s_active; - PolKitSession *s_inactive; - PolKitSession *s_active_remote; - PolKitSession *s_inactive_remote; - polkit_bool_t ret; - char buf[256]; - - if ((s_active = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_active, "/session1")) { - polkit_session_unref (s_active); - s_active = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_active, TRUE)); - kit_assert (polkit_session_set_ck_is_active (s_active, TRUE)); - } - } - - if ((s_inactive = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_inactive, "/session2")) { - polkit_session_unref (s_inactive); - s_inactive = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_inactive, TRUE)); - kit_assert (polkit_session_set_ck_is_active (s_inactive, FALSE)); - } - } - - if ((s_active_remote = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_active_remote, "/session3") || - !polkit_session_set_ck_remote_host (s_active_remote, "remotehost.com")) { - polkit_session_unref (s_active_remote); - s_active_remote = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_active_remote, FALSE)); - kit_assert (polkit_session_set_ck_is_active (s_active_remote, TRUE)); - } - } - - if ((s_inactive_remote = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_inactive_remote, "/session4") || - !polkit_session_set_ck_remote_host (s_inactive_remote, "remotehost.com")) { - polkit_session_unref (s_inactive_remote); - s_inactive_remote = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_inactive_remote, FALSE)); - kit_assert (polkit_session_set_ck_is_active (s_inactive_remote, FALSE)); - } - } - - /* local constraint */ - kit_assert ((ac = polkit_authorization_constraint_get_require_local ()) != NULL); - type = polkit_authorization_constraint_type (ac); - kit_assert (type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL); - kit_assert (_tst1 (s_active, ac, &ret) || ret == TRUE); - kit_assert (_tst1 (s_inactive, ac, &ret) || ret == TRUE); - kit_assert (_tst1 (s_active_remote, ac, &ret) || ret == FALSE); - kit_assert (_tst1 (s_inactive_remote, ac, &ret) || ret == FALSE); - _tst2 (ac); - - /* active constraint */ - kit_assert ((ac = polkit_authorization_constraint_get_require_active ()) != NULL); - type = polkit_authorization_constraint_type (ac); - kit_assert (type == POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE); - kit_assert (_tst1 (s_active, ac, &ret) || ret == TRUE); - kit_assert (_tst1 (s_inactive, ac, &ret) || ret == FALSE); - kit_assert (_tst1 (s_active_remote, ac, &ret) || ret == TRUE); - kit_assert (_tst1 (s_inactive_remote, ac, &ret) || ret == FALSE); - _tst2 (ac); - - -#if 0 - /* TODO: redo these tests; they are supposed to to verify that - * polkit_authorization_constraint_get_from_caller() works() - */ - for (n = 0; n < 4; n++) { - PolKitSession *s; - polkit_bool_t expected[4]; - - switch (n) { - case 0: - s = s_active; - expected[0] = TRUE; - expected[1] = FALSE; - expected[2] = FALSE; - expected[3] = FALSE; - break; - case 1: - s = s_inactive; - expected[0] = FALSE; - expected[1] = TRUE; - expected[2] = FALSE; - expected[3] = FALSE; - break; - case 2: - s = s_active_remote; - expected[0] = FALSE; - expected[1] = FALSE; - expected[2] = TRUE; - expected[3] = FALSE; - break; - case 3: - s = s_inactive_remote; - expected[0] = FALSE; - expected[1] = FALSE; - expected[2] = FALSE; - expected[3] = TRUE; - break; - } - - kit_assert (_tst3 (s, polkit_authorization_constraint_get_require_local_active (), &ret) || ret == expected[0]); - kit_assert (_tst3 (s, polkit_authorization_constraint_get_require_local (), &ret) || ret == expected[1]); - kit_assert (_tst3 (s, polkit_authorization_constraint_get_require_active (), &ret) || ret == expected[2]); - kit_assert (_tst3 (s, polkit_authorization_constraint_get_null (), &ret) || ret == expected[3]); - } -#endif - - if ((ac = _polkit_authorization_constraint_new ()) != NULL) { - polkit_authorization_constraint_validate (ac); - polkit_authorization_constraint_debug (ac); - polkit_authorization_constraint_ref (ac); - polkit_authorization_constraint_unref (ac); - polkit_authorization_constraint_unref (ac); - } - - char our_exe[256]; - int n; - n = polkit_sysdeps_get_exe_for_pid (getpid (), our_exe, sizeof (our_exe)); - kit_assert (n != -1); - kit_assert (n < (int) sizeof (our_exe)); - - if ((ac = polkit_authorization_constraint_get_require_exe (our_exe)) != NULL) { - const char *s; - PolKitCaller *c; - - kit_assert ((s = polkit_authorization_constraint_get_exe (ac)) != NULL && strcmp (s, our_exe) == 0); - kit_assert (polkit_authorization_constraint_to_string (ac, buf, sizeof (buf)) < sizeof (buf)); - if ((ac2 = polkit_authorization_constraint_from_string (buf)) != NULL) { - kit_assert (polkit_authorization_constraint_equal (ac, ac2)); - polkit_authorization_constraint_unref (ac2); - } - - if ((c = polkit_caller_new ()) != NULL) { - kit_assert (polkit_caller_set_pid (c, getpid ())); - kit_assert (polkit_authorization_constraint_check_caller (ac, c)); - kit_assert (polkit_caller_set_pid (c, getppid ())); - kit_assert (! polkit_authorization_constraint_check_caller (ac, c)); - polkit_caller_unref (c); - } - - - polkit_authorization_constraint_unref (ac); - } - - if ((ac = polkit_authorization_constraint_get_require_selinux_context ("httpd_exec_t")) != NULL) { - const char *s; - PolKitCaller *c; - - kit_assert ((s = polkit_authorization_constraint_get_selinux_context (ac)) != NULL && - strcmp (s, "httpd_exec_t") == 0); - kit_assert (polkit_authorization_constraint_to_string (ac, buf, sizeof (buf)) < sizeof (buf)); - if ((ac2 = polkit_authorization_constraint_from_string (buf)) != NULL) { - kit_assert (polkit_authorization_constraint_equal (ac, ac2)); - polkit_authorization_constraint_unref (ac2); - } - - if ((c = polkit_caller_new ()) != NULL) { - kit_assert (polkit_caller_set_pid (c, getpid ())); - - if (polkit_caller_set_selinux_context (c, "httpd_exec_t")) { - kit_assert (polkit_authorization_constraint_check_caller (ac, c)); - } else { - kit_assert (errno == ENOMEM); - } - - if (polkit_caller_set_selinux_context (c, "hald_exec_t")) { - kit_assert (! polkit_authorization_constraint_check_caller (ac, c)); - } else { - kit_assert (errno == ENOMEM); - } - - polkit_caller_unref (c); - } - - polkit_authorization_constraint_unref (ac); - } - - if (s_active != NULL) - polkit_session_unref (s_active); - - if (s_inactive != NULL) - polkit_session_unref (s_inactive); - - if (s_active_remote != NULL) - polkit_session_unref (s_active_remote); - - if (s_inactive_remote != NULL) - polkit_session_unref (s_inactive_remote); - - return TRUE; -} - - -KitTest _test_authorization_constraint = { - "polkit_authorization_constraint", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-authorization-constraint.h b/src/polkit/polkit-authorization-constraint.h deleted file mode 100644 index 2eee07a..0000000 --- a/src/polkit/polkit-authorization-constraint.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-constraint.h : Conditions that must be - * satisfied in order for an authorization to apply - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_AUTHORIZATION_CONSTRAINT_H -#define POLKIT_AUTHORIZATION_CONSTRAINT_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-session.h> -#include <polkit/polkit-caller.h> - -POLKIT_BEGIN_DECLS - -/** - * PolKitAuthorizationConstraintType: - * @POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL: the session or - * caller must be local - * @POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE: the session or - * caller must be in an active local session - * @POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE: the caller must - * be a specific program; use - * polkit_authorization_constraint_get_exe() to get the path of the - * program. - * @POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT: the - * caller must be in a specific security context; use - * polkit_authorization_constraint_get_selinux_context() to get the - * security context. - * - * This enumeration describes the type of the authorization - * constraint. - */ -typedef enum { - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_LOCAL, - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_ACTIVE, - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_EXE, - POLKIT_AUTHORIZATION_CONSTRAINT_TYPE_REQUIRE_SELINUX_CONTEXT, -} PolKitAuthorizationConstraintType; - -struct _PolKitAuthorizationConstraint; -typedef struct _PolKitAuthorizationConstraint PolKitAuthorizationConstraint; - -PolKitAuthorizationConstraint *polkit_authorization_constraint_get_require_local (void); -PolKitAuthorizationConstraint *polkit_authorization_constraint_get_require_active (void); -PolKitAuthorizationConstraint *polkit_authorization_constraint_get_require_exe (const char *path); -PolKitAuthorizationConstraint *polkit_authorization_constraint_get_require_selinux_context (const char *context); - -PolKitAuthorizationConstraint *polkit_authorization_constraint_ref (PolKitAuthorizationConstraint *authc); -void polkit_authorization_constraint_unref (PolKitAuthorizationConstraint *authc); -void polkit_authorization_constraint_debug (PolKitAuthorizationConstraint *authc); -polkit_bool_t polkit_authorization_constraint_validate (PolKitAuthorizationConstraint *authc); - -PolKitAuthorizationConstraintType polkit_authorization_constraint_type (PolKitAuthorizationConstraint *authc); - -const char *polkit_authorization_constraint_get_exe (PolKitAuthorizationConstraint *authc); - -const char *polkit_authorization_constraint_get_selinux_context (PolKitAuthorizationConstraint *authc); - -polkit_bool_t polkit_authorization_constraint_check_session (PolKitAuthorizationConstraint *authc, - PolKitSession *session); - -polkit_bool_t polkit_authorization_constraint_check_caller (PolKitAuthorizationConstraint *authc, - PolKitCaller *caller); - -size_t polkit_authorization_constraint_to_string (PolKitAuthorizationConstraint *authc, char *out_buf, size_t buf_size); -PolKitAuthorizationConstraint *polkit_authorization_constraint_from_string (const char *str); - -int polkit_authorization_constraint_get_from_caller (PolKitCaller *caller, PolKitAuthorizationConstraint **out_array, size_t array_size); - -polkit_bool_t polkit_authorization_constraint_equal (PolKitAuthorizationConstraint *a, - PolKitAuthorizationConstraint *b); - -POLKIT_END_DECLS - -#endif /* POLKIT_AUTHORIZATION_CONSTRAINT_H */ - - diff --git a/src/polkit/polkit-authorization-db-dummy.c b/src/polkit/polkit-authorization-db-dummy.c deleted file mode 100644 index 0b4c848..0000000 --- a/src/polkit/polkit-authorization-db-dummy.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-db.c : Dummy authorization database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <sys/time.h> -#include <sys/wait.h> -#include <errno.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <pwd.h> - -#include "polkit-debug.h" -#include "polkit-authorization-db.h" -#include "polkit-utils.h" -#include "polkit-private.h" -#include "polkit-test.h" - -/* PolKitAuthorizationDB structure is defined in polkit/polkit-private.h */ - -PolKitAuthorizationDBCapability -polkit_authorization_db_get_capabilities (void) -{ - return 0; -} - -PolKitAuthorizationDB * -_polkit_authorization_db_new (void) -{ - PolKitAuthorizationDB *authdb; - - authdb = kit_new0 (PolKitAuthorizationDB, 1); - authdb->refcount = 1; - - return authdb; -} - -polkit_bool_t -_polkit_authorization_db_pfe_foreach (PolKitPolicyCache *policy_cache, - PolKitPolicyCacheForeachFunc callback, - void *user_data) -{ - return FALSE; -} - -PolKitPolicyFileEntry* -_polkit_authorization_db_pfe_get_by_id (PolKitPolicyCache *policy_cache, - const char *action_id) -{ - return NULL; -} - -PolKitAuthorizationDB * -polkit_authorization_db_ref (PolKitAuthorizationDB *authdb) -{ - kit_return_val_if_fail (authdb != NULL, authdb); - authdb->refcount++; - return authdb; -} - -void -polkit_authorization_db_unref (PolKitAuthorizationDB *authdb) -{ - kit_return_if_fail (authdb != NULL); - authdb->refcount--; - if (authdb->refcount > 0) - return; - kit_free (authdb); -} - -void -polkit_authorization_db_debug (PolKitAuthorizationDB *authdb) -{ - kit_return_if_fail (authdb != NULL); - _pk_debug ("PolKitAuthorizationDB: refcount=%d", authdb->refcount); -} - -polkit_bool_t -polkit_authorization_db_validate (PolKitAuthorizationDB *authdb) -{ - kit_return_val_if_fail (authdb != NULL, FALSE); - - return TRUE; -} - -void -_polkit_authorization_db_invalidate_cache (PolKitAuthorizationDB *authdb) -{ -} - -polkit_bool_t -polkit_authorization_db_is_session_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitSession *session, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error) -{ - *out_is_authorized = FALSE; - *out_is_negative_authorized = FALSE; - return TRUE; -} - -polkit_bool_t -polkit_authorization_db_is_caller_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - polkit_bool_t revoke_if_one_shot, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error) -{ - *out_is_authorized = FALSE; - *out_is_negative_authorized = FALSE; - return TRUE; -} - - -polkit_bool_t -polkit_authorization_db_foreach (PolKitAuthorizationDB *authdb, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_foreach_for_uid (PolKitAuthorizationDB *authdb, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_foreach_for_action (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_foreach_for_action_for_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_revoke_entry (PolKitAuthorizationDB *authdb, - PolKitAuthorization *auth, - PolKitError **error) -{ - polkit_error_set_error (error, POLKIT_ERROR_NOT_SUPPORTED, "Not supported"); - return FALSE; -} - -polkit_bool_t -polkit_authorization_db_is_uid_blocked_by_self (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitError **error) -{ - polkit_error_set_error (error, POLKIT_ERROR_NOT_SUPPORTED, "Not supported"); - return FALSE; -} - - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_authorization_db = { - "polkit_authorization_db", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-authorization-db.c b/src/polkit/polkit-authorization-db.c deleted file mode 100644 index 2797b31..0000000 --- a/src/polkit/polkit-authorization-db.c +++ /dev/null @@ -1,1470 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-db.c : Represents the authorization database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <sys/time.h> -#include <sys/wait.h> -#include <errno.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <pwd.h> - -#include "polkit-debug.h" -#include "polkit-authorization-db.h" -#include "polkit-utils.h" -#include "polkit-private.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-authorization-db - * @title: Authorization Database - * @short_description: Reading from and writing to the database storing authorizations - * - * This class presents an abstraction of the authorization database as - * well as methods for reading and writing to it. - * - * The reading parts are in <literal>libpolkit</literal> and the - * writing parts are in <literal>libpolkit-grant</literal>. - * - * Since: 0.7 - **/ - -/** - * PolKitAuthorizationDB: - * - * Objects of this class are used to represent the authorization - * database. - * - * Since: 0.7 - **/ -struct _PolKitAuthorizationDB; - -/* PolKitAuthorizationDB structure is defined in polkit/polkit-private.h */ - -static kit_bool_t -clear_auth (void *data, void *user_data, KitList *list) -{ - PolKitAuthorization *auth = (PolKitAuthorization *) data; - polkit_authorization_unref (auth); - return FALSE; -} - -static void -_free_authlist (KitList *authlist) -{ - if (authlist != NULL) { - kit_list_foreach (authlist, clear_auth, NULL); - kit_list_free (authlist); - } -} - - -/** - * polkit_authorization_db_get_capabilities: - * - * Determine what capabilities the authorization backend has. - * - * Returns: Flags from the #PolKitAuthorizationDBCapability enumeration - * - * Since: 0.7 - */ -PolKitAuthorizationDBCapability -polkit_authorization_db_get_capabilities (void) -{ - return POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN; -} - -/** - * _polkit_authorization_db_new: - * - * Create a new #PolKitAuthorizationDB object. - * - * Returns: the new object - * - * Since: 0.7 - **/ -PolKitAuthorizationDB * -_polkit_authorization_db_new (void) -{ - PolKitAuthorizationDB *authdb; - - authdb = kit_new0 (PolKitAuthorizationDB, 1); - if (authdb == NULL) - goto oom; - authdb->refcount = 1; - - /* set up the hashtable */ - _polkit_authorization_db_invalidate_cache (authdb); -oom: - return authdb; -} - -/** - * polkit_authorization_db_ref: - * @authdb: the object - * - * Increase reference count. - * - * Returns: the object - * - * Since: 0.7 - **/ -PolKitAuthorizationDB * -polkit_authorization_db_ref (PolKitAuthorizationDB *authdb) -{ - kit_return_val_if_fail (authdb != NULL, authdb); - authdb->refcount++; - return authdb; -} - -/** - * polkit_authorization_db_unref: - * @authdb: the object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - * - * Since: 0.7 - **/ -void -polkit_authorization_db_unref (PolKitAuthorizationDB *authdb) -{ - kit_return_if_fail (authdb != NULL); - authdb->refcount--; - if (authdb->refcount > 0) - return; - if (authdb->uid_to_authlist != NULL) - kit_hash_unref (authdb->uid_to_authlist); - kit_free (authdb); -} - -/** - * polkit_authorization_db_debug: - * @authdb: the object - * - * Print debug details - * - * Since: 0.7 - **/ -void -polkit_authorization_db_debug (PolKitAuthorizationDB *authdb) -{ - kit_return_if_fail (authdb != NULL); - polkit_debug ("PolKitAuthorizationDB: refcount=%d", authdb->refcount); -} - -/** - * polkit_authorization_db_validate: - * @authdb: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - * - * Since: 0.7 - **/ -polkit_bool_t -polkit_authorization_db_validate (PolKitAuthorizationDB *authdb) -{ - kit_return_val_if_fail (authdb != NULL, FALSE); - - return TRUE; -} - -/** - * _polkit_authorization_db_invalidate_cache: - * @authdb: authorization database - * - * Tell the authorization database to invalidate any caches it might - * employ. This is called by #PolKitContext whenever configuration or - * anything else changes. - * - * Since: 0.7 - */ -void -_polkit_authorization_db_invalidate_cache (PolKitAuthorizationDB *authdb) -{ - /* out with the old, in the with new */ - if (authdb->uid_to_authlist != NULL) { - kit_hash_unref (authdb->uid_to_authlist); - authdb->uid_to_authlist = NULL; - } -} - -/** - * _authdb_get_auths_for_uid: - * @authdb: authorization database - * @uid: uid to get authorizations for. If -1 is passed authorizations - * for all users will be returned. - * @error: return location for error - * - * Internal function to get authorizations for a uid. - * - * Returns: A singly-linked list of #PolKitAuthorization - * objects. Caller shall not free this list. Returns #NULL if either - * calling process is not sufficiently privileged (error will be set) - * or if there are no authorizations for the given uid. - * - * Since: 0.7 - */ -static KitList * -_authdb_get_auths_for_uid (PolKitAuthorizationDB *authdb, - const uid_t uid, - PolKitError **error) -{ - KitList *ret; - char *helper_argv[] = {NULL, NULL, NULL}; - int exit_status; - char *standard_output; - size_t len; - off_t n; - - ret = NULL; - standard_output = NULL; - -#ifdef POLKIT_BUILD_TESTS - char helper_buf[256]; - char *helper_bin_dir; - if ((helper_bin_dir = getenv ("POLKIT_TEST_BUILD_DIR")) != NULL) { - kit_assert ((size_t) snprintf (helper_buf, sizeof (helper_buf), "%s/src/polkit/polkit-read-auth-helper-1", helper_bin_dir) < sizeof (helper_buf)); - helper_argv[0] = helper_buf; - } else { - helper_argv[0] = PACKAGE_LIBEXEC_DIR "/polkit-read-auth-helper-1"; - } -#else - helper_argv[0] = PACKAGE_LIBEXEC_DIR "/polkit-read-auth-helper-1"; -#endif - - /* first, see if this is in the cache */ - if (authdb->uid_to_authlist != NULL) { - ret = kit_hash_lookup (authdb->uid_to_authlist, (void *) uid, NULL); - if (ret != NULL) - goto out; - } - - helper_argv[1] = kit_strdup_printf ("%d", uid); - if (helper_argv[1] == NULL) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - goto out; - } - - /* we need to do this through a setgid polkituser helper - * because the auth file is readable only for uid 0 and gid - * polkituser. - */ - if (!kit_spawn_sync (NULL, /* const char *working_directory */ - 0, /* flags */ - helper_argv, /* char **argv */ - NULL, /* char **envp */ - NULL, /* char *stdin */ - &standard_output, /* char **stdout */ - NULL, /* char **stderr */ - &exit_status)) { /* int *exit_status */ - if (errno == ENOMEM) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "Error spawning read auth helper: OOM"); - } else { - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Error spawning read auth helper: %m"); - } - goto out; - } - - if (!WIFEXITED (exit_status)) { - kit_warning ("Read auth helper crashed!"); - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Read auth helper crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - polkit_error_set_error (error, - POLKIT_ERROR_NOT_AUTHORIZED_TO_READ_AUTHORIZATIONS_FOR_OTHER_USERS, - uid > 0 ? - "uid %d is not authorized to read authorizations for uid %d (requires org.freedesktop.policykit.read)" : - "uid %d is not authorized to read all authorizations (requires org.freedesktop.policykit.read)", - getuid (), uid); - goto out; - } - - //kit_warning ("standard_output='%s'", standard_output); - - if (standard_output != NULL) { - uid_t uid2; - len = strlen (standard_output); - - uid2 = uid; - - /* parse one line at a time (modifies standard_output in place) */ - n = 0; - while (n < len) { - off_t m; - char *line; - PolKitAuthorization *auth; - - m = n; - while (m < len && standard_output[m] != '\0') { - if (standard_output[m] == '\n') - break; - m++; - } - /* check EOF */ - if (standard_output[m] == '\0') - break; - standard_output[m] = '\0'; - - line = standard_output + n; - - if (strlen (line) >= 2 && strncmp (line, "#uid=", 5) == 0) { - uid2 = (uid_t) atoi (line + 5); - } - - if (strlen (line) >= 2 && line[0] != '#') { - auth = _polkit_authorization_new_for_uid (line, uid2); - if (auth == NULL) { - if (errno == ENOMEM) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - _free_authlist (ret); - ret = NULL; - goto out; - } else { - kit_warning ("Skipping invalid authline '%s'", line); - } - } - - //kit_warning (" #got %s", line); - - if (auth != NULL) { - KitList *ret2; - /* we need the authorizations in the chronological order... - * (TODO: optimized: prepend, then reverse after all items have been inserted) - */ - ret2 = kit_list_append (ret, auth); - if (ret2 == NULL) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - polkit_authorization_unref (auth); - _free_authlist (ret); - ret = NULL; - goto out; - } - ret = ret2; - } - } - - n = m + 1; - } - } - - if (authdb->uid_to_authlist == NULL) { - authdb->uid_to_authlist = kit_hash_new (kit_hash_direct_hash_func, - kit_hash_direct_equal_func, - NULL, - NULL, - NULL, - (KitFreeFunc) _free_authlist); - } - - if (authdb->uid_to_authlist == NULL || - !kit_hash_insert (authdb->uid_to_authlist, (void *) uid, ret)) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - _free_authlist (ret); - ret = NULL; - goto out; - } - -out: - kit_free (helper_argv[1]); - kit_free (standard_output); - return ret; -} - - -static polkit_bool_t -_internal_foreach (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - KitList *l; - KitList *auths; - KitList *auths_copy; - polkit_bool_t ret; - char *action_id; - - kit_return_val_if_fail (authdb != NULL, FALSE); - kit_return_val_if_fail (cb != NULL, FALSE); - - ret = FALSE; - - if (action == NULL) { - action_id = NULL; - } else { - if (!polkit_action_get_action_id (action, &action_id)) - goto out; - } - - auths = _authdb_get_auths_for_uid (authdb, uid, error); - if (auths == NULL) - goto out; - - /* have to copy the list and ref the auths because the authdb - * may disappear from under us due to revoke_if_one_shot... - */ - auths_copy = kit_list_copy (auths); - if (auths_copy == NULL) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - goto out; - } - for (l = auths_copy; l != NULL; l = l->next) - polkit_authorization_ref ((PolKitAuthorization *) l->data); - - for (l = auths_copy; l != NULL; l = l->next) { - PolKitAuthorization *auth = l->data; - - //kit_warning ("%d: action_id=%s uid=%d", - // uid, - // polkit_authorization_get_action_id (auth), - // polkit_authorization_get_uid (auth)); - - if (action_id != NULL) { - if (strcmp (polkit_authorization_get_action_id (auth), action_id) != 0) { - continue; - } - } - - if (cb (authdb, auth, user_data)) { - ret = TRUE; - break; - } - } - - for (l = auths_copy; l != NULL; l = l->next) - polkit_authorization_unref ((PolKitAuthorization *) l->data); - kit_list_free (auths_copy); - -out: - return ret; -} - - -/** - * polkit_authorization_db_foreach: - * @authdb: authorization database - * @cb: callback - * @user_data: user data to pass to callback - * @error: return location for error - * - * Iterate over all entries in the authorization database. - * - * Note that unless the calling process has the authorization - * org.freedesktop.policykit.read this function may return an error. - * - * Returns: #TRUE if the callback returned #TRUE to stop iterating. If - * #FALSE, either error may be set or the callback returns #FALSE on - * every invocation. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_foreach (PolKitAuthorizationDB *authdb, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return _internal_foreach (authdb, NULL, -1, cb, user_data, error); -} - -/** - * polkit_authorization_db_foreach_for_uid: - * @authdb: authorization database - * @uid: user to get authorizations for - * @cb: callback - * @user_data: user data to pass to callback - * @error: return location for error - * - * Iterate over all entries in the authorization database for a given - * user. - * - * Note that if the calling process asks for authorizations for a - * different uid than itself and it lacks the authorization - * org.freedesktop.policykit.read this function may return an error. - * - * Returns: #TRUE if the callback returned #TRUE to stop iterating. If - * #FALSE, either error may be set or the callback returns #FALSE on - * every invocation. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_foreach_for_uid (PolKitAuthorizationDB *authdb, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - return _internal_foreach (authdb, NULL, uid, cb, user_data, error); -} - -/** - * polkit_authorization_db_foreach_for_action: - * @authdb: authorization database - * @action: action to get authorizations for - * @cb: callback - * @user_data: user data to pass to callback - * @error: return location for error - * - * Iterate over all entries in the authorization database for a given - * action. - * - * Note that unless the calling process has the authorization - * org.freedesktop.policykit.read this function may return an error. - * - * Returns: #TRUE if the callback returned #TRUE to stop iterating. If - * #FALSE, either error may be set or the callback returns #FALSE on - * every invocation. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_foreach_for_action (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - kit_return_val_if_fail (action != NULL, FALSE); - return _internal_foreach (authdb, action, -1, cb, user_data, error); -} - -/** - * polkit_authorization_db_foreach_for_action_for_uid: - * @authdb: authorization database - * @action: action to get authorizations for - * @uid: user to get authorizations for - * @cb: callback - * @user_data: user data to pass to callback - * @error: return location for error - * - * Iterate over all entries in the authorization database for a given - * action and user. - * - * Note that if the calling process asks for authorizations for a - * different uid than itself and it lacks the authorization - * org.freedesktop.policykit.read this function may return an error. - * - * Returns: #TRUE if the callback returned #TRUE to stop iterating. If - * #FALSE, either error may be set or the callback returns #FALSE on - * every invocation. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_foreach_for_action_for_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error) -{ - kit_return_val_if_fail (action != NULL, FALSE); - return _internal_foreach (authdb, action, uid, cb, user_data, error); -} - - -typedef struct { - char *action_id; - uid_t session_uid; - char *session_objpath; - PolKitSession *session; - - polkit_bool_t *out_is_authorized; - polkit_bool_t *out_is_negative_authorized; -} CheckDataSession; - -static polkit_bool_t -_check_constraint_session (PolKitAuthorization *auth, PolKitAuthorizationConstraint *authc, void *user_data) -{ - PolKitSession *session = (PolKitSession *) user_data; - - if (!polkit_authorization_constraint_check_session (authc, session)) - goto no_match; - - return FALSE; -no_match: - return TRUE; -} - -static polkit_bool_t -_check_auth_for_session (PolKitAuthorizationDB *authdb, PolKitAuthorization *auth, void *user_data) -{ - polkit_bool_t ret; - uid_t pimp_uid; - polkit_bool_t is_negative; - CheckDataSession *cd = (CheckDataSession *) user_data; - - ret = FALSE; - - if (strcmp (polkit_authorization_get_action_id (auth), cd->action_id) != 0) - goto no_match; - - if (polkit_authorization_constraints_foreach (auth, _check_constraint_session, cd->session)) - goto no_match; - - switch (polkit_authorization_get_scope (auth)) - { - case POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT: - case POLKIT_AUTHORIZATION_SCOPE_PROCESS: - goto no_match; - - case POLKIT_AUTHORIZATION_SCOPE_SESSION: - if (strcmp (polkit_authorization_scope_session_get_ck_objref (auth), cd->session_objpath) != 0) - goto no_match; - break; - - case POLKIT_AUTHORIZATION_SCOPE_ALWAYS: - break; - } - - if (!polkit_authorization_was_granted_explicitly (auth, &pimp_uid, &is_negative)) - is_negative = FALSE; - - if (is_negative) { - *(cd->out_is_authorized) = FALSE; - *(cd->out_is_negative_authorized) = TRUE; - } else { - *(cd->out_is_authorized) = TRUE; - *(cd->out_is_negative_authorized) = FALSE; - } - - /* keep iterating; we may find negative auths... */ - - if (is_negative) { - *(cd->out_is_authorized) = FALSE; - *(cd->out_is_negative_authorized) = TRUE; - /* it only takes a single negative auth to block things so stop iterating */ - ret = TRUE; - } else { - *(cd->out_is_authorized) = TRUE; - *(cd->out_is_negative_authorized) = FALSE; - /* keep iterating; we may find negative auths... */ - } - -no_match: - return ret; -} - -/** - * polkit_authorization_db_is_session_authorized: - * @authdb: the authorization database - * @action: the action to check for - * @session: the session to check for - * @out_is_authorized: return location - * @out_is_negative_authorized: return location - * @error: return location for error - * - * Looks in the authorization database and determine if processes from - * the given session are authorized to do the given specific - * action. If there is an authorization record that matches the - * session, @out_is_authorized will be set to %TRUE. If there is a - * negative authorization record matching the session - * @out_is_negative_authorized will be set to %TRUE. - * - * Returns: #TRUE if the look up was performed; #FALSE if the caller - * of this function lacks privileges to ask this question (e.g. asking - * about a user that is not himself) or OOM (and @error will be set) - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_is_session_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitSession *session, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error) -{ - polkit_bool_t ret; - CheckDataSession cd; - - ret = FALSE; - - kit_return_val_if_fail (authdb != NULL, FALSE); - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_is_authorized != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &cd.action_id)) - return FALSE; - - if (!polkit_session_get_uid (session, &cd.session_uid)) - return FALSE; - - cd.session = session; - - if (!polkit_session_get_ck_objref (session, &cd.session_objpath) || cd.session_objpath == NULL) - return FALSE; - - ret = TRUE; - - cd.out_is_authorized = out_is_authorized; - cd.out_is_negative_authorized = out_is_negative_authorized; - *out_is_authorized = FALSE; - *out_is_negative_authorized = FALSE; - - if (polkit_authorization_db_foreach_for_uid (authdb, - cd.session_uid, - _check_auth_for_session, - &cd, - NULL)) { - ; - } - - return ret; -} - -typedef struct { - char *action_id; - uid_t caller_uid; - pid_t caller_pid; - polkit_uint64_t caller_pid_start_time; - char *session_objpath; - PolKitCaller *caller; - polkit_bool_t revoke_if_one_shot; - - polkit_bool_t *out_is_authorized; - polkit_bool_t *out_is_negative_authorized; - - PolKitError *error; -} CheckData; - -static polkit_bool_t -_check_constraint_caller (PolKitAuthorization *auth, PolKitAuthorizationConstraint *authc, void *user_data) -{ - PolKitCaller *caller = (PolKitCaller *) user_data; - - if (!polkit_authorization_constraint_check_caller (authc, caller)) - goto no_match; - - return FALSE; -no_match: - return TRUE; -} - -static polkit_bool_t -_check_auth_for_caller (PolKitAuthorizationDB *authdb, PolKitAuthorization *auth, void *user_data) -{ - polkit_bool_t ret; - uid_t pimp_uid; - polkit_bool_t is_negative; - pid_t caller_pid; - polkit_uint64_t caller_pid_start_time; - CheckData *cd = (CheckData *) user_data; - - ret = FALSE; - - if (strcmp (polkit_authorization_get_action_id (auth), cd->action_id) != 0) - goto no_match; - - if (polkit_authorization_constraints_foreach (auth, _check_constraint_caller, cd->caller)) - goto no_match; - - switch (polkit_authorization_get_scope (auth)) - { - case POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT: - case POLKIT_AUTHORIZATION_SCOPE_PROCESS: - if (!polkit_authorization_scope_process_get_pid (auth, &caller_pid, &caller_pid_start_time)) - goto no_match; - if (!(caller_pid == cd->caller_pid && caller_pid_start_time == cd->caller_pid_start_time)) - goto no_match; - - if (polkit_authorization_get_scope (auth) == POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT) { - - /* it's a match already; revoke if asked to do so */ - if (cd->revoke_if_one_shot) { - cd->error = NULL; - if (!polkit_authorization_db_revoke_entry (authdb, auth, &(cd->error))) { - //kit_warning ("Cannot revoke one-shot auth: %s: %s", - // polkit_error_get_error_name (cd->error), - // polkit_error_get_error_message (cd->error)); - /* stop iterating */ - ret = TRUE; - goto no_match; - } - /* revoked; now purge internal cache */ - _polkit_authorization_db_invalidate_cache (authdb); - } - } - break; - - case POLKIT_AUTHORIZATION_SCOPE_SESSION: - if (cd->session_objpath == NULL) - goto no_match; - if (strcmp (polkit_authorization_scope_session_get_ck_objref (auth), cd->session_objpath) != 0) - goto no_match; - break; - - case POLKIT_AUTHORIZATION_SCOPE_ALWAYS: - break; - } - - if (!polkit_authorization_was_granted_explicitly (auth, &pimp_uid, &is_negative)) - is_negative = FALSE; - - if (is_negative) { - *(cd->out_is_authorized) = FALSE; - *(cd->out_is_negative_authorized) = TRUE; - /* it only takes a single negative auth to block things so stop iterating */ - ret = TRUE; - } else { - *(cd->out_is_authorized) = TRUE; - *(cd->out_is_negative_authorized) = FALSE; - /* keep iterating; we may find negative auths... */ - } - - -no_match: - return ret; -} - -/** - * polkit_authorization_db_is_caller_authorized: - * @authdb: the authorization database - * @action: the action to check for - * @caller: the caller to check for - * @revoke_if_one_shot: Whether to revoke one-shot authorizations. See - * discussion in polkit_context_is_caller_authorized() for details. - * @out_is_authorized: return location - * @out_is_negative_authorized: return location - * @error: return location for error - * - * Looks in the authorization database if the given caller is - * authorized to do the given action. If there is an authorization - * record that matches the caller, @out_is_authorized will be set to - * %TRUE. If there is a negative authorization record matching the - * caller @out_is_negative_authorized will be set to %TRUE. - * - * Returns: #TRUE if the look up was performed; #FALSE if the caller - * of this function lacks privileges to ask this question (e.g. asking - * about a user that is not himself) or if OOM (and @error will be set) - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_is_caller_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - polkit_bool_t revoke_if_one_shot, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error) -{ - PolKitSession *session; - polkit_bool_t ret; - CheckData cd; - PolKitError *error2; - - ret = FALSE; - - kit_return_val_if_fail (authdb != NULL, FALSE); - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_is_authorized != NULL, FALSE); - - if (!polkit_action_get_action_id (action, &cd.action_id)) - goto out; - - if (!polkit_caller_get_pid (caller, &cd.caller_pid)) - goto out; - - if (!polkit_caller_get_uid (caller, &cd.caller_uid)) - goto out; - - cd.caller = caller; - cd.revoke_if_one_shot = revoke_if_one_shot; - cd.error = NULL; - - cd.caller_pid_start_time = polkit_sysdeps_get_start_time_for_pid (cd.caller_pid); - if (cd.caller_pid_start_time == 0) { - if (errno == ENOMEM) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "No memory"); - } else { - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Errno %d: %m", errno); - } - goto out; - } - - /* Caller does not _have_ to be member of a session */ - cd.session_objpath = NULL; - if (polkit_caller_get_ck_session (caller, &session) && session != NULL) { - if (!polkit_session_get_ck_objref (session, &cd.session_objpath)) - cd.session_objpath = NULL; - } - - cd.out_is_authorized = out_is_authorized; - cd.out_is_negative_authorized = out_is_negative_authorized; - *out_is_authorized = FALSE; - *out_is_negative_authorized = FALSE; - - error2 = NULL; - if (polkit_authorization_db_foreach_for_uid (authdb, - cd.caller_uid, - _check_auth_for_caller, - &cd, - &error2)) { - ; - } - - if (polkit_error_is_set (error2)) { - if (error != NULL) { - *error = error2; - } else { - polkit_error_free (error2); - } - goto out; - } - - if (polkit_error_is_set (cd.error)) { - if (error != NULL) { - *error = cd.error; - } else { - polkit_error_free (cd.error); - } - goto out; - } - - ret = TRUE; - -out: - return ret; -} - -/** - * polkit_authorization_db_revoke_entry: - * @authdb: the authorization database - * @auth: the authorization to revoke - * @error: return location for error - * - * Removes an authorization from the authorization database. This uses - * a privileged helper /usr/libexec/polkit-revoke-helper. - * - * Returns: #TRUE if the authorization was revoked, #FALSE otherwise and error is set - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_revoke_entry (PolKitAuthorizationDB *authdb, - PolKitAuthorization *auth, - PolKitError **error) -{ - char *helper_argv[] = {NULL, "", NULL, NULL, NULL}; - const char *auth_file_entry; - polkit_bool_t ret; - int exit_status; - - ret = FALSE; - - kit_return_val_if_fail (authdb != NULL, FALSE); - kit_return_val_if_fail (auth != NULL, FALSE); - - auth_file_entry = _polkit_authorization_get_authfile_entry (auth); - //g_debug ("should delete line '%s'", auth_file_entry); - -#ifdef POLKIT_BUILD_TESTS - char helper_buf[256]; - char *helper_bin_dir; - if ((helper_bin_dir = getenv ("POLKIT_TEST_BUILD_DIR")) != NULL) { - kit_assert ((size_t) snprintf (helper_buf, sizeof (helper_buf), "%s/src/polkit-grant/polkit-revoke-helper-1", helper_bin_dir) < sizeof (helper_buf)); - helper_argv[0] = helper_buf; - } else { - helper_argv[0] = PACKAGE_LIBEXEC_DIR "/polkit-revoke-helper-1"; - } -#else - helper_argv[0] = PACKAGE_LIBEXEC_DIR "/polkit-revoke-helper-1"; -#endif - - helper_argv[1] = (char *) auth_file_entry; - helper_argv[2] = "uid"; - helper_argv[3] = kit_strdup_printf ("%d", polkit_authorization_get_uid (auth)); - if (helper_argv[3] == NULL) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "Out of memory"); - goto out; - } - - if (!kit_spawn_sync (NULL, /* const char *working_directory */ - 0, /* flags */ - helper_argv, /* char **argv */ - NULL, /* char **envp */ - NULL, /* char *stdin */ - NULL, /* char **stdout */ - NULL, /* char **stderr */ - &exit_status)) { /* int *exit_status */ - if (errno == ENOMEM) { - polkit_error_set_error (error, - POLKIT_ERROR_OUT_OF_MEMORY, - "Error spawning revoke helper: OOM"); - } else { - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Error spawning revoke helper: %m"); - } - goto out; - } - - if (!WIFEXITED (exit_status)) { - kit_warning ("Revoke helper crashed!"); - polkit_error_set_error (error, - POLKIT_ERROR_GENERAL_ERROR, - "Revoke helper crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - polkit_error_set_error (error, - POLKIT_ERROR_NOT_AUTHORIZED_TO_REVOKE_AUTHORIZATIONS_FROM_OTHER_USERS, - "uid %d is not authorized to revoke authorizations from uid %d (requires org.freedesktop.policykit.revoke)", - getuid (), polkit_authorization_get_uid (auth)); - } else { - ret = TRUE; - } - -out: - kit_free (helper_argv[3]); - return ret; -} - -static polkit_bool_t -_check_self_block_foreach (PolKitAuthorizationDB *authdb, - PolKitAuthorization *auth, - void *user_data) -{ - polkit_bool_t *is_self_blocked = (polkit_bool_t *) user_data; - polkit_bool_t is_negative; - uid_t pimp_uid; - polkit_bool_t ret; - - if (!polkit_authorization_was_granted_explicitly (auth, &pimp_uid, &is_negative)) - is_negative = FALSE; - - if (is_negative) { - if (pimp_uid == getuid ()) { - *is_self_blocked = TRUE; - /* can't stop iterating.. there may be another one who blocked us too! */ - } else { - *is_self_blocked = FALSE; - ret = TRUE; - /* nope; someone else blocked us.. that's enough to ruin it */ - } - } - - return ret; -} - -/** - * polkit_authorization_db_is_uid_blocked_by_self: - * @authdb: the authorization database - * @action: the action to check for - * @uid: the user to check for - * @error: return location for error - * - * Determine whether there exists negative authorizations for the - * particular uid on the given action and whether those negative - * authorization are "granted" by the uid itself. - * - * If uid is different from getuid(), e.g. if the calling process asks - * for auths of another user this function will set an error if the - * calling user is not authorized for org.freedesktop.policykit.read. - * - * Returns: Result of computation described above; if error is set - * will return %FALSE. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_db_is_uid_blocked_by_self (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitError **error) -{ - polkit_bool_t is_self_blocked; - - kit_return_val_if_fail (authdb != NULL, FALSE); - kit_return_val_if_fail (action != NULL, FALSE); - - is_self_blocked = FALSE; - polkit_authorization_db_foreach_for_action_for_uid (authdb, - action, - uid, - _check_self_block_foreach, - &is_self_blocked, - error); - - return is_self_blocked; -} - - - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - PolKitAuthorizationDB *adb; - const char test_passwd[] = - "root:x:0:0:PolKit root user:/root:/bin/bash\n" - POLKIT_USER ":x:50400:50400:PolKit user:/:/sbin/nologin\n" - "pu1:x:50401:50401:PolKit Test user 0:/home/polkittest1:/bin/bash\n" - "pu2:x:50402:50402:PolKit Test user 1:/home/polkittest2:/bin/bash\n" - "pu3:x:50403:50403:PolKit Test user 2:/home/polkittest3:/bin/bash\n"; - const char test_pu1_run[] = - ""; - const char test_pu1_lib[] = - "scope=grant:action-id=org.freedesktop.policykit.read:when=1194634242:granted-by=0\n"; - const char test_pu2_run[] = - ""; - const char test_pu2_lib[] = - ""; - char test_pu3_run[512]; - const char test_pu3_lib[] = - ""; - PolKitCaller *caller; - PolKitAction *action; - PolKitSession *session; - polkit_bool_t is_auth; - polkit_bool_t is_neg; - PolKitError *error; - polkit_uint64_t start_time; - - - adb = NULL; - caller = NULL; - action = NULL; - session = NULL; - - start_time = polkit_sysdeps_get_start_time_for_pid (getpid ()); - if (start_time == 0) - goto out; - - if (snprintf (test_pu3_run, sizeof (test_pu3_run), - "scope=process:pid=%d:pid-start-time=%lld:action-id=org.example.per-process:when=1196307507:auth-as=500\n" - "scope=process-one-shot:pid=%d:pid-start-time=%lld:action-id=org.example.per-process-one-shot:when=1196307507:auth-as=500\n" - "scope=session:session-id=%%2FSession1:action-id=org.example.per-session:when=1196307507:auth-as=500\n", - getpid (), start_time, - getpid (), start_time) >= (int) sizeof (test_pu3_run)) - goto fail; - - if (setenv ("POLKIT_TEST_LOCALSTATE_DIR", TEST_DATA_DIR "authdb-test", 1) != 0) - goto fail; - - if (setenv ("POLKIT_TEST_BUILD_DIR", TEST_BUILD_DIR, 1) != 0) - goto fail; - - if (setenv ("KIT_TEST_PASSWD_FILE", TEST_DATA_DIR "authdb-test/passwd", 1) != 0) - goto fail; - - /* create test users */ - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/passwd", 0644, - test_passwd, sizeof (test_passwd) - 1)) - goto out; - - /* seed the authdb with known defaults */ - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/run/polkit-1/user-pu1.auths", 0644, - test_pu1_run, sizeof (test_pu1_run) - 1)) - goto out; - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/lib/polkit-1/user-pu1.auths", 0644, - test_pu1_lib, sizeof (test_pu1_lib) - 1)) - goto out; - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/run/polkit-1/user-pu2.auths", 0644, - test_pu2_run, sizeof (test_pu2_run) - 1)) - goto out; - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/lib/polkit-1/user-pu2.auths", 0644, - test_pu2_lib, sizeof (test_pu2_lib) - 1)) - goto out; - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/run/polkit-1/user-pu3.auths", 0644, - test_pu3_run, strlen (test_pu3_run))) - goto out; - if (!kit_file_set_contents (TEST_DATA_DIR "authdb-test/lib/polkit-1/user-pu3.auths", 0644, - test_pu3_lib, sizeof (test_pu3_lib) - 1)) - goto out; - - if ((adb = _polkit_authorization_db_new ()) == NULL) - goto out; - - - if ((action = polkit_action_new ()) == NULL) - goto out; - if ((caller = polkit_caller_new ()) == NULL) - goto out; - kit_assert (polkit_caller_set_pid (caller, getpid ())); - - /* initialize all pretend environment variables */ - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH", "", 1) != 0) - goto fail; - - /* - * test: "org.freedesktop.policykit.read" - */ - if (!polkit_action_set_action_id (action, "org.freedesktop.policykit.read")) - goto out; - - /* test: pu1 has the auth org.freedesktop.policykit.read */ - kit_assert (polkit_caller_set_uid (caller, 50401)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50401", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && is_auth && !is_neg); - } else { - //kit_warning ("%p: %d: %s: %s", - // error, - // polkit_error_get_error_code (error), - // polkit_error_get_error_name (error), - // polkit_error_get_error_message (error)); - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - /* test: pu2 does not have the auth org.freedesktop.policykit.read */ - kit_assert (polkit_caller_set_uid (caller, 50402)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50402", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error)); - kit_assert (!is_auth && !is_neg); - } else { - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - /************************/ - /* INVALIDATE THE CACHE */ - /************************/ - _polkit_authorization_db_invalidate_cache (adb); - - /* test: pu1 can check that pu2 does not have the auth org.freedesktop.policykit.read */ - kit_assert (polkit_caller_set_uid (caller, 50402)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50401", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && !is_auth && !is_neg); - } else { - kit_warning ("%p: %d: %s: %s", - error, - polkit_error_get_error_code (error), - polkit_error_get_error_name (error), - polkit_error_get_error_message (error)); - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - /* test: pu2 cannot check if pu1 have the auth org.freedesktop.policykit.read */ - kit_assert (polkit_caller_set_uid (caller, 50401)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50402", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_warning ("pu2 shouldn't be able to read auths for pu1: %d %d", is_auth, is_neg); - goto fail; - } else { - kit_assert (polkit_error_is_set (error) && - (polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY || - polkit_error_get_error_code (error) == POLKIT_ERROR_NOT_AUTHORIZED_TO_READ_AUTHORIZATIONS_FOR_OTHER_USERS)); - polkit_error_free (error); - } - - /* test: pu3 is authorized for org.example.per-process for just this process id */ - if (!polkit_action_set_action_id (action, "org.example.per-process")) - goto out; - - kit_assert (polkit_caller_set_uid (caller, 50403)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50403", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && is_auth && !is_neg); - } else { - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - /* test: pu3 is authorized for org.example.per-process-one-shot just once */ - if (!polkit_action_set_action_id (action, "org.example.per-process-one-shot")) - goto out; - - kit_assert (polkit_caller_set_uid (caller, 50403)); - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_UID", "50403", 1) != 0) - goto fail; - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, TRUE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && is_auth && !is_neg); - - /************************/ - /* INVALIDATE THE CACHE */ - /************************/ - _polkit_authorization_db_invalidate_cache (adb); - - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, TRUE, &is_auth, &is_neg, &error)) { - if (is_auth || is_neg) { - kit_warning ("pu3 shouldn't be authorized for something twice: %d %d", is_auth, is_neg); - goto fail; - } - } else { - kit_assert (polkit_error_is_set (error)); - kit_assert (polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - } else { - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - if ((session = polkit_session_new ()) == NULL) - goto out; - - /* test: pu3 only in the right session is authorized for org.example.per-session */ - if (!polkit_action_set_action_id (action, "org.example.per-session")) - goto out; - - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH", "/Session1", 1) != 0) - goto fail; - kit_assert (polkit_session_set_ck_is_local (session, TRUE)); - if (!polkit_session_set_ck_objref (session, "/Session1")) - goto out; - kit_assert (polkit_caller_set_ck_session (caller, session)); - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && is_auth && !is_neg); - } else { - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - - if (setenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH", "/Session2", 1) != 0) - goto fail; - if (!polkit_session_set_ck_objref (session, "/Session2")) - goto out; - kit_assert (polkit_session_set_ck_is_local (session, TRUE)); - kit_assert (polkit_caller_set_ck_session (caller, session)); - error = NULL; - if (polkit_authorization_db_is_caller_authorized (adb, action, caller, FALSE, &is_auth, &is_neg, &error)) { - kit_assert (! polkit_error_is_set (error) && !is_auth && !is_neg); - } else { - kit_assert (polkit_error_is_set (error) && - polkit_error_get_error_code (error) == POLKIT_ERROR_OUT_OF_MEMORY); - polkit_error_free (error); - } - -out: - - if (action != NULL) - polkit_action_unref (action); - - if (caller != NULL) - polkit_caller_unref (caller); - - if (session != NULL) - polkit_session_unref (session); - - if (adb != NULL) { - polkit_authorization_db_debug (adb); - polkit_authorization_db_validate (adb); - polkit_authorization_db_ref (adb); - polkit_authorization_db_unref (adb); - polkit_authorization_db_unref (adb); - } - - if (unsetenv ("POLKIT_TEST_PRETEND_TO_BE_UID") != 0) - goto fail; - - if (unsetenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH") != 0) - goto fail; - - if (unsetenv ("POLKIT_TEST_PRETEND_TO_BE_SELINUX_CONTEXT") != 0) - goto fail; - - if (unsetenv ("POLKIT_TEST_PRETEND_TO_BE_PID") != 0) - goto fail; - - if (unsetenv ("POLKIT_TEST_LOCALSTATE_DIR") != 0) - goto fail; - - if (unsetenv ("POLKIT_TEST_BUILD_DIR") != 0) - goto fail; - - if (unsetenv ("KIT_TEST_PASSWD_FILE") != 0) - goto fail; - - return TRUE; -fail: - return FALSE; -} - - -KitTest _test_authorization_db = { - "polkit_authorization_db", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-authorization-db.h b/src/polkit/polkit-authorization-db.h deleted file mode 100644 index c206a32..0000000 --- a/src/polkit/polkit-authorization-db.h +++ /dev/null @@ -1,175 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization-db.h : Represents the authorization database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_AUTHORIZATION_DB_H -#define POLKIT_AUTHORIZATION_DB_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-authorization.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-caller.h> -#include <polkit/polkit-session.h> -#include <polkit/polkit-error.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitAuthorizationDB; -typedef struct _PolKitAuthorizationDB PolKitAuthorizationDB; - -/** - * PolKitAuthorizationDBCapability: - * @POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN: Users can obtain - * authorizations through authentication - * - * Capabilities of the authorization database backend. - * - * Since: 0.7 - */ -typedef enum -{ - POLKIT_AUTHORIZATION_DB_CAPABILITY_CAN_OBTAIN = 1 << 0 -} PolKitAuthorizationDBCapability; - -PolKitAuthorizationDBCapability polkit_authorization_db_get_capabilities (void); - -PolKitAuthorizationDB *polkit_authorization_db_ref (PolKitAuthorizationDB *authdb); -void polkit_authorization_db_unref (PolKitAuthorizationDB *authdb); - -void polkit_authorization_db_debug (PolKitAuthorizationDB *authdb); -polkit_bool_t polkit_authorization_db_validate (PolKitAuthorizationDB *authdb); - -polkit_bool_t polkit_authorization_db_is_session_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitSession *session, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_is_caller_authorized (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - polkit_bool_t revoke_if_one_shot, - polkit_bool_t *out_is_authorized, - polkit_bool_t *out_is_negative_authorized, - PolKitError **error); - -/** - * PolKitAuthorizationDBForeach: - * @authdb: authorization database - * @auth: authorization; user shall not unref this object. Unless - * reffed by the user it will be destroyed when the callback function - * returns. - * @user_data: user data passed - * - * Type of callback function for iterating over authorizations. - * - * Returns: pass #TRUE to stop iterating - * - * Since: 0.7 - */ -typedef polkit_bool_t (*PolKitAuthorizationDBForeach) (PolKitAuthorizationDB *authdb, - PolKitAuthorization *auth, - void *user_data); - -polkit_bool_t polkit_authorization_db_foreach (PolKitAuthorizationDB *authdb, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_foreach_for_uid (PolKitAuthorizationDB *authdb, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_foreach_for_action (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_foreach_for_action_for_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationDBForeach cb, - void *user_data, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_add_entry_process_one_shot (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as); - -polkit_bool_t polkit_authorization_db_add_entry_process (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as); - -polkit_bool_t polkit_authorization_db_add_entry_session (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as); - -polkit_bool_t polkit_authorization_db_add_entry_always (PolKitAuthorizationDB *authdb, - PolKitAction *action, - PolKitCaller *caller, - uid_t user_authenticated_as); - -polkit_bool_t polkit_authorization_db_grant_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_grant_negative_to_uid (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitAuthorizationConstraint **constraints, - PolKitError **error); - -polkit_bool_t polkit_authorization_db_revoke_entry (PolKitAuthorizationDB *authdb, - PolKitAuthorization *auth, - PolKitError **error); - - -polkit_bool_t polkit_authorization_db_is_uid_blocked_by_self (PolKitAuthorizationDB *authdb, - PolKitAction *action, - uid_t uid, - PolKitError **error); - -POLKIT_END_DECLS - -#endif /* POLKIT_AUTHORIZATION_DB_H */ - - diff --git a/src/polkit/polkit-authorization.c b/src/polkit/polkit-authorization.c deleted file mode 100644 index 431fbb2..0000000 --- a/src/polkit/polkit-authorization.c +++ /dev/null @@ -1,879 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization.c : Represents an entry in the authorization - * database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-authorization.h" -#include "polkit-utils.h" -#include "polkit-private.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-authorization - * @title: Authorization Entry - * @short_description: An entry in the autothorization database - * - * This class is used to represent entries in the authorization - * database. - * - * Since: 0.7 - **/ - -/** - * PolKitAuthorization: - * - * Objects of this class are used to represent entries in the - * authorization database. - * - * Since: 0.7 - **/ -struct _PolKitAuthorization -{ - int refcount; - - char *entry_in_auth_file; - - PolKitAuthorizationScope scope; - KitList *constraints; - - char *action_id; - uid_t uid; - time_t when; - uid_t authenticated_as_uid; - - pid_t pid; - polkit_uint64_t pid_start_time; - - polkit_bool_t explicitly_granted; - uid_t explicitly_granted_by; - - polkit_bool_t is_negative; - - char *session_id; -}; - -const char * -_polkit_authorization_get_authfile_entry (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, NULL); - return auth->entry_in_auth_file; -} - - -/** - * polkit_authorization_type: - * @auth: the authorization object - * - * Determine the type of authorization. - * - * Returns: the authorization type - * - * Since: 0.7 - */ -PolKitAuthorizationType -polkit_authorization_type (PolKitAuthorization *auth) -{ - return POLKIT_AUTHORIZATION_TYPE_UID; -} - -#ifdef POLKIT_AUTHDB_DEFAULT - -typedef struct { - int cur_attr; - int req_attr; - - int cur_token; - PolKitAuthorization *auth; -} EntryParserData; - -enum { - ATTR_PID = 1<<0, - ATTR_PID_START_TIME = 1<<1, - ATTR_SESSION_ID = 1<<2, - ATTR_ACTION_ID = 1<<3, - ATTR_WHEN = 1<<4, - ATTR_AUTH_AS = 1<<5, - ATTR_GRANTED_BY = 1<<6, -}; - -static kit_bool_t -_parse_entry (const char *key, const char *value, void *user_data) -{ - char *ep; - kit_bool_t ret; - EntryParserData *epd = (EntryParserData *) user_data; - PolKitAuthorization *auth = epd->auth; - - ret = FALSE; - - /* scope needs to be first and there can only be only instance of it */ - if (strcmp (key, "scope") == 0) { - if (epd->cur_token != 0) - goto error; - - if (strcmp (value, "process-one-shot") == 0) { - auth->scope = POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT; - epd->req_attr = ATTR_PID | ATTR_PID_START_TIME | ATTR_ACTION_ID | ATTR_WHEN | ATTR_AUTH_AS; - } else if (strcmp (value, "process") == 0) { - auth->scope = POLKIT_AUTHORIZATION_SCOPE_PROCESS; - epd->req_attr = ATTR_PID | ATTR_PID_START_TIME | ATTR_ACTION_ID | ATTR_WHEN | ATTR_AUTH_AS; - } else if (strcmp (value, "session") == 0) { - auth->scope = POLKIT_AUTHORIZATION_SCOPE_SESSION; - epd->req_attr = ATTR_SESSION_ID | ATTR_ACTION_ID | ATTR_WHEN | ATTR_AUTH_AS; - } else if (strcmp (value, "always") == 0) { - auth->scope = POLKIT_AUTHORIZATION_SCOPE_ALWAYS; - epd->req_attr = ATTR_ACTION_ID | ATTR_WHEN | ATTR_AUTH_AS; - } else if (strcmp (value, "grant") == 0) { - auth->explicitly_granted = TRUE; - auth->scope = POLKIT_AUTHORIZATION_SCOPE_ALWAYS; - epd->req_attr = ATTR_ACTION_ID | ATTR_WHEN | ATTR_GRANTED_BY; - } else if (strcmp (value, "grant-negative") == 0) { - auth->is_negative = TRUE; - auth->explicitly_granted = TRUE; - auth->scope = POLKIT_AUTHORIZATION_SCOPE_ALWAYS; - epd->req_attr = ATTR_ACTION_ID | ATTR_WHEN | ATTR_GRANTED_BY; - } else { - goto error; - } - - } else if (strcmp (key, "pid") == 0) { - - if (epd->cur_attr & ATTR_PID) - goto error; - epd->cur_attr |= ATTR_PID; - - auth->pid = strtoul (value, &ep, 10); - if (strlen (value) == 0 || *ep != '\0') - goto error; - - } else if (strcmp (key, "pid-start-time") == 0) { - - if (epd->cur_attr & ATTR_PID_START_TIME) - goto error; - epd->cur_attr |= ATTR_PID_START_TIME; - - auth->pid_start_time = strtoull (value, &ep, 10); - if (strlen (value) == 0 || *ep != '\0') - goto error; - - } else if (strcmp (key, "session-id") == 0) { - - if (epd->cur_attr & ATTR_SESSION_ID) - goto error; - epd->cur_attr |= ATTR_SESSION_ID; - - auth->session_id = kit_strdup (value); - if (auth->session_id == NULL) - goto error; - - } else if (strcmp (key, "action-id") == 0) { - - if (epd->cur_attr & ATTR_ACTION_ID) - goto error; - epd->cur_attr |= ATTR_ACTION_ID; - - if (!polkit_action_validate_id (value)) - goto error; - auth->action_id = kit_strdup (value); - if (auth->action_id == NULL) - goto error; - - } else if (strcmp (key, "when") == 0) { - - if (epd->cur_attr & ATTR_WHEN) - goto error; - epd->cur_attr |= ATTR_WHEN; - - auth->when = strtoull (value, &ep, 10); - if (strlen (value) == 0 || *ep != '\0') - goto error; - - } else if (strcmp (key, "auth-as") == 0) { - - if (epd->cur_attr & ATTR_AUTH_AS) - goto error; - epd->cur_attr |= ATTR_AUTH_AS; - - auth->authenticated_as_uid = strtoul (value, &ep, 10); - if (strlen (value) == 0 || *ep != '\0') - goto error; - - } else if (strcmp (key, "granted-by") == 0) { - - if (epd->cur_attr & ATTR_GRANTED_BY) - goto error; - epd->cur_attr |= ATTR_GRANTED_BY; - - auth->explicitly_granted_by = strtoul (value, &ep, 10); - if (strlen (value) == 0 || *ep != '\0') - goto error; - - } else if (strcmp (key, "constraint") == 0) { - PolKitAuthorizationConstraint *c; - KitList *l; - - c = polkit_authorization_constraint_from_string (value); - if (c == NULL) - goto error; - - l = kit_list_append (auth->constraints, c); - if (l == NULL) - goto error; - auth->constraints = l; - } - - ret = TRUE; - -error: - epd->cur_token += 1; - return ret; -} - -PolKitAuthorization * -_polkit_authorization_new_for_uid (const char *entry_in_auth_file, uid_t uid) -{ - PolKitAuthorization *auth; - EntryParserData epd; - - kit_return_val_if_fail (entry_in_auth_file != NULL, NULL); - - auth = kit_new0 (PolKitAuthorization, 1); - if (auth == NULL) { - goto oom; - } - - auth->refcount = 1; - auth->entry_in_auth_file = kit_strdup (entry_in_auth_file); - if (auth->entry_in_auth_file == NULL) - goto oom; - - auth->uid = uid; - - epd.auth = auth; - epd.cur_token = 0; - epd.cur_attr = 0; - epd.req_attr = 0; - if (!kit_string_entry_parse (entry_in_auth_file, _parse_entry, &epd)) { - goto error; - } - - /* check that we have all core attributes */ - if (epd.cur_attr != epd.req_attr) { - goto error; - } - - return auth; - -error: - //g_warning ("Error parsing token %d from line '%s'", n, entry_in_auth_file); -oom: - if (auth != NULL) - polkit_authorization_unref (auth); - return NULL; -} - -#endif /* POLKIT_AUTHDB_DEFAULT */ - -/** - * polkit_authorization_ref: - * @auth: the authorization object - * - * Increase reference count. - * - * Returns: the object - * - * Since: 0.7 - **/ -PolKitAuthorization * -polkit_authorization_ref (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, auth); - auth->refcount++; - return auth; -} - -/** - * polkit_authorization_unref: - * @auth: the authorization object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - * - * Since: 0.7 - **/ -void -polkit_authorization_unref (PolKitAuthorization *auth) -{ - KitList *l; - - kit_return_if_fail (auth != NULL); - auth->refcount--; - if (auth->refcount > 0) - return; - - kit_free (auth->entry_in_auth_file); - kit_free (auth->action_id); - kit_free (auth->session_id); - - for (l = auth->constraints; l != NULL; l = l->next) { - PolKitAuthorizationConstraint *c = (PolKitAuthorizationConstraint *) l->data; - polkit_authorization_constraint_unref (c); - } - if (auth->constraints != NULL) - kit_list_free (auth->constraints); - - kit_free (auth); -} - -/** - * polkit_authorization_debug: - * @auth: the object - * - * Print debug details - * - * Since: 0.7 - **/ -void -polkit_authorization_debug (PolKitAuthorization *auth) -{ - kit_return_if_fail (auth != NULL); - polkit_debug ("PolKitAuthorization: refcount=%d", auth->refcount); - polkit_debug (" scope = %d", auth->scope); - polkit_debug (" pid = %d", auth->pid); - polkit_debug (" pid_start_time = %Lu", auth->pid_start_time); - polkit_debug (" action_id = %s", auth->action_id); - polkit_debug (" when = %Lu", (polkit_uint64_t) auth->when); - polkit_debug (" auth_as_uid = %d", auth->authenticated_as_uid); -} - -/** - * polkit_authorization_validate: - * @auth: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - * - * Since: 0.7 - **/ -polkit_bool_t -polkit_authorization_validate (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, FALSE); - - return TRUE; -} - -/** - * polkit_authorization_get_action_id: - * @auth: the object - * - * Get the action this authorization is for - * - * Returns: the action id. Caller should not free this string. - * - * Since: 0.7 - */ -const char * -polkit_authorization_get_action_id (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, NULL); - - return auth->action_id; -} - -/** - * polkit_authorization_get_scope: - * @auth: the object - * - * Get the scope of the authorization; e.g. whether it's confined to a - * single process, a single session or can be retained - * indefinitely. Also keep in mind that an authorization is subject to - * constraints, see polkit_authorization_constraints_foreach() for - * details. - * - * Returns: the scope - * - * Since: 0.7 - */ -PolKitAuthorizationScope -polkit_authorization_get_scope (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, 0); - - return auth->scope; -} - -/** - * polkit_authorization_scope_process_get_pid: - * @auth: the object - * @out_pid: return location - * @out_pid_start_time: return location - * - * If scope is #POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT or - * #POLKIT_AUTHORIZATION_SCOPE_PROCESS, get information about what - * process the authorization is confined to. - * - * As process identifiers can be recycled, the start time of the - * process (the unit is not well-defined; on Linux it's the number of - * milliseconds since the system was started) is also returned. - * - * Returns: #TRUE if information was returned - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_scope_process_get_pid (PolKitAuthorization *auth, - pid_t *out_pid, - polkit_uint64_t *out_pid_start_time) -{ - kit_return_val_if_fail (auth != NULL, FALSE); - kit_return_val_if_fail (out_pid != NULL, FALSE); - kit_return_val_if_fail (out_pid_start_time != NULL, FALSE); - kit_return_val_if_fail (auth->scope == POLKIT_AUTHORIZATION_SCOPE_PROCESS || - auth->scope == POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT, FALSE); - - *out_pid = auth->pid; - *out_pid_start_time = auth->pid_start_time; - - return TRUE; -} - -/** - * polkit_authorization_scope_session_get_ck_objref: - * @auth: the object - * - * Gets the ConsoleKit object path for the session the authorization - * is confined to. - * - * Returns: #NULL if scope wasn't session - * - * Since: 0.7 - */ -const char * -polkit_authorization_scope_session_get_ck_objref (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, FALSE); - kit_return_val_if_fail (auth->scope == POLKIT_AUTHORIZATION_SCOPE_SESSION, FALSE); - - return auth->session_id; -} - -/** - * polkit_authorization_get_uid: - * @auth: the object - * - * Gets the UNIX user id for the user the authorization is confined - * to. - * - * Returns: The UNIX user id for whom the authorization is confied to - * - * Since: 0.7 - */ -uid_t -polkit_authorization_get_uid (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, 0); - return auth->uid; -} - -/** - * polkit_authorization_get_time_of_grant: - * @auth: the object - * - * Returns the point in time the authorization was granted. The value - * is UNIX time, e.g. number of seconds since the Epoch Jan 1, 1970 - * 0:00 UTC. - * - * Returns: When authorization was granted - * - * Since: 0.7 - */ -time_t -polkit_authorization_get_time_of_grant (PolKitAuthorization *auth) -{ - kit_return_val_if_fail (auth != NULL, 0); - return auth->when; -} - -/** - * polkit_authorization_was_granted_via_defaults: - * @auth: the object - * @out_user_authenticated_as: return location - * - * Determine if the authorization was obtained by the user by - * authenticating as himself or an administrator via the the - * "defaults" section in the <literal>.policy</literal> file for the - * action (e.g. "allow_any", "allow_inactive", "allow_active"). - * - * Compare with polkit_authorization_was_granted_explicitly() - only - * one of these functions can return #TRUE. - * - * Returns: #TRUE if the authorization was obtained by the user - * himself authenticating. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_was_granted_via_defaults (PolKitAuthorization *auth, - uid_t *out_user_authenticated_as) -{ - kit_return_val_if_fail (auth != NULL, FALSE); - kit_return_val_if_fail (out_user_authenticated_as != NULL, FALSE); - - if (auth->explicitly_granted) - return FALSE; - - *out_user_authenticated_as = auth->authenticated_as_uid; - return TRUE; -} - -/** - * polkit_authorization_was_granted_explicitly: - * @auth: the object - * @out_by_whom: return location - * @out_is_negative: return location - * - * Determine if the authorization was explicitly granted by a - * sufficiently privileged user. - * - * Compare with polkit_authorization_was_granted_via_defaults() - only - * one of these functions can return #TRUE. - * - * Returns: #TRUE if the authorization was explicitly granted by a - * sufficiently privileger user. If %TRUE, the user who granted the - * authorization is returned in %out_by_whom. If the authorization is - * negative, %TRUE is returned in %out_is_negative. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_was_granted_explicitly (PolKitAuthorization *auth, - uid_t *out_by_whom, - polkit_bool_t *out_is_negative) -{ - kit_return_val_if_fail (auth != NULL, FALSE); - kit_return_val_if_fail (out_by_whom != NULL, FALSE); - kit_return_val_if_fail (out_is_negative != NULL, FALSE); - - if (!auth->explicitly_granted) - return FALSE; - - *out_by_whom = auth->explicitly_granted_by; - *out_is_negative = auth->is_negative; - - return TRUE; -} - -/** - * polkit_authorization_constraints_foreach: - * @auth: the object - * @cb: callback function - * @user_data: user data - * - * Iterate over all constraints associated with an authorization. - * - * Returns: %TRUE if the caller short-circuited the iteration. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_authorization_constraints_foreach (PolKitAuthorization *auth, - PolKitAuthorizationConstraintsForeachFunc cb, - void *user_data) -{ - KitList *i; - - kit_return_val_if_fail (auth != NULL, TRUE); - kit_return_val_if_fail (cb != NULL, TRUE); - - for (i = auth->constraints; i != NULL; i = i->next) { - PolKitAuthorizationConstraint *c = i->data; - - if (cb (auth, c, user_data)) - return TRUE; - } - - return FALSE; -} - -#ifdef POLKIT_BUILD_TESTS - -#ifdef POLKIT_AUTHDB_DEFAULT - -typedef struct { - const char *entry; - PolKitAuthorizationType type; - PolKitAuthorizationScope scope; - const char *action_id; - time_t time_of_grant; - pid_t pid; - polkit_uint64_t pid_start_time; - const char *session; - PolKitAuthorizationConstraint *constraint; - polkit_bool_t explicit; - uid_t from; -} TestAuth; - -static polkit_bool_t -_run_test (void) -{ - const char *invalid_auths[] = { - "scope=non-existant", - - /* wrong number of items */ - "scope=process-one-shot", - "scope=process", - "scope=session", - "scope=always", - "scope=grant", - "scope=grant-negative", - - /* repetition of core attributes */ - "scope=process:pid=1:pid=2", - "scope=process:pid-start-time=1:pid-start-time=2", - "scope=process:session-id=1:session-id=2", - "scope=process:action-id=org.foo:action-id=org.bar", - "scope=process:when=1:when=2", - "scope=process:auth-as=1:auth-as=2", - "scope=process:granted-by=1:granted-by=2", - - /* malformed components */ - "scope=process:pid=14485xyz:pid-start-time=26817340:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763:auth-as=500:constraint=local", - "scope=process:pid=14485:pid-start-time=26817340xyz:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763:auth-as=500:constraint=local", - "scope=process:pid=14485:pid-start-time=26817340:0xyaction-id=org.gnome.policykit.examples.frobnicate:when=1194631763:auth-as=500:constraint=local", - "scope=process:pid=14485:pid-start-time=26817340:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763xyz:auth-as=500:constraint=local", - "scope=process:pid=14485:pid-start-time=26817340:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763:500xyz:constraint=local", - "scope=process:pid=14485:pid-start-time=26817340:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763:auth-as=500:constraint=MALFORMED_CONSTRAINT", - - /* TODO: validate ConsoleKit paths - "scope=session:xyz/org/freedesktop/ConsoleKit/Session1:action-id=org.gnome.policykit.examples.punch:1194631779:auth-as=500:constraint=local",*/ - "scope=session:/org/freedesktop/ConsoleKit/Session1:0xyaction-id=org.gnome.policykit.examples.punch:1194631779:auth-as=500:constraint=local", - "scope=session:/org/freedesktop/ConsoleKit/Session1:action-id=org.gnome.policykit.examples.punch:1194631779xyz:auth-as=500:constraint=local", - "scope=session:/org/freedesktop/ConsoleKit/Session1:action-id=org.gnome.policykit.examples.punch:1194631779:500xyz:constraint=local", - "scope=session:/org/freedesktop/ConsoleKit/Session1:action-id=org.gnome.policykit.examples.punch:1194631779:auth-as=500:constraint=MALFORMED", - - "scope=always:action-id=0xyorg.gnome.clockapplet.mechanism.settimezone:when=1193598494:auth-as=500:constraint=local", - "scope=always:action-id=org.gnome.clockapplet.mechanism.settimezone:when=xyz1193598494:auth-as=500:constraint=local", - "scope=always:action-id=org.gnome.clockapplet.mechanism.settimezone:when=1193598494:auth-as=xyz500:constraint=local", - "scope=always:action-id=org.gnome.clockapplet.mechanism.settimezone:when=1193598494:auth-as=500:constraint=MALFORMED", - - "scope=grant:action-id=0xyorg.freedesktop.policykit.read:when=1194634242:granted-by=0:constraint=none", - "scope=grant:action-id=org.freedesktop.policykit.read:when=xyz1194634242:granted-by=0:constraint=none", - "scope=grant:action-id=org.freedesktop.policykit.read:when=1194634242:granted-by=xyz0:constraint=none", - "scope=grant:action-id=org.freedesktop.policykit.read:when=1194634242:granted-by=0:constraint=MALFORMED", - - "random-future-key=some-value:scope=always:action-id=org.gnome.clockapplet.mechanism.settimezone:when=1193598494:auth-as500:constraint=local", - - }; - size_t num_invalid_auths = sizeof (invalid_auths) / sizeof (const char *); - TestAuth valid_auths[] = { - { - "scope=always:action-id=org.gnome.clockapplet.mechanism.settimezone:when=1193598494:auth-as=500", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_ALWAYS, - "org.gnome.clockapplet.mechanism.settimezone", - 1193598494, - 0, 0, NULL, - NULL, - FALSE, 500 - }, - - { - "scope=process:pid=14485:pid-start-time=26817340:action-id=org.gnome.policykit.examples.frobnicate:when=1194631763:auth-as=500", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_PROCESS, - "org.gnome.policykit.examples.frobnicate", - 1194631763, - 14485, 26817340, NULL, - NULL, - FALSE, 500 - }, - - { - "scope=process:pid=14485:pid-start-time=26817340:action-id=org.gnome.policykit.examples.tweak:when=1194631774:auth-as=0", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_PROCESS, - "org.gnome.policykit.examples.tweak", - 1194631774, - 14485, 26817340, NULL, - NULL, - FALSE, 0 - }, - - { - "scope=session:session-id=%2Forg%2Ffreedesktop%2FConsoleKit%2FSession1:action-id=org.gnome.policykit.examples.punch:when=1194631779:auth-as=500", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_SESSION, - "org.gnome.policykit.examples.punch", - 1194631779, - 0, 0, "/org/freedesktop/ConsoleKit/Session1", - NULL, - FALSE, 500 - }, - - { - "scope=process-one-shot:pid=27860:pid-start-time=26974819:action-id=org.gnome.policykit.examples.jump:when=1194633344:auth-as=500", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT, - "org.gnome.policykit.examples.jump", - 1194633344, - 27860, 26974819, NULL, - NULL, - FALSE, 500 - }, - - { - "scope=grant:action-id=org.freedesktop.policykit.read:when=1194634242:granted-by=0", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_ALWAYS, - "org.freedesktop.policykit.read", - 1194634242, - 0, 0, NULL, - NULL, - TRUE, 0 - }, - - /* this test ensures we can add new key/value pairs in the future */ - { - "scope=grant:FUTURE-KEY=FUTURE-VALUE:action-id=org.freedesktop.policykit.read:when=1194634242:granted-by=0", - POLKIT_AUTHORIZATION_TYPE_UID, - POLKIT_AUTHORIZATION_SCOPE_ALWAYS, - "org.freedesktop.policykit.read", - 1194634242, - 0, 0, NULL, - NULL, - TRUE, 0 - }, - - }; - size_t num_valid_auths = sizeof (valid_auths) / sizeof (TestAuth); - unsigned int n; - pid_t pid; - polkit_uint64_t pid_start_time; - const char *s; - //PolKitAuthorizationConstraint *ac; - uid_t uid; - polkit_bool_t is_neg; - - for (n = 0; n < num_valid_auths; n++) { - PolKitAuthorization *a; - TestAuth *t = &(valid_auths[n]); - - if ((a = _polkit_authorization_new_for_uid (t->entry, 500)) != NULL) { - - polkit_authorization_debug (a); - polkit_authorization_validate (a); - - kit_assert (t->type == polkit_authorization_type (a)); - kit_assert (t->scope == polkit_authorization_get_scope (a)); - kit_assert (t->time_of_grant == polkit_authorization_get_time_of_grant (a)); - kit_assert (500 == polkit_authorization_get_uid (a)); - - switch (t->scope) { - case POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT: /* explicit fallthrough */ - case POLKIT_AUTHORIZATION_SCOPE_PROCESS: - kit_assert (polkit_authorization_scope_process_get_pid (a, &pid, &pid_start_time) && - t->pid == pid && t->pid_start_time == pid_start_time); - break; - case POLKIT_AUTHORIZATION_SCOPE_SESSION: - kit_assert ((s = polkit_authorization_scope_session_get_ck_objref (a)) != NULL && - strcmp (s, t->session) == 0); - break; - case POLKIT_AUTHORIZATION_SCOPE_ALWAYS: - break; - } - - kit_assert ((s = _polkit_authorization_get_authfile_entry (a)) != NULL && strcmp (t->entry, s) == 0); - - kit_assert ((s = polkit_authorization_get_action_id (a)) != NULL && strcmp (t->action_id, s) == 0); - - kit_assert (t->time_of_grant == polkit_authorization_get_time_of_grant (a)); - - //TODO: - //kit_assert ((ac = polkit_authorization_get_constraint (a)) != NULL && - // polkit_authorization_constraint_equal (ac, t->constraint)); - - if (t->explicit) { - kit_assert (!polkit_authorization_was_granted_via_defaults (a, &uid)); - kit_assert (polkit_authorization_was_granted_explicitly (a, &uid, &is_neg) && - uid == t->from && !is_neg); - } else { - kit_assert (polkit_authorization_was_granted_via_defaults (a, &uid) && uid == t->from); - kit_assert (!polkit_authorization_was_granted_explicitly (a, &uid, &is_neg)); - } - - polkit_authorization_ref (a); - polkit_authorization_unref (a); - polkit_authorization_unref (a); - } else { - kit_assert (errno == ENOMEM); - } - } - - for (n = 0; n < num_invalid_auths; n++) { - kit_assert (_polkit_authorization_new_for_uid (invalid_auths[n], 500) == NULL); - } - - return TRUE; -} - -#else /* POLKIT_AUTHDB_DEFAULT */ - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -#endif /* POLKIT_AUTHDB_DEFAULT */ - -KitTest _test_authorization = { - "polkit_authorization", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-authorization.h b/src/polkit/polkit-authorization.h deleted file mode 100644 index 5428a04..0000000 --- a/src/polkit/polkit-authorization.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-authorization.h : Represents an entry in the authorization - * database - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_AUTHORIZATION_H -#define POLKIT_AUTHORIZATION_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-authorization-constraint.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitAuthorization; -typedef struct _PolKitAuthorization PolKitAuthorization; - -PolKitAuthorization *polkit_authorization_ref (PolKitAuthorization *auth); -void polkit_authorization_unref (PolKitAuthorization *auth); - -void polkit_authorization_debug (PolKitAuthorization *auth); -polkit_bool_t polkit_authorization_validate (PolKitAuthorization *auth); - - -/** - * PolKitAuthorizationScope: - * @POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT: The authorization is - * limited for a single shot for a single process on the system - * @POLKIT_AUTHORIZATION_SCOPE_PROCESS: The authorization is limited - * for a single process on the system - * @POLKIT_AUTHORIZATION_SCOPE_SESSION: The authorization is limited - * for processes originating from a given session - * @POLKIT_AUTHORIZATION_SCOPE_ALWAYS: The authorization is retained - * indefinitely. - * - * The scope of an authorization; e.g. whether it's limited to a - * process, a session or unlimited. - * - * Since: 0.7 - */ -typedef enum { - POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT, - POLKIT_AUTHORIZATION_SCOPE_PROCESS, - POLKIT_AUTHORIZATION_SCOPE_SESSION, - POLKIT_AUTHORIZATION_SCOPE_ALWAYS, -} PolKitAuthorizationScope; - -/** - * PolKitAuthorizationType: - * @POLKIT_AUTHORIZATION_TYPE_UID: The authorization is for a UNIX user - * - * The type of authorization; e.g. whether it applies to a user, - * group, security context and so on (right now only users are - * supported). - * - * Since: 0.7 - */ -typedef enum { - POLKIT_AUTHORIZATION_TYPE_UID, -} PolKitAuthorizationType; - -PolKitAuthorizationType polkit_authorization_type (PolKitAuthorization *auth); - -const char *polkit_authorization_get_action_id (PolKitAuthorization *auth); - -uid_t polkit_authorization_get_uid (PolKitAuthorization *auth); - -time_t polkit_authorization_get_time_of_grant (PolKitAuthorization *auth); - -PolKitAuthorizationScope polkit_authorization_get_scope (PolKitAuthorization *auth); - - -polkit_bool_t polkit_authorization_scope_process_get_pid (PolKitAuthorization *auth, - pid_t *out_pid, - polkit_uint64_t *out_pid_start_time); - -const char *polkit_authorization_scope_session_get_ck_objref (PolKitAuthorization *auth); - - -polkit_bool_t polkit_authorization_was_granted_via_defaults (PolKitAuthorization *auth, - uid_t *out_user_authenticated_as); - -polkit_bool_t polkit_authorization_was_granted_explicitly (PolKitAuthorization *auth, - uid_t *out_by_whom, - polkit_bool_t *out_is_negative); - -/** - * PolKitAuthorizationConstraintsForeachFunc: - * @auth: authorization - * @authc: authorization constraint - * @user_data: user data - * - * Callback function for polkit_authorization_constraints_foreach(). - * - * Returns: Pass #TRUE to short-circuit, e.g. stop the iteration - */ -typedef polkit_bool_t (*PolKitAuthorizationConstraintsForeachFunc) (PolKitAuthorization *auth, - PolKitAuthorizationConstraint *authc, - void *user_data); - -polkit_bool_t -polkit_authorization_constraints_foreach (PolKitAuthorization *auth, - PolKitAuthorizationConstraintsForeachFunc cb, - void *user_data); - -POLKIT_END_DECLS - -#endif /* POLKIT_AUTHORIZATION_H */ - - diff --git a/src/polkit/polkit-caller.c b/src/polkit/polkit-caller.c deleted file mode 100644 index 147bcdc..0000000 --- a/src/polkit/polkit-caller.c +++ /dev/null @@ -1,461 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-caller.c : callers - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/** - * SECTION:polkit-caller - * @title: Caller - * @short_description: Represents a process requesting a mechanism to do something. - * - * This class is used to represent a caller in another process that is - * calling into a mechanism to make the mechanism do something. - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-caller.h" -#include "polkit-utils.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * PolKitCaller: - * - * Objects of this class are used to record information about a caller - * in another process. - **/ -struct _PolKitCaller -{ - int refcount; - char *dbus_name; - uid_t uid; - pid_t pid; - char *selinux_context; - PolKitSession *session; -}; - -/** - * polkit_caller_new: - * - * Creates a new #PolKitCaller object. - * - * Returns: the new object - **/ -PolKitCaller * -polkit_caller_new (void) -{ - PolKitCaller *caller; - caller = kit_new0 (PolKitCaller, 1); - if (caller == NULL) - goto out; - caller->refcount = 1; -out: - return caller; -} - -/** - * polkit_caller_ref: - * @caller: The caller object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitCaller * -polkit_caller_ref (PolKitCaller *caller) -{ - kit_return_val_if_fail (caller != NULL, caller); - caller->refcount++; - return caller; -} - - -/** - * polkit_caller_unref: - * @caller: The caller object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_caller_unref (PolKitCaller *caller) -{ - kit_return_if_fail (caller != NULL); - caller->refcount--; - if (caller->refcount > 0) - return; - kit_free (caller->dbus_name); - kit_free (caller->selinux_context); - if (caller->session != NULL) - polkit_session_unref (caller->session); - kit_free (caller); -} - -/** - * polkit_caller_set_dbus_name: - * @caller: The caller object - * @dbus_name: unique system bus connection name - * - * Set the callers unique system bus connection name. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_caller_set_dbus_name (PolKitCaller *caller, const char *dbus_name) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - - if (dbus_name != NULL && ! _pk_validate_unique_bus_name (dbus_name)) - return FALSE; - - if (caller->dbus_name != NULL) - kit_free (caller->dbus_name); - if (dbus_name == NULL) { - caller->dbus_name = NULL; - return TRUE; - } else { - caller->dbus_name = kit_strdup (dbus_name); - if (caller->dbus_name == NULL) - return FALSE; - else - return TRUE; - } -} - -/** - * polkit_caller_set_uid: - * @caller: The caller object - * @uid: UNIX user id - * - * Set the callers UNIX user id. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_caller_set_uid (PolKitCaller *caller, uid_t uid) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - caller->uid = uid; - return TRUE; -} - -/** - * polkit_caller_set_pid: - * @caller: The caller object - * @pid: UNIX process id - * - * Set the callers UNIX process id. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_caller_set_pid (PolKitCaller *caller, pid_t pid) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - caller->pid = pid; - return TRUE; -} - -/** - * polkit_caller_set_selinux_context: - * @caller: The caller object - * @selinux_context: SELinux security context - * - * Set the callers SELinux security context. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_caller_set_selinux_context (PolKitCaller *caller, const char *selinux_context) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - /* TODO: probably should have a separate validation function for SELinux contexts */ - kit_return_val_if_fail (selinux_context == NULL || _pk_validate_identifier (selinux_context), FALSE); - - if (caller->selinux_context != NULL) - kit_free (caller->selinux_context); - if (selinux_context == NULL) { - caller->selinux_context = NULL; - return TRUE; - } else { - caller->selinux_context = kit_strdup (selinux_context); - if (caller->selinux_context == NULL) - return FALSE; - else - return TRUE; - } -} - -/** - * polkit_caller_set_ck_session: - * @caller: The caller object - * @session: a session object - * - * Set the callers session. The reference count on the given object - * will be increased by one. If an existing session object was set - * already, the reference count on that one will be decreased by one. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_caller_set_ck_session (PolKitCaller *caller, PolKitSession *session) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (session == NULL || polkit_session_validate (session), FALSE); - if (caller->session != NULL) - polkit_session_unref (caller->session); - caller->session = session != NULL ? polkit_session_ref (session) : NULL; - return TRUE; -} - -/** - * polkit_caller_get_dbus_name: - * @caller: The caller object - * @out_dbus_name: Returns the unique system bus connection name. The caller shall not free this string. - * - * Get the callers unique system bus connection name. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_caller_get_dbus_name (PolKitCaller *caller, char **out_dbus_name) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_dbus_name != NULL, FALSE); - *out_dbus_name = caller->dbus_name; - return TRUE; -} - -/** - * polkit_caller_get_uid: - * @caller: The caller object - * @out_uid: Returns the UNIX user id - * - * Get the callers UNIX user id. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_caller_get_uid (PolKitCaller *caller, uid_t *out_uid) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_uid != NULL, FALSE); - *out_uid = caller->uid; - return TRUE; -} - -/** - * polkit_caller_get_pid: - * @caller: The caller object - * @out_pid: Returns the UNIX process id - * - * Get the callers UNIX process id. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_caller_get_pid (PolKitCaller *caller, pid_t *out_pid) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_pid != NULL, FALSE); - *out_pid = caller->pid; - return TRUE; -} - -/** - * polkit_caller_get_selinux_context: - * @caller: The caller object - * @out_selinux_context: Returns the SELinux security context. The caller shall not free this string. - * - * Get the callers SELinux security context. Note that this may be - * #NULL if SELinux is not available on the system. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_caller_get_selinux_context (PolKitCaller *caller, char **out_selinux_context) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_selinux_context != NULL, FALSE); - *out_selinux_context = caller->selinux_context; - return TRUE; -} - -/** - * polkit_caller_get_ck_session: - * @caller: The caller object - * @out_session: Returns the session object. Caller shall not unref it. - * - * Get the callers session. Note that this may be #NULL if the caller - * is not in any session. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_caller_get_ck_session (PolKitCaller *caller, PolKitSession **out_session) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (out_session != NULL, FALSE); - *out_session = caller->session; - return TRUE; -} - -/** - * polkit_caller_debug: - * @caller: the object - * - * Print debug details - **/ -void -polkit_caller_debug (PolKitCaller *caller) -{ - kit_return_if_fail (caller != NULL); - polkit_debug ("PolKitCaller: refcount=%d dbus_name=%s uid=%d pid=%d selinux_context=%s", - caller->refcount, caller->dbus_name, caller->uid, caller->pid, caller->selinux_context); - if (caller->session != NULL) - polkit_session_debug (caller->session); -} - - -/** - * polkit_caller_validate: - * @caller: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - **/ -polkit_bool_t -polkit_caller_validate (PolKitCaller *caller) -{ - kit_return_val_if_fail (caller != NULL, FALSE); - kit_return_val_if_fail (caller->pid > 0, FALSE); - return TRUE; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - char *s; - PolKitCaller *c; - pid_t pid; - uid_t uid; - PolKitSeat *seat; - PolKitSession *session; - PolKitSession *session2; - - if ((c = polkit_caller_new ()) != NULL) { - - kit_assert (! polkit_caller_set_dbus_name (c, "org.invalid.name")); - kit_assert (polkit_caller_set_dbus_name (c, NULL)); - if (polkit_caller_set_dbus_name (c, ":1.43")) { - kit_assert (polkit_caller_get_dbus_name (c, &s) && strcmp (s, ":1.43") == 0); - - if (polkit_caller_set_dbus_name (c, ":1.44")) { - kit_assert (polkit_caller_get_dbus_name (c, &s) && strcmp (s, ":1.44") == 0); - } - } - - kit_assert (polkit_caller_set_selinux_context (c, NULL)); - if (polkit_caller_set_selinux_context (c, "system_u:object_r:bin_t")) { - kit_assert (polkit_caller_get_selinux_context (c, &s) && strcmp (s, "system_u:object_r:bin_t") == 0); - - if (polkit_caller_set_selinux_context (c, "system_u:object_r:httpd_exec_t")) { - kit_assert (polkit_caller_get_selinux_context (c, &s) && strcmp (s, "system_u:object_r:httpd_exec_t") == 0); - } - } - - kit_assert (polkit_caller_set_uid (c, 0)); - kit_assert (polkit_caller_get_uid (c, &uid) && uid == 0); - kit_assert (polkit_caller_set_pid (c, 1)); - kit_assert (polkit_caller_get_pid (c, &pid) && pid == 1); - - /* validate where caller is not in a session */ - kit_assert (polkit_caller_validate (c)); - polkit_caller_ref (c); - kit_assert (polkit_caller_validate (c)); - polkit_caller_unref (c); - kit_assert (polkit_caller_validate (c)); - - if ((session = polkit_session_new ()) != NULL) { - if (polkit_session_set_ck_objref (session, "/somesession")) { - if ((seat = polkit_seat_new ()) != NULL) { - if (polkit_seat_set_ck_objref (seat, "/someseat")) { - kit_assert (polkit_session_set_seat (session, seat)); - kit_assert (polkit_session_set_ck_is_local (session, TRUE)); - - kit_assert (polkit_caller_set_ck_session (c, NULL)); - kit_assert (polkit_caller_get_ck_session (c, &session2) && session2 == NULL); - - kit_assert (polkit_caller_set_ck_session (c, session)); - kit_assert (polkit_caller_set_ck_session (c, session)); - kit_assert (polkit_caller_get_ck_session (c, &session2) && session2 == session); - /* validate where caller is in a session */ - kit_assert (polkit_caller_validate (c)); - - polkit_caller_debug (c); - - - } - polkit_seat_unref (seat); - } - } - polkit_session_unref (session); - } - - - - polkit_caller_unref (c); - } - - return TRUE; -} - -KitTest _test_caller = { - "polkit_caller", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-caller.h b/src/polkit/polkit-caller.h deleted file mode 100644 index 28f032e..0000000 --- a/src/polkit/polkit-caller.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-caller.h : callers - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_CALLER_H -#define POLKIT_CALLER_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-session.h> -#include <sys/types.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitCaller; -typedef struct _PolKitCaller PolKitCaller; - -PolKitCaller *polkit_caller_new (void); -PolKitCaller *polkit_caller_ref (PolKitCaller *caller); -void polkit_caller_unref (PolKitCaller *caller); -polkit_bool_t polkit_caller_set_dbus_name (PolKitCaller *caller, const char *dbus_name); -polkit_bool_t polkit_caller_set_uid (PolKitCaller *caller, uid_t uid); -polkit_bool_t polkit_caller_set_pid (PolKitCaller *caller, pid_t pid); -polkit_bool_t polkit_caller_set_selinux_context (PolKitCaller *caller, const char *selinux_context); -polkit_bool_t polkit_caller_set_ck_session (PolKitCaller *caller, PolKitSession *session); -polkit_bool_t polkit_caller_get_dbus_name (PolKitCaller *caller, char **out_dbus_name); -polkit_bool_t polkit_caller_get_uid (PolKitCaller *caller, uid_t *out_uid); -polkit_bool_t polkit_caller_get_pid (PolKitCaller *caller, pid_t *out_pid); -polkit_bool_t polkit_caller_get_selinux_context (PolKitCaller *caller, char **out_selinux_context); -polkit_bool_t polkit_caller_get_ck_session (PolKitCaller *caller, PolKitSession **out_session); - -void polkit_caller_debug (PolKitCaller *caller); -polkit_bool_t polkit_caller_validate (PolKitCaller *caller); - -POLKIT_END_DECLS - -#endif /* POLKIT_H */ diff --git a/src/polkit/polkit-context.c b/src/polkit/polkit-context.c deleted file mode 100644 index fac4f12..0000000 --- a/src/polkit/polkit-context.c +++ /dev/null @@ -1,622 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-context.c : context for PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#define _GNU_SOURCE - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#if HAVE_SOLARIS -#include <sys/stat.h> -#endif -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> -#include <syslog.h> -#include <fcntl.h> -#include <dirent.h> - -#include "polkit-debug.h" -#include "polkit-context.h" -#include "polkit-private.h" -#include "polkit-test.h" - -/** - * SECTION:polkit - * @short_description: Centralized policy management. - * - * libpolkit is a C library for centralized policy management. - **/ - -/** - * SECTION:polkit-context - * @title: Context - * @short_description: The main interface used to query PolicyKit. - * - * This class is used to represent the interface to PolicyKit - it is - * used by Mechanisms that use PolicyKit for making - * decisions. Typically, it's used as a singleton: - * - * <itemizedlist> - * <listitem>First, the Mechanism need to declare one or more PolicyKit Actions by dropping a <literal>.policy</literal> file into <literal>/usr/share/polkit-1/actions</literal>. This is described in the PolicyKit specification.</listitem> - * <listitem>The mechanism starts up and uses polkit_context_new() to create a new context</listitem> - * <listitem>If the mechanism is a long running daemon, it should use polkit_context_set_config_changed() to register a callback when configuration changes. This is useful if, for example, the mechanism needs to revise decisions based on earlier answers from libpolkit. For example, a daemon that manages permissions on <literal>/dev</literal> may want to add/remove ACL's when configuration changes. - * <listitem>If polkit_context_set_config_changed() is used, the mechanism must also use polkit_context_set_io_watch_functions() to integrate libpolkit into the mainloop.</listitem> - * <listitem>The mechanism needs to call polkit_context_init() such that libpolkit can load configuration files and properly initialize.</listitem> - * <listitem>Whenever the mechanism needs to make a decision whether a caller is allowed to make a perform some action, the mechanism prepares a #PolKitAction and #PolKitCaller object (or #PolKitSession if applicable) and calls polkit_context_can_caller_do_action() (or polkit_context_can_session_do_action() if applicable). The mechanism may use the libpolkit-dbus library (specifically the polkit_caller_new_from_dbus_name() or polkit_caller_new_from_pid() functions) but may opt, for performance reasons, to construct #PolKitCaller (or #PolKitSession if applicable) from it's own cache of information.</listitem> - * <listitem>The mechanism will get a #PolKitResult object back that describes whether it should carry out the action. This result stems from a number of sources, see the PolicyKit specification document for details.</listitem> - * <listitem>If the result is #POLKIT_RESULT_YES, the mechanism should carry out the action. If the result is not #POLKIT_RESULT_YES nor #POLKIT_RESULT_UNKNOWN (this would never be returned but is mentioned here for completeness), the mechanism should throw an expcetion to the caller detailing the #PolKitResult as a textual string using polkit_result_to_string_representation(). For example, if the mechanism is using D-Bus it could throw an com.some-mechanism.DeniedByPolicy exception with the #PolKitResult textual representation in the detail field. Then the caller can interpret this exception and then act on it (for example it can attempt to gain that privilege).</listitem> - * </itemizedlist> - * - * For more information about using PolicyKit in mechanisms and - * callers, refer to the PolicyKit-gnome project which includes a - * sample application on how to use this in the GNOME desktop. - **/ - -/** - * PolKitContext: - * - * Context object for users of PolicyKit. - **/ -struct _PolKitContext -{ - int refcount; - - PolKitContextConfigChangedCB config_changed_cb; - void *config_changed_user_data; - - char *policy_dir; - - PolKitAuthorizationDB *authdb; - - KitList *action_descriptions; -}; - -/** - * polkit_context_new: - * - * Create a new context - * - * Returns: the object - **/ -PolKitContext * -polkit_context_new (void) -{ - PolKitContext *pk_context; - pk_context = kit_new0 (PolKitContext, 1); - pk_context->refcount = 1; - /* TODO: May want to rethink instantiating this on demand.. */ - pk_context->authdb = _polkit_authorization_db_new (); - return pk_context; -} - -/** - * polkit_context_init: - * @pk_context: the context object - * @error: return location for error - * - * Initializes a new context; loads PolicyKit files from - * /usr/share/polkit-1/actions. - * - * Returns: #FALSE if @error was set, otherwise #TRUE - **/ -polkit_bool_t -polkit_context_init (PolKitContext *pk_context, PolKitError **error) -{ - - kit_return_val_if_fail (pk_context != NULL, FALSE); - - pk_context->policy_dir = kit_strdup (PACKAGE_DATA_DIR "/polkit-1/actions"); - polkit_debug ("Using policy files from directory %s", pk_context->policy_dir); - - return TRUE; - //error: - //return FALSE; -} - -/** - * polkit_context_ref: - * @pk_context: the context object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitContext * -polkit_context_ref (PolKitContext *pk_context) -{ - kit_return_val_if_fail (pk_context != NULL, pk_context); - pk_context->refcount++; - return pk_context; -} - -/** - * polkit_context_unref: - * @pk_context: the context object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_context_unref (PolKitContext *pk_context) -{ - - kit_return_if_fail (pk_context != NULL); - pk_context->refcount--; - if (pk_context->refcount > 0) - return; - - kit_free (pk_context); -} - -/** - * polkit_context_set_config_changed: - * @pk_context: the context object - * @cb: the callback to invoke - * @user_data: user data to pass to the callback - * - * Register the callback function for when configuration changes. - * Mechanisms should use this callback to e.g. reconfigure all - * permissions / acl's they have set in response to policy decisions - * made from information provided by PolicyKit. - * - * Note that this function may be called many times within a short - * interval due to how file monitoring works if e.g. the user is - * editing a configuration file (editors typically create back-up - * files). Mechanisms should use a "cool-off" timer (of, say, one - * second) to avoid doing many expensive operations (such as - * reconfiguring all ACL's for all devices) within a very short - * timeframe. - * - * This method must be called before polkit_context_init(). - **/ -void -polkit_context_set_config_changed (PolKitContext *pk_context, - PolKitContextConfigChangedCB cb, - void *user_data) -{ - kit_return_if_fail (pk_context != NULL); - pk_context->config_changed_cb = cb; - pk_context->config_changed_user_data = user_data; -} - -/** - * polkit_context_is_session_authorized: - * @pk_context: the PolicyKit context - * @action: the type of access to check for - * @session: the session in question - * @error: return location for error - * - * Determine if any caller from a giver session is authorized to do a - * given action. - * - * Returns: A #PolKitResult specifying if, and how, the caller can - * do a specific action. - * - * Since: 0.7 - */ -PolKitResult -polkit_context_is_session_authorized (PolKitContext *pk_context, - PolKitAction *action, - PolKitSession *session, - PolKitError **error) -{ - //PolKitPolicyCache *cache; - PolKitResult result_from_grantdb; - polkit_bool_t from_authdb; - polkit_bool_t from_authdb_negative; - PolKitResult result; - - result = POLKIT_RESULT_NO; - kit_return_val_if_fail (pk_context != NULL, result); - - if (action == NULL || session == NULL) - goto out; - - /* now validate the incoming objects */ - if (!polkit_action_validate (action)) - goto out; - if (!polkit_session_validate (session)) - goto out; - - //cache = polkit_context_get_policy_cache (pk_context); - //if (cache == NULL) - // goto out; - - result_from_grantdb = POLKIT_RESULT_UNKNOWN; - from_authdb_negative = FALSE; - if (polkit_authorization_db_is_session_authorized (pk_context->authdb, - action, - session, - &from_authdb, - &from_authdb_negative, - NULL /* TODO */)) { - if (from_authdb) - result_from_grantdb = POLKIT_RESULT_YES; - } - - /* If we have a positive answer from the authdb, use it */ - if (result_from_grantdb == POLKIT_RESULT_YES) { - result = POLKIT_RESULT_YES; - goto found; - } - - /* Otherwise, unless we found a negative auth, fall back to defaults as specified in the .policy file */ - if (!from_authdb_negative) { - PolKitActionDescription *pfe; - - pfe = NULL; //pfe = polkit_policy_cache_get_entry (cache, action); - if (pfe != NULL) { - PolKitImplicitAuthorization *implicit_authorization; - - implicit_authorization = polkit_action_description_get_implicit_authorization (pfe); - if (implicit_authorization != NULL) { - result = polkit_implicit_authorization_can_session_do_action (implicit_authorization, action, session); - } - } - } - -found: - /* Never return UNKNOWN to user */ - if (result == POLKIT_RESULT_UNKNOWN) - result = POLKIT_RESULT_NO; - -out: - polkit_debug ("... result was %s", polkit_result_to_string_representation (result)); - return result; -} - -/** - * polkit_context_is_caller_authorized: - * @pk_context: the PolicyKit context - * @action: the type of access to check for - * @caller: the caller in question - * @revoke_if_one_shot: Whether to revoke one-shot authorizations. See - * below for discussion. - * @error: return location for error - * - * Determine if a given caller is authorized to do a given - * action. - * - * It is important to understand how one-shot authorizations work. - * The revoke_if_one_shot parameter, if #TRUE, specifies whether - * one-shot authorizations should be revoked if they are used - * to make the decision to return #POLKIT_RESULT_YES. - * - * UI applications wanting to hint whether a caller is authorized must - * pass #FALSE here. Mechanisms that wants to check authorizations - * before carrying out work on behalf of a caller must pass #TRUE - * here. - * - * As a side-effect, any process with the authorization - * org.freedesktop.policykit.read can revoke one-shot authorizations - * from other users. Even though the window for doing so is small - * (one-shot auths are typically used right away), be careful who you - * grant that authorization to. - * - * This can fail with the following errors: - * #POLKIT_ERROR_NOT_AUTHORIZED_TO_READ_AUTHORIZATIONS_FOR_OTHER_USERS - * - * Returns: A #PolKitResult specifying if, and how, the caller can - * do a specific action. - * - * Since: 0.7 - */ -PolKitResult -polkit_context_is_caller_authorized (PolKitContext *pk_context, - PolKitAction *action, - PolKitCaller *caller, - polkit_bool_t revoke_if_one_shot, - PolKitError **error) -{ - //PolKitPolicyCache *cache; - PolKitResult result; - PolKitResult result_from_grantdb; - polkit_bool_t from_authdb; - polkit_bool_t from_authdb_negative; - - result = POLKIT_RESULT_NO; - kit_return_val_if_fail (pk_context != NULL, result); - - if (action == NULL || caller == NULL) - goto out; - - //cache = polkit_context_get_policy_cache (pk_context); - //if (cache == NULL) - // goto out; - - /* now validate the incoming objects */ - if (!polkit_action_validate (action)) - goto out; - if (!polkit_caller_validate (caller)) - goto out; - - result_from_grantdb = POLKIT_RESULT_UNKNOWN; - from_authdb_negative = FALSE; - if (polkit_authorization_db_is_caller_authorized (pk_context->authdb, - action, - caller, - revoke_if_one_shot, - &from_authdb, - &from_authdb_negative, - NULL /* TODO */)) { - if (from_authdb) - result_from_grantdb = POLKIT_RESULT_YES; - } - - /* If we have a positive answer from the authdb, use it */ - if (result_from_grantdb == POLKIT_RESULT_YES) { - result = POLKIT_RESULT_YES; - goto found; - } - - /* Otherwise, unless we found a negative auth, fall back to defaults as specified in the .policy file */ - if (!from_authdb_negative) { - PolKitActionDescription *pfe; - - pfe = NULL; //pfe = polkit_policy_cache_get_entry (cache, action); - if (pfe != NULL) { - PolKitImplicitAuthorization *implicit_authorization; - - implicit_authorization = polkit_action_description_get_implicit_authorization (pfe); - if (implicit_authorization != NULL) { - result = polkit_implicit_authorization_can_caller_do_action (implicit_authorization, action, caller); - } - } - } - -found: - - /* Never return UNKNOWN to user */ - if (result == POLKIT_RESULT_UNKNOWN) - result = POLKIT_RESULT_NO; -out: - polkit_debug ("... result was %s", polkit_result_to_string_representation (result)); - return result; -} - -/** - * polkit_context_get_authorization_db: - * @pk_context: the PolicyKit context - * - * Returns an object that provides access to the authorization - * database. Applications using PolicyKit should never use this - * method; it's only here for integration with other PolicyKit - * components. - * - * Returns: A #PolKitAuthorizationDB object. Caller should not unref - * this object. - */ -PolKitAuthorizationDB * -polkit_context_get_authorization_db (PolKitContext *pk_context) -{ - return pk_context->authdb; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_context = { - "polkit_context", - NULL, - NULL, - _run_test -}; - - -#endif /* POLKIT_BUILD_TESTS */ - - -static polkit_bool_t -_prepend_entry (PolKitActionDescription *action_description, - void *user_data) -{ - KitList *l; - PolKitContext *pk_context = user_data; - - polkit_action_description_ref (action_description); - l = kit_list_prepend (pk_context->action_descriptions, action_description); - if (l == NULL) { - polkit_action_description_unref (action_description); - goto oom; - } - pk_context->action_descriptions = l; - return FALSE; -oom: - return TRUE; -} - -static void -get_descriptions (PolKitContext *pk_context, PolKitError **error) -{ - DIR *dir; -#ifdef HAVE_READDIR64 - struct dirent64 *d; -#else - struct dirent *d; -#endif - struct stat statbuf; - const char *dirname = PACKAGE_DATA_DIR "/polkit-1/actions"; - - dir = NULL; - - dir = opendir (dirname); - if (dir == NULL) { - polkit_error_set_error (error, POLKIT_ERROR_POLICY_FILE_INVALID, - "Cannot load policy files from directory %s: %m", - dirname); - goto out; - } - -#ifdef HAVE_READDIR64 - while ((d = readdir64 (dir)) != NULL) { -#else - while ((d = readdir (dir)) != NULL) { -#endif - char *path; - PolKitError *pk_error; - size_t name_len; - char *filename; - static const char suffix[] = ".policy"; - - path = kit_strdup_printf ("%s/%s", dirname, d->d_name); - if (path == NULL) { - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, "Out of memory"); - goto out; - } - - if (stat (path, &statbuf) != 0) { - polkit_error_set_error (error, POLKIT_ERROR_GENERAL_ERROR, "stat()"); - kit_free (path); - goto out; - } - - if (!S_ISREG (statbuf.st_mode)) { - kit_free (path); - continue; - } - - filename = d->d_name; - name_len = strlen (filename); - if (name_len < sizeof (suffix) || strcmp ((filename + name_len - sizeof (suffix) + 1), suffix) != 0) { - kit_free (path); - continue; - } - - polkit_debug ("Loading %s", path); - pk_error = NULL; - - if (polkit_action_description_get_from_file (path, _prepend_entry, pk_context, &pk_error)) { - /* OOM failure from _prepend_entry */ - polkit_error_set_error (error, POLKIT_ERROR_OUT_OF_MEMORY, "Out of memory"); - goto out; - } - - if (polkit_error_is_set (pk_error)) { - if (polkit_error_get_error_code (pk_error) == POLKIT_ERROR_OUT_OF_MEMORY) { - if (error != NULL) - *error = pk_error; - else - polkit_error_free (pk_error); - goto out; - } - - kit_warning ("ignoring malformed policy file: %s", - polkit_error_get_error_message (pk_error)); - polkit_error_free (pk_error); - } - - } - closedir (dir); - - return; - -out: - if (dir != NULL) - closedir(dir); -} - -static void -ensure_descriptions (PolKitContext *pk_context) -{ - PolKitError *error; - error = NULL; - - if (pk_context->action_descriptions != NULL) - goto out; - - get_descriptions (pk_context, &error); - if (polkit_error_is_set (error)) { - kit_warning ("Error loading policy files: %s: %s", - polkit_error_get_error_name (error), - polkit_error_get_error_message (error)); - polkit_error_free (error); - goto out; - } - - out: - ; -} - -polkit_bool_t -polkit_context_action_description_foreach (PolKitContext *pk_context, - PolKitActionDescriptionForeachFunc cb, - void *user_data) -{ - KitList *l; - polkit_bool_t short_circuit; - - ensure_descriptions (pk_context); - - short_circuit = FALSE; - for (l = pk_context->action_descriptions; l != NULL; l = l->next) { - PolKitActionDescription *action_description = l->data; - - if (cb (action_description, user_data)) { - short_circuit = TRUE; - break; - } - } - - return short_circuit; -} - -PolKitActionDescription * -polkit_context_get_action_description (PolKitContext *pk_context, - const char *action_id) -{ - KitList *l; - PolKitActionDescription *action_description; - - ensure_descriptions (pk_context); - - action_description = NULL; - - for (l = pk_context->action_descriptions; l != NULL; l = l->next) { - PolKitActionDescription *ad = l->data; - if (strcmp (polkit_action_description_get_id (ad), action_id) == 0) { - action_description = ad; - break; - } - } - - return action_description; -} diff --git a/src/polkit/polkit-context.h b/src/polkit/polkit-context.h deleted file mode 100644 index 3c14e4f..0000000 --- a/src/polkit/polkit-context.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-context.h : PolicyKit context - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_CONTEXT_H -#define POLKIT_CONTEXT_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-error.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-context.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-action-description.h> -#include <polkit/polkit-seat.h> -#include <polkit/polkit-session.h> -#include <polkit/polkit-caller.h> -#include <polkit/polkit-authorization-db.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitContext; -typedef struct _PolKitContext PolKitContext; - -/** - * PolKitContextConfigChangedCB: - * @pk_context: PolicyKit context - * @user_data: user data - * - * The type of the callback function for when configuration changes. - * Mechanisms should use this callback to e.g. reconfigure all - * permissions / acl's they have set in response to policy decisions - * made from information provided by PolicyKit. - * - * The user must have set up watches using #polkit_context_set_io_watch_functions - * for this to work. - * - * Note that this function may be called many times within a short - * interval due to how file monitoring works if e.g. the user is - * editing a configuration file (editors typically create back-up - * files). Mechanisms should use a "cool-off" timer (of, say, one - * second) to avoid doing many expensive operations (such as - * reconfiguring all ACL's for all devices) within a very short - * timeframe. - */ -typedef void (*PolKitContextConfigChangedCB) (PolKitContext *pk_context, - void *user_data); - -/** - * PolKitActionDescriptionForeachFunc: - * @action_description: the entry - * @user_data: user data - * - * Type for function used in to iterate over action descriptions. - * - * Returns: #TRUE to short-circuit, e.g. stop the iteration - **/ -typedef polkit_bool_t (*PolKitActionDescriptionForeachFunc) (PolKitActionDescription *action_description, - void *user_data); - -PolKitContext *polkit_context_new (void); -void polkit_context_set_config_changed (PolKitContext *pk_context, - PolKitContextConfigChangedCB cb, - void *user_data); -polkit_bool_t polkit_context_init (PolKitContext *pk_context, - PolKitError **error); -PolKitContext *polkit_context_ref (PolKitContext *pk_context); -void polkit_context_unref (PolKitContext *pk_context); - -PolKitResult polkit_context_is_caller_authorized (PolKitContext *pk_context, - PolKitAction *action, - PolKitCaller *caller, - polkit_bool_t revoke_if_one_shot, - PolKitError **error); - -PolKitResult polkit_context_is_session_authorized (PolKitContext *pk_context, - PolKitAction *action, - PolKitSession *session, - PolKitError **error); - -polkit_bool_t polkit_context_action_description_foreach (PolKitContext *pk_context, - PolKitActionDescriptionForeachFunc cb, - void *user_data); - -PolKitActionDescription *polkit_context_get_action_description (PolKitContext *pk_context, - const char *action_id); - -/* TODO: move to private static lib */ -polkit_bool_t polkit_action_description_get_from_file (const char *path, - PolKitActionDescriptionForeachFunc cb, - void *user_data, - PolKitError **error); - - -PolKitAuthorizationDB *polkit_context_get_authorization_db (PolKitContext *pk_context); - -POLKIT_END_DECLS - -#endif /* POLKIT_CONTEXT_H */ - - diff --git a/src/polkit/polkit-debug.c b/src/polkit/polkit-debug.c deleted file mode 100644 index 72ef71a..0000000 --- a/src/polkit/polkit-debug.c +++ /dev/null @@ -1,87 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit.c : library for querying system-wide policy - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/** - * SECTION:polkit-debug - * @short_description: Internal debug functions for polkit. - * - * These functions are used for debug purposes. - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdarg.h> -#include <stdlib.h> -#include <sys/time.h> -#include <time.h> - -#include "polkit-types.h" -#include "polkit-debug.h" - -/** - * polkit_debug: - * @format: format - * - * Prints a debug message to stdout if the environment variable - * POLKIT_DEBUG is set. In production builds this function may - * be a no-op. - **/ -void -polkit_debug (const char *format, ...) -{ - va_list args; - static polkit_bool_t show_debug = FALSE; - static polkit_bool_t init = FALSE; - - if (!init) { - init = TRUE; - if (getenv ("POLKIT_DEBUG") != NULL) { - show_debug = TRUE; - } - } - - if (show_debug) { - struct timeval tnow; - struct tm *tlocaltime; - struct timezone tzone; - char tbuf[256]; - gettimeofday (&tnow, &tzone); - tlocaltime = localtime ((time_t *) &tnow.tv_sec); - strftime (tbuf, sizeof (tbuf), "%H:%M:%S", tlocaltime); - fprintf (stdout, "%s.%03d: ", tbuf, (int)(tnow.tv_usec/1000)); - - va_start (args, format); - vfprintf (stdout, format, args); - va_end (args); - fprintf (stdout, "\n"); - } -} diff --git a/src/polkit/polkit-debug.h b/src/polkit/polkit-debug.h deleted file mode 100644 index 4a8256f..0000000 --- a/src/polkit/polkit-debug.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-debug.h : debug infrastructure for polkit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifndef POLKIT_DEBUG_H -#define POLKIT_DEBUG_H - -#ifdef __sun -void polkit_debug (const char *format, ...); -#else -void polkit_debug (const char *format, ...) __attribute__((__format__ (__printf__, 1, 2))); -#endif - -#endif /* POLKIT_DEBUG_H */ - - diff --git a/src/polkit/polkit-error.c b/src/polkit/polkit-error.c deleted file mode 100644 index 3583162..0000000 --- a/src/polkit/polkit-error.c +++ /dev/null @@ -1,253 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-error.c : GError error codes from PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/** - * SECTION:polkit-error - * @title: Error reporting - * @short_description: Representation of recoverable errors. - * - * Error codes from PolicyKit. - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-types.h" -#include "polkit-error.h" -#include "polkit-debug.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * PolKitError: - * - * Objects of this class are used for error reporting. - **/ -struct _PolKitError -{ - polkit_bool_t is_static; - PolKitErrorCode error_code; - char *error_message; -}; - -/** - * polkit_error_is_set: - * @error: the error - * - * Determine if an error set - * - * Returns: #TRUE if, and only if, the error is set - * - * Since: 0.7 - */ -polkit_bool_t -polkit_error_is_set (PolKitError *error) -{ - return error != NULL; -} - -static const char *error_names[POLKIT_ERROR_NUM_ERROR_CODES] = { - "OutOfMemory", - "PolicyFileInvalid", - "GeneralError", - "NotAuthorizedToReadAuthorizationsForOtherUsers", - "NotAuthorizedToRevokeAuthorizationsFromOtherUsers", - "NotAuthorizedToGrantAuthorization", - "AuthorizationAlreadyExists", - "NotSupported", - "NotAuthorizedToModifyDefaults", -}; - -/** - * polkit_error_get_error_name: - * @error: the error - * - * Get the CamelCase name for the error; - * e.g. #POLKIT_ERROR_OUT_OF_MEMORY maps to "OutOfMemory" and so on. - * - * Returns: the string - * - * Since: 0.7 - */ -const char * -polkit_error_get_error_name (PolKitError *error) -{ - kit_return_val_if_fail (error != NULL, NULL); - kit_return_val_if_fail (error->error_code >= 0 && error->error_code < POLKIT_ERROR_NUM_ERROR_CODES, NULL); - - return error_names[error->error_code]; -} - -/** - * polkit_error_get_error_code: - * @error: the error object - * - * Returns the error code. - * - * Returns: A value from the #PolKitErrorCode enumeration. - **/ -PolKitErrorCode -polkit_error_get_error_code (PolKitError *error) -{ - kit_return_val_if_fail (error != NULL, -1); - return error->error_code; -} - -/** - * polkit_error_get_error_message: - * @error: the error object - * - * Get the error message. - * - * Returns: A string describing the error. Caller shall not free this string. - **/ -const char * -polkit_error_get_error_message (PolKitError *error) -{ - kit_return_val_if_fail (error != NULL, NULL); - return error->error_message; -} - -/** - * polkit_error_free: - * @error: the error - * - * Free an error. - **/ -void -polkit_error_free (PolKitError *error) -{ - kit_return_if_fail (error != NULL); - if (!error->is_static) { - kit_free (error->error_message); - kit_free (error); - } -} - - -static PolKitError _oom_error = {TRUE, POLKIT_ERROR_OUT_OF_MEMORY, "Pre-allocated OOM error object"}; - -/** - * polkit_error_set_error: - * @error: the error object - * @error_code: A value from the #PolKitErrorCode enumeration. - * @format: printf style formatting string - * @Varargs: printf style arguments - * - * Sets an error. If OOM, the error will be set to a pre-allocated OOM error. - * - * Returns: TRUE if the error was set - **/ -polkit_bool_t -polkit_error_set_error (PolKitError **error, PolKitErrorCode error_code, const char *format, ...) -{ - va_list args; - PolKitError *e; - - kit_return_val_if_fail (format != NULL, FALSE); - - if (error_code < 0 || error_code >= POLKIT_ERROR_NUM_ERROR_CODES) - return FALSE; - - if (error == NULL) - goto out; - - e = kit_new0 (PolKitError, 1); - if (e == NULL) { - *error = &_oom_error; - } else { - e->is_static = FALSE; - e->error_code = error_code; - va_start (args, format); - e->error_message = kit_strdup_vprintf (format, args); - va_end (args); - if (e->error_message == NULL) { - kit_free (e); - *error = &_oom_error; - } else { - *error = e; - } - } - -out: - return TRUE; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - unsigned int n; - PolKitError *e; - char s[256]; - - e = NULL; - kit_assert (! polkit_error_is_set (e)); - kit_assert (! polkit_error_set_error (&e, -1, "Testing")); - kit_assert (! polkit_error_set_error (&e, POLKIT_ERROR_NUM_ERROR_CODES, "Testing")); - - for (n = 0; n < POLKIT_ERROR_NUM_ERROR_CODES; n++) { - polkit_error_set_error (&e, n, "Testing error code %d", n); - kit_assert (polkit_error_is_set (e)); - kit_assert (polkit_error_get_error_code (e) == n || polkit_error_get_error_code (e) == POLKIT_ERROR_OUT_OF_MEMORY); - kit_assert (strcmp (polkit_error_get_error_name (e), error_names[polkit_error_get_error_code (e)]) == 0); - - if (polkit_error_get_error_code (e) != POLKIT_ERROR_OUT_OF_MEMORY) { - snprintf (s, sizeof (s), "Testing error code %d", n); - kit_assert (strcmp (polkit_error_get_error_message (e), s) == 0); - } - - polkit_error_free (e); - } - - kit_assert (polkit_error_set_error (NULL, POLKIT_ERROR_OUT_OF_MEMORY, "This error will never get set")); - - return TRUE; -} - - -KitTest _test_error = { - "polkit_error", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-error.h b/src/polkit/polkit-error.h deleted file mode 100644 index 6044677..0000000 --- a/src/polkit/polkit-error.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-error.h : error reporting from PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_ERROR_H -#define POLKIT_ERROR_H - -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -/** - * PolKitErrorCode: - * @POLKIT_ERROR_OUT_OF_MEMORY: Out of memory - * @POLKIT_ERROR_POLICY_FILE_INVALID: There was an error parsing the given policy file - * @POLKIT_ERROR_GENERAL_ERROR: A general error code typically - * indicating problems with the installation of PolicyKit, - * e.g. helpers missing or wrong owner / permission. - * @POLKIT_ERROR_NOT_AUTHORIZED_TO_READ_AUTHORIZATIONS_FOR_OTHER_USERS: - * An attempt was made to read authorizations for other users and the - * calling process is not authorized. - * @POLKIT_ERROR_NOT_AUTHORIZED_TO_REVOKE_AUTHORIZATIONS_FROM_OTHER_USERS: - * An attempt was made to revoke authorizations for other users and the - * calling process is not authorized. - * @POLKIT_ERROR_NOT_AUTHORIZED_TO_GRANT_AUTHORIZATION: An attempt was - * made to grant an authorization and the calling process is not - * authorized. - * @POLKIT_ERROR_AUTHORIZATION_ALREADY_EXISTS: Subject already has an - * similar authorization already (modulo time of grant and who granted). - * @POLKIT_ERROR_NOT_SUPPORTED: The operation is not supported by the - * authorization database backend - * @POLKIT_ERROR_NOT_AUTHORIZED_TO_MODIFY_DEFAULTS: An attempt was - * made to modify the defaults for implicit authorizations and the - * calling process is not authorized. - * @POLKIT_ERROR_NUM_ERROR_CODES: Number of error codes. This may change - * from version to version; do not rely on it. - * - * Errors returned by PolicyKit - */ -typedef enum -{ - POLKIT_ERROR_OUT_OF_MEMORY, - POLKIT_ERROR_POLICY_FILE_INVALID, - POLKIT_ERROR_GENERAL_ERROR, - POLKIT_ERROR_NOT_AUTHORIZED_TO_READ_AUTHORIZATIONS_FOR_OTHER_USERS, - POLKIT_ERROR_NOT_AUTHORIZED_TO_REVOKE_AUTHORIZATIONS_FROM_OTHER_USERS, - POLKIT_ERROR_NOT_AUTHORIZED_TO_GRANT_AUTHORIZATION, - POLKIT_ERROR_AUTHORIZATION_ALREADY_EXISTS, - POLKIT_ERROR_NOT_SUPPORTED, - POLKIT_ERROR_NOT_AUTHORIZED_TO_MODIFY_DEFAULTS, - - POLKIT_ERROR_NUM_ERROR_CODES -} PolKitErrorCode; - -struct _PolKitError; -typedef struct _PolKitError PolKitError; - -polkit_bool_t polkit_error_is_set (PolKitError *error); -const char *polkit_error_get_error_name (PolKitError *error); -PolKitErrorCode polkit_error_get_error_code (PolKitError *error); -const char *polkit_error_get_error_message (PolKitError *error); -void polkit_error_free (PolKitError *error); -#ifdef __sun -polkit_bool_t polkit_error_set_error (PolKitError **error, PolKitErrorCode error_code, const char *format, ...); -#else -polkit_bool_t polkit_error_set_error (PolKitError **error, PolKitErrorCode error_code, const char *format, ...) __attribute__((__format__ (__printf__, 3, 4))); -#endif - -POLKIT_END_DECLS - -#endif /* POLKIT_ERROR_H */ diff --git a/src/polkit/polkit-implicit-authorization.c b/src/polkit/polkit-implicit-authorization.c deleted file mode 100644 index 68aac21..0000000 --- a/src/polkit/polkit-implicit-authorization.c +++ /dev/null @@ -1,572 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-implicit-authorization.c : policy definition for the defaults - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-error.h" -#include "polkit-implicit-authorization.h" -#include "polkit-private.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-implicit-authorization - * @title: Defaults - * @short_description: Models the default policy for an action. - * - * This class records the default policy of an action. - **/ - -/** - * PolKitImplicitAuthorization: - * - * Objects of this class are used to record information about a - * default policy for an action. - **/ -struct _PolKitImplicitAuthorization -{ - int refcount; - PolKitResult default_any; - PolKitResult default_inactive; - PolKitResult default_active; -}; - -/** - * polkit_implicit_authorization_new: - * - * Construct a new object with all defaults set as restrictive as possible. - * - * Returns: a new object or #NULL on OOM. - * - * Since: 0.7 - */ -PolKitImplicitAuthorization * -polkit_implicit_authorization_new (void) -{ - PolKitImplicitAuthorization *pd; - - pd = kit_new0 (PolKitImplicitAuthorization, 1); - if (pd == NULL) - goto out; - pd->refcount = 1; - pd->default_any = POLKIT_RESULT_NO; - pd->default_inactive = POLKIT_RESULT_NO; - pd->default_active = POLKIT_RESULT_NO; -out: - return pd; -} - -/** - * polkit_implicit_authorization_clone: - * @implicit_authorization: object to clone - * - * Create a new object with the same value as the given object - * - * Returns: a new object or #NULL on OOM. - * - * Since: 0.7 - */ -PolKitImplicitAuthorization * -polkit_implicit_authorization_clone (PolKitImplicitAuthorization *implicit_authorization) -{ - PolKitImplicitAuthorization *pd; - - kit_return_val_if_fail (implicit_authorization != NULL, NULL); - - pd = polkit_implicit_authorization_new (); - if (pd == NULL) - goto out; - pd->refcount = 1; - pd->default_any = implicit_authorization->default_any; - pd->default_inactive = implicit_authorization->default_inactive; - pd->default_active = implicit_authorization->default_active; -out: - return pd; -} - - -/** - * polkit_implicit_authorization_equals: - * @a: a #PolKitImplicitAuthorization object - * @b: a #PolKitImplicitAuthorization object - * - * Compare if two objects are equal. - * - * Returns: %TRUE only if the objects are equal - */ -polkit_bool_t -polkit_implicit_authorization_equals (PolKitImplicitAuthorization *a, PolKitImplicitAuthorization *b) -{ - polkit_bool_t ret; - - kit_return_val_if_fail (a != NULL, FALSE); - kit_return_val_if_fail (b != NULL, FALSE); - - if (a->default_any == b->default_any && - a->default_inactive == b->default_inactive && - a->default_active == b->default_active) { - ret = TRUE; - } else { - ret = FALSE; - } - - return ret; -} - -PolKitImplicitAuthorization * -_polkit_implicit_authorization_new (PolKitResult defaults_allow_any, - PolKitResult defaults_allow_inactive, - PolKitResult defaults_allow_active) -{ - PolKitImplicitAuthorization *pd; - - pd = kit_new0 (PolKitImplicitAuthorization, 1); - if (pd == NULL) - goto out; - pd->refcount = 1; - pd->default_any = defaults_allow_any; - pd->default_inactive = defaults_allow_inactive; - pd->default_active = defaults_allow_active; -out: - return pd; -} - -/** - * polkit_implicit_authorization_ref: - * @implicit_authorization: the policy object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitImplicitAuthorization * -polkit_implicit_authorization_ref (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_val_if_fail (implicit_authorization != NULL, implicit_authorization); - implicit_authorization->refcount++; - return implicit_authorization; -} - -/** - * polkit_implicit_authorization_unref: - * @implicit_authorization: the object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_implicit_authorization_unref (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_if_fail (implicit_authorization != NULL); - implicit_authorization->refcount--; - if (implicit_authorization->refcount > 0) - return; - kit_free (implicit_authorization); -} - -/** - * polkit_implicit_authorization_debug: - * @implicit_authorization: the object - * - * Print debug details - **/ -void -polkit_implicit_authorization_debug (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_if_fail (implicit_authorization != NULL); - polkit_debug ("PolKitImplicitAuthorization: refcount=%d\n" - " default_any=%s\n" - " default_inactive=%s\n" - " default_active=%s", - implicit_authorization->refcount, - polkit_result_to_string_representation (implicit_authorization->default_any), - polkit_result_to_string_representation (implicit_authorization->default_inactive), - polkit_result_to_string_representation (implicit_authorization->default_active)); -} - - -/** - * polkit_implicit_authorization_can_session_do_action: - * @implicit_authorization: the object - * @action: the type of access to check for - * @session: the session in question - * - * Using the default policy for an action, determine if a given - * session can do a given action. - * - * Returns: A #PolKitResult - can only be one of - * #POLKIT_RESULT_YES, #POLKIT_RESULT_NO. - **/ -PolKitResult -polkit_implicit_authorization_can_session_do_action (PolKitImplicitAuthorization *implicit_authorization, - PolKitAction *action, - PolKitSession *session) -{ - polkit_bool_t is_local; - polkit_bool_t is_active; - PolKitResult ret; - - ret = POLKIT_RESULT_NO; - - kit_return_val_if_fail (implicit_authorization != NULL, ret); - kit_return_val_if_fail (action != NULL, ret); - kit_return_val_if_fail (session != NULL, ret); - - ret = implicit_authorization->default_any; - - polkit_session_get_ck_is_local (session, &is_local); - polkit_session_get_ck_is_active (session, &is_active); - - if (!is_local) - goto out; - - if (is_active) { - ret = implicit_authorization->default_active; - } else { - ret = implicit_authorization->default_inactive; - } -out: - return ret; -} - -/** - * polkit_implicit_authorization_can_caller_do_action: - * @implicit_authorization: the object - * @action: the type of access to check for - * @caller: the caller in question - * - * Using the default policy for an action, determine if a given - * caller can do a given action. - * - * Returns: A #PolKitResult specifying if, and how, the caller can - * do the given action. - **/ -PolKitResult -polkit_implicit_authorization_can_caller_do_action (PolKitImplicitAuthorization *implicit_authorization, - PolKitAction *action, - PolKitCaller *caller) -{ - polkit_bool_t is_local; - polkit_bool_t is_active; - PolKitSession *session; - PolKitResult ret; - - ret = POLKIT_RESULT_NO; - - kit_return_val_if_fail (implicit_authorization != NULL, ret); - kit_return_val_if_fail (action != NULL, ret); - kit_return_val_if_fail (caller != NULL, ret); - - ret = implicit_authorization->default_any; - - polkit_caller_get_ck_session (caller, &session); - if (session == NULL) - goto out; - - polkit_session_get_ck_is_local (session, &is_local); - polkit_session_get_ck_is_active (session, &is_active); - - if (!is_local) - goto out; - - if (is_active) { - ret = implicit_authorization->default_active; - } else { - ret = implicit_authorization->default_inactive; - } - -out: - return ret; -} - -/** - * polkit_implicit_authorization_set_allow_any: - * @implicit_authorization: the object - * @value: the value to set - * - * Set default policy. - * - **/ -void -polkit_implicit_authorization_set_allow_any (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value) -{ - kit_return_if_fail (implicit_authorization != NULL); - implicit_authorization->default_any = value; -} - -/** - * polkit_implicit_authorization_set_allow_inactive: - * @implicit_authorization: the object - * @value: the value to set - * - * Set default policy. - * - **/ -void -polkit_implicit_authorization_set_allow_inactive (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value) -{ - kit_return_if_fail (implicit_authorization != NULL); - implicit_authorization->default_inactive = value; -} - -/** - * polkit_implicit_authorization_set_allow_active: - * @implicit_authorization: the object - * @value: the value to set - * - * Set default policy. - * - **/ -void -polkit_implicit_authorization_set_allow_active (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value) -{ - kit_return_if_fail (implicit_authorization != NULL); - implicit_authorization->default_active = value; -} - -/** - * polkit_implicit_authorization_get_allow_any: - * @implicit_authorization: the object - * - * Get default policy. - * - * Returns: default policy - **/ -PolKitResult -polkit_implicit_authorization_get_allow_any (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_val_if_fail (implicit_authorization != NULL, POLKIT_RESULT_NO); - return implicit_authorization->default_any; -} - -/** - * polkit_implicit_authorization_get_allow_inactive: - * @implicit_authorization: the object - * - * Get default policy. - * - * Returns: default policy - **/ -PolKitResult -polkit_implicit_authorization_get_allow_inactive (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_val_if_fail (implicit_authorization != NULL, POLKIT_RESULT_NO); - return implicit_authorization->default_inactive; -} - -/** - * polkit_implicit_authorization_get_allow_active: - * @implicit_authorization: the object - * - * Get default policy. - * - * Returns: default policy - **/ -PolKitResult -polkit_implicit_authorization_get_allow_active (PolKitImplicitAuthorization *implicit_authorization) -{ - kit_return_val_if_fail (implicit_authorization != NULL, POLKIT_RESULT_NO); - return implicit_authorization->default_active; -} - - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_ts (PolKitSession *s, PolKitResult any, PolKitResult inactive, PolKitResult active, PolKitResult *ret) -{ - PolKitAction *a; - PolKitImplicitAuthorization *d; - polkit_bool_t oom; - - oom = TRUE; - - if (s == NULL) - goto out; - - if ((a = polkit_action_new ()) != NULL) { - if (polkit_action_set_action_id (a, "org.dummy")) { - if ((d = _polkit_implicit_authorization_new (any, - inactive, - active)) != NULL) { - PolKitCaller *c; - - *ret = polkit_implicit_authorization_can_session_do_action (d, a, s); - oom = FALSE; - - if ((c = polkit_caller_new ()) != NULL) { - kit_assert (polkit_implicit_authorization_can_caller_do_action (d, a, c) == any); - - kit_assert (polkit_caller_set_ck_session (c, s)); - kit_assert (polkit_implicit_authorization_can_caller_do_action (d, a, c) == *ret); - polkit_caller_unref (c); - } - - polkit_implicit_authorization_ref (d); - polkit_implicit_authorization_get_allow_any (d); - polkit_implicit_authorization_get_allow_inactive (d); - polkit_implicit_authorization_get_allow_active (d); - polkit_implicit_authorization_unref (d); - polkit_implicit_authorization_debug (d); - polkit_implicit_authorization_unref (d); - } - } - polkit_action_unref (a); - } - -out: - return oom; -} - -static polkit_bool_t -_run_test (void) -{ - PolKitResult ret; - PolKitSession *s_active; - PolKitSession *s_inactive; - PolKitSession *s_active_remote; - PolKitSession *s_inactive_remote; - - if ((s_active = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_active, "/session1")) { - polkit_session_unref (s_active); - s_active = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_active, TRUE)); - kit_assert (polkit_session_set_ck_is_active (s_active, TRUE)); - } - } - - if ((s_inactive = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_inactive, "/session2")) { - polkit_session_unref (s_inactive); - s_inactive = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_inactive, TRUE)); - kit_assert (polkit_session_set_ck_is_active (s_inactive, FALSE)); - } - } - - if ((s_active_remote = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_active_remote, "/session3") || - !polkit_session_set_ck_remote_host (s_active_remote, "remotehost.com")) { - polkit_session_unref (s_active_remote); - s_active_remote = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_active_remote, FALSE)); - kit_assert (polkit_session_set_ck_is_active (s_active_remote, TRUE)); - } - } - - if ((s_inactive_remote = polkit_session_new ()) != NULL) { - if (!polkit_session_set_ck_objref (s_inactive_remote, "/session4") || - !polkit_session_set_ck_remote_host (s_inactive_remote, "remotehost.com")) { - polkit_session_unref (s_inactive_remote); - s_inactive_remote = NULL; - } else { - kit_assert (polkit_session_set_ck_is_local (s_inactive_remote, FALSE)); - kit_assert (polkit_session_set_ck_is_active (s_inactive_remote, FALSE)); - } - } - - kit_assert (_ts (s_active, - POLKIT_RESULT_NO, POLKIT_RESULT_NO, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_inactive, - POLKIT_RESULT_NO, POLKIT_RESULT_NO, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_NO); - kit_assert (_ts (s_active_remote, - POLKIT_RESULT_NO, POLKIT_RESULT_NO, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_NO); - kit_assert (_ts (s_inactive_remote, - POLKIT_RESULT_NO, POLKIT_RESULT_NO, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_NO); - - kit_assert (_ts (s_active, - POLKIT_RESULT_NO, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_inactive, - POLKIT_RESULT_NO, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_active_remote, - POLKIT_RESULT_NO, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_NO); - kit_assert (_ts (s_inactive_remote, - POLKIT_RESULT_NO, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_NO); - - kit_assert (_ts (s_active, - POLKIT_RESULT_YES, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_inactive, - POLKIT_RESULT_YES, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_active_remote, - POLKIT_RESULT_YES, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - kit_assert (_ts (s_inactive_remote, - POLKIT_RESULT_YES, POLKIT_RESULT_YES, POLKIT_RESULT_YES, &ret) || - ret == POLKIT_RESULT_YES); - - if (s_active != NULL) - polkit_session_unref (s_active); - - if (s_inactive != NULL) - polkit_session_unref (s_inactive); - - if (s_active_remote != NULL) - polkit_session_unref (s_active_remote); - - if (s_inactive_remote != NULL) - polkit_session_unref (s_inactive_remote); - - return TRUE; -} - -KitTest _test_implicit_authorization = { - "polkit_implicit_authorization", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-implicit-authorization.h b/src/polkit/polkit-implicit-authorization.h deleted file mode 100644 index 3bc55e3..0000000 --- a/src/polkit/polkit-implicit-authorization.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-implicit-authorization.h : policy definition for the defaults - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_IMPLICIT_AUTHORIZATION_H -#define POLKIT_IMPLICIT_AUTHORIZATION_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-session.h> -#include <polkit/polkit-caller.h> -#include <polkit/polkit-error.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitImplicitAuthorization; -typedef struct _PolKitImplicitAuthorization PolKitImplicitAuthorization; - -PolKitImplicitAuthorization *polkit_implicit_authorization_new (void); -PolKitImplicitAuthorization *polkit_implicit_authorization_ref (PolKitImplicitAuthorization *implicit_authorization); -void polkit_implicit_authorization_unref (PolKitImplicitAuthorization *implicit_authorization); -void polkit_implicit_authorization_debug (PolKitImplicitAuthorization *implicit_authorization); -PolKitImplicitAuthorization *polkit_implicit_authorization_clone (PolKitImplicitAuthorization *implicit_authorization); - -polkit_bool_t polkit_implicit_authorization_equals (PolKitImplicitAuthorization *a, PolKitImplicitAuthorization *b); - -PolKitResult polkit_implicit_authorization_can_session_do_action (PolKitImplicitAuthorization *implicit_authorization, - PolKitAction *action, - PolKitSession *session); - -PolKitResult polkit_implicit_authorization_can_caller_do_action (PolKitImplicitAuthorization *implicit_authorization, - PolKitAction *action, - PolKitCaller *caller); - -PolKitResult polkit_implicit_authorization_get_allow_any (PolKitImplicitAuthorization *implicit_authorization); -PolKitResult polkit_implicit_authorization_get_allow_inactive (PolKitImplicitAuthorization *implicit_authorization); -PolKitResult polkit_implicit_authorization_get_allow_active (PolKitImplicitAuthorization *implicit_authorization); - -void polkit_implicit_authorization_set_allow_any (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value); -void polkit_implicit_authorization_set_allow_inactive (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value); -void polkit_implicit_authorization_set_allow_active (PolKitImplicitAuthorization *implicit_authorization, PolKitResult value); - - -/* TODO: export knobs for "default policy" */ - -POLKIT_END_DECLS - -#endif /* POLKIT_IMPLICIT_AUTHORIZATION_H */ - - diff --git a/src/polkit/polkit-private.h b/src/polkit/polkit-private.h deleted file mode 100644 index 51a240f..0000000 --- a/src/polkit/polkit-private.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-private.h : Private functions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) -#error "This is a private file and shouldn't be included outside PolicyKit." -#endif - -#ifndef POLKIT_PRIVATE_H -#define POLKIT_PRIVATE_H - -#include <kit/kit.h> -#include <polkit/polkit.h> -#include <polkit/polkit-debug.h> - -/** - * SECTION:polkit-private - * @short_description: Private symbols for libpolkit - * - * Private symbols for libpolkit. - */ - -POLKIT_BEGIN_DECLS - -void _polkit_memory_reset (void); -int _polkit_memory_get_current_allocations (void); -int _polkit_memory_get_total_allocations (void); -void _polkit_memory_fail_nth_alloc (int number); - -PolKitAuthorization *_polkit_authorization_new_for_uid (const char *entry_in_auth_file, uid_t uid); -const char *_polkit_authorization_get_authfile_entry (PolKitAuthorization *auth); - -polkit_bool_t _polkit_authorization_db_auth_file_add (polkit_bool_t transient, uid_t uid, char *str_to_add); - -PolKitAuthorizationDB *_polkit_authorization_db_new (void); -void _polkit_authorization_db_invalidate_cache (PolKitAuthorizationDB *authdb); - - -PolKitImplicitAuthorization *_polkit_implicit_authorization_new (PolKitResult defaults_allow_any, - PolKitResult defaults_allow_inactive, - PolKitResult defaults_allow_active); - -polkit_bool_t _polkit_action_description_set_descriptions (PolKitActionDescription *pfe, - const char *policy_description, - const char *policy_message); - - -PolKitImplicitAuthorization *_polkit_implicit_authorization_new (PolKitResult defaults_allow_any, - PolKitResult defaults_allow_inactive, - PolKitResult defaults_allow_active); - - -PolKitActionDescription *_polkit_action_description_new (const char *action_id, - const char *vendor, - const char *vendor_url, - const char *icon_name, - PolKitResult defaults_allow_any, - PolKitResult defaults_allow_inactive, - PolKitResult defaults_allow_active, - KitHash *annotations); - - -#ifdef POLKIT_AUTHDB_DUMMY -struct _PolKitAuthorizationDB -{ - /*< private >*/ - int refcount; -}; -#elif POLKIT_AUTHDB_DEFAULT -struct _PolKitAuthorizationDB -{ - /*< private >*/ - int refcount; - KitHash *uid_to_authlist; -}; - -#endif - -POLKIT_END_DECLS - -#endif /* POLKIT_PRIVATE_H */ - diff --git a/src/polkit/polkit-read-auth-helper.c b/src/polkit/polkit-read-auth-helper.c deleted file mode 100644 index 65ca8b7..0000000 --- a/src/polkit/polkit-read-auth-helper.c +++ /dev/null @@ -1,421 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-read-auth-helper.c : setgid polkituser helper for PolicyKit - * to read authorizations - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/param.h> -#include <sys/stat.h> -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> -#include <fcntl.h> -#include <dirent.h> -#ifdef HAVE_SOLARIS -#include <limits.h> -#define LOG_AUTHPRIV (10<<3) -#endif - -#include <polkit/polkit.h> -#include <polkit/polkit-private.h> - -static polkit_bool_t -dump_auths_from_file (const char *path, uid_t uid) -{ - int ret; - int fd; - char buf[256]; - struct stat statbuf; - ssize_t num_bytes_read; - ssize_t num_bytes_to_read; - ssize_t num_bytes_remaining_to_read; - ssize_t num_bytes_to_write; - ssize_t num_bytes_written; - ssize_t num_bytes_remaining_to_write; - polkit_bool_t have_written_uid; - - ret = FALSE; - - if (stat (path, &statbuf) != 0) { - /* this is fine; the file does not have to exist.. */ - if (errno == ENOENT) { - ret = TRUE; - goto out; - } - fprintf (stderr, "polkit-read-auth-helper: cannot stat %s: %m\n", path); - goto out; - } - - fd = open (path, O_RDONLY); - if (fd < 0) { - fprintf (stderr, "polkit-read-auth-helper: cannot open %s: %m\n", path); - goto out; - } - - num_bytes_remaining_to_read = statbuf.st_size; - - have_written_uid = FALSE; - while (num_bytes_remaining_to_read > 0) { - - /* start with writing the uid - this is necessary when dumping all authorizations via uid=1 */ - if (!have_written_uid) { - have_written_uid = TRUE; - snprintf (buf, sizeof (buf), "#uid=%d\n", uid); - num_bytes_read = strlen (buf); - } else { - - if (num_bytes_remaining_to_read > (ssize_t) sizeof (buf)) - num_bytes_to_read = (ssize_t) sizeof (buf); - else - num_bytes_to_read = num_bytes_remaining_to_read; - - again: - num_bytes_read = read (fd, buf, num_bytes_to_read); - if (num_bytes_read == -1) { - if (errno == EAGAIN || errno == EINTR) { - goto again; - } else { - fprintf (stderr, "polkit-read-auth-helper: error reading file %s: %m\n", path); - close (fd); - goto out; - } - } - - num_bytes_remaining_to_read -= num_bytes_read; - } - - /* write to stdout */ - num_bytes_to_write = num_bytes_read; - num_bytes_remaining_to_write = num_bytes_read; - - while (num_bytes_remaining_to_write > 0) { - again_write: - num_bytes_written = write (STDOUT_FILENO, - buf + (num_bytes_to_write - num_bytes_remaining_to_write), - num_bytes_remaining_to_write); - if (num_bytes_written == -1) { - if (errno == EAGAIN || errno == EINTR) { - goto again_write; - } else { - fprintf (stderr, "polkit-read-auth-helper: error writing to stdout: %m\n"); - close (fd); - goto out; - } - } - - num_bytes_remaining_to_write -= num_bytes_written; - } - - } - - - close (fd); - - ret = TRUE; - -out: - return ret; -} - -static polkit_bool_t -dump_auths_all (const char *root) -{ - DIR *dir; - int dfd; -#ifdef HAVE_READDIR64 - struct dirent64 *d; -#else - struct dirent *d; -#endif - polkit_bool_t ret; - - ret = FALSE; - - dir = opendir (root); - if (dir == NULL) { - fprintf (stderr, "polkit-read-auth-helper: error calling opendir on %s: %m\n", root); - goto out; - } - - dfd = dirfd (dir); - if (dfd == -1) { - fprintf (stderr, "polkit-read-auth-helper: error calling dirfd(): %m\n"); - goto out; - } - -#ifdef HAVE_READDIR64 - while ((d = readdir64(dir)) != NULL) { -#else - while ((d = readdir(dir)) != NULL) { -#endif - unsigned int n, m; - uid_t uid; - size_t name_len; - char *filename; - char username[PATH_MAX]; - char path[PATH_MAX]; - static const char suffix[] = ".auths"; - struct passwd *pw; - struct stat statbuf; - - if (d->d_name == NULL) - continue; - - if (snprintf (path, sizeof (path), "%s/%s", root, d->d_name) >= (int) sizeof (path)) { - fprintf (stderr, "polkit-read-auth-helper: string was truncated (1)\n"); - goto out; - } - - if (stat (path, &statbuf) != 0) { - fprintf (stderr, "polkit-read-auth-helper: cannot stat %s: %m\n", path); - goto out; - } - - if (!S_ISREG(statbuf.st_mode)) - continue; - - filename = d->d_name; - name_len = strlen (filename); - if (name_len < sizeof (suffix)) - continue; - - if (strcmp ((filename + name_len - sizeof (suffix) + 1), suffix) != 0) - continue; - - /* find the user name.. */ - for (n = 0; n < name_len; n++) { - if (filename[n] == '-') - break; - } - if (filename[n] == '\0') { - fprintf (stderr, "polkit-read-auth-helper: file name '%s' is malformed (1)\n", filename); - continue; - } - n++; - m = n; - for ( ; n < name_len; n++) { - if (filename[n] == '.') - break; - } - - if (filename[n] == '\0') { - fprintf (stderr, "polkit-read-auth-helper: file name '%s' is malformed (2)\n", filename); - continue; - } - if (n - m > sizeof (username) - 1) { - fprintf (stderr, "polkit-read-auth-helper: file name '%s' is malformed (3)\n", filename); - continue; - } - strncpy (username, filename + m, n - m); - username[n - m] = '\0'; - - pw = kit_getpwnam (username); - if (pw == NULL) { - fprintf (stderr, "polkit-read-auth-helper: cannot look up uid for username %s\n", username); - continue; - } - uid = pw->pw_uid; - - if (!dump_auths_from_file (path, uid)) - goto out; - } - - ret = TRUE; - -out: - if (dir != NULL) - closedir (dir); - return ret; -} - -static polkit_bool_t -dump_auths_for_uid (const char *root, uid_t uid) -{ - char path[256]; - struct passwd *pw; - - pw = kit_getpwuid (uid); - if (pw == NULL) { - fprintf (stderr, "polkit-read-auth-helper: cannot lookup user name for uid %d\n", uid); - return FALSE; - } - - if (snprintf (path, sizeof (path), "%s/user-%s.auths", root, pw->pw_name) >= (int) sizeof (path)) { - fprintf (stderr, "polkit-read-auth-helper: string was truncated (1)\n"); - return FALSE; - } - - return dump_auths_from_file (path, uid); -} - - -int -main (int argc, char *argv[]) -{ - int ret; - uid_t caller_uid; - uid_t requesting_info_for_uid; - char *endp; - uid_t uid_for_polkit_user; - - ret = 1; - -#ifndef POLKIT_BUILD_TESTS - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); -#endif - - openlog ("polkit-read-auth-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 2) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-read-auth-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - caller_uid = getuid (); - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-read-auth-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - -#ifdef POLKIT_BUILD_TESTS - char *pretend; - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_UID")) != NULL) { - caller_uid = atoi (pretend); - goto skip_check; - } -#endif - gid_t egid; - struct group *group; - struct passwd *pw; - - /* check that we are setgid polkituser */ - egid = getegid (); - group = getgrgid (egid); - if (group == NULL) { - fprintf (stderr, "polkit-read-auth-helper: cannot lookup group info for gid %d\n", egid); - goto out; - } - if (strcmp (group->gr_name, POLKIT_GROUP) != 0) { - fprintf (stderr, "polkit-read-auth-helper: needs to be setgid " POLKIT_GROUP "\n"); - goto out; - } - -#ifdef POLKIT_BUILD_TESTS -skip_check: -#endif - - pw = kit_getpwnam (POLKIT_USER); - if (pw == NULL) { - fprintf (stderr, "polkit-read-auth-helper: cannot lookup uid for " POLKIT_USER "\n"); - goto out; - } - uid_for_polkit_user = pw->pw_uid; - - /*----------------------------------------------------------------------------------------------------*/ - - requesting_info_for_uid = strtoul (argv[1], &endp, 10); - if (strlen (argv[1]) == 0 || *endp != '\0') { - fprintf (stderr, "polkit-read-auth-helper: requesting_info_for_uid malformed (3)\n"); - goto out; - } - - /* uid 0 and user polkituser is allowed to read anything */ - if (caller_uid != 0 && caller_uid != uid_for_polkit_user) { - if (caller_uid != requesting_info_for_uid) { - pid_t ppid; - - ppid = getppid (); - if (ppid == 1) - goto out; - - if (polkit_check_auth (ppid, - "org.freedesktop.policykit.read", - "org.freedesktop.policykit.grant", NULL) == 0) { - goto out; - } - } - } - -#ifdef POLKIT_BUILD_TESTS - char *test_dir; - char dir_run[256]; - char dir_lib[256]; - - if ((test_dir = getenv ("POLKIT_TEST_LOCALSTATE_DIR")) == NULL) { - test_dir = PACKAGE_LOCALSTATE_DIR; - } - kit_assert ((size_t) snprintf (dir_run, sizeof (dir_run), "%s/run/polkit-1", test_dir) < sizeof (dir_run)); - kit_assert ((size_t) snprintf (dir_lib, sizeof (dir_lib), "%s/lib/polkit-1", test_dir) < sizeof (dir_lib)); - -#else - char *dir_run = PACKAGE_LOCALSTATE_DIR "/run/polkit-1"; - char *dir_lib = PACKAGE_LOCALSTATE_DIR "/lib/polkit-1"; -#endif - - if (requesting_info_for_uid == (uid_t) -1) { - if (!dump_auths_all (dir_run)) - goto out; - - if (!dump_auths_all (dir_lib)) - goto out; - } else { - if (!dump_auths_for_uid (dir_run, requesting_info_for_uid)) - goto out; - - if (!dump_auths_for_uid (dir_lib, requesting_info_for_uid)) - goto out; - } - - ret = 0; - -out: - return ret; -} - diff --git a/src/polkit/polkit-resolve-exe-helper.c b/src/polkit/polkit-resolve-exe-helper.c deleted file mode 100644 index 36dc018..0000000 --- a/src/polkit/polkit-resolve-exe-helper.c +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-resolve-exe-helper.c : setuid root helper for PolicyKit to - * resolve /proc/$pid/exe symlinks - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#ifdef HAVE_FREEBSD -#include <sys/param.h> -#endif -#include <security/pam_appl.h> -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> -#include <fcntl.h> -#include <dirent.h> - -#include <polkit/polkit.h> -#include <polkit/polkit-private.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#define PATH_MAX 1024 -#endif - -int -main (int argc, char *argv[]) -{ - int ret; - uid_t caller_uid; - pid_t requesting_info_for_pid; - char *endp; - uid_t uid_for_polkit_user; - struct passwd *pw; - gid_t egid; - struct group *group; - int n; - char buf[PATH_MAX]; - polkit_bool_t is_setgid_polkit; - - ret = 1; - - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - openlog ("polkit-resolve-exe-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (argc != 2) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-resolve-exe-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - caller_uid = getuid (); - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-resolve-exe-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - - pw = getpwnam (POLKIT_USER); - if (pw == NULL) { - fprintf (stderr, "polkit-resolve-exe-helper: cannot lookup uid for " POLKIT_USER "\n"); - goto out; - } - uid_for_polkit_user = pw->pw_uid; - - /* check if we are setgid polkituser */ - egid = getegid (); - group = getgrgid (egid); - if (group == NULL) { - fprintf (stderr, "polkit-resolve-exe-helper: cannot lookup group info for gid %d\n", egid); - goto out; - } - if (strcmp (group->gr_name, POLKIT_GROUP) == 0) { - is_setgid_polkit = TRUE; - } else { - is_setgid_polkit = FALSE; - } - - /*----------------------------------------------------------------------------------------------------*/ - - requesting_info_for_pid = strtoul (argv[1], &endp, 10); - if (strlen (argv[1]) == 0 || *endp != '\0') { - fprintf (stderr, "polkit-resolve-exe-helper: requesting_info_for_pid malformed\n"); - goto out; - } - - /* user polkituser is allowed to resolve anything. So is any program that is setgid polkituser. */ - if (caller_uid != uid_for_polkit_user && !is_setgid_polkit) { - pid_t ppid; - - ppid = getppid (); - if (ppid == 1) - goto out; - - /* need to set the real uid of the process to root ... otherwise D-Bus won't work */ - if (setuid (0) != 0) { - fprintf (stderr, "polkit-resolve-exe-helper: cannot do setuid(0): %m\n"); - goto out; - } - - if (polkit_check_auth (ppid, - "org.freedesktop.policykit.read", NULL) == 0) { - fprintf (stderr, "polkit-resolve-exe-helper: not authorized for org.freedesktop.policykit.read\n"); - goto out; - } - } - - n = polkit_sysdeps_get_exe_for_pid (requesting_info_for_pid, buf, sizeof (buf)); - if (n == -1 || n >= (int) sizeof (buf)) { - fprintf (stderr, "polkit-resolve-exe-helper: Cannot resolve link for pid %d\n", - requesting_info_for_pid); - goto out; - } - - printf ("%s", buf); - - ret = 0; - -out: - return ret; -} - diff --git a/src/polkit/polkit-result.c b/src/polkit/polkit-result.c deleted file mode 100644 index 6fb5219..0000000 --- a/src/polkit/polkit-result.c +++ /dev/null @@ -1,155 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-result.c : result codes from PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/** - * SECTION:polkit-result - * @title: Results - * @short_description: Definition of results of PolicyKit queries. - * - * These functions are used to manipulate PolicyKit results. - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-result.h" -#include "polkit-test.h" -#include "polkit-private.h" - - -static const struct { - PolKitResult result; - const char *str; -} mapping[POLKIT_RESULT_N_RESULTS] = -{ - {POLKIT_RESULT_UNKNOWN, "unknown"}, - {POLKIT_RESULT_NO, "no"}, - {POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH, "auth_admin"}, - {POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION, "auth_admin_keep_session"}, - {POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS, "auth_admin_keep_always"}, - {POLKIT_RESULT_ONLY_VIA_SELF_AUTH, "auth_self"}, - {POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION, "auth_self_keep_session"}, - {POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS, "auth_self_keep_always"}, - {POLKIT_RESULT_YES, "yes"}, - {POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT, "auth_admin_one_shot"}, - {POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT, "auth_self_one_shot"}, -}; - - -/** - * polkit_result_to_string_representation: - * @result: the given result to get a textual representation of - * - * Gives a textual representation of a #PolKitResult object. This - * string is not suitable for displaying to an end user (it's not - * localized for starters) but is useful for serialization as it can - * be converted back to a #PolKitResult object using - * polkit_result_from_string_representation(). - * - * Returns: string representing the result (do not free) or #NULL if the given result is invalid - **/ -const char * -polkit_result_to_string_representation (PolKitResult result) -{ - if (result < 0 || result >= POLKIT_RESULT_N_RESULTS) { - kit_warning ("The passed result code, %d, is not valid", result); - return NULL; - } - - return mapping[result].str; -} - -/** - * polkit_result_from_string_representation: - * @string: textual representation of a #PolKitResult object - * @out_result: return location for #PolKitResult - * - * Given a textual representation of a #PolKitResult object, find the - * #PolKitResult value. - * - * Returns: TRUE if the textual representation was valid, otherwise FALSE - **/ -polkit_bool_t -polkit_result_from_string_representation (const char *string, PolKitResult *out_result) -{ - int n; - - kit_return_val_if_fail (out_result != NULL, FALSE); - - for (n = 0; n < POLKIT_RESULT_N_RESULTS; n++) { - if (strcmp (mapping[n].str, string) == 0) { - *out_result = mapping[n].result; - goto found; - } - } - - return FALSE; -found: - return TRUE; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - PolKitResult n; - PolKitResult m; - - for (n = 0; n < POLKIT_RESULT_N_RESULTS; n++) { - kit_assert (polkit_result_from_string_representation (polkit_result_to_string_representation (n), &m) && n== m); - } - - kit_assert (polkit_result_to_string_representation ((PolKitResult) -1) == NULL); - kit_assert (polkit_result_to_string_representation (POLKIT_RESULT_N_RESULTS) == NULL); - - kit_assert (! polkit_result_from_string_representation ("non-exiting-result-id", &m)); - - - return TRUE; -} - -KitTest _test_result = { - "polkit_result", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-result.h b/src/polkit/polkit-result.h deleted file mode 100644 index 16d0a0b..0000000 --- a/src/polkit/polkit-result.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-result.h : result codes from PolicyKit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_RESULT_H -#define POLKIT_RESULT_H - -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -/** - * PolKitResult: - * @POLKIT_RESULT_UNKNOWN: The result is unknown / cannot be - * computed. This is mostly used internally in libpolkit. - * @POLKIT_RESULT_NO: Access denied. - * @POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT: Access denied, but - * authentication by the caller as administrator (e.g. root or a - * member in the wheel group depending on configuration) will grant - * access exactly one time to the process the caller is originating - * from. See polkit_context_is_caller_authorized() for discussion (and - * limitations) about one-shot authorizations. - * @POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH: Access denied, but - * authentication by the caller as administrator (e.g. root or a - * member in the wheel group depending on configuration) will grant - * access to the process the caller is originating from. - * @POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION: Access denied, but - * authentication by the caller as administrator (e.g. root or a - * member in the wheel group depending on configuration) will grant - * access for the remainder of the session - * @POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS: Access denied, but - * authentication by the caller as administrator (e.g. root or a - * member in the wheel group depending on configuration) will grant - * access in the future. - * @POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT: Access denied, but - * authentication by the caller as himself will grant access exactly - * one time to the process the caller is originating from. See - * polkit_context_is_caller_authorized() for discussion (and - * limitations) about one-shot authorizations. - * @POLKIT_RESULT_ONLY_VIA_SELF_AUTH: Access denied, but - * authentication by the caller as himself will grant access to the - * process the caller is originating from. - * @POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION: Access denied, but - * authentication by the caller as himself will grant access to the - * resource for the remainder of the session - * @POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS: Access denied, but - * authentication by the caller as himself will grant access to the - * resource in the future. - * @POLKIT_RESULT_YES: Access granted. - * @POLKIT_RESULT_N_RESULTS: Number of result codes - * - * Result codes from queries to PolicyKit. This enumeration may grow - * in the future. One should never rely on the ordering - */ -typedef enum -{ - POLKIT_RESULT_UNKNOWN, - - POLKIT_RESULT_NO, - - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH, - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_SESSION, - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_KEEP_ALWAYS, - - POLKIT_RESULT_ONLY_VIA_SELF_AUTH, - POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_SESSION, - POLKIT_RESULT_ONLY_VIA_SELF_AUTH_KEEP_ALWAYS, - - POLKIT_RESULT_YES, - - POLKIT_RESULT_ONLY_VIA_ADMIN_AUTH_ONE_SHOT, - POLKIT_RESULT_ONLY_VIA_SELF_AUTH_ONE_SHOT, - - POLKIT_RESULT_N_RESULTS -} PolKitResult; - -const char * -polkit_result_to_string_representation (PolKitResult result); - -polkit_bool_t -polkit_result_from_string_representation (const char *string, PolKitResult *out_result); - -POLKIT_END_DECLS - -#endif /* POLKIT_RESULT_H */ diff --git a/src/polkit/polkit-seat.c b/src/polkit/polkit-seat.c deleted file mode 100644 index b7880dd..0000000 --- a/src/polkit/polkit-seat.c +++ /dev/null @@ -1,234 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-seat.c : seat - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-seat.h" -#include "polkit-utils.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-seat - * @title: Seat - * @short_description: Represents a ConsoleKit Seat. - * - * This class is used to represent a seat. - **/ - -/** - * PolKitSeat: - * - * Objects of this class are used to record information about a - * seat. - **/ -struct _PolKitSeat -{ - int refcount; - char *ck_objref; -}; - -/** - * polkit_seat_new: - * - * Creates a new #PolKitSeat object. - * - * Returns: the new object - **/ -PolKitSeat * -polkit_seat_new (void) -{ - PolKitSeat *seat; - seat = kit_new0 (PolKitSeat, 1); - if (seat == NULL) - goto out; - seat->refcount = 1; -out: - return seat; -} - -/** - * polkit_seat_ref: - * @seat: the seat object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitSeat * -polkit_seat_ref (PolKitSeat *seat) -{ - kit_return_val_if_fail (seat != NULL, seat); - seat->refcount++; - return seat; -} - -/** - * polkit_seat_unref: - * @seat: the seat object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_seat_unref (PolKitSeat *seat) -{ - kit_return_if_fail (seat != NULL); - seat->refcount--; - if (seat->refcount > 0) - return; - kit_free (seat->ck_objref); - kit_free (seat); -} - -/** - * polkit_seat_set_ck_objref: - * @seat: the seat object - * @ck_objref: the D-Bus object path to the ConsoleKit seat object - * - * Set the D-Bus object path to the ConsoleKit seat object. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_seat_set_ck_objref (PolKitSeat *seat, const char *ck_objref) -{ - kit_return_val_if_fail (seat != NULL, FALSE); - kit_return_val_if_fail (_pk_validate_identifier (ck_objref), FALSE); - if (seat->ck_objref != NULL) - kit_free (seat->ck_objref); - seat->ck_objref = kit_strdup (ck_objref); - if (seat->ck_objref == NULL) - return FALSE; - else - return TRUE; -} - -/** - * polkit_seat_get_ck_objref: - * @seat: the seat object - * @out_ck_objref: Returns the D-Bus object path to the ConsoleKit seat object. The caller shall not free this string. - * - * Get the D-Bus object path to the ConsoleKit seat object. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_seat_get_ck_objref (PolKitSeat *seat, char **out_ck_objref) -{ - kit_return_val_if_fail (seat != NULL, FALSE); - kit_return_val_if_fail (out_ck_objref != NULL, FALSE); - *out_ck_objref = seat->ck_objref; - return TRUE; -} - -/** - * polkit_seat_debug: - * @seat: the object - * - * Print debug details - **/ -void -polkit_seat_debug (PolKitSeat *seat) -{ - kit_return_if_fail (seat != NULL); - polkit_debug ("PolKitSeat: refcount=%d objpath=%s", seat->refcount, seat->ck_objref); -} - -/** - * polkit_seat_validate: - * @seat: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - **/ -polkit_bool_t -polkit_seat_validate (PolKitSeat *seat) -{ - kit_return_val_if_fail (seat != NULL, FALSE); - kit_return_val_if_fail (seat->ck_objref != NULL, FALSE); - return TRUE; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - char *str; - PolKitSeat *s; - - s = polkit_seat_new (); - if (s == NULL) { - /* OOM */ - } else { - if (! polkit_seat_set_ck_objref (s, "/someseat")) { - /* OOM */ - } else { - kit_assert (polkit_seat_get_ck_objref (s, &str) && strcmp (str, "/someseat") == 0); - kit_assert (polkit_seat_validate (s)); - polkit_seat_ref (s); - kit_assert (polkit_seat_validate (s)); - polkit_seat_unref (s); - kit_assert (polkit_seat_validate (s)); - polkit_seat_debug (s); - if (! polkit_seat_set_ck_objref (s, "/someseat2")) { - /* OOM */ - } else { - kit_assert (polkit_seat_get_ck_objref (s, &str) && strcmp (str, "/someseat2") == 0); - } - } - polkit_seat_unref (s); - } - - return TRUE; -} - -KitTest _test_seat = { - "polkit_seat", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-seat.h b/src/polkit/polkit-seat.h deleted file mode 100644 index 25e9b59..0000000 --- a/src/polkit/polkit-seat.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-seat.h : seats - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_SEAT_H -#define POLKIT_SEAT_H - -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitSeat; -typedef struct _PolKitSeat PolKitSeat; - -PolKitSeat *polkit_seat_new (void); -PolKitSeat *polkit_seat_ref (PolKitSeat *seat); -void polkit_seat_unref (PolKitSeat *seat); -polkit_bool_t polkit_seat_set_ck_objref (PolKitSeat *seat, const char *ck_objref); -polkit_bool_t polkit_seat_get_ck_objref (PolKitSeat *seat, char **out_ck_objref); - -void polkit_seat_debug (PolKitSeat *seat); -polkit_bool_t polkit_seat_validate (PolKitSeat *seat); - -POLKIT_END_DECLS - -#endif /* POLKIT_SEAT_H */ - - diff --git a/src/polkit/polkit-session.c b/src/polkit/polkit-session.c deleted file mode 100644 index 1900209..0000000 --- a/src/polkit/polkit-session.c +++ /dev/null @@ -1,504 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-session.c : sessions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#include "polkit-debug.h" -#include "polkit-session.h" -#include "polkit-utils.h" -#include "polkit-test.h" -#include "polkit-private.h" - -/** - * SECTION:polkit-session - * @title: Session - * @short_description: Represents a ConsoleKit Session. - * - * This class is used to represent a session. - **/ - -/** - * PolKitSession: - * - * Objects of this class are used to record information about a - * session. - **/ -struct _PolKitSession -{ - int refcount; - uid_t uid; - PolKitSeat *seat; - char *ck_objref; - polkit_bool_t is_active; - polkit_bool_t is_local; - char *remote_host; -}; - -/** - * polkit_session_new: - * - * Creates a new #PolKitSession object. - * - * Returns: the new object - **/ -PolKitSession * -polkit_session_new (void) -{ - PolKitSession *session; - session = kit_new0 (PolKitSession, 1); - if (session == NULL) - goto out; - session->refcount = 1; -out: - return session; -} - -/** - * polkit_session_ref: - * @session: The session object - * - * Increase reference count. - * - * Returns: the object - **/ -PolKitSession * -polkit_session_ref (PolKitSession *session) -{ - kit_return_val_if_fail (session != NULL, session); - session->refcount++; - return session; -} - - -/** - * polkit_session_unref: - * @session: The session object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - **/ -void -polkit_session_unref (PolKitSession *session) -{ - kit_return_if_fail (session != NULL); - session->refcount--; - if (session->refcount > 0) - return; - kit_free (session->ck_objref); - kit_free (session->remote_host); - if (session->seat != NULL) - polkit_seat_unref (session->seat); - kit_free (session); -} - -/** - * polkit_session_set_uid: - * @session: The session object - * @uid: UNIX user id - * - * Set the UNIX user id of the user owning the session. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_uid (PolKitSession *session, uid_t uid) -{ - kit_return_val_if_fail (session != NULL, FALSE); - session->uid = uid; - return TRUE; -} - -/** - * polkit_session_set_ck_objref: - * @session: The session object - * @ck_objref: D-Bus object path - * - * Set the D-Bus object path to the ConsoleKit session object. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_ck_objref (PolKitSession *session, const char *ck_objref) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (_pk_validate_identifier (ck_objref), FALSE); - if (session->ck_objref != NULL) - kit_free (session->ck_objref); - session->ck_objref = kit_strdup (ck_objref); - if (session->ck_objref == NULL) - return FALSE; - else - return TRUE; -} - -/** - * polkit_session_set_ck_is_active: - * @session: The session object - * @is_active: whether ConsoleKit reports the session as active - * - * Set whether ConsoleKit regard the session as active. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_ck_is_active (PolKitSession *session, polkit_bool_t is_active) -{ - kit_return_val_if_fail (session != NULL, FALSE); - session->is_active = is_active; - return TRUE; -} - -/** - * polkit_session_set_ck_is_local: - * @session: The session object - * @is_local: whether ConsoleKit reports the session as local - * - * Set whether ConsoleKit regard the session as local. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_ck_is_local (PolKitSession *session, polkit_bool_t is_local) -{ - kit_return_val_if_fail (session != NULL, FALSE); - session->is_local = is_local; - return TRUE; -} - -/** - * polkit_session_set_ck_remote_host: - * @session: The session object - * @remote_host: hostname of the host/display that ConsoleKit reports - * the session to occur at - * - * Set the remote host/display that ConsoleKit reports the session to - * occur at. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_ck_remote_host (PolKitSession *session, const char *remote_host) -{ - kit_return_val_if_fail (session != NULL, FALSE); - /* TODO: FIXME: probably need to allow a lot more here */ - kit_return_val_if_fail (_pk_validate_identifier (remote_host), FALSE); - if (session->remote_host != NULL) - kit_free (session->remote_host); - session->remote_host = kit_strdup (remote_host); - if (session->remote_host == NULL) - return FALSE; - else - return TRUE; -} - -/** - * polkit_session_set_seat: - * @session: The session object - * @seat: a #PolKitSeat object - * - * Set the seat that the session belongs to. The reference count on - * the given object will be increased by one. If an existing seat - * object was set already, the reference count on that one will be - * decreased by one. - * - * Returns: #TRUE only if the value validated and was set - **/ -polkit_bool_t -polkit_session_set_seat (PolKitSession *session, PolKitSeat *seat) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (polkit_seat_validate (seat), FALSE); - if (session->seat != NULL) - polkit_seat_unref (session->seat); - session->seat = seat != NULL ? polkit_seat_ref (seat) : NULL; - return TRUE; -} - -/** - * polkit_session_get_uid: - * @session: The session object - * @out_uid: UNIX user id - * - * Get the UNIX user id of the user owning the session. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_uid (PolKitSession *session, uid_t *out_uid) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_uid != NULL, FALSE); - *out_uid = session->uid; - return TRUE; -} - -/** - * polkit_session_get_ck_objref: - * @session: The session object - * @out_ck_objref: D-Bus object path. Shall not be freed by the caller. - * - * Get the D-Bus object path to the ConsoleKit session object. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_ck_objref (PolKitSession *session, char **out_ck_objref) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_ck_objref != NULL, FALSE); - *out_ck_objref = session->ck_objref; - return TRUE; -} - -/** - * polkit_session_get_ck_is_active: - * @session: The session object - * @out_is_active: whether ConsoleKit reports the session as active - * - * Get whether ConsoleKit regard the session as active. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_ck_is_active (PolKitSession *session, polkit_bool_t *out_is_active) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_is_active != NULL, FALSE); - *out_is_active = session->is_active; - return TRUE; -} - -/** - * polkit_session_get_ck_is_local: - * @session: The session object - * @out_is_local: whether ConsoleKit reports the session as local - * - * Set whether ConsoleKit regard the session as local. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_ck_is_local (PolKitSession *session, polkit_bool_t *out_is_local) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_is_local != NULL, FALSE); - *out_is_local = session->is_local; - return TRUE; -} - -/** - * polkit_session_get_ck_remote_host: - * @session: The session object - * @out_remote_host: hostname of the host/display that ConsoleKit - * reports the session to occur at. Shall not be freed by the caller. - * - * Get the remote host/display that ConsoleKit reports the session to - * occur at. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_ck_remote_host (PolKitSession *session, char **out_remote_host) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_remote_host != NULL, FALSE); - *out_remote_host = session->remote_host; - return TRUE; -} - -/** - * polkit_session_get_seat: - * @session: The session object - * @out_seat: Returns the seat the session belongs to. Shall not - * be unreffed by the caller. - * - * Get the seat that the session belongs to. - * - * Returns: TRUE iff the value is returned - **/ -polkit_bool_t -polkit_session_get_seat (PolKitSession *session, PolKitSeat **out_seat) -{ - kit_return_val_if_fail (session != NULL, FALSE); - kit_return_val_if_fail (out_seat != NULL, FALSE); - *out_seat = session->seat; - return TRUE; -} - -/** - * polkit_session_debug: - * @session: the object - * - * Print debug details - **/ -void -polkit_session_debug (PolKitSession *session) -{ - kit_return_if_fail (session != NULL); - polkit_debug ("PolKitSession: refcount=%d uid=%d objpath=%s is_active=%d is_local=%d remote_host=%s", - session->refcount, session->uid, - session->ck_objref, session->is_active, session->is_local, session->remote_host); - if (session->seat != NULL) - polkit_seat_debug (session->seat); -} - - -/** - * polkit_session_validate: - * @session: the object - * - * Validate the object - * - * Returns: #TRUE iff the object is valid. - **/ -polkit_bool_t -polkit_session_validate (PolKitSession *session) -{ - polkit_bool_t ret; - kit_return_val_if_fail (session != NULL, FALSE); - - ret = FALSE; - if (session->is_local) { - if (session->remote_host != NULL) - goto error; - } else { - if (session->remote_host == NULL) - goto error; - } - ret = TRUE; -error: - return ret; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - char *str; - PolKitSession *s; - PolKitSeat *seat; - PolKitSeat *seat2; - uid_t uid; - polkit_bool_t b; - - s = polkit_session_new (); - if (s == NULL) { - /* OOM */ - } else { - if (! polkit_session_set_ck_objref (s, "/somesession")) { - /* OOM */ - } else { - kit_assert (polkit_session_get_ck_objref (s, &str) && strcmp (str, "/somesession") == 0); - polkit_session_ref (s); - polkit_session_unref (s); - polkit_session_debug (s); - if (! polkit_session_set_ck_objref (s, "/somesession2")) { - /* OOM */ - } else { - kit_assert (polkit_session_get_ck_objref (s, &str) && strcmp (str, "/somesession2") == 0); - } - - if ((seat = polkit_seat_new ()) != NULL) { - if (polkit_seat_set_ck_objref (seat, "/someseat")) { - kit_assert (polkit_session_set_seat (s, seat)); - kit_assert (polkit_session_get_seat (s, &seat2) && seat == seat2); - } - polkit_seat_unref (seat); - if ((seat = polkit_seat_new ()) != NULL) { - if (polkit_seat_set_ck_objref (seat, "/someseat2")) { - kit_assert (polkit_session_set_seat (s, seat)); - kit_assert (polkit_session_get_seat (s, &seat2) && seat == seat2); - } - polkit_seat_unref (seat); - } - } - - kit_assert (polkit_session_set_uid (s, 0)); - kit_assert (polkit_session_get_uid (s, &uid) && uid == 0); - kit_assert (polkit_session_set_ck_is_active (s, TRUE)); - kit_assert (polkit_session_get_ck_is_active (s, &b) && b == TRUE); - kit_assert (polkit_session_set_ck_is_local (s, TRUE)); - kit_assert (polkit_session_get_ck_is_local (s, &b) && b == TRUE); - kit_assert (polkit_session_validate (s)); - - kit_assert (polkit_session_set_uid (s, 500)); - kit_assert (polkit_session_get_uid (s, &uid) && uid == 500); - kit_assert (polkit_session_set_ck_is_active (s, FALSE)); - kit_assert (polkit_session_get_ck_is_active (s, &b) && b == FALSE); - kit_assert (polkit_session_set_ck_is_local (s, FALSE)); - kit_assert (polkit_session_get_ck_is_local (s, &b) && b == FALSE); - - /* not valid because remote host is not set.. */ - kit_assert (!polkit_session_validate (s)); - - - if (polkit_session_set_ck_remote_host (s, "somehost.com")) { - kit_assert (polkit_session_get_ck_remote_host (s, &str) && strcmp (str, "somehost.com") == 0); - kit_assert (polkit_session_validate (s)); - - /* not valid because remote host is set and local==TRUE */ - kit_assert (polkit_session_set_ck_is_local (s, TRUE)); - kit_assert (!polkit_session_validate (s)); - kit_assert (polkit_session_set_ck_is_local (s, FALSE)); - - if (polkit_session_set_ck_remote_host (s, "somehost2.com")) { - kit_assert (polkit_session_get_ck_remote_host (s, &str) && strcmp (str, "somehost2.com") == 0); - kit_assert (polkit_session_validate (s)); - } - polkit_session_debug (s); - } - - } - polkit_session_unref (s); - } - - return TRUE; -} - -KitTest _test_session = { - "polkit_session", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-session.h b/src/polkit/polkit-session.h deleted file mode 100644 index 5a371cb..0000000 --- a/src/polkit/polkit-session.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-session.h : sessions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_SESSION_H -#define POLKIT_SESSION_H - -#include <polkit/polkit-types.h> -#include <polkit/polkit-seat.h> - -#include <sys/types.h> - -POLKIT_BEGIN_DECLS - -struct _PolKitSession; -typedef struct _PolKitSession PolKitSession; - -PolKitSession *polkit_session_new (void); -PolKitSession *polkit_session_ref (PolKitSession *session); -void polkit_session_unref (PolKitSession *session); -polkit_bool_t polkit_session_set_uid (PolKitSession *session, uid_t uid); -polkit_bool_t polkit_session_set_seat (PolKitSession *session, PolKitSeat *seat); -polkit_bool_t polkit_session_set_ck_objref (PolKitSession *session, const char *ck_objref); -polkit_bool_t polkit_session_set_ck_is_active (PolKitSession *session, polkit_bool_t is_active); -polkit_bool_t polkit_session_set_ck_is_local (PolKitSession *session, polkit_bool_t is_local); -polkit_bool_t polkit_session_set_ck_remote_host (PolKitSession *session, const char *remote_host); -polkit_bool_t polkit_session_get_uid (PolKitSession *session, uid_t *out_uid); -polkit_bool_t polkit_session_get_seat (PolKitSession *session, PolKitSeat **out_seat); -polkit_bool_t polkit_session_get_ck_objref (PolKitSession *session, char **out_ck_objref); -polkit_bool_t polkit_session_get_ck_is_active (PolKitSession *session, polkit_bool_t *out_is_active); -polkit_bool_t polkit_session_get_ck_is_local (PolKitSession *session, polkit_bool_t *out_is_local); -polkit_bool_t polkit_session_get_ck_remote_host (PolKitSession *session, char **out_remote_host); - -void polkit_session_debug (PolKitSession *session); -polkit_bool_t polkit_session_validate (PolKitSession *session); - -POLKIT_END_DECLS - -#endif /* POLKIT_SESSION_H */ diff --git a/src/polkit/polkit-set-default-helper.c b/src/polkit/polkit-set-default-helper.c deleted file mode 100644 index eb1fb9d..0000000 --- a/src/polkit/polkit-set-default-helper.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-set-default-helper.c : setgid polkituser helper for PolicyKit - * to set defaults - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#define _GNU_SOURCE - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/time.h> -#include <grp.h> -#include <pwd.h> -#include <syslog.h> -#include <errno.h> -#include <string.h> -#include <utime.h> -#include <fcntl.h> -#include <dirent.h> -#include <utime.h> - -#include <polkit/polkit.h> -#include <polkit/polkit-private.h> - -#ifdef HAVE_SOLARIS -#define LOG_AUTHPRIV (10<<3) -#endif - -static polkit_bool_t -set_default (const char *action_id, const char *any, const char *inactive, const char *active) -{ - char *path; - char *contents; - polkit_bool_t ret; - - path = NULL; - contents = NULL; - ret = FALSE; - - path = kit_strdup_printf (PACKAGE_LOCALSTATE_DIR "/lib/polkit-public-1/%s.defaults-override", action_id); - if (path == NULL) - goto out; - - contents = kit_strdup_printf ("%s:%s:%s", - any, inactive, active); - if (contents == NULL) - goto out; - - if (!kit_file_set_contents (path, 0644, contents, strlen (contents))) { - kit_warning ("Error writing override file '%s': %m\n", path); - goto out; - } - - ret = TRUE; - -out: - if (path == NULL) - kit_free (path); - if (contents == NULL) - kit_free (contents); - return ret; -} - -static polkit_bool_t -clear_default (const char *action_id) -{ - char *path; - polkit_bool_t ret; - - ret = FALSE; - - path = kit_strdup_printf (PACKAGE_LOCALSTATE_DIR "/lib/polkit-public-1/%s.defaults-override", action_id); - if (path == NULL) - goto out; - - if (unlink (path) != 0) { - kit_warning ("Error unlinking file %s: %m", path); - } - - ret = TRUE; - -out: - if (path == NULL) - kit_free (path); - return ret; - -} - -int -main (int argc, char *argv[]) -{ - int ret; - uid_t caller_uid; - uid_t euid; - struct passwd *pw; - - ret = 1; - /* clear the entire environment to avoid attacks using with libraries honoring environment variables */ - if (kit_clearenv () != 0) - goto out; - /* set a minimal environment */ - setenv ("PATH", "/usr/sbin:/usr/bin:/sbin:/bin", 1); - - openlog ("polkit-set-default-helper-1", LOG_CONS | LOG_PID, LOG_AUTHPRIV); - - /* check for correct invocation */ - if (! (argc == 3 || argc == 6)) { - syslog (LOG_NOTICE, "inappropriate use of helper, wrong number of arguments [uid=%d]", getuid ()); - fprintf (stderr, "polkit-set-default-helper: wrong number of arguments. This incident has been logged.\n"); - goto out; - } - - caller_uid = getuid (); - - /* check we're running with a non-tty stdin */ - if (isatty (STDIN_FILENO) != 0) { - syslog (LOG_NOTICE, "inappropriate use of helper, stdin is a tty [uid=%d]", getuid ()); - fprintf (stderr, "polkit-set-default-helper: inappropriate use of helper, stdin is a tty. This incident has been logged.\n"); - goto out; - } - - /* check that we are setuid polkituser */ - euid = geteuid (); - pw = getpwuid (euid); - if (pw == NULL) { - fprintf (stderr, "polkit-set-default-helper: cannot lookup passwd info for uid %d\n", euid); - goto out; - } - if (strcmp (pw->pw_name, POLKIT_USER) != 0) { - fprintf (stderr, "polkit-set-default-helper: needs to be setuid " POLKIT_USER "\n"); - goto out; - } - - /*----------------------------------------------------------------------------------------------------*/ - - /* uid 0 is allowed to set anything */ - if (caller_uid != 0) { - pid_t ppid; - - ppid = getppid (); - if (ppid == 1) - goto out; - - if (polkit_check_auth (ppid, "org.freedesktop.policykit.modify-defaults", NULL) == 0) { - goto out; - } - } - - PolKitResult any; - PolKitResult inactive; - PolKitResult active; - - if (!polkit_action_validate_id (argv[1])) { - goto out; - } - - /* sanity check */ - if (argc == 3) { - if (strcmp (argv[2], "clear") != 0) - goto out; - - if (!clear_default (argv[1])) - goto out; - } else if (argc == 6) { - if (strcmp (argv[2], "set") != 0) - goto out; - - if (!polkit_result_from_string_representation (argv[3], &any)) { - goto out; - } - if (!polkit_result_from_string_representation (argv[4], &inactive)) { - goto out; - } - if (!polkit_result_from_string_representation (argv[5], &active)) { - goto out; - } - - if (!set_default (argv[1], argv[3], argv[4], argv[5])) - goto out; - } else { - goto out; - } - - /* trigger a reload */ - if (utimes (PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload", NULL) != 0) { - kit_warning ("Error updating access+modification time on file '%s': %m\n", - PACKAGE_LOCALSTATE_DIR "/lib/misc/polkit-1.reload"); - } - - ret = 0; - -out: - return ret; -} - diff --git a/src/polkit/polkit-simple.c b/src/polkit/polkit-simple.c deleted file mode 100644 index abdcdfe..0000000 --- a/src/polkit/polkit-simple.c +++ /dev/null @@ -1,599 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-simple.c : Simple convenience interface - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -/** - * SECTION:polkit-simple - * @title: Simple convenience interface - * @short_description: Simple convenience interface - * - * Simple convenience interface - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdarg.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> -#include <limits.h> - -#include <polkit/polkit-private.h> -#include "polkit-simple.h" - -/** - * polkit_check_auth: - * @pid: process to check for; typically you want to pass the result of getpid() here - * @...: %NULL terminated list of action identifiers to check for - * - * A simple convenience function to check whether a given process is - * authorized for a number of actions. - * - * This is useful for programs that just wants to check whether they - * should carry out some action. Note that the user identity used for - * the purpose of checking authorizations is the Real one compared to - * the e.g. Effective one (e.g. getuid(), getgid() is used instead of - * e.g. geteuid(), getegid()). This is typically what one wants in a - * setuid root program if the setuid root program is designed to do - * work on behalf of the unprivileged user who invoked it (for - * example, the PulseAudio sound server is setuid root only so it can - * become a real time process; after that it drops all privileges). - * - * It varies whether one wants to pass getpid() or getppid() as the - * process id to this function. For example, in the PulseAudio case it - * is the right thing to pass getpid(). However, in a setup where the - * process is a privileged helper, one wants to pass the process id of - * the parent. Beware though, if the parent dies, getppid() will - * return 1 (the process id of <literal>/sbin/init</literal>) which is - * almost certainly guaranteed to be privileged as it is running as - * uid 0. - * - * Note that this function will open a connection to the system - * message bus and query ConsoleKit for details. In addition, it will - * load PolicyKit specific files and spawn privileged helpers if - * necessary. As such, there is a bit of IPC, context switching, - * syscall overhead and I/O involved in using this function. If you - * are planning on calling this function multiple times (e.g. from a - * daemon) on a frequent basis and/or need more detail you should use - * the #PolKitContext and #PolKitTracker classes instead as these are - * designed to aggresively cache information. - * - * The return value is a bit mask indicating whether the given process - * is authorized for the given actions. Bit 0 represents the first - * action; bit 1 represents the 2nd action and so forth. A bit is set - * to 1 if, and only if, the caller is authorized for the given - * action. If the given action is unknown zero will be returned as well. - * - * If the function succeeds, errno will be set to 0. If an error - * occurs 0 is returned and errno will be set: - * <itemizedlist> - * <listitem><literal>ENOMEM</literal>: Out of memory.</listitem> - * <listitem><literal>ENOENT</literal>: Failed to connect to either the system message bus or ConsoleKit.</listitem> - * </itemizedlist> - * - * Returns: See above - * - * Since: 0.7 - */ -polkit_uint64_t -polkit_check_auth (pid_t pid, ...) -{ - int n; - va_list args; - char *action_id; - polkit_uint64_t ret; - const char *action_ids[65]; - - ret = 0; - - n = 0; - va_start (args, pid); - while ((action_id = va_arg (args, char *)) != NULL) { - if (n == 64) { - errno = EOVERFLOW; - goto out; - } - action_ids[n++] = action_id; - } - va_end (args); - action_ids[n] = NULL; - - ret = polkit_check_authv (pid, action_ids); -out: - return ret; -} - -/** - * polkit_check_authv: - * @pid: See docs for polkit_check_auth() - * @action_ids: %NULL terminated array of action id's - * - * This function is similar to polkit_check_auth() but takes an %NULL - * terminated array instead of being a varadic function. - * - * Returns: See docs for polkit_check_auth() - * - * Since: 0.7 - */ -polkit_uint64_t -polkit_check_authv (pid_t pid, const char **action_ids) -{ - int n; - polkit_uint64_t ret; - DBusError error; - DBusConnection *bus; - PolKitCaller *caller; - PolKitContext *context; - PolKitError *pk_error; - PolKitResult pk_result; - - ret = 0; - errno = ENOENT; - context = NULL; - caller = NULL; - bus = NULL; - - dbus_error_init (&error); - -#ifdef POLKIT_BUILD_TESTS - char *pretend; - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH")) != NULL) { - /* see polkit_caller_new_from_pid() - basically, it's - * if POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH is set - * then the bus won't be used at all - */ - goto no_bus; - } -#endif - bus = dbus_bus_get (DBUS_BUS_SYSTEM, &error); - if (bus == NULL) { - kit_warning ("cannot connect to system bus: %s: %s", error.name, error.message); - dbus_error_free (&error); - goto out; - } -#ifdef POLKIT_BUILD_TESTS -no_bus: -#endif - - caller = polkit_caller_new_from_pid (bus, pid, &error); - if (caller == NULL) { - kit_warning ("cannot get caller from pid: %s: %s", error.name, error.message); - goto out; - } - - context = polkit_context_new (); - if (context == NULL) { - kit_warning ("cannot allocate PolKitContext"); - errno = ENOMEM; - goto out; - } - - pk_error = NULL; - if (!polkit_context_init (context, &pk_error)) { - kit_warning ("cannot initialize polkit context: %s: %s", - polkit_error_get_error_name (pk_error), - polkit_error_get_error_message (pk_error)); - polkit_error_free (pk_error); - goto out; - } - - for (n = 0; action_ids[n] != NULL; n++) { - PolKitAction *action; - - action = polkit_action_new (); - if (action == NULL) { - kit_warning ("cannot allocate PolKitAction"); - errno = ENOMEM; - goto out; - } - if (!polkit_action_set_action_id (action, action_ids[n])) { - polkit_action_unref (action); - kit_warning ("cannot set action_id"); - errno = ENOMEM; - goto out; - } - - pk_error = NULL; - pk_result = polkit_context_is_caller_authorized (context, action, caller, FALSE, &pk_error); - - if (polkit_error_is_set (pk_error)) { - polkit_error_free (pk_error); - pk_error = NULL; - } else { - if (pk_result == POLKIT_RESULT_YES) - ret |= (1<<n); - } - - polkit_action_unref (action); - } - -out: - if (bus != NULL) - dbus_connection_unref (bus); - if (caller != NULL) - polkit_caller_unref (caller); - if (context != NULL) - polkit_context_unref (context); - - return ret; -} - -extern char **environ; - -static polkit_bool_t -_auth_show_dialog_text (const char *action_id, pid_t pid, DBusError *error) -{ - unsigned int n; - polkit_bool_t ret; - int exit_status; - char *helper_argv[] = {PACKAGE_BIN_DIR "/polkit-auth", "--obtain", NULL, NULL}; - char **envp; - size_t envsize; - char buf[256]; - - ret = FALSE; - - if (isatty (STDOUT_FILENO) != 1 || isatty (STDIN_FILENO) != 1) { - dbus_set_error (error, - "org.freedesktop.PolicyKit.LocalError", - "stdout and/or stdin is not a tty"); - goto out; - } - - envsize = kit_strv_length (environ); - envp = kit_new0 (char *, envsize + 3); - if (envp == NULL) - goto out; - for (n = 0; n < envsize; n++) - envp[n] = environ[n]; - envp[envsize] = "POLKIT_AUTH_FORCE_TEXT=1"; - snprintf (buf, sizeof (buf), "POLKIT_AUTH_GRANT_TO_PID=%d", pid); - envp[envsize+1] = buf; - - helper_argv[2] = (char *) action_id; - - if (!kit_spawn_sync (NULL, /* const char *working_directory */ - KIT_SPAWN_CHILD_INHERITS_STDIN, /* flags */ - helper_argv, /* char **argv */ - envp, /* char **envp */ - NULL, /* char *stdin */ - NULL, /* char **stdout */ - NULL, /* char **stderr */ - &exit_status)) { /* int *exit_status */ - dbus_set_error (error, - "org.freedesktop.PolicyKit.LocalError", - "Error spawning polkit-auth: %m"); - goto out; - } - - if (!WIFEXITED (exit_status)) { - dbus_set_error (error, - "org.freedesktop.PolicyKit.LocalError", - "polkit-auth crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - goto out; - } - - ret = TRUE; - -out: - return ret; -} - -/** - * polkit_auth_obtain: - * @action_id: The action_id for the #PolKitAction to make the user - * authenticate for - * @xid: X11 window ID for the window that the dialog will be - * transient for. If there is no window, pass 0. - * @pid: Process ID of process to grant authorization to. Normally one wants to pass result of getpid(). - * @error: return location for error; cannot be %NULL - * - * Convenience function to prompt the user to authenticate to gain an - * authorization for the given action. First, an attempt to reach an - * Authentication Agent on the session message bus is made. If that - * doesn't work and stdout/stdin are both tty's, polkit-auth(1) is - * invoked. - * - * This is a blocking call. If you're using GTK+ see - * polkit_gnome_auth_obtain() for a non-blocking version. - * - * Returns: %TRUE if, and only if, the user successfully - * authenticated. %FALSE if the user failed to authenticate or if - * error is set - * - * Since: 0.7 - */ -polkit_bool_t -polkit_auth_obtain (const char *action_id, polkit_uint32_t xid, pid_t pid, DBusError *error) -{ - polkit_bool_t ret; - DBusConnection *bus; - DBusMessage *message; - DBusMessage *reply; - - kit_return_val_if_fail (action_id != NULL, FALSE); - kit_return_val_if_fail (error != NULL, FALSE); - kit_return_val_if_fail (!dbus_error_is_set (error), FALSE); - - bus = NULL; - message = NULL; - reply = NULL; - ret = FALSE; - - bus = dbus_bus_get (DBUS_BUS_SESSION, error); - if (bus == NULL) { - dbus_error_init (error); - ret = _auth_show_dialog_text (action_id, pid, error); - goto out; - } - - message = dbus_message_new_method_call ("org.freedesktop.PolicyKit.AuthenticationAgent", /* service */ - "/", /* object path */ - "org.freedesktop.PolicyKit.AuthenticationAgent", /* interface */ - "ObtainAuthorization"); - dbus_message_append_args (message, - DBUS_TYPE_STRING, &action_id, - DBUS_TYPE_UINT32, &xid, - DBUS_TYPE_UINT32, &pid, - DBUS_TYPE_INVALID); - reply = dbus_connection_send_with_reply_and_block (bus, message, INT_MAX, error); - if (reply == NULL || dbus_error_is_set (error)) { - ret = _auth_show_dialog_text (action_id, pid, error); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_BOOLEAN, &ret, - DBUS_TYPE_INVALID)) { - dbus_error_init (error); - ret = _auth_show_dialog_text (action_id, pid, error); - goto out; - } - -out: - if (bus != NULL) - dbus_connection_unref (bus); - if (message != NULL) - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - - return ret; -} - - -/** - * polkit_dbus_error_generate: - * @action: the action that the caller needs an authorization for - * @result: the result from e.g. polkit_context_is_caller_authorized() - * @error: the #DBusError to set - * - * Convenience function to generate a #DBusError that encapsulates - * information that the caller is not authorized. This includes - * information such as @action that describes what action the caller - * lacks an authorization for, as well as @result that describes if - * the caller can obtain an authorization through authentication. - * - * Typically a privileged mechanism uses this function to generate - * errors. At the other end of the wire, the caller can use - * polkit_dbus_error_parse() to extract @action and @result. - * - * The form of the #DBusError is as follows. The name is - * set to - * <literal>org.freedesktop.PolicyKit.Error.NotAuthorized</literal> - * and the message consists of two strings separated by a single - * space: the string representation of the action - * (cf. polkit_action_to_string_representation()) and the string - * representation of the result - * (cf. polkit_result_to_string_representation()). - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: TRUE if @error was set. FALSE on error or OOM. - * - * Since: 0.8 - */ -polkit_bool_t -polkit_dbus_error_generate (PolKitAction *action, PolKitResult result, DBusError *error) -{ - polkit_bool_t ret; - const char *action_str; - const char *result_str; - - ret = FALSE; - - kit_return_val_if_fail (error != NULL && !dbus_error_is_set (error), FALSE); - kit_return_val_if_fail (action != NULL && polkit_action_validate (action), FALSE); - - action_str = polkit_action_to_string_representation (action); - if (action_str == NULL) - goto out; - - result_str = polkit_result_to_string_representation (result); - if (result_str == NULL) - goto out; - - dbus_set_error (error, - "org.freedesktop.PolicyKit.Error.NotAuthorized", - "%s %s", - action_str, result_str); - - /* on OOM, error->name and error->message are set to preallocated strings */ - if (strcmp (error->name, "org.freedesktop.PolicyKit.Error.NotAuthorized") != 0) - goto out; - - ret = TRUE; - -out: - return ret; -} - -/** - * polkit_dbus_error_parse: - * @error: error to parse; must be set - * @action: return location for #PolKitAction object - * @result: return location for #PolKitResult variable - * - * Parse an error received over D-Bus, typically generated by - * polkit_dbus_error_generate(), into what action an authorization is - * missing for and whether that authorization can be obtained. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: TRUE only if @error was successfully parsed and @action - * and @result is set (and caller must free @action using - * polkit_action_unref()). - * - * Since: 0.8 - */ -polkit_bool_t -polkit_dbus_error_parse (DBusError *error, PolKitAction **action, PolKitResult *result) -{ - char **tokens; - size_t num_tokens; - polkit_bool_t ret; - - kit_return_val_if_fail (error != NULL && dbus_error_is_set (error), FALSE); - kit_return_val_if_fail (action != NULL, FALSE); - kit_return_val_if_fail (result != NULL, FALSE); - - ret = FALSE; - tokens = NULL; - *action = NULL; - - if (!dbus_error_has_name (error, "org.freedesktop.PolicyKit.Error.NotAuthorized")) - goto out; - - tokens = kit_strsplit (error->message, ' ', &num_tokens); - if (tokens == NULL || num_tokens != 2) - goto out; - - *action = polkit_action_new_from_string_representation (tokens[0]); - if (*action == NULL) - goto out; - - if (!polkit_result_from_string_representation (tokens[1], result)) { - polkit_action_unref (*action); - *action = NULL; - goto out; - } - - ret = TRUE; - -out: - if (!ret) - *result = POLKIT_RESULT_UNKNOWN; - - - if (tokens != NULL) - kit_strfreev (tokens); - - return ret; -} - -/** - * polkit_dbus_error_parse_from_strings: - * @error_name: name of D-Bus error - * @error_message: message of D-Bus error - * @action: return location for #PolKitAction object - * @result: return location for #PolKitResult variable - * - * Like polkit_dbus_error_parse(), only it takes the name and message - * instead of a #DBusError. This is useful when usings D-Bus bindings - * (such as dbus-glib) that don't expose the #DBusError object - * directly. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: See polkit_dbus_error_parse(). - * - * Since: 0.8 - */ -polkit_bool_t -polkit_dbus_error_parse_from_strings (const char *error_name, - const char *error_message, - PolKitAction **action, - PolKitResult *result) -{ - DBusError error; - - dbus_error_init (&error); - dbus_set_error_const (&error, error_name, error_message); - - return polkit_dbus_error_parse (&error, action, result); -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - PolKitAction *a; - PolKitResult r; - - a = polkit_action_new (); - r = POLKIT_RESULT_ONLY_VIA_SELF_AUTH; - if (a != NULL) { - if (polkit_action_set_action_id (a, "org.example.foo")) { - DBusError error; - - dbus_error_init (&error); - if (polkit_dbus_error_generate (a, r, &error)) { - PolKitAction *a2; - PolKitResult r2; - - if (polkit_dbus_error_parse_from_strings (error.name, error.message, &a2, &r2)) { - kit_assert (polkit_action_equal (a, a2)); - kit_assert (r == r2); - polkit_action_unref (a2); - } - } - } - polkit_action_unref (a); - } - - return TRUE; -} - -KitTest _test_simple = { - "polkit_simple", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-simple.h b/src/polkit/polkit-simple.h deleted file mode 100644 index 1cf9753..0000000 --- a/src/polkit/polkit-simple.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-simple.h : Simple convenience interface - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_SIMPLE_H -#define POLKIT_SIMPLE_H - -#include <polkit/polkit.h> - -POLKIT_BEGIN_DECLS - -polkit_uint64_t polkit_check_auth (pid_t pid, ...); -polkit_uint64_t polkit_check_authv (pid_t pid, const char **action_ids); - -polkit_bool_t polkit_auth_obtain (const char *action_id, polkit_uint32_t xid, pid_t pid, DBusError *error); - -polkit_bool_t polkit_dbus_error_generate (PolKitAction *action, PolKitResult result, DBusError *error); -polkit_bool_t polkit_dbus_error_parse (DBusError *error, PolKitAction **action, PolKitResult *result); -polkit_bool_t polkit_dbus_error_parse_from_strings (const char *error_name, const char *error_message, PolKitAction **action, PolKitResult *result); - -POLKIT_END_DECLS - -#endif /* POLKIT_SIMPLE_H */ diff --git a/src/polkit/polkit-sysdeps.c b/src/polkit/polkit-sysdeps.c deleted file mode 100644 index ad8b7a0..0000000 --- a/src/polkit/polkit-sysdeps.c +++ /dev/null @@ -1,406 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-sysdeps.c : Various platform specific utility functions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> - -#ifdef HAVE_SOLARIS -#include <fcntl.h> -#include <sys/time.h> -#if _FILE_OFFSET_BITS==64 -#undef _FILE_OFFSET_BITS -#include <procfs.h> -#define _FILE_OFFSET_BITS 64 -#else -#include <procfs.h> -#endif -#elif defined(HAVE_INOTIFY) -#include <sys/inotify.h> -#endif -#include <syslog.h> - -#include "polkit-sysdeps.h" -#include "polkit-private.h" -#include "polkit-test.h" - -/** - * SECTION:polkit-sysdeps - * @title: System Dependencies - * @short_description: Various platform specific utility functions - * - * Various platform specific utility functions. - * - * Since: 0.7 - **/ - - -/** - * polkit_sysdeps_get_start_time_for_pid: - * @pid: process id - * - * Get when a process started. - * - * Returns: start time for the process or 0 if an error occured and errno will be set - * - * Since: 0.7 - */ -polkit_uint64_t -polkit_sysdeps_get_start_time_for_pid (pid_t pid) -{ - char *filename; - char *contents; - size_t length; - polkit_uint64_t start_time; -#ifdef HAVE_SOLARIS - struct psinfo info; -#else - char **tokens; - size_t num_tokens; - char *p; - char *endp; -#endif - - start_time = 0; - contents = NULL; - -#ifdef HAVE_SOLARIS - if (polkit_sysdeps_pid_psinfo ( pid, &info)) { - goto out; - } - start_time = (unsigned long long) (info.pr_start.tv_sec); -#else -#ifdef __FreeBSD__ - filename = kit_strdup_printf ("/proc/%d/status", pid); -#else - filename = kit_strdup_printf ("/proc/%d/stat", pid); -#endif - if (filename == NULL) { - errno = ENOMEM; - goto out; - } - - if (!kit_file_get_contents (filename, &contents, &length)) { - //fprintf (stderr, "Cannot get contents of '%s': %s\n", filename, error->message); - goto out; - } - -#ifdef __FreeBSD__ - tokens = kit_strsplit (contents, ' ', &num_tokens); - if (tokens == NULL) - goto out; - if (num_tokens < 8) { - kit_strfreev (tokens); - goto out; - } - - p = kit_strdup (tokens[7]); - kit_strfreev (tokens); - - tokens = kit_strsplit (p, ',', &num_tokens); - kit_free (p); - if (tokens == NULL) - goto out; - if (num_tokens >= 1) { - start_time = strtoll (tokens[0], &endp, 10); - if (endp == tokens[0]) { - kit_strfreev (tokens); - goto out; - } - } else { - kit_strfreev (tokens); - goto out; - } - - kit_strfreev (tokens); -#else - - /* start time is the 19th token after the '(process name)' entry */ - - p = strchr (contents, ')'); - if (p == NULL) { - goto out; - } - p += 2; /* skip ') ' */ - if (p - contents >= (int) length) { - goto out; - } - - tokens = kit_strsplit (p, ' ', &num_tokens); - if (tokens == NULL) - goto out; - - if (num_tokens < 20) { - goto out; - } - - start_time = strtoll (tokens[19], &endp, 10); - if (endp == tokens[19]) { - goto out; - } - - kit_strfreev (tokens); -#endif -#endif - -out: -#ifndef HAVE_SOLARIS - kit_free (filename); - kit_free (contents); -#endif - return start_time; -} - -/** - * polkit_sysdeps_get_exe_for_pid: - * @pid: process id - * @out_buf: buffer to store the string representation in - * @buf_size: size of buffer - * - * Get the name of the binary a given process was started from. - * - * Note that this is not necessary reliable information and as such - * shouldn't be relied on 100% to make a security decision. In fact, - * this information is only trustworthy in situations where the given - * binary is securely locked down meaning that 1) it can't be - * <literal>ptrace(2)</literal>'d; 2) libc secure mode kicks in (e.g - * <literal>LD_PRELOAD</literal> won't work); 3) there are no other - * attack vectors (e.g. GTK_MODULES, X11, CORBA, D-Bus) to patch - * running code into the process. - * - * In other words: the risk of relying on constraining an - * authorization to the output of this function is high. Suppose that - * the program <literal>/usr/bin/gullible</literal> obtains an - * authorization via authentication for the action - * <literal>org.example.foo</literal>. We add a constraint to say that - * the gained authorization only applies to processes for whom - * <literal>/proc/pid/exe</literal> points to - * <literal>/usr/bin/gullible</literal>. Now enter - * <literal>/usr/bin/evil</literal>. It knows that the program - * <literal>/usr/bin/gullible</literal> is not "securely locked down" - * (per the definition in the above paragraph). So - * <literal>/usr/bin/evil</literal> simply sets - * <literal>LD_PRELOAD</literal> and execs - * <literal>/usr/bin/gullible</literal> and it can now run code in a - * process where <literal>/proc/pid/exe</literal> points to - * <literal>/usr/bin/gullible</literal>. Thus, the recently gained - * authorization for <literal>org.example.foo</literal> applies. Also, - * <literal>/usr/bin/evil</literal> could use a host of other attack - * vectors to run it's own code under the disguise of pretending to be - * <literal>/usr/bin/gullible</literal>. - * - * Specifically for interpreted languages like Python and Mono it is - * the case that <literal>/proc/pid/exe</literal> always points to - * <literal>/usr/bin/python</literal> - * resp. <literal>/usr/bin/mono</literal>. Thus, it's not very useful - * to rely on that the result for this function if you want to - * constrain an authorization to - * e.g. <literal>/usr/bin/tomboy</literal> or - * <literal>/usr/bin/banshee</literal>. - * - * If the information could not be obtained, such as if the given - * process is owned by another user than the caller, -1 is returned - * and out_buf will be set to "(unknown)". See also the function - * polkit_sysdeps_get_exe_for_pid_with_helper(). - * - * Returns: Number of characters written (not including trailing - * '\0'). If the output was truncated due to the buffer being too - * small, buf_size will be returned. Thus, a return value of buf_size - * or more indicates that the output was truncated (see snprintf(3)) - * or an error occured. If the name cannot be found, -1 will be - * returned. - * - * Since: 0.7 - */ -int -polkit_sysdeps_get_exe_for_pid (pid_t pid, char *out_buf, size_t buf_size) -{ - int ret; - char proc_name[32]; - - /* TODO: to avoid work we should maintain a cache. The key - * into the cache should be (pid, pid_start_time) and the - * values should be the exe-paths - */ - - ret = 0; - -#ifdef HAVE_SOLARIS - struct psinfo info; - - if (polkit_sysdeps_pid_psinfo (pid, &info)) { - goto out; - } - ret = strlen (info.pr_psargs); - strncpy (out_buf, info.pr_psargs, ret); -#else -#ifdef __FreeBSD__ - snprintf (proc_name, sizeof (proc_name), "/proc/%d/file", pid); -#else - snprintf (proc_name, sizeof (proc_name), "/proc/%d/exe", pid); -#endif - ret = readlink (proc_name, out_buf, buf_size - 1); - if (ret == -1) { - strncpy (out_buf, "(unknown)", buf_size); - goto out; - } -#endif - kit_assert (ret >= 0 && ret < (int) buf_size - 1); - out_buf[ret] = '\0'; - -out: - return ret; -} - -/** - * polkit_sysdeps_get_exe_for_pid_with_helper: - * @pid: process id - * @out_buf: buffer to store the string representation in - * @buf_size: size of buffer - * - * Like polkit_sysdeps_get_exe_for_pid() but if the given process is - * owned by another user, a setuid root helper is used to obtain the - * information. This helper only works if 1) the caller is authorized - * for the org.freedesktop.policykit.read authorization; or 2) the - * calling user is polkituser; or 3) the calling user is setegid - * polkituser. - * - * So -1 might still be returned (the process might also have exited). - * - * Returns: See polkit_sysdeps_get_exe_for_pid(). - * - * Since: 0.8 - */ -int -polkit_sysdeps_get_exe_for_pid_with_helper (pid_t pid, char *out_buf, size_t buf_size) -{ - int ret; - - /* TODO: to avoid work we should maintain a cache. The key - * into the cache should be (pid, pid_start_time) and the - * values should be the exe-paths - */ - - ret = polkit_sysdeps_get_exe_for_pid (pid, out_buf, buf_size); - if (ret == -1) { - char buf[32]; - char *helper_argv[3] = {PACKAGE_LIBEXEC_DIR "/polkit-resolve-exe-helper-1", buf, NULL}; - char *standard_output; - int exit_status; - - /* Uh uh.. This means that we don't have permission to read /proc/$pid/exe for - * the given process id... this can happen if the mechanism in question runs - * as an unprivileged user instead of uid 0 (e.g. user 'haldaemon'). - * - * This blows. - * - * To work around this we use a setuid root helper that - * - * 1. checks whether the caller (us) has the 1) org.freedesktop.policykit.read - * authorization; or 2) is $POLKIT_USER; or 3) is group $POLKIT_USER - * - * 2. If so, resolves /prod/$pid/exe and writes it to stdout - */ - - snprintf (buf, sizeof (buf), "%d", pid); - - if (!kit_spawn_sync (NULL, /* const char *working_directory */ - 0, /* flags */ - helper_argv, /* char **argv */ - NULL, /* char **envp */ - NULL, /* char *stdin */ - &standard_output, /* char **stdout */ - NULL, /* char **stderr */ - &exit_status)) { /* int *exit_status */ - goto out; - } - - if (!WIFEXITED (exit_status)) { - kit_warning ("resolve exe helper crashed!"); - goto out; - } else if (WEXITSTATUS(exit_status) != 0) { - goto out; - } - - strncpy (out_buf, standard_output, buf_size); - out_buf[buf_size - 1] = '\0'; - ret = strlen (standard_output); - } - -out: - return ret; -} - - -#ifdef HAVE_SOLARIS -int -polkit_sysdeps_pid_psinfo (pid_t pid, struct psinfo *ps) -{ - char pname[32]; - int procfd; - - (void) snprintf(pname, sizeof(pname), "/proc/%d/psinfo", pid); - if ((procfd = open(pname, O_RDONLY)) == -1) { - return -1; - } - if (read(procfd, ps, sizeof(struct psinfo)) < 0) { - (void) close(procfd); - return -1; - } - (void) close(procfd); - return 0; -} -#endif - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_sysdeps = { - "polkit_sysdeps", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-sysdeps.h b/src/polkit/polkit-sysdeps.h deleted file mode 100644 index 6203bc2..0000000 --- a/src/polkit/polkit-sysdeps.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-sysdeps.h : Various platform specific utility functions - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_SYSDEPS_H -#define POLKIT_SYSDEPS_H - -#include <sys/types.h> -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -polkit_uint64_t polkit_sysdeps_get_start_time_for_pid (pid_t pid); - -int polkit_sysdeps_get_exe_for_pid (pid_t pid, char *out_buf, size_t buf_size); - -int polkit_sysdeps_get_exe_for_pid_with_helper (pid_t pid, char *out_buf, size_t buf_size); - - -POLKIT_END_DECLS - -#endif diff --git a/src/polkit/polkit-test.c b/src/polkit/polkit-test.c deleted file mode 100644 index 927339c..0000000 --- a/src/polkit/polkit-test.c +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-test.c : PolicyKit test - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#include <stdio.h> -#include <stdlib.h> -#include <syslog.h> -#include <polkit/polkit-test.h> -#include <polkit/polkit-private.h> -#include <polkit/polkit-private.h> - -#define MAX_TESTS 64 - -/** - * SECTION:polkit-test - * @short_description: Testing code for libpolkit - * - * Testing code for libpolkit. - */ - -static KitTest *tests[] = { - &_test_action, - &_test_error, - &_test_result, - &_test_seat, - &_test_session, - &_test_caller, - &_test_policy_default, - &_test_policy_file_entry, - &_test_policy_file, - &_test_policy_cache, - &_test_authorization_constraint, - &_test_authorization, - &_test_authorization_db, - &_test_sysdeps, - &_test_utils, - &_test_context, -}; - -int -main (int argc, char *argv[]) -{ - /* Some of the code will log to syslog because .policy files - * etc. may be malformed. Since this will open a socket to the - * system logger preempt this so the fd-leak checking don't - * freak out. - */ - syslog (LOG_INFO, "libpolkit: initiating test; bogus alerts may be written to syslog"); - - if (kit_test_run (tests, sizeof (tests) / sizeof (KitTest*))) - return 0; - else - return 1; -} diff --git a/src/polkit/polkit-test.h b/src/polkit/polkit-test.h deleted file mode 100644 index 056b3dc..0000000 --- a/src/polkit/polkit-test.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-test.h : PolicyKit test - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) -#error "polkit-test.h is a private file" -#endif - -#ifndef POLKIT_TEST_H -#define POLKIT_TEST_H - -#include <kit/kit.h> -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -extern KitTest _test_action; -extern KitTest _test_error; -extern KitTest _test_result; -extern KitTest _test_seat; -extern KitTest _test_session; -extern KitTest _test_caller; -extern KitTest _test_policy_default; -extern KitTest _test_policy_file_entry; -extern KitTest _test_policy_file; -extern KitTest _test_policy_cache; -extern KitTest _test_authorization_constraint; -extern KitTest _test_authorization; -extern KitTest _test_authorization_db; -extern KitTest _test_sysdeps; -extern KitTest _test_utils; -extern KitTest _test_context; - -POLKIT_END_DECLS - -#endif /* POLKIT_TEST_H */ - - diff --git a/src/polkit/polkit-tracker.c b/src/polkit/polkit-tracker.c deleted file mode 100644 index 0dad442..0000000 --- a/src/polkit/polkit-tracker.c +++ /dev/null @@ -1,1556 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-tracker.c : track callers - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <pwd.h> -#include <grp.h> -#include <unistd.h> -#include <errno.h> -#include <ctype.h> - -#include "polkit-debug.h" -#include "polkit-tracker.h" - -/** - * SECTION:polkit-tracker - * @title: Track callers - * @short_description: Obtaining seat, session and caller information - * via D-Bus and ConsoleKit. - * - * Helper class for obtaining seat, session and caller information - * via D-Bus and ConsoleKit. This library is only useful when writing - * a mechanism. - * - * If the mechanism itself is a daemon exposing a remote services via - * the system message bus it's often a better idea, to reduce - * roundtrips, to use the high-level #PolKitTracker class rather than - * the low-level functions polkit_caller_new_from_dbus_name() and - * polkit_caller_new_from_pid(). - * - **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdarg.h> -#include <stdlib.h> -#include <sys/time.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <unistd.h> -#include <errno.h> -#include <time.h> -#include <string.h> - -#ifdef HAVE_SELINUX -#include <selinux/selinux.h> -#endif - -#include <polkit/polkit-debug.h> -#include <polkit/polkit-test.h> -#include <polkit/polkit-private.h> -#include "polkit-tracker.h" - -/** - * polkit_session_new_from_objpath: - * @con: D-Bus system bus connection - * @objpath: object path of ConsoleKit session object - * @uid: the user owning the session or -1 if unknown - * @error: D-Bus error - * - * This function will construct a #PolKitSession object by querying - * the ConsoleKit daemon for information. Note that this will do a lot - * of blocking IO so it is best avoided if your process already - * tracks/caches all the information. If you pass in @uid as a - * non-negative number, a round trip can be saved. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the new object or #NULL if an error occured (in which case - * @error will be set) - **/ -PolKitSession * -polkit_session_new_from_objpath (DBusConnection *con, const char *objpath, uid_t uid, DBusError *error) -{ - PolKitSeat *seat; - PolKitSession *session; - DBusMessage *message; - DBusMessage *reply; - char *str; - dbus_bool_t is_active; - dbus_bool_t is_local; - char *remote_host; - char *seat_path; - - kit_return_val_if_fail (con != NULL, NULL); - kit_return_val_if_fail (objpath != NULL, NULL); - kit_return_val_if_fail (error != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - session = NULL; - remote_host = NULL; - seat_path = NULL; - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - objpath, - "org.freedesktop.ConsoleKit.Session", - "IsActive"); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing Session.IsActive on ConsoleKit: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_BOOLEAN, &is_active, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid IsActive reply from CK"); - goto out; - } - dbus_message_unref (message); - dbus_message_unref (reply); - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - objpath, - "org.freedesktop.ConsoleKit.Session", - "IsLocal"); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing Session.IsLocal on ConsoleKit: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_BOOLEAN, &is_local, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid IsLocal reply from CK"); - goto out; - } - dbus_message_unref (message); - dbus_message_unref (reply); - - if (!is_local) { - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - objpath, - "org.freedesktop.ConsoleKit.Session", - "GetRemoteHostName"); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing Session.GetRemoteHostName on ConsoleKit: %s: %s", - error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_STRING, &str, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid GetRemoteHostName reply from CK"); - goto out; - } - remote_host = kit_strdup (str); - dbus_message_unref (message); - dbus_message_unref (reply); - } - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - objpath, - "org.freedesktop.ConsoleKit.Session", - "GetSeatId"); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing Session.GetSeatId on ConsoleKit: %s: %s", - error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_OBJECT_PATH, &str, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid GetSeatId reply from CK"); - goto out; - } - seat_path = kit_strdup (str); - dbus_message_unref (message); - dbus_message_unref (reply); - - if ((int) uid == -1) { - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - objpath, - "org.freedesktop.ConsoleKit.Session", - "GetUnixUser"); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing Session.GetUnixUser on ConsoleKit: %s: %s",error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_INT32, &uid, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid GetUnixUser reply from CK"); - goto out; - } - dbus_message_unref (message); - dbus_message_unref (reply); - } - - session = polkit_session_new (); - if (session == NULL) { - goto out; - } - if (!polkit_session_set_uid (session, uid)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!polkit_session_set_ck_objref (session, objpath)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!polkit_session_set_ck_is_active (session, is_active)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!polkit_session_set_ck_is_local (session, is_local)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!is_local) { - if (!polkit_session_set_ck_remote_host (session, remote_host)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - - } - - seat = polkit_seat_new (); - if (seat == NULL) { - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!polkit_seat_set_ck_objref (seat, seat_path)) { - polkit_seat_unref (seat); - seat = NULL; - polkit_session_unref (session); - session = NULL; - goto out; - } - if (!polkit_seat_validate (seat)) { - polkit_seat_unref (seat); - seat = NULL; - polkit_session_unref (session); - session = NULL; - goto out; - } - - if (!polkit_session_set_seat (session, seat)) { - polkit_seat_unref (seat); - seat = NULL; - polkit_session_unref (session); - session = NULL; - goto out; - } - polkit_seat_unref (seat); /* session object now owns this object */ - seat = NULL; - - if (!polkit_session_validate (session)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - -out: - kit_free (remote_host); - kit_free (seat_path); - return session; -} - -/** - * polkit_session_new_from_cookie: - * @con: D-Bus system bus connection - * @cookie: a ConsoleKit XDG_SESSION_COOKIE - * @error: D-Bus error - * - * This function will construct a #PolKitSession object by querying - * the ConsoleKit daemon for information. Note that this will do a lot - * of blocking IO so it is best avoided if your process already - * tracks/caches all the information. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the new object or #NULL if an error occured (in which case - * @error will be set) - **/ -PolKitSession * -polkit_session_new_from_cookie (DBusConnection *con, const char *cookie, DBusError *error) -{ - PolKitSession *session; - DBusMessage *message; - DBusMessage *reply; - char *str; - char *objpath; - - kit_return_val_if_fail (con != NULL, NULL); - kit_return_val_if_fail (cookie != NULL, NULL); - kit_return_val_if_fail (error != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - objpath = NULL; - session = NULL; - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - "/org/freedesktop/ConsoleKit/Manager", - "org.freedesktop.ConsoleKit.Manager", - "GetSessionForCookie"); - dbus_message_append_args (message, DBUS_TYPE_STRING, &cookie, DBUS_TYPE_INVALID); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - //kit_warning ("Error doing Manager.GetSessionForCookie on ConsoleKit: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - if (!dbus_message_get_args (reply, NULL, - DBUS_TYPE_OBJECT_PATH, &str, - DBUS_TYPE_INVALID)) { - kit_warning ("Invalid GetSessionForCookie reply from CK"); - goto out; - } - objpath = kit_strdup (str); - dbus_message_unref (message); - dbus_message_unref (reply); - - session = polkit_session_new_from_objpath (con, objpath, -1, error); - -out: - kit_free (objpath); - return session; -} - - -/** - * polkit_caller_new_from_dbus_name: - * @con: D-Bus system bus connection - * @dbus_name: unique system bus connection name - * @error: D-Bus error - * - * This function will construct a #PolKitCaller object by querying - * both the system bus daemon and the ConsoleKit daemon for - * information. Note that this will do a lot of blocking IO so it is - * best avoided if your process already tracks/caches all the - * information. You can use the #PolKitTracker class for this. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the new object or #NULL if an error occured (in which case - * @error will be set) - **/ -PolKitCaller * -polkit_caller_new_from_dbus_name (DBusConnection *con, const char *dbus_name, DBusError *error) -{ - PolKitCaller *caller; - pid_t pid; - uid_t uid; - char *selinux_context; - char *ck_session_objpath; - PolKitSession *session; - DBusMessage *message; - DBusMessage *reply; - DBusMessageIter iter; - DBusMessageIter sub_iter; - char *str; - int num_elems; - - kit_return_val_if_fail (con != NULL, NULL); - kit_return_val_if_fail (dbus_name != NULL, NULL); - kit_return_val_if_fail (error != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - selinux_context = NULL; - ck_session_objpath = NULL; - - caller = NULL; - session = NULL; - - uid = dbus_bus_get_unix_user (con, dbus_name, error); - if (dbus_error_is_set (error)) { - kit_warning ("Could not get uid for connection: %s %s", error->name, error->message); - goto out; - } - - message = dbus_message_new_method_call ("org.freedesktop.DBus", - "/org/freedesktop/DBus/Bus", - "org.freedesktop.DBus", - "GetConnectionUnixProcessID"); - dbus_message_iter_init_append (message, &iter); - dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &dbus_name); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing GetConnectionUnixProcessID on Bus: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } - dbus_message_iter_init (reply, &iter); - dbus_message_iter_get_basic (&iter, &pid); - dbus_message_unref (message); - dbus_message_unref (reply); - - message = dbus_message_new_method_call ("org.freedesktop.DBus", - "/org/freedesktop/DBus/Bus", - "org.freedesktop.DBus", - "GetConnectionSELinuxSecurityContext"); - dbus_message_iter_init_append (message, &iter); - dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &dbus_name); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - /* SELinux might not be enabled */ - if (dbus_error_is_set (error) && - strcmp (error->name, "org.freedesktop.DBus.Error.SELinuxSecurityContextUnknown") == 0) { - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - dbus_error_init (error); - } else if (reply == NULL || dbus_error_is_set (error)) { - kit_warning ("Error doing GetConnectionSELinuxSecurityContext on Bus: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - goto out; - } else { - /* TODO: verify signature */ - dbus_message_iter_init (reply, &iter); - dbus_message_iter_recurse (&iter, &sub_iter); - dbus_message_iter_get_fixed_array (&sub_iter, (void *) &str, &num_elems); - if (str != NULL && num_elems > 0) - selinux_context = kit_strndup (str, num_elems); - dbus_message_unref (message); - dbus_message_unref (reply); - } - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - "/org/freedesktop/ConsoleKit/Manager", - "org.freedesktop.ConsoleKit.Manager", - "GetSessionForUnixProcess"); - dbus_message_iter_init_append (message, &iter); - dbus_message_iter_append_basic (&iter, DBUS_TYPE_UINT32, &pid); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - //kit_warning ("Error doing GetSessionForUnixProcess on ConsoleKit: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - /* OK, this is not a catastrophe; just means the caller is not a - * member of any session or that ConsoleKit is not available.. - */ - goto not_in_session; - } - dbus_message_iter_init (reply, &iter); - dbus_message_iter_get_basic (&iter, &str); - ck_session_objpath = kit_strdup (str); - dbus_message_unref (message); - dbus_message_unref (reply); - - session = polkit_session_new_from_objpath (con, ck_session_objpath, uid, error); - if (session == NULL) { - kit_warning ("Got a session objpath but couldn't construct session object!"); - goto out; - } - if (!polkit_session_validate (session)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - -not_in_session: - - caller = polkit_caller_new (); - if (caller == NULL) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - goto out; - } - - if (!polkit_caller_set_dbus_name (caller, dbus_name)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - if (!polkit_caller_set_uid (caller, uid)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - if (!polkit_caller_set_pid (caller, pid)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - if (selinux_context != NULL) { - if (!polkit_caller_set_selinux_context (caller, selinux_context)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - } - if (session != NULL) { - if (!polkit_caller_set_ck_session (caller, session)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - polkit_session_unref (session); /* caller object now own this object */ - session = NULL; - } - - if (!polkit_caller_validate (caller)) { - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - -out: - kit_free (selinux_context); - kit_free (ck_session_objpath); - return caller; -} - -/** - * polkit_caller_new_from_pid: - * @con: D-Bus system bus connection - * @pid: process id - * @error: D-Bus error - * - * This function will construct a #PolKitCaller object by querying - * both information in /proc (on Linux) and the ConsoleKit daemon for - * information about a given process. Note that this will do a lot of - * blocking IO so it is best avoided if your process already - * tracks/caches all the information. You can use the #PolKitTracker - * class for this. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the new object or #NULL if an error occured (in which case - * @error will be set) - **/ -PolKitCaller * -polkit_caller_new_from_pid (DBusConnection *con, pid_t pid, DBusError *error) -{ - PolKitCaller *caller; - uid_t uid; - char *selinux_context; - char *ck_session_objpath; - PolKitSession *session; - DBusMessage *message; - DBusMessage *reply; - DBusMessageIter iter; - char *str; - char *proc_path; - struct stat statbuf; -#ifdef HAVE_SELINUX - security_context_t secon; -#endif - -#ifndef POLKIT_BUILD_TESTS - /* for testing it's fine to pass con==NULL if POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH is set */ - kit_return_val_if_fail (con != NULL, NULL); -#endif - kit_return_val_if_fail (error != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - selinux_context = NULL; - ck_session_objpath = NULL; - uid = (uid_t) -1; - caller = NULL; - session = NULL; - proc_path = NULL; - -#ifdef POLKIT_BUILD_TESTS - char *pretend; - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_UID")) != NULL) { - uid = atoi (pretend); - } - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_PID")) != NULL) { - pid = atoi (pretend); - } - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_SELINUX_CONTEXT")) != NULL) { - selinux_context = kit_strdup (pretend); - } - if ((pretend = getenv ("POLKIT_TEST_PRETEND_TO_BE_CK_SESSION_OBJPATH")) != NULL) { - ck_session_objpath = kit_strdup (pretend); - } else { - kit_return_val_if_fail (con != NULL, NULL); - } -#endif - - if (uid == (uid_t) -1) { - proc_path = kit_strdup_printf ("/proc/%d", pid); - if (proc_path && stat (proc_path, &statbuf) != 0) { - kit_warning ("Cannot lookup information for pid %d: %s", pid, strerror (errno)); - goto out; - } - uid = statbuf.st_uid; - } - -#ifdef HAVE_SELINUX - /* only get the context if we are enabled */ - if (selinux_context == NULL) { - if (is_selinux_enabled () != 0) { - if (getpidcon (pid, &secon) != 0) { - kit_warning ("Cannot lookup SELinux context for pid %d: %s", pid, strerror (errno)); - goto out; - } - selinux_context = kit_strdup (secon); - freecon (secon); - } - } -#else - selinux_context = NULL; -#endif - - if (ck_session_objpath == NULL) { - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - "/org/freedesktop/ConsoleKit/Manager", - "org.freedesktop.ConsoleKit.Manager", - "GetSessionForUnixProcess"); - dbus_message_iter_init_append (message, &iter); - dbus_message_iter_append_basic (&iter, DBUS_TYPE_UINT32, &pid); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - //kit_warning ("Error doing GetSessionForUnixProcess on ConsoleKit: %s: %s", error->name, error->message); - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - /* OK, this is not a catastrophe; just means the caller is not a - * member of any session or that ConsoleKit is not available.. - */ - goto not_in_session; - } - dbus_message_iter_init (reply, &iter); - dbus_message_iter_get_basic (&iter, &str); - ck_session_objpath = kit_strdup (str); - dbus_message_unref (message); - dbus_message_unref (reply); - } else { - if (strlen (ck_session_objpath) == 0) - goto not_in_session; - } - - session = polkit_session_new_from_objpath (con, ck_session_objpath, uid, error); - if (session == NULL) { - kit_warning ("Got a session objpath but couldn't construct session object!"); - goto out; - } - if (!polkit_session_validate (session)) { - polkit_session_unref (session); - session = NULL; - goto out; - } - -not_in_session: - - caller = polkit_caller_new (); - if (caller == NULL) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - goto out; - } - - if (!polkit_caller_set_uid (caller, uid)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - - if (!polkit_caller_set_pid (caller, pid)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - if (selinux_context != NULL) { - if (!polkit_caller_set_selinux_context (caller, selinux_context)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - } - if (session != NULL) { - if (!polkit_caller_set_ck_session (caller, session)) { - if (session != NULL) { - polkit_session_unref (session); - session = NULL; - } - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - polkit_session_unref (session); /* caller object now own this object */ - session = NULL; - } - - if (!polkit_caller_validate (caller)) { - polkit_caller_unref (caller); - caller = NULL; - goto out; - } - -out: - kit_free (selinux_context); - kit_free (ck_session_objpath); - kit_free (proc_path); - return caller; -} - -static kit_bool_t -_free_elem_in_list (void *data, void *user_data, KitList *list) -{ - kit_free (data); - return FALSE; -} - -static KitList * -_get_list_of_sessions (DBusConnection *con, uid_t uid, DBusError *error) -{ - KitList *ret; - DBusMessage *message; - DBusMessage *reply; - DBusMessageIter iter; - DBusMessageIter iter_array; - const char *value; - - ret = NULL; - - message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit", - "/org/freedesktop/ConsoleKit/Manager", - "org.freedesktop.ConsoleKit.Manager", - "GetSessionsForUnixUser"); - dbus_message_append_args (message, DBUS_TYPE_UINT32, &uid, DBUS_TYPE_INVALID); - reply = dbus_connection_send_with_reply_and_block (con, message, -1, error); - if (reply == NULL || dbus_error_is_set (error)) { - goto out; - } - - dbus_message_iter_init (reply, &iter); - if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_ARRAY) { - kit_warning ("Wrong reply from ConsoleKit (not an array)"); - goto out; - } - - dbus_message_iter_recurse (&iter, &iter_array); - while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID) { - - if (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_OBJECT_PATH) { - kit_warning ("Wrong reply from ConsoleKit (element is not a string)"); - kit_list_foreach (ret, _free_elem_in_list, NULL); - kit_list_free (ret); - goto out; - } - - dbus_message_iter_get_basic (&iter_array, &value); - ret = kit_list_append (ret, kit_strdup (value)); - - dbus_message_iter_next (&iter_array); - } - -out: - if (message != NULL) - dbus_message_unref (message); - if (reply != NULL) - dbus_message_unref (reply); - return ret; -} - -static polkit_bool_t -_polkit_is_authorization_relevant_internal (DBusConnection *con, - PolKitAuthorization *auth, - KitList *sessions, - DBusError *error) -{ - pid_t pid; - polkit_uint64_t pid_start_time; - polkit_bool_t ret; - polkit_bool_t del_sessions; - KitList *i; - uid_t uid; - - kit_return_val_if_fail (con != NULL, FALSE); - kit_return_val_if_fail (auth != NULL, FALSE); - kit_return_val_if_fail (error != NULL, FALSE); - kit_return_val_if_fail (! dbus_error_is_set (error), FALSE); - - ret = FALSE; - - uid = polkit_authorization_get_uid (auth); - - switch (polkit_authorization_get_scope (auth)) { - case POLKIT_AUTHORIZATION_SCOPE_PROCESS_ONE_SHOT: - case POLKIT_AUTHORIZATION_SCOPE_PROCESS: - if (!polkit_authorization_scope_process_get_pid (auth, - &pid, - &pid_start_time)) { - /* this should never fail */ - kit_warning ("Cannot determine (pid,start_time) for authorization"); - goto out; - } - if (polkit_sysdeps_get_start_time_for_pid (pid) == pid_start_time) { - ret = TRUE; - goto out; - } - break; - - case POLKIT_AUTHORIZATION_SCOPE_SESSION: - del_sessions = FALSE; - if (sessions == NULL) { - sessions = _get_list_of_sessions (con, uid, error); - del_sessions = TRUE; - } - - if (sessions != NULL) { - for (i = sessions; i != NULL; i = i->next) { - char *session_id = i->data; - if (strcmp (session_id, polkit_authorization_scope_session_get_ck_objref (auth)) == 0) { - ret = TRUE; - break; - } - } - - if (del_sessions) { - kit_list_foreach (sessions, _free_elem_in_list, NULL); - kit_list_free (sessions); - } - } - break; - - case POLKIT_AUTHORIZATION_SCOPE_ALWAYS: - ret = TRUE; - break; - } - -out: - return ret; -} - -/** - * polkit_is_authorization_relevant: - * @con: D-Bus system bus connection - * @auth: authorization to check for - * @error: return location for error - * - * As explicit authorizations are scoped (process single shot, - * process, session or everything), they become irrelevant once the - * entity (process or session) ceases to exist. This function - * determines whether the authorization is still relevant; it's useful - * for reporting and graphical tools displaying authorizations. - * - * Note that this may do blocking IO to check for session - * authorizations so it is best avoided if your process already - * tracks/caches all the information. You can use the - * polkit_tracker_is_authorization_relevant() method on the - * #PolKitTracker class for this. - * - * Returns: #TRUE if the authorization still applies, #FALSE if an - * error occurred (then error will be set) or if the entity the - * authorization refers to has gone out of scope. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_is_authorization_relevant (DBusConnection *con, PolKitAuthorization *auth, DBusError *error) -{ - return _polkit_is_authorization_relevant_internal (con, auth, NULL, error); -} - -/** - * PolKitTracker: - * - * Instances of this class are used to cache information about - * callers; typically this is used in scenarios where the same caller - * is calling into a mechanism multiple times. - * - * Thus, an application can use this class to get the #PolKitCaller - * object; the class will listen to both NameOwnerChanged and - * ActivityChanged signals from the message bus and update / retire - * the #PolKitCaller objects. - * - * An example of how to use #PolKitTracker is provided here. First, build the following program - * - * <programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../../examples/tracker-example/tracker-example.c" parse="text"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting> - * - * with - * - * <programlisting>gcc -o tracker-example `pkg-config --cflags --libs dbus-glib-1 polkit-dbus` tracker-example.c</programlisting> - * - * Then put the following content - * - * <programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../../examples/tracker-example/dk.fubar.PolKitTestService.conf" parse="text"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting> - * - * in the file <literal>/etc/dbus-1/system.d/dk.fubar.PolKitTestService.conf</literal>. Finally, - * create a small Python client like this - * - * <programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../../examples/tracker-example/tracker-example-client.py" parse="text"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting> - * - * as <literal>tracker-example-client.py</literal>. Now, run <literal>tracker-example</literal> - * in one window and <literal>tracker-example-client</literal> in another. The output of - * the former should look like this - * - * - * <programlisting> - * 18:20:00.414: PolKitCaller: refcount=1 dbus_name=:1.473 uid=500 pid=8636 selinux_context=system_u:system_r:unconfined_t - * 18:20:00.414: PolKitSession: refcount=1 uid=0 objpath=/org/freedesktop/ConsoleKit/Session1 is_active=1 is_local=1 remote_host=(null) - * 18:20:00.414: PolKitSeat: refcount=1 objpath=/org/freedesktop/ConsoleKit/Seat1 - * - * 18:20:01.424: PolKitCaller: refcount=1 dbus_name=:1.473 uid=500 pid=8636 selinux_context=system_u:system_r:unconfined_t - * 18:20:01.424: PolKitSession: refcount=1 uid=0 objpath=/org/freedesktop/ConsoleKit/Session1 is_active=1 is_local=1 remote_host=(null) - * 18:20:01.424: PolKitSeat: refcount=1 objpath=/org/freedesktop/ConsoleKit/Seat1 - * - * 18:20:02.434: PolKitCaller: refcount=1 dbus_name=:1.473 uid=500 pid=8636 selinux_context=system_u:system_r:unconfined_t - * 18:20:02.434: PolKitSession: refcount=1 uid=0 objpath=/org/freedesktop/ConsoleKit/Session1 is_active=0 is_local=1 remote_host=(null) - * 18:20:02.434: PolKitSeat: refcount=1 objpath=/org/freedesktop/ConsoleKit/Seat1 - * - * 18:20:03.445: PolKitCaller: refcount=1 dbus_name=:1.473 uid=500 pid=8636 selinux_context=system_u:system_r:unconfined_t - * 18:20:03.445: PolKitSession: refcount=1 uid=0 objpath=/org/freedesktop/ConsoleKit/Session1 is_active=1 is_local=1 remote_host=(null) - * 18:20:03.445: PolKitSeat: refcount=1 objpath=/org/freedesktop/ConsoleKit/Seat1 - * </programlisting> - * - * The point of the test program is simply to gather caller - * information about clients (the small Python program, you may launch - * multiple instances of it) that repeatedly calls into the D-Bus - * service; if one runs <literal>strace(1)</literal> in front of the - * test program one will notice that there is only syscall / IPC - * overhead (except for printing to stdout) on the first call from the - * client. - * - * The careful reader will notice that, during the testing session, we - * did a quick VT switch away from the session (and back) which is - * reflected in the output. - * - * These functions are in <literal>libpolkit-dbus</literal>. - **/ -struct _PolKitTracker { - int refcount; - DBusConnection *con; - - KitHash *dbus_name_to_caller; - - KitHash *pid_start_time_to_caller; -}; - -typedef struct { - pid_t pid; - polkit_uint64_t start_time; -} _PidStartTimePair; - -static _PidStartTimePair * -_pid_start_time_new (pid_t pid, polkit_uint64_t start_time) -{ - _PidStartTimePair *obj; - obj = kit_new (_PidStartTimePair, 1); - obj->pid = pid; - obj->start_time = start_time; - return obj; -} - -static uint32_t -_pid_start_time_hash (const void *a) -{ - uint32_t val; - _PidStartTimePair *pst = (_PidStartTimePair *) a; - - val = pst->pid + ((int) pst->start_time); - - return val; -} - -static kit_bool_t -_pid_start_time_equal (const void *a, const void *b) -{ - _PidStartTimePair *_a = (_PidStartTimePair *) a; - _PidStartTimePair *_b = (_PidStartTimePair *) b; - - return (_a->pid == _b->pid) && (_a->start_time == _b->start_time); -} - -/** - * polkit_tracker_new: - * - * Creates a new #PolKitTracker object. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the new object - * - * Since: 0.7 - **/ -PolKitTracker * -polkit_tracker_new (void) -{ - PolKitTracker *pk_tracker; - pk_tracker = kit_new0 (PolKitTracker, 1); - pk_tracker->refcount = 1; - pk_tracker->dbus_name_to_caller = kit_hash_new (kit_hash_str_hash_func, - kit_hash_str_equal_func, - NULL, - NULL, - (KitFreeFunc) kit_free, - (KitFreeFunc) polkit_caller_unref); - pk_tracker->pid_start_time_to_caller = kit_hash_new (_pid_start_time_hash, - _pid_start_time_equal, - NULL, - NULL, - (KitFreeFunc) kit_free, - (KitFreeFunc) polkit_caller_unref); - return pk_tracker; -} - -/** - * polkit_tracker_ref: - * @pk_tracker: the tracker object - * - * Increase reference count. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: the object - * - * Since: 0.7 - **/ -PolKitTracker * -polkit_tracker_ref (PolKitTracker *pk_tracker) -{ - kit_return_val_if_fail (pk_tracker != NULL, pk_tracker); - pk_tracker->refcount++; - return pk_tracker; -} - -/** - * polkit_tracker_unref: - * @pk_tracker: the tracker object - * - * Decreases the reference count of the object. If it becomes zero, - * the object is freed. Before freeing, reference counts on embedded - * objects are decresed by one. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - **/ -void -polkit_tracker_unref (PolKitTracker *pk_tracker) -{ - kit_return_if_fail (pk_tracker != NULL); - pk_tracker->refcount--; - if (pk_tracker->refcount > 0) - return; - kit_hash_unref (pk_tracker->dbus_name_to_caller); - kit_hash_unref (pk_tracker->pid_start_time_to_caller); - dbus_connection_unref (pk_tracker->con); - kit_free (pk_tracker); -} - -/** - * polkit_tracker_set_system_bus_connection: - * @pk_tracker: the tracker object - * @con: the connection to the system message bus - * - * Tell the #PolKitTracker object to use the given D-Bus connection - * when it needs to fetch information from the system message bus and - * ConsoleKit services. This is used for priming the cache. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -void -polkit_tracker_set_system_bus_connection (PolKitTracker *pk_tracker, DBusConnection *con) -{ - kit_return_if_fail (pk_tracker != NULL); - pk_tracker->con = dbus_connection_ref (con); -} - -/** - * polkit_tracker_init: - * @pk_tracker: the tracker object - * - * Initialize the tracker. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -void -polkit_tracker_init (PolKitTracker *pk_tracker) -{ - kit_return_if_fail (pk_tracker != NULL); - /* This is currently a no-op */ -} - -/*--------------------------------------------------------------------------------------------------------------*/ - -static void -_set_session_inactive_iter (void *key, PolKitCaller *caller, const char *session_objpath, KitHash *hash) -{ - char *objpath; - PolKitSession *session; - if (!polkit_caller_get_ck_session (caller, &session)) - return; - if (!polkit_session_get_ck_objref (session, &objpath)) - return; - if (strcmp (objpath, session_objpath) != 0) - return; - polkit_session_set_ck_is_active (session, FALSE); -} - -static void -_set_session_active_iter (void *key, PolKitCaller *caller, const char *session_objpath, KitHash *hash) -{ - char *objpath; - PolKitSession *session; - if (!polkit_caller_get_ck_session (caller, &session)) - return; - if (!polkit_session_get_ck_objref (session, &objpath)) - return; - if (strcmp (objpath, session_objpath) != 0) - return; - polkit_session_set_ck_is_active (session, TRUE); -} - -static void -_update_session_is_active (PolKitTracker *pk_tracker, const char *session_objpath, kit_bool_t is_active) -{ - kit_hash_foreach (pk_tracker->dbus_name_to_caller, - (KitHashForeachFunc) (is_active ? _set_session_active_iter : _set_session_inactive_iter), - (void *) session_objpath); -} - -/*--------------------------------------------------------------------------------------------------------------*/ - -static kit_bool_t -_remove_caller_by_session_iter (void *key, PolKitCaller *caller, const char *session_objpath, KitHash *hash) -{ - char *objpath; - PolKitSession *session; - if (!polkit_caller_get_ck_session (caller, &session)) - return FALSE; - if (!polkit_session_get_ck_objref (session, &objpath)) - return FALSE; - if (strcmp (objpath, session_objpath) != 0) - return FALSE; - return TRUE; -} - -static void -_remove_caller_by_session (PolKitTracker *pk_tracker, const char *session_objpath) -{ - kit_hash_foreach_remove (pk_tracker->dbus_name_to_caller, - (KitHashForeachFunc) _remove_caller_by_session_iter, - (void *) session_objpath); -} - -/*--------------------------------------------------------------------------------------------------------------*/ - -static kit_bool_t -_remove_caller_by_dbus_name_iter (void *key, PolKitCaller *caller, const char *dbus_name, KitHash *hash) -{ - char *name; - if (!polkit_caller_get_dbus_name (caller, &name)) - return FALSE; - if (strcmp (name, dbus_name) != 0) - return FALSE; - return TRUE; -} - -static void -_remove_caller_by_dbus_name (PolKitTracker *pk_tracker, const char *dbus_name) -{ - kit_hash_foreach_remove (pk_tracker->dbus_name_to_caller, - (KitHashForeachFunc) _remove_caller_by_dbus_name_iter, - (void *) dbus_name); -} - -/*--------------------------------------------------------------------------------------------------------------*/ - -/** - * polkit_tracker_dbus_func: - * @pk_tracker: the tracker object - * @message: message to pass - * - * The owner of the #PolKitTracker object must pass signals from the - * system message bus (just NameOwnerChanged will do) and all signals - * from the ConsoleKit service into this function. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Returns: #TRUE only if there was a change in the ConsoleKit database. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_tracker_dbus_func (PolKitTracker *pk_tracker, DBusMessage *message) -{ - kit_bool_t ret; - - ret = FALSE; - - if (dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) { - char *name; - char *new_service_name; - char *old_service_name; - - if (!dbus_message_get_args (message, NULL, - DBUS_TYPE_STRING, &name, - DBUS_TYPE_STRING, &old_service_name, - DBUS_TYPE_STRING, &new_service_name, - DBUS_TYPE_INVALID)) { - - /* TODO: should be _pk_critical */ - polkit_debug ("The NameOwnerChanged signal on the " DBUS_INTERFACE_DBUS " " - "interface has the wrong signature! Your system is misconfigured."); - goto out; - } - - if (strlen (new_service_name) == 0) { - _remove_caller_by_dbus_name (pk_tracker, name); - } - - } else if (dbus_message_is_signal (message, "org.freedesktop.ConsoleKit.Session", "ActiveChanged")) { - dbus_bool_t is_active; - DBusError error; - const char *session_objpath; - - ret = TRUE; - - dbus_error_init (&error); - session_objpath = dbus_message_get_path (message); - if (!dbus_message_get_args (message, &error, - DBUS_TYPE_BOOLEAN, &is_active, - DBUS_TYPE_INVALID)) { - - /* TODO: should be _pk_critical */ - kit_warning ("The ActiveChanged signal on the org.freedesktop.ConsoleKit.Session " - "interface for object %s has the wrong signature! " - "Your system is misconfigured.", session_objpath); - - /* as a security measure, remove all sessions with this path from the cache; - * cuz then the user of PolKitTracker probably gets to deal with a DBusError - * the next time he tries something... - */ - _remove_caller_by_session (pk_tracker, session_objpath); - goto out; - } - - /* now go through all Caller objects and update the is_active field as appropriate */ - _update_session_is_active (pk_tracker, session_objpath, is_active); - - } else if (dbus_message_is_signal (message, "org.freedesktop.ConsoleKit.Seat", "SessionAdded")) { - DBusError error; - const char *seat_objpath; - const char *session_objpath; - - /* If a session is added, update our list of sessions.. also notify the user.. */ - - ret = TRUE; - - dbus_error_init (&error); - seat_objpath = dbus_message_get_path (message); - if (!dbus_message_get_args (message, &error, - DBUS_TYPE_STRING, &session_objpath, - DBUS_TYPE_INVALID)) { - - /* TODO: should be _pk_critical */ - kit_warning ("The SessionAdded signal on the org.freedesktop.ConsoleKit.Seat " - "interface for object %s has the wrong signature! " - "Your system is misconfigured.", seat_objpath); - - goto out; - } - - /* TODO: add to sessions - see polkit_tracker_is_authorization_relevant() */ - - } else if (dbus_message_is_signal (message, "org.freedesktop.ConsoleKit.Seat", "SessionRemoved")) { - DBusError error; - const char *seat_objpath; - const char *session_objpath; - - /* If a session is removed, authorizations scoped for that session - * may become inactive.. so do notify the user about it.. - */ - - ret = TRUE; - - dbus_error_init (&error); - seat_objpath = dbus_message_get_path (message); - if (!dbus_message_get_args (message, &error, - DBUS_TYPE_STRING, &session_objpath, - DBUS_TYPE_INVALID)) { - - /* TODO: should be _pk_critical */ - kit_warning ("The SessionRemoved signal on the org.freedesktop.ConsoleKit.Seat " - "interface for object %s has the wrong signature! " - "Your system is misconfigured.", seat_objpath); - - goto out; - } - - _remove_caller_by_session (pk_tracker, session_objpath); - - /* TODO: remove from sessions - see polkit_tracker_is_authorization_relevant() */ - } - - /* TODO: when ConsoleKit gains the ability to attach/detach a session to a seat (think - * hot-desking), we want to update our local caches too - */ - -out: - return ret; -} - -/** - * polkit_tracker_get_caller_from_dbus_name: - * @pk_tracker: the tracker object - * @dbus_name: unique name on the system message bus - * @error: D-Bus error - * - * This function is similar to polkit_caller_new_from_dbus_name() - * except that it uses the cache in #PolKitTracker. So on the second - * and subsequent calls, for the same D-Bus name, there will be no - * syscall or IPC overhead in calling this function. - * - * Returns: A #PolKitCaller object; the caller must use - * polkit_caller_unref() on the object when done with it. Returns - * #NULL if an error occured (in which case error will be set). - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -PolKitCaller * -polkit_tracker_get_caller_from_dbus_name (PolKitTracker *pk_tracker, const char *dbus_name, DBusError *error) -{ - PolKitCaller *caller; - - kit_return_val_if_fail (pk_tracker != NULL, NULL); - kit_return_val_if_fail (pk_tracker->con != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - /* kit_debug ("Looking up cache for PolKitCaller for dbus_name %s...", dbus_name); */ - - caller = kit_hash_lookup (pk_tracker->dbus_name_to_caller, (void *) dbus_name, NULL); - if (caller != NULL) - return polkit_caller_ref (caller); - - /* kit_debug ("Have to compute PolKitCaller for dbus_name %s...", dbus_name); */ - - caller = polkit_caller_new_from_dbus_name (pk_tracker->con, dbus_name, error); - if (caller == NULL) - return NULL; - - kit_hash_insert (pk_tracker->dbus_name_to_caller, kit_strdup (dbus_name), caller); - return polkit_caller_ref (caller); -} - - -/** - * polkit_tracker_get_caller_from_pid: - * @pk_tracker: the tracker object - * @pid: UNIX process id to look at - * @error: D-Bus error - * - * This function is similar to polkit_caller_new_from_pid() - * except that it uses the cache in #PolKitTracker. So on the second - * and subsequent calls, for the same D-Bus name, there will be no - * IPC overhead in calling this function. - * - * There will be some syscall overhead to lookup the time when the - * given process is started (on Linux, looking up /proc/$pid/stat); - * this is needed because pid's can be recycled and the cache thus - * needs to record this in addition to the pid. - * - * Returns: A #PolKitCaller object; the caller must use - * polkit_caller_unref() on the object when done with it. Returns - * #NULL if an error occured (in which case error will be set). - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -PolKitCaller * -polkit_tracker_get_caller_from_pid (PolKitTracker *pk_tracker, pid_t pid, DBusError *error) -{ - PolKitCaller *caller; - polkit_uint64_t start_time; - _PidStartTimePair *pst; - - kit_return_val_if_fail (pk_tracker != NULL, NULL); - kit_return_val_if_fail (pk_tracker->con != NULL, NULL); - kit_return_val_if_fail (! dbus_error_is_set (error), NULL); - - start_time = polkit_sysdeps_get_start_time_for_pid (pid); - if (start_time == 0) { - if (error != NULL) { - dbus_set_error (error, - "org.freedesktop.PolicyKit", - "Cannot look up start time for pid %d", pid); - } - return NULL; - } - - pst = _pid_start_time_new (pid, start_time); - - /* kit_debug ("Looking up cache for pid %d (start_time %lld)...", pid, start_time); */ - - caller = kit_hash_lookup (pk_tracker->pid_start_time_to_caller, (void *) pst, NULL); - if (caller != NULL) { - kit_free (pst); - return polkit_caller_ref (caller); - } - - /* kit_debug ("Have to compute PolKitCaller from pid %d (start_time %lld)...", pid, start_time); */ - - caller = polkit_caller_new_from_pid (pk_tracker->con, pid, error); - if (caller == NULL) { - kit_free (pst); - return NULL; - } - - /* TODO: we need to evict old entries.. - * - * Say, timestamp the entries in _PidStartTimePair and do - * garbage collection every hour or so (e.g. record when we - * last did garbage collection and check this time on the next - * call into this function). - */ - - kit_hash_insert (pk_tracker->pid_start_time_to_caller, pst, caller); - return polkit_caller_ref (caller); -} - - -/** - * polkit_tracker_is_authorization_relevant: - * @pk_tracker: the tracker - * @auth: authorization to check for - * @error: return location for error - * - * As explicit authorizations are scoped (process single shot, - * process, session or everything), they become irrelevant once the - * entity (process or session) ceases to exist. This function - * determines whether the authorization is still relevant; it's useful - * for reporting and graphical tools displaying authorizations. - * - * This function is similar to polkit_is_authorization_relevant() only - * that it avoids IPC overhead on the 2nd and subsequent calls when - * checking authorizations scoped for a session. - * - * Returns: #TRUE if the authorization still applies, #FALSE if an - * error occurred (then error will be set) or if the entity the - * authorization refers to has gone out of scope. - * - * This function is in <literal>libpolkit-dbus</literal>. - * - * Since: 0.7 - */ -polkit_bool_t -polkit_tracker_is_authorization_relevant (PolKitTracker *pk_tracker, PolKitAuthorization *auth, DBusError *error) -{ - - kit_return_val_if_fail (pk_tracker != NULL, FALSE); - kit_return_val_if_fail (pk_tracker->con != NULL, FALSE); - kit_return_val_if_fail (! dbus_error_is_set (error), FALSE); - - /* TODO: optimize... in order to do this sanely we need CK's Manager object to export - * a method GetAllSessions() - otherwise we'd need to key off every uid. - * - * It's no biggie we don't have this optimization yet.. it's only used by polkit-auth(1) - * and the GNOME utility for managing authorizations. - */ - return _polkit_is_authorization_relevant_internal (pk_tracker->con, auth, NULL, error); -} diff --git a/src/polkit/polkit-tracker.h b/src/polkit/polkit-tracker.h deleted file mode 100644 index f994129..0000000 --- a/src/polkit/polkit-tracker.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-tracker.h : track callers - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_TRACKER_H -#define POLKIT_TRACKER_H - -#include <dbus/dbus.h> -#include <polkit/polkit-caller.h> -#include <polkit/polkit-authorization.h> - -POLKIT_BEGIN_DECLS - -PolKitSession *polkit_session_new_from_objpath (DBusConnection *con, const char *objpath, uid_t uid, DBusError *error); -PolKitSession *polkit_session_new_from_cookie (DBusConnection *con, const char *cookie, DBusError *error); - -PolKitCaller *polkit_caller_new_from_dbus_name (DBusConnection *con, const char *dbus_name, DBusError *error); - -PolKitCaller *polkit_caller_new_from_pid (DBusConnection *con, pid_t pid, DBusError *error); - -polkit_bool_t polkit_is_authorization_relevant (DBusConnection *con, PolKitAuthorization *auth, DBusError *error); - -struct _PolKitTracker; -typedef struct _PolKitTracker PolKitTracker; - -PolKitTracker *polkit_tracker_new (void); -PolKitTracker *polkit_tracker_ref (PolKitTracker *pk_tracker); -void polkit_tracker_unref (PolKitTracker *pk_tracker); -void polkit_tracker_set_system_bus_connection (PolKitTracker *pk_tracker, DBusConnection *con); -void polkit_tracker_init (PolKitTracker *pk_tracker); -polkit_bool_t polkit_tracker_dbus_func (PolKitTracker *pk_tracker, DBusMessage *message); -PolKitCaller *polkit_tracker_get_caller_from_dbus_name (PolKitTracker *pk_tracker, const char *dbus_name, DBusError *error); -PolKitCaller *polkit_tracker_get_caller_from_pid (PolKitTracker *pk_tracker, pid_t pid, DBusError *error); -polkit_bool_t -polkit_tracker_is_authorization_relevant (PolKitTracker *pk_tracker, PolKitAuthorization *auth, DBusError *error); - -POLKIT_END_DECLS - -#endif /* POLKIT_ACTION_H */ - - diff --git a/src/polkit/polkit-types.h b/src/polkit/polkit-types.h deleted file mode 100644 index 8144dee..0000000 --- a/src/polkit/polkit-types.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-types.h : fundamental types such as polkit_bool_t - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#if !defined (POLKIT_COMPILATION) && !defined(_POLKIT_INSIDE_POLKIT_H) -#error "Only <polkit/polkit.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef POLKIT_TYPES_H -#define POLKIT_TYPES_H - -#ifdef __cplusplus -# define POLKIT_BEGIN_DECLS extern "C" { -# define POLKIT_END_DECLS } -#else -/** - * POLKIT_BEGIN_DECLS: - * - * C++ include header guard. - */ -# define POLKIT_BEGIN_DECLS -/** - * POLKIT_END_DECLS: - * - * C++ include header guard. - */ -# define POLKIT_END_DECLS -#endif - -#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) -#define POLKIT_GNUC_DEPRECATED \ - __attribute__((__deprecated__)) -#else -/** - * POLKIT_GNUC_DEPRECATED: - * - * Used in front of deprecated functions. - */ -#define POLKIT_GNUC_DEPRECATED -#endif /* __GNUC__ */ - -POLKIT_BEGIN_DECLS - -/** - * SECTION:polkit-types - * @title: Basic types - * @short_description: Type definitions for common primitive types. - * - * Type definitions for common primitive types. - **/ - -/** - * polkit_bool_t: - * - * A boolean, valid values are #TRUE and #FALSE. - */ -typedef int polkit_bool_t; - -/** - * polkit_uint32_t: - * - * Type for unsigned 32 bit integer. - */ -typedef unsigned int polkit_uint32_t; - -/** - * polkit_uint64_t: - * - * Type for unsigned 64 bit integer. - */ -typedef unsigned long long polkit_uint64_t; - -#ifndef TRUE -# define TRUE 1 -#endif -#ifndef FALSE -# define FALSE 0 -#endif - -POLKIT_END_DECLS - -#endif /* POLKIT_TYPES_H */ - - diff --git a/src/polkit/polkit-utils.c b/src/polkit/polkit-utils.c deleted file mode 100644 index be68086..0000000 --- a/src/polkit/polkit-utils.c +++ /dev/null @@ -1,175 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-utils.c : internal utilities used in polkit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <stdio.h> -#include <stdarg.h> -#include <stdlib.h> -#include <sys/time.h> -#include <time.h> -#include <string.h> - -#include "polkit-utils.h" -#include "polkit-debug.h" -#include "polkit-private.h" -#include "polkit-test.h" - -/** - * SECTION:polkit-utils - * @short_description: Internal utility functions for polkit. - * - * Internal utility functions for polkit. - **/ - -/** - * _pk_validate_identifier: - * @identifier: the NUL-terminated string to validate - * - * Validates strings used for an identifier; PolicyKit conventions - * state that identifiers must be NUL-terminated ASCII strings less - * than 256 bytes and only contain the characters "[a-z][A-Z]0-9]._-:/" - * - * Returns: #TRUE iff the identifier validates - **/ -polkit_bool_t -_pk_validate_identifier (const char *identifier) -{ - unsigned int n; - polkit_bool_t ret; - - kit_return_val_if_fail (identifier != NULL, FALSE); - - ret = FALSE; - for (n = 0; identifier[n] != '\0'; n++) { - char c = identifier[n]; - - if (n >= 255) { - polkit_debug ("identifier too long"); - goto out; - } - - if ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - c == '.' || - c == '_' || - c == '-' || - c == ':' || - c == '/') - continue; - - polkit_debug ("invalid character in identifier"); - goto out; - } - - ret = TRUE; -out: - return ret; -} - - -/* Determine wether the given character is valid as a second or later character in a bus name */ -#define VALID_BUS_NAME_CHARACTER(c) \ - ( ((c) >= '0' && (c) <= '9') || \ - ((c) >= 'A' && (c) <= 'Z') || \ - ((c) >= 'a' && (c) <= 'z') || \ - ((c) == '_') || ((c) == '-')) - -polkit_bool_t -_pk_validate_unique_bus_name (const char *unique_bus_name) -{ - int len; - const char *s; - const char *end; - const char *last_dot; - polkit_bool_t ret; - - ret = FALSE; - - if (unique_bus_name == NULL) - goto error; - - len = strlen (unique_bus_name); - if (len == 0) - goto error; - - end = unique_bus_name + len; - last_dot = NULL; - - s = unique_bus_name; - - /* check special cases of first char so it doesn't have to be done - * in the loop. Note we know len > 0 - */ - if (*s == ':') { - /* unique name */ - ++s; - while (s != end) { - if (*s == '.') { - if ((s + 1) == end) - goto error; - if (!VALID_BUS_NAME_CHARACTER (*(s + 1))) - goto error; - ++s; /* we just validated the next char, so skip two */ - } else if (!VALID_BUS_NAME_CHARACTER (*s)) { - goto error; - } - ++s; - } - } else { - goto error; - } - - ret = TRUE; - -error: - if (!ret) - polkit_debug ("name '%s' did not validate", unique_bus_name); - return ret; -} - -#ifdef POLKIT_BUILD_TESTS - -static polkit_bool_t -_run_test (void) -{ - return TRUE; -} - -KitTest _test_utils = { - "polkit_utils", - NULL, - NULL, - _run_test -}; - -#endif /* POLKIT_BUILD_TESTS */ diff --git a/src/polkit/polkit-utils.h b/src/polkit/polkit-utils.h deleted file mode 100644 index fc65178..0000000 --- a/src/polkit/polkit-utils.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit-utils.h : internal utilities used in polkit - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifndef POLKIT_UTILS_H -#define POLKIT_UTILS_H - -#include <polkit/polkit-types.h> - -POLKIT_BEGIN_DECLS - -polkit_bool_t _pk_validate_identifier (const char *identifier); - -polkit_bool_t _pk_validate_unique_bus_name (const char *unique_bus_name); - -POLKIT_END_DECLS - -#endif /* POLKIT_UTILS_H */ - - diff --git a/src/polkit/polkit.h b/src/polkit/polkit.h deleted file mode 100644 index 3487c95..0000000 --- a/src/polkit/polkit.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ -/*************************************************************************** - * - * polkit.h : library for querying system-wide policy - * - * Copyright (C) 2007 David Zeuthen, <david@fubar.dk> - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - **************************************************************************/ - -#ifndef POLKIT_H -#define POLKIT_H - -#define _POLKIT_INSIDE_POLKIT_H 1 -#include <polkit/polkit-types.h> -#include <polkit/polkit-sysdeps.h> -#include <polkit/polkit-error.h> -#include <polkit/polkit-result.h> -#include <polkit/polkit-context.h> -#include <polkit/polkit-action.h> -#include <polkit/polkit-seat.h> -#include <polkit/polkit-session.h> -#include <polkit/polkit-caller.h> -#include <polkit/polkit-action-description.h> -#include <polkit/polkit-implicit-authorization.h> -#include <polkit/polkit-authorization.h> -#include <polkit/polkit-authorization-db.h> -#include <polkit/polkit-tracker.h> -#include <polkit/polkit-simple.h> -#undef _POLKIT_INSIDE_POLKIT_H - -#endif /* POLKIT_H */ - - |