From 65da2c64aed64c631d0fd90b272c00270d05dae9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Harun=20G=C3=BCltekin?= Date: Fri, 3 Apr 2026 16:32:03 +0300 Subject: [PATCH 1/4] =?UTF-8?q?cmakelists.txt=20dosyas=C4=B1=20modernle?= =?UTF-8?q?=C5=9Ftirildi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sürüm bilgisi 'cmakelists.txt'ye taşındı - config.h dosyası 'cmakelists.txt'den değişken alabilmesi için config.h.in olarak değiştirildi --- .gitignore | 5 + CMakeLists.txt | 160 +++++++++++++++--------------- include/{config.h => config.h.in} | 40 ++++---- 3 files changed, 109 insertions(+), 96 deletions(-) create mode 100644 .gitignore rename include/{config.h => config.h.in} (72%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4cb9b03 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +build +__pycache__ +*.pyc +*swp +*.bak diff --git a/CMakeLists.txt b/CMakeLists.txt index 58be103..9840742 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,110 +1,114 @@ -SET(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "set prefix: /usr" FORCE) +cmake_minimum_required(VERSION 4.1) +set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "set prefix: /usr" FORCE) # Project name -PROJECT (comar) -# TODO: python3 için eklenen py3 ifadeleri silinecek -# CMake 2.6 required -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +project(comar VERSION 4.0.0) # Python is required -FIND_PACKAGE(PythonInterp "3" REQUIRED) -FIND_PACKAGE(PythonLibs "3" REQUIRED) +find_package(Python "3" REQUIRED COMPONENTS Development) -FIND_PACKAGE(PkgConfig) -PKG_CHECK_MODULES (DBUS REQUIRED dbus-1) +find_package(PkgConfig QUIET REQUIRED) +pkg_check_modules(Dbus REQUIRED IMPORTED_TARGET dbus-1) # Application name -SET (APP_NAME "comar") -SET (APP_SUFFIX "3") -# Uncomment this for production releases. -SET (VERSION_SUFFIX "") -#SET (FLAGS "-g -O0 -Werror -Wcast-align -Wno-uninitialized -Wall -fstrict-aliasing") +set(APP_NAME "comar") + +option(USE_APP_SUFFIX "set application suffix as version major" ON) +if(USE_APP_SUFFIX) + set(APP_SUFFIX "${PROJECT_VERSION_MAJOR}") +else() + set(APP_SUFFIX "") +endif() -# Uncomment this for gprof profiling -# SET (FLAGS "-g -O0 -Werror -Wcast-align -Wno-uninitialized -Wall -fstrict-aliasing -fprofile-arcs -ftest-coverage") -#SET (CMAKE_C_FLAGS "${FLAGS}") -# Uncomment this for sparse building -# SET (CMAKE_C_COMPILER cgcc) +# Uncomment this for production releases. +set(VERSION_SUFFIX "") # Append name suffix, if specified -IF (APP_SUFFIX) - SET (APP_NAME "${APP_NAME}${APP_SUFFIX}") -ENDIF (APP_SUFFIX) +if(APP_SUFFIX) + set(APP_NAME "${APP_NAME}${APP_SUFFIX}") +endif(APP_SUFFIX) # Define version, config dir, data dir and log file. -ADD_DEFINITIONS ( - -D'PID_FILE="/run/${APP_NAME}.pid"' - -D'DATA_DIR="/var/lib/${APP_NAME}"' - -D'LOG_DIR="/var/log/${APP_NAME}py3"') +add_definitions ( + -DPID_FILE="/run/${APP_NAME}.pid" + -DDATA_DIR="/var/lib/${APP_NAME}" + -DLOG_DIR="/var/log/${APP_NAME}") + +configure_file(include/config.h.in config.h) # Set standard sources -SET (SOURCES src/main.c - src/bus.c - src/config.c - src/db.c - src/iksemel.c - src/log.c - src/loop.c - src/process.c - src/policy.c - src/pydbus.c - src/script.c - src/utils.c) - -# Set standard libraries -SET (LIBS ${PYTHON_LIBRARIES} - dbus-1) - -include_directories(include/ - ${PYTHON_INCLUDE_DIRS} - ${DBUS_INCLUDE_DIRS}) +set(SOURCES src/main.c + src/bus.c + src/config.c + src/db.c + src/iksemel.c + src/log.c + src/loop.c + src/process.c + src/policy.c + src/pydbus.c + src/script.c + src/utils.c) # Compile comar from specified sources -ADD_EXECUTABLE (comar ${SOURCES}) +add_executable(comar ${SOURCES}) + +# change app name +set_target_properties(comar PROPERTIES + OUTPUT_NAME ${APP_NAME} +) + +target_include_directories(comar PUBLIC + include + "${CMAKE_CURRENT_BINARY_DIR}") # Link comar to specified libraries -TARGET_LINK_LIBRARIES(comar ${LIBS} ) +target_link_libraries(comar + Python::Python + PkgConfig::Dbus) # Install comar to /usr/sbin/ -INSTALL (PROGRAMS comar - DESTINATION /usr/sbin) +install(TARGETS comar + DESTINATION /usr/sbin + RENAME ${APP_NAME}) # Install Models -INSTALL (DIRECTORY - models - DESTINATION /var/db/${APP_NAME} - PATTERN ".svn" EXCLUDE) +install(DIRECTORY + models + DESTINATION /var/db/${APP_NAME} + PATTERN ".svn" EXCLUDE) # Install Modules -INSTALL (DIRECTORY - modules - DESTINATION /var/db/${APP_NAME} - PATTERN ".svn" EXCLUDE) +install(DIRECTORY + modules + DESTINATION /var/db/${APP_NAME} + PATTERN ".svn" EXCLUDE) # Install service activation config under /usr/share/dbus-1/system-services/ -INSTALL (FILES - config/tr.org.pardus.comar.service - config/tr.org.pardus.comar2.service - DESTINATION /usr/share/dbus-1/system-services/) +install(FILES + config/tr.org.pardus.comar.service + config/tr.org.pardus.comar2.service + DESTINATION /usr/share/dbus-1/system-services/) # Install polkit policies -INSTALL (DIRECTORY - policy/ - DESTINATION /usr/share/polkit-1/actions - FILES_MATCHING PATTERN "*.policy" - PATTERN ".svn" EXCLUDE) +install(DIRECTORY + policy/ + DESTINATION /usr/share/polkit-1/actions + FILES_MATCHING PATTERN "*.policy" + PATTERN ".svn" EXCLUDE) # Install system bus policy under /etc/dbus-1/system.d/ -INSTALL (FILES - config/tr.org.pardus.comar.conf - DESTINATION /etc/dbus-1/system.d) +install(FILES + config/tr.org.pardus.comar.conf + DESTINATION /etc/dbus-1/system.d) # Install hav to /usr/bin/hav -INSTALL (PROGRAMS tools/hav.py - DESTINATION /usr/bin - RENAME havpy3) - -# Install hav to /usr/bin/comar2to3 -INSTALL (PROGRAMS tools/comar2to3.py - DESTINATION /usr/bin - RENAME comar2to3py3) +install(PROGRAMS tools/hav.py + DESTINATION /usr/bin + RENAME "hav${APP_SUFFIX}") + +# python2 ile çalışan son comar sürümü 3 olduğundan kaldırıldı +# # Install hav to /usr/bin/comar2to3 +# install(PROGRAMS tools/comar2to3.py +# DESTINATION /usr/bin +# RENAME comar2to3py3) diff --git a/include/config.h b/include/config.h.in similarity index 72% rename from include/config.h rename to include/config.h.in index dca6f4b..0c8a833 100644 --- a/include/config.h +++ b/include/config.h.in @@ -28,7 +28,11 @@ #define CONFIG_H #ifndef VERSION -#define VERSION "3.0.3" +#define VERSION "@PROJECT_VERSION@" +#endif + +#ifndef APP_SUFFIX +#define APP_SUFFIX "@APP_SUFFIX@" #endif #ifndef DBUS_SERVER_ADDRESS @@ -48,28 +52,28 @@ #endif #ifndef DIR_DATA -#define DIR_DATA "/var/db/comar3" +#define DIR_DATA "/var/db/comar" APP_SUFFIX #endif #ifndef DIR_LOG -#define DIR_LOG "/var/log/comar3" +#define DIR_LOG "/var/log/comar" APP_SUFFIX #endif #ifndef FILE_PID -#define FILE_PID "/run/comar3.pid" +#define FILE_PID "/run/comar" APP_SUFFIX ".pid" #endif #ifndef WWW_BUGS #define WWW_BUGS "http://bugs.pardus.org.tr" #endif -extern char *config_server_address; -extern const char *config_unique_address; -extern char *config_service_name; -extern char *config_interface; -extern char *config_dir_data; -extern char *config_dir_log; -extern char *config_file_pid; +extern char* config_server_address; +extern const char* config_unique_address; +extern char* config_service_name; +extern char* config_interface; +extern char* config_dir_data; +extern char* config_dir_log; +extern char* config_file_pid; extern int config_timeout; extern int config_debug; @@ -77,12 +81,12 @@ extern int config_print; extern int config_runlevel; extern int config_ignore_missing; -extern char *config_dir_models; -extern char *config_dir_modules; -extern char *config_dir_scripts; -extern char *config_dir_apps; -extern char *config_file_log_access; -extern char *config_file_log_traceback; +extern char* config_dir_models; +extern char* config_dir_modules; +extern char* config_dir_scripts; +extern char* config_dir_apps; +extern char* config_file_log_access; +extern char* config_file_log_traceback; -void config_init(int argc, char *argv[]); +void config_init(int argc, char* argv[]); #endif /* CONFIG_H */ From 7049cabf7df44b7c46e76a113ed785fd9e010233 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Harun=20G=C3=BCltekin?= Date: Fri, 3 Apr 2026 16:45:21 +0300 Subject: [PATCH 2/4] =?UTF-8?q?python3=20ile=20=C3=A7al=C4=B1=C5=9F=C4=B1r?= =?UTF-8?q?=20hale=20getirildi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - formatter kullanılarak kod daha düzenli hale getirildi --- modules/core.py | 33 +-- src/bus.c | 135 ++++++------ src/db.c | 95 ++++---- src/loop.c | 181 +++++++--------- src/pydbus.c | 530 ++++++++++++++++++++++----------------------- src/script.c | 266 +++++++++-------------- tools/comar2to3.py | 9 +- tools/hav.py | 22 +- 8 files changed, 594 insertions(+), 677 deletions(-) diff --git a/modules/core.py b/modules/core.py index 8a5b479..619703e 100644 --- a/modules/core.py +++ b/modules/core.py @@ -4,6 +4,7 @@ import os import shutil + def listModelApplications(model): apps = [] scriptDir = os.path.join(config_datapath(), "scripts", model) @@ -14,6 +15,7 @@ def listModelApplications(model): apps.append(i[:-3]) return apps + def listApplicationModels(app): models = [] scriptDir = os.path.join(config_datapath(), "apps", app) @@ -24,12 +26,13 @@ def listApplicationModels(app): models.append(i) return models + def register(app, model, filename): scriptDir = os.path.join(config_datapath(), "scripts", model) scriptFile = os.path.join(scriptDir, "%s.py" % app) try: os.mkdir(scriptDir) - except: + except Exception: pass shutil.copy(filename, scriptFile) @@ -37,15 +40,16 @@ def register(app, model, filename): scriptFile = os.path.join(scriptDir, model) try: os.mkdir(scriptDir) - except: + except Exception: pass try: - file(scriptFile, "w").write("") - except: + open(scriptFile, "w").write("") + except Exception: pass return True + def remove(app): scriptDir = os.path.join(config_datapath(), "apps", app) if not os.path.exists(scriptDir): @@ -55,16 +59,19 @@ def remove(app): scriptFile = os.path.join(config_datapath(), "scripts", i, "%s.py" % app) try: os.unlink(scriptFile) - except: + except Exception: pass shutil.rmtree(scriptDir) + def model_xml(modelName): if modelName == "Core": xml = '' % config_interface() else: xml = '' % (config_interface(), modelName) - for _name, (_type, _action_id, _sig_in, _sig_out) in config_modelbase()[modelName].iteritems(): + for _name, (_type, _action_id, _sig_in, _sig_out) in config_modelbase()[ + modelName + ].items(): if _type == 0: xml += '' % _name else: @@ -74,27 +81,27 @@ def model_xml(modelName): for arg in _sig_out: xml += '' % arg if _type == 0: - xml += '' + xml += "" else: - xml += '' - xml += '' + xml += "" + xml += "" return xml def introspect(): path = bus_path() xml = '' % path - if path == '/': + if path == "/": xml += model_xml("Core") xml += '' - elif path == '/package': + elif path == "/package": scriptDir = os.path.join(config_datapath(), "apps") for i in os.listdir(scriptDir): if not i.startswith("."): xml += '' % i - elif path.startswith('/package/'): + elif path.startswith("/package/"): app = path.split("/package/")[1] for name in listApplicationModels(app): xml += model_xml(name) - xml += '' + xml += "" return xml diff --git a/src/bus.c b/src/bus.c index dad7458..4aef868 100644 --- a/src/bus.c +++ b/src/bus.c @@ -31,25 +31,22 @@ #include "script.h" #include "utils.h" +#include +#include #include #include #include -#include #include #include #include #include #include -#include - - //! DBus connection -DBusConnection *bus_conn; +DBusConnection* bus_conn; //! Sends a DBus message -void -bus_send(DBusMessage *bus_msg) +void bus_send(DBusMessage* bus_msg) { /*! * Sends a DBus message and flushes connection. @@ -65,26 +62,24 @@ bus_send(DBusMessage *bus_msg) } //! Replies to a DBus message with an error message -void -bus_reply_error(DBusMessage *bus_msg, const char *name, const char *msg) +void bus_reply_error(DBusMessage* bus_msg, const char* name, const char* msg) { // DBus error = interface + name int size = strlen(config_interface) + 1 + strlen(name) + 1; - char *exception = malloc(size); + char* exception = malloc(size); snprintf(exception, size, "%s.%s", config_interface, name); exception[size - 1] = '\0'; - DBusMessage *error = dbus_message_new_error(bus_msg, exception, msg); + DBusMessage* error = dbus_message_new_error(bus_msg, exception, msg); free(exception); bus_send(error); dbus_message_unref(error); } //! Replies to a DBus message with a Python object -void -bus_reply_object(DBusMessage *bus_msg, PyObject *py_obj, char *signature) +void bus_reply_object(DBusMessage* bus_msg, PyObject* py_obj, char* signature) { - DBusMessage *reply; + DBusMessage* reply; DBusMessageIter iter; char *eStr, *vStr; @@ -93,12 +88,11 @@ bus_reply_object(DBusMessage *bus_msg, PyObject *py_obj, char *signature) // If signature is not null, append Python object to message if (strcmp(signature, "") != 0) { - PyObject *py_tuple; + PyObject* py_tuple; if (!PyTuple_Check(py_obj)) { py_tuple = PyTuple_New(1); PyTuple_SetItem(py_tuple, 0, py_obj); - } - else { + } else { py_tuple = py_obj; } if (pydbus_export(&iter, py_tuple, signature) != 0) { @@ -113,23 +107,21 @@ bus_reply_object(DBusMessage *bus_msg, PyObject *py_obj, char *signature) } //! Replies to a DBus message with a "UnknownMethod" error -void -bus_reply_unknown_method(DBusMessage *bus_msg) +void bus_reply_unknown_method(DBusMessage* bus_msg) { - DBusMessage *error = dbus_message_new_error_printf(bus_msg, "org.freedesktop.DBus.Error.UnknownMethod", - "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist", - dbus_message_get_member(bus_msg), - dbus_message_get_signature(bus_msg), - dbus_message_get_interface(bus_msg)); + DBusMessage* error = dbus_message_new_error_printf(bus_msg, "org.freedesktop.DBus.Error.UnknownMethod", + "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist", + dbus_message_get_member(bus_msg), + dbus_message_get_signature(bus_msg), + dbus_message_get_interface(bus_msg)); bus_send(error); dbus_message_unref(error); } //! Emits a DBus signal with a Python object -int -bus_signal(const char *path, const char *interface, const char *member, PyObject *obj, char *signature) +int bus_signal(const char* path, const char* interface, const char* member, PyObject* obj, char* signature) { - DBusMessage *msg; + DBusMessage* msg; DBusMessageIter iter; msg = dbus_message_new_signal(path, interface, member); @@ -137,12 +129,11 @@ bus_signal(const char *path, const char *interface, const char *member, PyObject // If signature is not null, append Python object to message if (obj && obj != Py_None && strcmp(signature, "") != 0) { - PyObject *py_tuple; + PyObject* py_tuple; if (!PyTuple_Check(obj)) { py_tuple = PyTuple_New(1); PyTuple_SetItem(py_tuple, 0, obj); - } - else { + } else { py_tuple = obj; } if (pydbus_export(&iter, py_tuple, signature) != 0) { @@ -156,8 +147,8 @@ bus_signal(const char *path, const char *interface, const char *member, PyObject } //! Calls a method and returns reply. -PyObject * -bus_execute(DBusConnection *conn, const char *path, const char *interface, const char *member, PyObject *obj, int timeout, char *signature) +PyObject* +bus_execute(DBusConnection* conn, const char* path, const char* interface, const char* member, PyObject* obj, int timeout, char* signature) { DBusMessage *msg, *reply; DBusMessageIter iter; @@ -168,12 +159,11 @@ bus_execute(DBusConnection *conn, const char *path, const char *interface, const // If signature is not null, append Python object to message if (strcmp(signature, "") != 0) { - PyObject *py_tuple; + PyObject* py_tuple; if (!PyTuple_Check(obj)) { py_tuple = PyTuple_New(1); PyTuple_SetItem(py_tuple, 0, obj); - } - else { + } else { py_tuple = obj; } if (pydbus_export(&iter, py_tuple, signature) != 0) { @@ -198,22 +188,22 @@ bus_execute(DBusConnection *conn, const char *path, const char *interface, const return NULL; } - PyObject *ret; + PyObject* ret; switch (dbus_message_get_type(reply)) { - case DBUS_MESSAGE_TYPE_METHOD_RETURN: - // Method returned a reply - ret = pydbus_import(reply); - if (ret && PyTuple_Size(ret) == 1) { - ret = PyTuple_GetItem(ret, 0); - } - dbus_message_unref(reply); - return ret; - case DBUS_MESSAGE_TYPE_ERROR: - // Method retuned an error, raise an exception - PyErr_SetString(PyExc_DBus, dbus_message_get_error_name(reply)); - dbus_message_unref(reply); - return NULL; + case DBUS_MESSAGE_TYPE_METHOD_RETURN: + // Method returned a reply + ret = pydbus_import(reply); + if (ret && PyTuple_Size(ret) == 1) { + ret = PyTuple_GetItem(ret, 0); + } + dbus_message_unref(reply); + return ret; + case DBUS_MESSAGE_TYPE_ERROR: + // Method retuned an error, raise an exception + PyErr_SetString(PyExc_DBus, dbus_message_get_error_name(reply)); + dbus_message_unref(reply); + return NULL; } Py_INCREF(Py_None); @@ -221,8 +211,8 @@ bus_execute(DBusConnection *conn, const char *path, const char *interface, const } //! Calls a method and returns reply. -PyObject * -bus_execute2(DBusConnection *conn, const char *destination, const char *path, const char *interface, const char *member, PyObject *obj, int timeout, char *signature) +PyObject* +bus_execute2(DBusConnection* conn, const char* destination, const char* path, const char* interface, const char* member, PyObject* obj, int timeout, char* signature) { DBusMessage *msg, *reply; DBusMessageIter iter; @@ -233,12 +223,11 @@ bus_execute2(DBusConnection *conn, const char *destination, const char *path, co // If signature is not null, append Python object to message if (strcmp(signature, "") != 0) { - PyObject *py_tuple; + PyObject* py_tuple; if (!PyTuple_Check(obj)) { py_tuple = PyTuple_New(1); PyTuple_SetItem(py_tuple, 0, obj); - } - else { + } else { py_tuple = obj; } if (pydbus_export(&iter, py_tuple, signature) != 0) { @@ -263,22 +252,22 @@ bus_execute2(DBusConnection *conn, const char *destination, const char *path, co return NULL; } - PyObject *ret; + PyObject* ret; switch (dbus_message_get_type(reply)) { - case DBUS_MESSAGE_TYPE_METHOD_RETURN: - // Method returned a reply - ret = pydbus_import(reply); - if (ret && PyTuple_Size(ret) == 1) { - ret = PyTuple_GetItem(ret, 0); - } - dbus_message_unref(reply); - return ret; - case DBUS_MESSAGE_TYPE_ERROR: - // Method retuned an error, raise an exception - PyErr_SetString(PyExc_DBus, dbus_message_get_error_name(reply)); - dbus_message_unref(reply); - return NULL; + case DBUS_MESSAGE_TYPE_METHOD_RETURN: + // Method returned a reply + ret = pydbus_import(reply); + if (ret && PyTuple_Size(ret) == 1) { + ret = PyTuple_GetItem(ret, 0); + } + dbus_message_unref(reply); + return ret; + case DBUS_MESSAGE_TYPE_ERROR: + // Method retuned an error, raise an exception + PyErr_SetString(PyExc_DBus, dbus_message_get_error_name(reply)); + dbus_message_unref(reply); + return NULL; } Py_INCREF(Py_None); @@ -286,10 +275,10 @@ bus_execute2(DBusConnection *conn, const char *destination, const char *path, co } //! Opens a connection, sets locale and calls interface.member() -PyObject * -bus_call(const char *path, const char *interface, const char *member, PyObject *obj, int timeout, const char *lang, char *signature) +PyObject* +bus_call(const char* path, const char* interface, const char* member, PyObject* obj, int timeout, const char* lang, char* signature) { - DBusConnection *conn; + DBusConnection* conn; DBusError err; // Open a new connection @@ -302,10 +291,10 @@ bus_call(const char *path, const char *interface, const char *member, PyObject * } // setLocale first - PyObject *args = PyTuple_New(1); + PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, PyUnicode_FromString(lang)); - PyObject *ret = bus_execute(conn, "/", config_interface, "setLocale", args, 25, "s"); + PyObject* ret = bus_execute(conn, "/", config_interface, "setLocale", args, 25, "s"); if (!ret) { dbus_connection_close(conn); dbus_connection_unref(conn); diff --git a/src/db.c b/src/db.c index 27ea2e3..620cbbc 100644 --- a/src/db.c +++ b/src/db.c @@ -26,20 +26,19 @@ #include "config.h" #include "iksemel.h" -#include "script.h" #include "log.h" +#include "script.h" #include "utils.h" #include -#include #include #include +#include #include //! Validates model file -int -db_validate_model(iks *xml, char *filename) +int db_validate_model(iks* xml, char* filename) { /*! * Validates model file. @@ -104,21 +103,18 @@ db_validate_model(iks *xml, char *filename) log_error("Argument tag with a non-single element type (%s/%s/%s) in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), iks_find_attrib(arg, "name"), filename); return -1; } - } - else if (iks_strcmp(iks_name(arg), "annotation") == 0) { + } else if (iks_strcmp(iks_name(arg), "annotation") == 0) { // Attributes must have a "name" attribute if (!iks_strlen(iks_find_attrib(arg, "name"))) { log_error("Annotation tag without name under '%s' in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename); return -1; } - } - else { + } else { log_error("Unknown tag '%s' under '%s/%s' in XML: %s\n", iks_name(arg), iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename); return -1; } } - } - else { + } else { log_error("Unknown tag '%s' under '%s' in XML: %s\n", iks_name(met), iks_find_attrib(iface, "name"), filename); return -1; } @@ -129,17 +125,15 @@ db_validate_model(iks *xml, char *filename) } //! Gets PolicyKit action ID of a method -char * -db_action_id(char *iface_name, iks *met) +char* db_action_id(char* iface_name, iks* met) { // If necerssary, get PolicyKit action ID from XML - char *action_id = iks_find_attrib(met, "action_id"); + char* action_id = iks_find_attrib(met, "action_id"); if (action_id) { return action_id; - } - else { + } else { // Else, make action ID from alias attribute - char *alias = iks_find_attrib(met, "alias"); + char* alias = iks_find_attrib(met, "alias"); if (!alias) { // or, from access_label attribute alias = iks_find_attrib(met, "access_label"); @@ -152,12 +146,13 @@ db_action_id(char *iface_name, iks *met) // Append alias to interface name int size = strlen(config_interface) + 1 + strlen(iface_name) + 1 + strlen(alias) + 1; action_id = malloc(size); - if (!action_id) oom(); + if (!action_id) + oom(); snprintf(action_id, size, "%s.%s.%s", config_interface, iface_name, alias); action_id[size - 1] = '\0'; // All chars must be lowercase - char *t; + char* t; for (t = action_id; *t != '\0'; t++) { *t = tolower(*t); } @@ -167,8 +162,7 @@ db_action_id(char *iface_name, iks *met) } //! Loads model to database -void -db_load_model(iks *xml, PyObject **py_models) +void db_load_model(iks* xml, PyObject** py_models) { /*! * Loads models to database @@ -181,28 +175,27 @@ db_load_model(iks *xml, PyObject **py_models) iks *iface, *met, *arg; for (iface = iks_first_tag(xml); iface; iface = iks_next_tag(iface)) { - PyObject *py_methods = PyDict_New(); + PyObject* py_methods = PyDict_New(); - char *iface_name = iks_find_attrib(iface, "name"); + char* iface_name = iks_find_attrib(iface, "name"); for (met = iks_first_tag(iface); met; met = iks_next_tag(met)) { - PyObject *py_tuple = PyTuple_New(4); + PyObject* py_tuple = PyTuple_New(4); // First argument is type. 0 for methods, 1 for signals if (iks_strcmp(iks_name(met), "method") == 0) { - PyTuple_SetItem(py_tuple, 0, PyLong_FromLong((long) 0)); - } - else { - PyTuple_SetItem(py_tuple, 0, PyLong_FromLong((long) 1)); + PyTuple_SetItem(py_tuple, 0, PyLong_FromLong((long)0)); + } else { + PyTuple_SetItem(py_tuple, 0, PyLong_FromLong((long)1)); } // Second argument is PolicyKit action ID - char *action_id = db_action_id(iface_name, met); + char* action_id = db_action_id(iface_name, met); PyTuple_SetItem(py_tuple, 1, PyUnicode_FromString(action_id)); // Build argument lists - PyObject *py_args_in = PyList_New(0); - PyObject *py_args_out = PyList_New(0); + PyObject* py_args_in = PyList_New(0); + PyObject* py_args_out = PyList_New(0); int noreply = 0; for (arg = iks_first_tag(met); arg; arg = iks_next_tag(arg)) { if (iks_strcmp(iks_name(arg), "attribute") == 0) { @@ -211,17 +204,14 @@ db_load_model(iks *xml, PyObject **py_models) noreply = 1; } } - } - else if (iks_strcmp(iks_name(arg), "arg") == 0) { + } else if (iks_strcmp(iks_name(arg), "arg") == 0) { if (iks_strcmp(iks_name(met), "method") == 0) { if (iks_strcmp(iks_find_attrib(arg, "direction"), "out") == 0) { PyList_Append(py_args_out, PyUnicode_FromString(iks_find_attrib(arg, "type"))); - } - else { + } else { PyList_Append(py_args_in, PyUnicode_FromString(iks_find_attrib(arg, "type"))); } - } - else if (iks_strcmp(iks_name(met), "signal") == 0) { + } else if (iks_strcmp(iks_name(met), "signal") == 0) { PyList_Append(py_args_out, PyUnicode_FromString(iks_find_attrib(arg, "type"))); } } @@ -244,8 +234,7 @@ db_load_model(iks *xml, PyObject **py_models) } //! Returns a dictionar of models: methods -int -db_load_models(PyObject **py_models) +int db_load_models(PyObject** py_models) { /*! * Returns a dictionary of models and their methods. @@ -255,9 +244,9 @@ db_load_models(PyObject **py_models) * */ - struct dirent *dp; - DIR *dir = opendir(config_dir_models); - iks *xml; + struct dirent* dp; + DIR* dir = opendir(config_dir_models); + iks* xml; *py_models = PyDict_New(); @@ -269,21 +258,22 @@ db_load_models(PyObject **py_models) // Load XML int size = strlen(config_dir_models) + 1 + strlen(dp->d_name) + 1; - char *fn_xml = malloc(size); - if (fn_xml == NULL) oom(); + char* fn_xml = malloc(size); + if (fn_xml == NULL) + oom(); snprintf(fn_xml, size, "%s/%s", config_dir_models, dp->d_name); fn_xml[size - 1] = 0; switch (iks_load(fn_xml, &xml)) { - case IKS_NOMEM: - free(fn_xml); - oom(); - case IKS_FILE_RWERR: - case IKS_FILE_NOACCESS: - log_error("Unable to open XML: %s\n", fn_xml); - closedir(dir); - free(fn_xml); - return -1; + case IKS_NOMEM: + free(fn_xml); + oom(); + case IKS_FILE_RWERR: + case IKS_FILE_NOACCESS: + log_error("Unable to open XML: %s\n", fn_xml); + closedir(dir); + free(fn_xml); + return -1; } // Validate XML @@ -296,7 +286,6 @@ db_load_models(PyObject **py_models) // Load model db_load_model(xml, py_models); - } closedir(dir); diff --git a/src/loop.c b/src/loop.c index 6aea979..34a02c5 100644 --- a/src/loop.c +++ b/src/loop.c @@ -27,37 +27,36 @@ #include "bus.h" #include "config.h" #include "log.h" -#include "process.h" #include "policy.h" +#include "process.h" #include "pydbus.h" #include "script.h" #include "utils.h" +#include +#include #include #include #include -#include #include #include #include #include #include -#include #define MAX_FDS 1024 #define MAX_PROC 500 #define MAX_WATCHES 10 static struct pollfd bus_fds[MAX_WATCHES]; -static DBusWatch *bus_watches[MAX_WATCHES]; +static DBusWatch* bus_watches[MAX_WATCHES]; static int bus_nr_watches = 0; //! Executes registered Python code of app/model -void -message_execute(DBusMessage *msg, const char *app, const char *model, const char *method) +void message_execute(DBusMessage* msg, const char* app, const char* model, const char* method) { - PyObject *py_ret; - PyObject *py_args = pydbus_import(msg); + PyObject* py_ret; + PyObject* py_args = pydbus_import(msg); char *eStr, *vStr; // Validate model and method @@ -68,13 +67,13 @@ message_execute(DBusMessage *msg, const char *app, const char *model, const char // Check policy - PyObject *model_def = PyDict_GetItemString(PyDict_GetItemString(py_core, "models"), model); - PyObject *method_def = PyDict_GetItemString(model_def, method); - char *signature = script_signature(model, method, 1); + PyObject* model_def = PyDict_GetItemString(PyDict_GetItemString(py_core, "models"), model); + PyObject* method_def = PyDict_GetItemString(model_def, method); + char* signature = script_signature(model, method, 1); if (PyDict_GetItemString(model_def, method) != Py_None) { - const char *action_id = PyUnicode_AsUTF8(PyTuple_GetItem(method_def, 1)); - const char *sender = dbus_message_get_sender(my_proc.bus_msg); + const char* action_id = PyUnicode_AsUTF8(PyTuple_GetItem(method_def, 1)); + const char* sender = dbus_message_get_sender(my_proc.bus_msg); if (strcmp(action_id, "") != 0) { int result; @@ -83,8 +82,7 @@ message_execute(DBusMessage *msg, const char *app, const char *model, const char bus_reply_error(msg, "Comar.PolicyKit", action_id); return; } - } - else { + } else { bus_reply_error(msg, "Comar.PolicyKit", "error"); return; } @@ -93,91 +91,83 @@ message_execute(DBusMessage *msg, const char *app, const char *model, const char // Execute method switch (py_execute(app, model, method, py_args, &py_ret)) { - case 0: - // Success - bus_reply_object(msg, py_ret, signature); - break; - case -1: - case -2: - // Python exception raised - py_catch(&eStr, &vStr, 1); - bus_reply_error(msg, eStr, vStr); - break; - case -3: - case -4: - // PolicyKit exception raised - py_catch(&eStr, &vStr, 0); - bus_reply_error(msg, eStr, vStr); - break; + case 0: + // Success + bus_reply_object(msg, py_ret, signature); + break; + case -1: + case -2: + // Python exception raised + py_catch(&eStr, &vStr, 1); + bus_reply_error(msg, eStr, vStr); + break; + case -3: + case -4: + // PolicyKit exception raised + py_catch(&eStr, &vStr, 0); + bus_reply_error(msg, eStr, vStr); + break; } } //! Handles a DBus message and executes related script -void -handle_message(DBusMessage *msg) +void handle_message(DBusMessage* msg) { Py_Initialize(); - const char *method = dbus_message_get_member(msg); - const char *iface = dbus_message_get_interface(msg); - const char *path = dbus_message_get_path(msg); + const char* method = dbus_message_get_member(msg); + const char* iface = dbus_message_get_interface(msg); + const char* path = dbus_message_get_path(msg); if (method == NULL || path == NULL || method == NULL) { bus_reply_unknown_method(msg); - } - else if (strcmp("org.freedesktop.DBus.Introspectable", iface) == 0 && strcmp("Introspect", method) == 0) { + } else if (strcmp("org.freedesktop.DBus.Introspectable", iface) == 0 && strcmp("Introspect", method) == 0) { // Introspection method message_execute(msg, NULL, "Core", "introspect"); - } - else if (strcmp(config_interface, iface) == 0) { + } else if (strcmp(config_interface, iface) == 0) { // Core methods message_execute(msg, NULL, "Core", method); - } - else if (strncmp(config_interface, iface, strlen(config_interface)) == 0 && iface[strlen(config_interface)] == '.') { + } else if (strncmp(config_interface, iface, strlen(config_interface)) == 0 && iface[strlen(config_interface)] == '.') { // Model.method - char *model = strsub(iface, strlen(config_interface) + 1, strlen(iface)); - char *app = strsub(path, strlen("/package/"), strlen(path)); + char* model = strsub(iface, strlen(config_interface) + 1, strlen(iface)); + char* app = strsub(path, strlen("/package/"), strlen(path)); message_execute(msg, app, model, method); free(model); free(app); - } - else { + } else { bus_reply_unknown_method(msg); } Py_Finalize(); } -void -handle_core_message(DBusMessage *bus_msg, const char *path, const char *iface, const char *method, const char *sender, PyObject *py_args) +void handle_core_message(DBusMessage* bus_msg, const char* path, const char* iface, const char* method, const char* sender, PyObject* py_args) { if (strcmp(method, "setLocale") == 0) { PyDict_SetItemString(PyDict_GetItemString(py_core, "locales"), sender, PyTuple_GetItem(py_args, 0)); bus_reply_object(bus_msg, Py_True, "b"); - } - else if (strcmp(method, "cancel") == 0) { + } else if (strcmp(method, "cancel") == 0) { log_debug("Cancel requested.\n"); int i; int total = 0; // Iterate over all child processes for (i = 0; i < my_proc.nr_children; i++) { - struct ProcChild *child = &my_proc.children[i]; + struct ProcChild* child = &my_proc.children[i]; if (dbus_message_has_sender(child->bus_msg, sender)) { kill(child->pid, SIGINT); total++; } } log_debug("Killed %d processes.\n", total); - bus_reply_object(bus_msg, PyLong_FromLong((long) total), "i"); - } - else if (strcmp(method, "listRunning") == 0) { + bus_reply_object(bus_msg, PyLong_FromLong((long)total), "i"); + } else if (strcmp(method, "listRunning") == 0) { int i; - PyObject *py_list = PyList_New(0); + PyObject* py_list = PyList_New(0); // Iterate over all child processes for (i = 0; i < my_proc.nr_children; i++) { - struct ProcChild *child = &my_proc.children[i]; + struct ProcChild* child = &my_proc.children[i]; if (PyTuple_GetItem(py_args, 0) == Py_True || dbus_message_has_sender(child->bus_msg, sender)) { PyList_Append(py_list, PyUnicode_FromFormat("%s.%s", dbus_message_get_interface(child->bus_msg), dbus_message_get_member(child->bus_msg))); } @@ -187,14 +177,14 @@ handle_core_message(DBusMessage *bus_msg, const char *path, const char *iface, c } static DBusHandlerResult -filter_func(DBusConnection *conn, DBusMessage *bus_msg, void *data) +filter_func(DBusConnection* conn, DBusMessage* bus_msg, void* data) { - const char *method = dbus_message_get_member(bus_msg); - const char *iface = dbus_message_get_interface(bus_msg); - const char *sender = dbus_message_get_sender(bus_msg); - const char *path = dbus_message_get_path(bus_msg); + const char* method = dbus_message_get_member(bus_msg); + const char* iface = dbus_message_get_interface(bus_msg); + const char* sender = dbus_message_get_sender(bus_msg); + const char* path = dbus_message_get_path(bus_msg); - PyObject *py_args = pydbus_import(bus_msg); + PyObject* py_args = pydbus_import(bus_msg); if (!dbus_message_has_destination(bus_msg, config_unique_address) && strncmp(dbus_message_get_destination(bus_msg), DBUS_SERVICE_NAME, strlen(DBUS_SERVICE_NAME))) { @@ -202,37 +192,34 @@ filter_func(DBusConnection *conn, DBusMessage *bus_msg, void *data) } switch (dbus_message_get_type(bus_msg)) { - case DBUS_MESSAGE_TYPE_METHOD_CALL: - if (my_proc.nr_children > MAX_PROC) { - // Busy - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - else { - log_debug("Got message '%s.%s' from '%s'\n", iface, method, sender); - if (strcmp(config_interface, iface) == 0 && strcmp(path, "/") == 0) { - // "setLocale" and "cancel" methods are handled in main process - if (strcmp(method, "setLocale") == 0 || strcmp(method, "cancel") == 0 || strcmp(method, "listRunning") == 0) { - handle_core_message(bus_msg, path, iface, method, sender, py_args); - } - else { - // Else, handle in child process - proc_fork(handle_message, bus_msg); - } - } - else { + case DBUS_MESSAGE_TYPE_METHOD_CALL: + if (my_proc.nr_children > MAX_PROC) { + // Busy + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } else { + log_debug("Got message '%s.%s' from '%s'\n", iface, method, sender); + if (strcmp(config_interface, iface) == 0 && strcmp(path, "/") == 0) { + // "setLocale" and "cancel" methods are handled in main process + if (strcmp(method, "setLocale") == 0 || strcmp(method, "cancel") == 0 || strcmp(method, "listRunning") == 0) { + handle_core_message(bus_msg, path, iface, method, sender, py_args); + } else { // Else, handle in child process proc_fork(handle_message, bus_msg); } - break; + } else { + // Else, handle in child process + proc_fork(handle_message, bus_msg); } - case DBUS_MESSAGE_TYPE_SIGNAL: - log_debug("Got signal '%s.%s' from '%s'\n", iface, method, sender); break; + } + case DBUS_MESSAGE_TYPE_SIGNAL: + log_debug("Got signal '%s.%s' from '%s'\n", iface, method, sender); + break; } return DBUS_HANDLER_RESULT_HANDLED; } -static dbus_bool_t add_watch(DBusWatch *watch, void *data) +static dbus_bool_t add_watch(DBusWatch* watch, void* data) { short cond = POLLHUP | POLLERR; int fd = dbus_watch_get_unix_fd(watch); @@ -251,7 +238,7 @@ static dbus_bool_t add_watch(DBusWatch *watch, void *data) return 1; } -static void remove_watch(DBusWatch *watch, void *data) +static void remove_watch(DBusWatch* watch, void* data) { int i, found = 0; @@ -262,17 +249,18 @@ static void remove_watch(DBusWatch *watch, void *data) } } if (!found) { - log_error("Missing DBus watch: %p\n", (void *) watch); + log_error("Missing DBus watch: %p\n", (void*)watch); return; } memset(&bus_fds[i], 0, sizeof(bus_fds[i])); bus_watches[i] = NULL; - if (i == bus_nr_watches && bus_nr_watches > 0) --bus_nr_watches; + if (i == bus_nr_watches && bus_nr_watches > 0) + --bus_nr_watches; } -static void fd_handler(short events, DBusWatch *watch) +static void fd_handler(short events, DBusWatch* watch) { unsigned int flags = 0; @@ -291,13 +279,13 @@ static void fd_handler(short events, DBusWatch *watch) } dbus_connection_ref(bus_conn); - while (dbus_connection_dispatch(bus_conn) == DBUS_DISPATCH_DATA_REMAINS); + while (dbus_connection_dispatch(bus_conn) == DBUS_DISPATCH_DATA_REMAINS) + ; dbus_connection_unref(bus_conn); } //! Main loop -int -loop_exec() +int loop_exec() { /*! * This is the main loop function. @@ -358,11 +346,12 @@ loop_exec() /* This clears any pending messages avoiding weird timeouts on some systems * with dbus >= 1.2.22 */ - while (dbus_connection_dispatch(bus_conn) == DBUS_DISPATCH_DATA_REMAINS); + while (dbus_connection_dispatch(bus_conn) == DBUS_DISPATCH_DATA_REMAINS) + ; while (1) { struct pollfd fds[MAX_FDS]; - DBusWatch *watches[MAX_WATCHES]; + DBusWatch* watches[MAX_WATCHES]; int i, j; int nr_fds = 0; int nr_watches = 0; @@ -401,8 +390,7 @@ loop_exec() if (config_timeout == 0) { // If no timeout defined, wait forever. poll_result = poll(fds, nr_fds, -1); - } - else { + } else { // wait seconds poll_result = poll(fds, nr_fds, config_timeout * 1000); } @@ -413,8 +401,7 @@ loop_exec() break; } continue; - } - else if (poll_result < 0) { + } else if (poll_result < 0) { perror("poll"); return -1; } diff --git a/src/pydbus.c b/src/pydbus.c index 1190605..b7ff2e2 100644 --- a/src/pydbus.c +++ b/src/pydbus.c @@ -25,12 +25,11 @@ */ #include "pydbus.h" -#include "utils.h" #include "script.h" +#include "utils.h" //! Returns DBus object type of a Python object -char * -get_obj_sign(PyObject *obj) +char* get_obj_sign(PyObject* obj) { /*! * Returns DBus object type of a Python object. @@ -40,39 +39,30 @@ get_obj_sign(PyObject *obj) * */ - if (PyUnicode_Check(obj) || PyUnicode_Check(obj)) { + if (/*PyString_Check(obj) || */ PyUnicode_Check(obj)) { return "s"; - } - else if (PyBool_Check(obj)) { + } else if (PyBool_Check(obj)) { return "b"; - } - else if (PyLong_Check(obj)) { + } else if (PyLong_Check(obj)) { return "i"; - } - else if (PyLong_Check(obj)) { + } else if (PyLong_Check(obj)) { return "x"; - } - else if (PyFloat_Check(obj)) { + } else if (PyFloat_Check(obj)) { return "d"; - } - else if (PyList_Check(obj)) { + } else if (PyList_Check(obj)) { return "a"; - } - else if (PyTuple_Check(obj)) { + } else if (PyTuple_Check(obj)) { return "r"; - } - else if (PyDict_Check(obj)) { + } else if (PyDict_Check(obj)) { return "D"; - } - else if (obj == Py_None) { + } else if (obj == Py_None) { return "N"; } return "?"; } //! Appends a Python tuple to a DBus message iterator -int -pydbus_export(DBusMessageIter *iter, PyObject *obj, char *signature) +int pydbus_export(DBusMessageIter* iter, PyObject* obj, char* signature) { /*! * Appends a Python tuple to a DBus message iterator. @@ -90,12 +80,11 @@ pydbus_export(DBusMessageIter *iter, PyObject *obj, char *signature) } // Check signature and tuple size - PyObject *py_list = script_signature_each(signature); + PyObject* py_list = script_signature_each(signature); if (py_list == NULL) { PyErr_SetString(PyExc_COMAR_Invalid, "Method signature is invalid."); return -1; - } - else if (PyList_Size(py_list) != PyTuple_Size(obj)) { + } else if (PyList_Size(py_list) != PyTuple_Size(obj)) { PyErr_SetString(PyExc_COMAR_Invalid, "Method signature does not match with object."); return -1; } @@ -103,8 +92,8 @@ pydbus_export(DBusMessageIter *iter, PyObject *obj, char *signature) // Append tuple's items to DBus message int i; for (i = 0; i < PyTuple_Size(obj); i++) { - PyObject *py_sign = PyList_GetItem(py_list, i); - PyObject *py_item = PyTuple_GetItem(obj, i); + PyObject* py_sign = PyList_GetItem(py_list, i); + PyObject* py_item = PyTuple_GetItem(obj, i); if (pydbus_export_item(iter, py_item, PyUnicode_AsUTF8(py_sign)) != 0) { return -1; } @@ -114,8 +103,7 @@ pydbus_export(DBusMessageIter *iter, PyObject *obj, char *signature) } //! Appends a Python object to a DBus message iterator -int -pydbus_export_item(DBusMessageIter *iter, PyObject *obj, char *signature) +int pydbus_export_item(DBusMessageIter* iter, PyObject* obj, char* signature) { /*! * Appends a Python object to a DBus message iterator @@ -128,20 +116,20 @@ pydbus_export_item(DBusMessageIter *iter, PyObject *obj, char *signature) */ DBusMessageIter sub, sub_dict; - char *sign_content = NULL; - char *sign_subcontent = NULL; - char *sign_key = NULL; - char *sign_value = NULL; - PyObject *item = NULL; - PyObject *key = NULL; - PyObject *value = NULL; + char* sign_content = NULL; + char* sign_subcontent = NULL; + char* sign_key = NULL; + char* sign_value = NULL; + PyObject* item = NULL; + PyObject* key = NULL; + PyObject* value = NULL; int e = 0; int i = 0; Py_ssize_t pos = 0; union { - const char *s; + const char* s; dbus_bool_t b; dbus_int16_t i16; dbus_uint16_t u16; @@ -152,175 +140,168 @@ pydbus_export_item(DBusMessageIter *iter, PyObject *obj, char *signature) } p; switch (signature[0]) { - case 'a': - // A list or dictionary object found - - // Find signature of content - sign_subcontent = strsub(signature, 1, strlen(signature)); - if (!sign_subcontent) { - e = 0; - break; - } + case 'a': + // A list or dictionary object found + + // Find signature of content + sign_subcontent = strsub(signature, 1, strlen(signature)); + if (!sign_subcontent) { + e = 0; + break; + } + + // Open a container + e = dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, sign_subcontent, &sub); + if (!e) + break; - // Open a container - e = dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, sign_subcontent, &sub); - if (!e) break; - - // Oh, this is not a list, a dictionary instead. - // a{??} means dictionary, not list of dictionaries - if (sign_subcontent[0] == '{') { - // Get key and value signatures - sign_key = strsub(signature, 2, 3); - sign_value = strsub(signature, 3, strlen(signature) - 1); - pos = 0; // Go to first index - while (PyDict_Next(obj, &pos, &key, &value)) { - e = dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub_dict); - if (pydbus_export_item(&sub_dict, key, sign_key) != 0 || pydbus_export_item(&sub_dict, value, sign_value) != 0) { - return -1; - } - dbus_message_iter_close_container(&sub, &sub_dict); + // Oh, this is not a list, a dictionary instead. + // a{??} means dictionary, not list of dictionaries + if (sign_subcontent[0] == '{') { + // Get key and value signatures + sign_key = strsub(signature, 2, 3); + sign_value = strsub(signature, 3, strlen(signature) - 1); + pos = 0; // Go to first index + while (PyDict_Next(obj, &pos, &key, &value)) { + e = dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub_dict); + if (pydbus_export_item(&sub_dict, key, sign_key) != 0 || pydbus_export_item(&sub_dict, value, sign_value) != 0) { + return -1; } + dbus_message_iter_close_container(&sub, &sub_dict); } - else { - // This is a list. Append items to message - for (i = 0; i < PyList_Size(obj); i++) { - item = PyList_GetItem(obj, i); - if (pydbus_export_item(&sub, item, sign_subcontent) != 0) { - return -1; - } + } else { + // This is a list. Append items to message + for (i = 0; i < PyList_Size(obj); i++) { + item = PyList_GetItem(obj, i); + if (pydbus_export_item(&sub, item, sign_subcontent) != 0) { + return -1; } } - dbus_message_iter_close_container(iter, &sub); - free(sign_subcontent); + } + dbus_message_iter_close_container(iter, &sub); + free(sign_subcontent); + break; + case '(': + // A tuple found + + // Find signature of content + sign_content = strsub(signature, 1, strlen(signature) - 1); + if (!sign_content) { + e = 0; break; - case '(': - // A tuple found - - // Find signature of content - sign_content = strsub(signature, 1, strlen(signature) - 1); - if (!sign_content) { - e = 0; - break; - } + } - // Open a container - e = dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL, &sub); - if (!e) break; + // Open a container + e = dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL, &sub); + if (!e) + break; - // Append items to message - if (pydbus_export(&sub, obj, sign_content) != 0) { - free(sign_content); - return -1; - } + // Append items to message + if (pydbus_export(&sub, obj, sign_content) != 0) { free(sign_content); - dbus_message_iter_close_container(iter, &sub); - break; - case 'b': - if (PyBool_Check(obj)) { - p.b = (obj == Py_True) ? 1 :0; - } - else { - // TODO: Raise error - p.b = 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &p.b); - break; - case 'n': - if (PyLong_Check(obj)) { - p.i16 = (short) PyLong_AsLong(obj); - } - else { - // TODO: Raise error - p.i16 = (short) 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT16, &p.i16); - break; - case 'q': - if (PyLong_Check(obj)) { - p.u16 = (unsigned short) PyLong_AsLong(obj); - } - else { - // TODO: Raise error - p.u16 = (unsigned short) 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &p.u16); - break; - case 'i': - if (PyLong_Check(obj)) { - p.i32 = (int) PyLong_AsLong(obj); - } - else { - // TODO: Raise error - p.i32 = 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT32, &p.i32); - break; - case 'u': - if (PyLong_Check(obj)) { - p.u32 = (long) PyLong_AsLong(obj); - } - else { - // TODO: Raise error - p.u32 = 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT32, &p.u32); - break; - case 'x': - if (PyLong_Check(obj)) { - p.i64 = (long) PyLong_AsLong(obj); - } - else { - // TODO: Raise error - p.i64 = 0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT64, &p.i64); - break; - case 't': - // TODO: Long long support - break; - case 'd': - if (PyFloat_Check(obj)) { - p.d = PyFloat_AsDouble(obj); - } - else { - // TODO: Raise error - p.d = 0.0; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_DOUBLE, &p.d); - break; - case 's': - if (PyUnicode_Check(obj)) { - p.s = PyUnicode_AsUTF8(obj); - } - else { - // TODO: Raise error - p.s = ""; - } - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &p.s); - break; - case 'o': - // TODO: Object path - break; - case 'g': - // TODO: Type signature - break; - case 'v': - sign_content = get_obj_sign(obj); - if (strstr(TYPES_BASIC, sign_content) == NULL) { - PyErr_SetString(PyExc_COMAR_Invalid, "Aboo Variant content must be single typed."); - return -1; - } - e = dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, sign_content, &sub); - if (pydbus_export_item(&sub, obj, sign_content) != 0) { - return -1; - } - dbus_message_iter_close_container(iter, &sub); - break; - case 'N': - // TODO: Remove + return -1; + } + free(sign_content); + dbus_message_iter_close_container(iter, &sub); + break; + case 'b': + if (PyBool_Check(obj)) { + p.b = (obj == Py_True) ? 1 : 0; + } else { + // TODO: Raise error + p.b = 0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &p.b); + break; + case 'n': + if (PyLong_Check(obj)) { + p.i16 = (short)PyLong_AsLong(obj); + } else { + // TODO: Raise error + p.i16 = (short)0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT16, &p.i16); + break; + case 'q': + if (PyLong_Check(obj)) { + p.u16 = (unsigned short)PyLong_AsLong(obj); + } else { + // TODO: Raise error + p.u16 = (unsigned short)0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &p.u16); + break; + case 'i': + if (PyLong_Check(obj)) { + p.i32 = (int)PyLong_AsLong(obj); + } else { + // TODO: Raise error + p.i32 = 0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT32, &p.i32); + break; + case 'u': + if (PyLong_Check(obj)) { + p.u32 = (long)PyLong_AsLong(obj); + } else { + // TODO: Raise error + p.u32 = 0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT32, &p.u32); + break; + case 'x': + if (PyLong_Check(obj)) { + p.i64 = (long)PyLong_AsLong(obj); + } else { + // TODO: Raise error + p.i64 = 0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_INT64, &p.i64); + break; + case 't': + // TODO: Long long support + break; + case 'd': + if (PyFloat_Check(obj)) { + p.d = PyFloat_AsDouble(obj); + } else { + // TODO: Raise error + p.d = 0.0; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_DOUBLE, &p.d); + break; + case 's': + if (PyUnicode_Check(obj)) { + p.s = PyUnicode_AsUTF8(obj); + } else { + // TODO: Raise error p.s = ""; - e = dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &p.s); - break; + } + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &p.s); + break; + case 'o': + // TODO: Object path + break; + case 'g': + // TODO: Type signature + break; + case 'v': + sign_content = get_obj_sign(obj); + if (strstr(TYPES_BASIC, sign_content) == NULL) { + PyErr_SetString(PyExc_COMAR_Invalid, "Aboo Variant content must be single typed."); + return -1; + } + e = dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, sign_content, &sub); + if (pydbus_export_item(&sub, obj, sign_content) != 0) { + return -1; + } + dbus_message_iter_close_container(iter, &sub); + break; + case 'N': + // TODO: Remove + p.s = ""; + e = dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &p.s); + break; } if (!e) { @@ -333,7 +314,7 @@ pydbus_export_item(DBusMessageIter *iter, PyObject *obj, char *signature) // IMPORT -PyObject * +PyObject* py_get_item(DBusMessageIter* iter) { /*! @@ -345,7 +326,7 @@ py_get_item(DBusMessageIter* iter) */ union { - const char *s; + const char* s; unsigned char y; dbus_bool_t b; double d; @@ -357,84 +338,83 @@ py_get_item(DBusMessageIter* iter) dbus_int64_t i64; } obj; - PyObject *ret = NULL; + PyObject* ret = NULL; DBusMessageIter sub; int type = 0; type = dbus_message_iter_get_arg_type(iter); switch (type) { - case DBUS_TYPE_BYTE: - dbus_message_iter_get_basic(iter, &obj.y); - ret = Py_BuildValue("i", (int)obj.y); - break; - case DBUS_TYPE_STRING: - case DBUS_TYPE_OBJECT_PATH: - case DBUS_TYPE_SIGNATURE: - dbus_message_iter_get_basic(iter, &obj.s); - ret = Py_BuildValue("s", obj.s); - // ret = Py_BuildValue("N", PyUnicode_DecodeUTF8(obj.s, strlen(obj.s), NULL)); - break; - case DBUS_TYPE_DOUBLE: - dbus_message_iter_get_basic(iter, &obj.d); - ret = Py_BuildValue("f", obj.d); - break; - case DBUS_TYPE_INT16: - dbus_message_iter_get_basic(iter, &obj.i16); - ret = Py_BuildValue("i", (int)obj.i16); - break; - case DBUS_TYPE_UINT16: - dbus_message_iter_get_basic(iter, &obj.u16); - ret = Py_BuildValue("i", (int)obj.u16); - break; - case DBUS_TYPE_INT32: - dbus_message_iter_get_basic(iter, &obj.i32); - ret = Py_BuildValue("l", (long)obj.i32); - break; - case DBUS_TYPE_UINT32: - dbus_message_iter_get_basic(iter, &obj.u32); - ret = Py_BuildValue("k", (unsigned long)obj.u32); - break; - case DBUS_TYPE_INT64: - dbus_message_iter_get_basic(iter, &obj.i64); - ret = Py_BuildValue("L", (PY_LONG_LONG)obj.i64); - break; - case DBUS_TYPE_UINT64: - dbus_message_iter_get_basic(iter, &obj.u64); - ret = Py_BuildValue("K", (PY_LONG_LONG)obj.u64); - break; - case DBUS_TYPE_BOOLEAN: - dbus_message_iter_get_basic(iter, &obj.b); - ret = (long)obj.b == 1 ? PyBool_FromLong(1) : PyBool_FromLong(0); - break; - case DBUS_TYPE_DICT_ENTRY: - break; - case DBUS_TYPE_ARRAY: - type = dbus_message_iter_get_element_type(iter); - if (type == DBUS_TYPE_DICT_ENTRY) { - dbus_message_iter_recurse(iter, &sub); - ret = py_get_dict(&sub); - } - else { - dbus_message_iter_recurse(iter, &sub); - ret = py_get_list(&sub); - } - break; - case DBUS_TYPE_STRUCT: + case DBUS_TYPE_BYTE: + dbus_message_iter_get_basic(iter, &obj.y); + ret = Py_BuildValue("i", (int)obj.y); + break; + case DBUS_TYPE_STRING: + case DBUS_TYPE_OBJECT_PATH: + case DBUS_TYPE_SIGNATURE: + dbus_message_iter_get_basic(iter, &obj.s); + ret = Py_BuildValue("s", obj.s); + // ret = Py_BuildValue("N", PyUnicode_DecodeUTF8(obj.s, strlen(obj.s), NULL)); + break; + case DBUS_TYPE_DOUBLE: + dbus_message_iter_get_basic(iter, &obj.d); + ret = Py_BuildValue("f", obj.d); + break; + case DBUS_TYPE_INT16: + dbus_message_iter_get_basic(iter, &obj.i16); + ret = Py_BuildValue("i", (int)obj.i16); + break; + case DBUS_TYPE_UINT16: + dbus_message_iter_get_basic(iter, &obj.u16); + ret = Py_BuildValue("i", (int)obj.u16); + break; + case DBUS_TYPE_INT32: + dbus_message_iter_get_basic(iter, &obj.i32); + ret = Py_BuildValue("l", (long)obj.i32); + break; + case DBUS_TYPE_UINT32: + dbus_message_iter_get_basic(iter, &obj.u32); + ret = Py_BuildValue("k", (unsigned long)obj.u32); + break; + case DBUS_TYPE_INT64: + dbus_message_iter_get_basic(iter, &obj.i64); + ret = Py_BuildValue("L", (long long)obj.i64); + break; + case DBUS_TYPE_UINT64: + dbus_message_iter_get_basic(iter, &obj.u64); + ret = Py_BuildValue("K", (long long)obj.u64); + break; + case DBUS_TYPE_BOOLEAN: + dbus_message_iter_get_basic(iter, &obj.b); + ret = (long)obj.b == 1 ? PyBool_FromLong(1) : PyBool_FromLong(0); + break; + case DBUS_TYPE_DICT_ENTRY: + break; + case DBUS_TYPE_ARRAY: + type = dbus_message_iter_get_element_type(iter); + if (type == DBUS_TYPE_DICT_ENTRY) { dbus_message_iter_recurse(iter, &sub); - ret = PyList_AsTuple(py_get_list(&sub)); - break; - case DBUS_TYPE_VARIANT: + ret = py_get_dict(&sub); + } else { dbus_message_iter_recurse(iter, &sub); - type = dbus_message_iter_get_arg_type(&sub); - ret = py_get_item(&sub); - break; + ret = py_get_list(&sub); + } + break; + case DBUS_TYPE_STRUCT: + dbus_message_iter_recurse(iter, &sub); + ret = PyList_AsTuple(py_get_list(&sub)); + break; + case DBUS_TYPE_VARIANT: + dbus_message_iter_recurse(iter, &sub); + type = dbus_message_iter_get_arg_type(&sub); + ret = py_get_item(&sub); + break; } return ret; } -PyObject * -py_get_dict(DBusMessageIter *iter) +PyObject* +py_get_dict(DBusMessageIter* iter) { /*! * Extracts Python dict object from a D-Bus message iterator. @@ -444,9 +424,9 @@ py_get_dict(DBusMessageIter *iter) * */ - PyObject *dict = NULL; - PyObject *key = NULL; - PyObject *value = NULL; + PyObject* dict = NULL; + PyObject* key = NULL; + PyObject* value = NULL; dict = PyDict_New(); @@ -478,8 +458,8 @@ py_get_dict(DBusMessageIter *iter) return dict; } -PyObject * -py_get_tuple(DBusMessageIter *iter) +PyObject* +py_get_tuple(DBusMessageIter* iter) { /*! * Extracts Python tuple object from a D-Bus message iterator. @@ -490,7 +470,7 @@ py_get_tuple(DBusMessageIter *iter) */ int type = 0; - PyObject *list = NULL; + PyObject* list = NULL; list = PyList_New(0); @@ -501,8 +481,8 @@ py_get_tuple(DBusMessageIter *iter) return PyList_AsTuple(list); } -PyObject * -py_get_list(DBusMessageIter *iter) +PyObject* +py_get_list(DBusMessageIter* iter) { /*! * Extracts Python list object from a D-Bus message iterator. @@ -513,7 +493,7 @@ py_get_list(DBusMessageIter *iter) */ int type = 0; - PyObject *list = NULL; + PyObject* list = NULL; list = PyList_New(0); @@ -524,8 +504,8 @@ py_get_list(DBusMessageIter *iter) return list; } -PyObject * -pydbus_import(DBusMessage *msg) +PyObject* +pydbus_import(DBusMessage* msg) { /*! * Extracts Python object from D-Bus message. diff --git a/src/script.c b/src/script.c index a1cafed..97dc7dc 100644 --- a/src/script.c +++ b/src/script.c @@ -24,11 +24,11 @@ * */ +#include "script.h" #include "bus.h" #include "config.h" #include "db.h" #include "log.h" -#include "script.h" #include "policy.h" #include "process.h" #include "utils.h" @@ -36,19 +36,18 @@ #include //! Core dictionary -PyObject *py_core; +PyObject* py_core; //! Exceptions -PyObject *PyExc_COMAR_Internal; -PyObject *PyExc_COMAR_Invalid; -PyObject *PyExc_COMAR_Script; -PyObject *PyExc_COMAR_Missing; -PyObject *PyExc_DBus; -PyObject *PyExc_PolicyKit; +PyObject* PyExc_COMAR_Internal; +PyObject* PyExc_COMAR_Invalid; +PyObject* PyExc_COMAR_Script; +PyObject* PyExc_COMAR_Missing; +PyObject* PyExc_DBus; +PyObject* PyExc_PolicyKit; //! Initializes Python VM -int -script_init() +int script_init() { Py_InitializeEx(0); @@ -61,7 +60,7 @@ script_init() PyExc_PolicyKit = PyErr_NewException("Comar.PolicyKit", NULL, NULL); // Load model definitions - PyObject *py_models; + PyObject* py_models; if (db_load_models(&py_models) != 0) { return -1; } @@ -83,15 +82,13 @@ script_init() } //! Finalizes Python VM -void -script_finalize() +void script_finalize() { Py_Finalize(); } //! Returns method's signature -char * -script_signature(const char *model, const char *member, int direction) +char* script_signature(const char* model, const char* member, int direction) { /*! * Returns method's signature @@ -103,47 +100,45 @@ script_signature(const char *model, const char *member, int direction) * */ - PyObject *py_models = PyDict_GetItemString(py_core, "models"); - PyObject *py_model = PyDict_GetItemString(py_models, model); - PyObject *py_method = PyDict_GetItemString(py_model, member); - PyObject *py_str = PyUnicode_FromString(""); - PyObject *py_list; + PyObject* py_models = PyDict_GetItemString(py_core, "models"); + PyObject* py_model = PyDict_GetItemString(py_models, model); + PyObject* py_method = PyDict_GetItemString(py_model, member); + PyObject* py_str = PyUnicode_FromString(""); + PyObject* py_list; if (direction == 0) { py_list = PyTuple_GetItem(py_method, 2); - } - else { + } else { py_list = PyTuple_GetItem(py_method, 3); } int i; for (i = 0; i < PyList_Size(py_list); i++) { - PyUnicode_Concat(py_str, PyList_GetItem(py_list, i)); + py_str = PyUnicode_Concat(py_str, PyList_GetItem(py_list, i)); } return PyUnicode_AsUTF8(py_str); } //! Splits signature into atomic DBus object signatures -PyObject * -script_signature_each(const char *signature) +PyObject* +script_signature_each(const char* signature) { - PyObject *py_list = PyList_New(0); + PyObject* py_list = PyList_New(0); DBusError error; DBusSignatureIter iter; dbus_signature_iter_init(&iter, signature); while (dbus_signature_iter_get_current_type(&iter) != DBUS_TYPE_INVALID) { - char *sign = dbus_signature_iter_get_signature(&iter); + char* sign = dbus_signature_iter_get_signature(&iter); dbus_error_init(&error); dbus_signature_validate(sign, &error); if (dbus_error_is_set(&error)) { dbus_error_free(&error); return NULL; - } - else { + } else { PyList_Append(py_list, PyUnicode_FromString(sign)); } @@ -155,8 +150,7 @@ script_signature_each(const char *signature) } //! Catches raised Python exceptions -void -py_catch(char **eStr, char **vStr, int log) +void py_catch(char** eStr, char** vStr, int log) { /*! * Catches a Python exception. @@ -196,14 +190,14 @@ py_catch(char **eStr, char **vStr, int log) py_frame = PyObject_GetAttrString(py_trace, "tb_frame"); py_code = PyObject_GetAttrString(py_frame, "f_code"); log_error(" File %s, line %d, in %s()\n", PyUnicode_AsUTF8(PyObject_GetAttrString(py_code, "co_filename")), - (int) PyLong_AsLong(PyObject_GetAttrString(py_trace, "tb_lineno")), - PyUnicode_AsUTF8(PyObject_GetAttrString(py_code, "co_name"))); + (int)PyLong_AsLong(PyObject_GetAttrString(py_trace, "tb_lineno")), + PyUnicode_AsUTF8(PyObject_GetAttrString(py_code, "co_name"))); py_trace = PyObject_GetAttrString(py_trace, "tb_next"); } } //! Returns sender's locale -const char * +const char* sender_language() { /*! @@ -213,14 +207,13 @@ sender_language() * */ - const char *sender = dbus_message_get_sender(my_proc.bus_msg); - PyObject *py_locales = PyDict_GetItemString(py_core, "locales"); - const char *lang; + const char* sender = dbus_message_get_sender(my_proc.bus_msg); + PyObject* py_locales = PyDict_GetItemString(py_core, "locales"); + const char* lang; if (PyDict_Contains(py_locales, PyUnicode_FromString(sender))) { lang = PyUnicode_AsUTF8(PyDict_GetItemString(py_locales, sender)); - } - else { + } else { lang = "en"; } @@ -228,8 +221,7 @@ sender_language() } //! Tells if model.member is defined in model database -int -validate_model_member(const char *model, const char *member, int type) +int validate_model_member(const char* model, const char* member, int type) { /*! * Tells if model.member is defined in model database. @@ -242,10 +234,10 @@ validate_model_member(const char *model, const char *member, int type) */ if (PyDict_Contains(PyDict_GetItemString(py_core, "models"), PyUnicode_FromString(model))) { - PyObject *py_dict_model = PyDict_GetItemString(PyDict_GetItemString(py_core, "models"), model); + PyObject* py_dict_model = PyDict_GetItemString(PyDict_GetItemString(py_core, "models"), model); if (PyDict_Contains(py_dict_model, PyUnicode_FromString(member))) { - PyObject *py_tuple = PyDict_GetItemString(py_dict_model, member); - if (PyLong_AsLong(PyTuple_GetItem(py_tuple, 0)) == (long) type) { + PyObject* py_tuple = PyDict_GetItemString(py_dict_model, member); + if (PyLong_AsLong(PyTuple_GetItem(py_tuple, 0)) == (long)type) { return 0; } } @@ -254,54 +246,53 @@ validate_model_member(const char *model, const char *member, int type) } //! Returns DBus message path, used in scripts -static PyObject * -c_bus_path(PyObject *self, PyObject *args) +static PyObject* +c_bus_path(PyObject* self, PyObject* args) { - const char *path = dbus_message_get_path(my_proc.bus_msg); - PyObject *py_str = PyUnicode_FromString(path); + const char* path = dbus_message_get_path(my_proc.bus_msg); + PyObject* py_str = PyUnicode_FromString(path); Py_INCREF(py_str); - printf("%s\n", py_str); return py_str; } //! Returns DBus message interface, used in scripts -static PyObject * -c_bus_interface(PyObject *self, PyObject *args) +static PyObject* +c_bus_interface(PyObject* self, PyObject* args) { - const char *iface = dbus_message_get_interface(my_proc.bus_msg); - PyObject *py_str = PyUnicode_FromString(iface); + const char* iface = dbus_message_get_interface(my_proc.bus_msg); + PyObject* py_str = PyUnicode_FromString(iface); Py_INCREF(py_str); return py_str; } //! Returns DBus message member, used in scripts -static PyObject * -c_bus_member(PyObject *self, PyObject *args) +static PyObject* +c_bus_member(PyObject* self, PyObject* args) { - const char *member = dbus_message_get_member(my_proc.bus_msg); - PyObject *py_str = PyUnicode_FromString(member); + const char* member = dbus_message_get_member(my_proc.bus_msg); + PyObject* py_str = PyUnicode_FromString(member); Py_INCREF(py_str); return py_str; } //! Returns DBus message sender, used in scripts -static PyObject * -c_bus_sender(PyObject *self, PyObject *args) +static PyObject* +c_bus_sender(PyObject* self, PyObject* args) { - const char *sender = dbus_message_get_sender(my_proc.bus_msg); - PyObject *py_str = PyUnicode_FromString(sender); + const char* sender = dbus_message_get_sender(my_proc.bus_msg); + PyObject* py_str = PyUnicode_FromString(sender); Py_INCREF(py_str); return py_str; } //! Returns package name, used in scripts -static PyObject * -c_package(PyObject *self, PyObject *args) +static PyObject* +c_package(PyObject* self, PyObject* args) { - const char *path = dbus_message_get_path(my_proc.bus_msg); + const char* path = dbus_message_get_path(my_proc.bus_msg); if (strncmp(path, "/package/", strlen("/package/")) == 0) { - const char *app = strsub(path, strlen("/package/"), strlen(path)); + const char* app = strsub(path, strlen("/package/"), strlen(path)); if (strlen(app) > 0) { return PyUnicode_FromString(app); } @@ -312,13 +303,13 @@ c_package(PyObject *self, PyObject *args) } //! Returns model name, used in scripts -static PyObject * -c_model(PyObject *self, PyObject *args) +static PyObject* +c_model(PyObject* self, PyObject* args) { - const char *iface = dbus_message_get_interface(my_proc.bus_msg); + const char* iface = dbus_message_get_interface(my_proc.bus_msg); if (strncmp(iface, config_interface, strlen(config_interface)) == 0) { - const char *model = strsub(iface, strlen(config_interface) + 1, strlen(iface)); + const char* model = strsub(iface, strlen(config_interface) + 1, strlen(iface)); if (strlen(model) > 0) { return PyUnicode_FromString(model); } @@ -329,35 +320,34 @@ c_model(PyObject *self, PyObject *args) } //! i18n method, used in scripts -static PyObject * -c_i18n(PyObject *self, PyObject *args) +static PyObject* +c_i18n(PyObject* self, PyObject* args) { - PyObject *py_dict; + PyObject* py_dict; if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &py_dict)) { return NULL; } - PyObject *py_lang = PyUnicode_FromString(sender_language()); + PyObject* py_lang = PyUnicode_FromString(sender_language()); if (!PyDict_Contains(py_dict, py_lang)) { py_lang = PyUnicode_FromString("en"); } if (PyDict_Contains(py_dict, py_lang)) { return PyDict_GetItem(py_dict, py_lang); - } - else { + } else { PyErr_Format(PyExc_COMAR_Script, "Script is lack of default ('en') locale string."); return NULL; } } //! Signal emitter method, used in scripts -static PyObject * -c_notify(PyObject *self, PyObject *args) +static PyObject* +c_notify(PyObject* self, PyObject* args) { const char *model, *signal; - PyObject *py_tuple = NULL; + PyObject* py_tuple = NULL; if (!PyArg_ParseTuple(args, "ss|O", &model, &signal, &py_tuple)) { return NULL; @@ -368,14 +358,14 @@ c_notify(PyObject *self, PyObject *args) return NULL; } - const char *path = dbus_message_get_path(my_proc.bus_msg); + const char* path = dbus_message_get_path(my_proc.bus_msg); int size = strlen(config_interface) + 1 + strlen(model) + 1; - char *interface = malloc(size); + char* interface = malloc(size); snprintf(interface, size, "%s.%s", config_interface, model); interface[size - 1] = '\0'; - char *signature = script_signature(model, signal, 1); + char* signature = script_signature(model, signal, 1); if (bus_signal(path, interface, signal, py_tuple, signature) != 0) { free(interface); @@ -389,13 +379,13 @@ c_notify(PyObject *self, PyObject *args) } //! Internal method call method, used in scripts -static PyObject * -c_call(PyObject *self, PyObject *args, PyObject *keywds) +static PyObject* +c_call(PyObject* self, PyObject* args, PyObject* keywds) { const char *app, *model, *method; - PyObject *py_tuple = NULL; + PyObject* py_tuple = NULL; int timeout = -1; - static char *kwlist[] = {"app", "model", "method", "args", "timeout", NULL}; + static char* kwlist[] = { "app", "model", "method", "args", "timeout", NULL }; if (!PyArg_ParseTupleAndKeywords(args, keywds, "sss|Oi", kwlist, &app, &model, &method, &py_tuple, &timeout)) { return NULL; @@ -412,26 +402,26 @@ c_call(PyObject *self, PyObject *args, PyObject *keywds) // Build DBus interface from model name int size = strlen(config_interface) + 1 + strlen(model) + 1; - char *interface = malloc(size); + char* interface = malloc(size); snprintf(interface, size, "%s.%s", config_interface, model); interface[size - 1] = '\0'; // Build DBus path from application name size = strlen("/package/") + strlen(app) + 1; - char *path = malloc(size); + char* path = malloc(size); snprintf(path, size, "/package/%s", app); path[size - 1] = '\0'; log_debug("Internal call: %s.%s %s\n", interface, method, path); // Get language - const char *lang = sender_language(); + const char* lang = sender_language(); // Get signature - char *signature = script_signature(model, method, 0); + char* signature = script_signature(model, method, 0); // Call method - PyObject *ret = bus_call(path, interface, method, py_tuple, timeout, lang, signature); + PyObject* ret = bus_call(path, interface, method, py_tuple, timeout, lang, signature); free(path); free(interface); @@ -440,10 +430,10 @@ c_call(PyObject *self, PyObject *args, PyObject *keywds) } //! Abort method, used in scripts -static PyObject * -c_fail(PyObject *self, PyObject *args) +static PyObject* +c_fail(PyObject* self, PyObject* args) { - const char *strerr; + const char* strerr; if (!PyArg_ParseTuple(args, "s", &strerr)) { return NULL; @@ -454,28 +444,28 @@ c_fail(PyObject *self, PyObject *args) } //! Returns data path, used in scripts -static PyObject * -c_cfg_datapath(PyObject *self, PyObject *args) +static PyObject* +c_cfg_datapath(PyObject* self, PyObject* args) { - PyObject *py_str = PyUnicode_FromString(config_dir_data); + PyObject* py_str = PyUnicode_FromString(config_dir_data); Py_INCREF(py_str); return py_str; } //! Returns model database, used in scripts -static PyObject * -c_cfg_modelbase(PyObject *self, PyObject *args) +static PyObject* +c_cfg_modelbase(PyObject* self, PyObject* args) { - PyObject *py_dict = PyDict_GetItemString(py_core, "models"); + PyObject* py_dict = PyDict_GetItemString(py_core, "models"); Py_INCREF(py_dict); return py_dict; } //! Returns default interface -static PyObject * -c_cfg_interface(PyObject *self, PyObject *args) +static PyObject* +c_cfg_interface(PyObject* self, PyObject* args) { - PyObject *py_str = PyUnicode_FromString(config_interface); + PyObject* py_str = PyUnicode_FromString(config_interface); Py_INCREF(py_str); return py_str; } @@ -487,7 +477,7 @@ static PyMethodDef methods[] = { { "script", c_package, METH_NOARGS, "Alias to package()" }, { "_", c_i18n, METH_VARARGS, "i18n" }, { "notify", c_notify, METH_VARARGS, "Emit signal" }, - { "call", (PyCFunction) c_call, METH_VARARGS|METH_KEYWORDS, "Call COMAR method" }, + { "call", (PyCFunction)c_call, METH_VARARGS | METH_KEYWORDS, "Call COMAR method" }, { "fail", c_fail, METH_VARARGS, "Abort script" }, // Configuration { "config_datapath", c_cfg_datapath, METH_NOARGS, "Return data path" }, @@ -501,41 +491,8 @@ static PyMethodDef methods[] = { { NULL, NULL, 0, NULL } }; - -// struct module_state { -// PyObject *error; -// }; -// -// #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) -// -// static int comar_traverse(PyObject *m, visitproc visit, void *arg) { -// Py_VISIT(GETSTATE(m)->error); -// return 0; -// } -// -// static int comar_clear(PyObject *m) { -// Py_CLEAR(GETSTATE(m)->error); -// return 0; -// } -// -// -// static struct PyModuleDef comardef = { -// PyModuleDef_HEAD_INIT, -// "comar", -// NULL, -// sizeof(struct module_state), -// methods, -// NULL, -// comar_traverse, -// comar_clear, -// NULL -// }; -// -// #define INITERROR return NULL - //! Executes given method of app/model -int -py_execute(const char *app, const char *model, const char *method, PyObject *py_args, PyObject **py_ret) +int py_execute(const char* app, const char* model, const char* method, PyObject* py_args, PyObject** py_ret) { /*! * Loads app/model.py and calls method with given arguments. If app or module is null, this @@ -550,17 +507,14 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ * */ - // PyObject *m; - // m = PyModule_Create(&comardef); - PyObject *py_mod_script, *py_mod_builtin; PyObject *py_dict_script, *py_dict_builtin; PyObject *py_code, *py_method_code, *py_kwargs, *py_func = NULL; - PyMethodDef *py_method; + PyMethodDef* py_method; PyObject *py_module, *py_dict, *py_list; - PyObject *py_dict_core; - PyObject *py_mod_core; + PyObject* py_dict_core; + PyObject* py_mod_core; // Add core module directory to sys.path py_module = PyImport_ImportModule("sys"); @@ -569,7 +523,7 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ PyList_Insert(py_list, 0, PyUnicode_FromString(config_dir_modules)); // Put CSL methods into __builtin__ - py_mod_builtin = PyImport_AddModule("__builtin__"); + py_mod_builtin = PyImport_AddModule("builtins"); py_dict_builtin = PyModule_GetDict(py_mod_builtin); for (py_method = methods; py_method->ml_name; py_method++) { py_method_code = PyCFunction_New(py_method, NULL); @@ -580,8 +534,9 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ if (model != NULL && app != NULL) { // Import script int size = strlen(config_dir_scripts) + 1 + strlen(model) + 1 + strlen(app) + 3 + 1; - char *fn_script = malloc(size); - if (fn_script == NULL) oom(); + char* fn_script = malloc(size); + if (fn_script == NULL) + oom(); snprintf(fn_script, size, "%s/%s/%s.py", config_dir_scripts, model, app); fn_script[size - 1] = 0; @@ -594,7 +549,7 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ } // Load script file - char *code = load_file(fn_script, NULL); + char* code = load_file(fn_script, NULL); if (!code) { log_error("Unable to read script: %s\n", fn_script); PyErr_Format(PyExc_COMAR_Internal, "Unable to read '%s'", fn_script); @@ -644,21 +599,18 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ if (config_ignore_missing) { Py_INCREF(Py_None); *py_ret = Py_None; - } - else { + } else { PyErr_Format(PyExc_COMAR_Missing, "Method '%s' is not defined in script", method); return -2; } - } - else if (!PyCallable_Check(py_func)) { + } else if (!PyCallable_Check(py_func)) { PyErr_Format(PyExc_COMAR_Script, "Method '%s' is not callable in script", method); return -2; - } - else { + } else { // Check if PolicyKit action defined at runtime if (PyObject_HasAttrString(py_func, "policy_action_id")) { - const char *action_id = PyUnicode_AsUTF8(PyObject_GetAttrString(py_func, "policy_action_id")); - const char *sender = dbus_message_get_sender(my_proc.bus_msg); + const char* action_id = PyUnicode_AsUTF8(PyObject_GetAttrString(py_func, "policy_action_id")); + const char* sender = dbus_message_get_sender(my_proc.bus_msg); int result; if (policy_check(sender, action_id, &result) == 0) { @@ -666,8 +618,7 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ PyErr_Format(PyExc_PolicyKit, action_id); return -3; } - } - else { + } else { PyErr_Format(PyExc_PolicyKit, "error"); return -4; } @@ -681,5 +632,4 @@ py_execute(const char *app, const char *model, const char *method, PyObject *py_ } return 0; - // return m; } diff --git a/tools/comar2to3.py b/tools/comar2to3.py index 59b96d1..77340c8 100644 --- a/tools/comar2to3.py +++ b/tools/comar2to3.py @@ -12,6 +12,7 @@ COMAR_IFACE = "tr.org.pardus.comar" COMAR_TIMEOUT = 10 + def main(): if os.getuid() != 0: print("Must be run as root.") @@ -65,10 +66,16 @@ def main(): # If COMAR package is already registered, pass if _app == "comar" and ignore_comar: continue - obj.register(_app, _model, os.path.join(COMAR_DB_OLD, filename), dbus_interface=COMAR_IFACE) + obj.register( + _app, + _model, + os.path.join(COMAR_DB_OLD, filename), + dbus_interface=COMAR_IFACE, + ) print("Registering %s" % filename) return 0 + if __name__ == "__main__": main() diff --git a/tools/hav.py b/tools/hav.py index dba6853..1935627 100755 --- a/tools/hav.py +++ b/tools/hav.py @@ -1,19 +1,20 @@ #!/usr/bin/python3 # -*- coding: utf-8 -*- +import sys +if "/usr/lib/pisilinux3" not in sys.path: + sys.path.insert(0, "/usr/lib/pisilinux3") -import sys -if not "/usr/lib/pisilinux" in sys.path: - sys.path.append("/usr/lib/pisilinux") - -import py3comar as comar +import comar import dbus import locale +import sys import os import piksemel + def printUsage(): print("Usage: %s " % sys.argv[0]) print("Commands:") @@ -25,6 +26,7 @@ def printUsage(): print(" remove ") sys.exit(1) + def introspect(link, path="/"): bus = dbus.SystemBus() obj = bus.get_object(link.address, path) @@ -32,7 +34,9 @@ def introspect(link, path="/"): nodes = [] interfaces = {} - xml = piksemel.parseString(obj.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")) + xml = piksemel.parseString( + obj.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable") + ) for tag in xml.tags(): if tag.name() == "node": nodes.append(tag.getAttribute("name")) @@ -49,6 +53,7 @@ def introspect(link, path="/"): return nodes, interfaces + def main(): if len(sys.argv) == 1: printUsage() @@ -132,7 +137,9 @@ def main(): print(met.call()) except dbus.exceptions.DBusException as e: if e._dbus_error_name.endswith(".Comar.PolicyKit"): - print("Access to '%s' PolicyKit action required." % e.get_dbus_message()) + print( + "Access to '%s' PolicyKit action required." % e.get_dbus_message() + ) else: print("Error:") print(" %s" % e.get_dbus_message()) @@ -142,5 +149,6 @@ def main(): return 0 + if __name__ == "__main__": sys.exit(main()) From cc6ede2773883dbb1d7b4f6e8f7ec1cc16d104c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Harun=20G=C3=BCltekin?= Date: Sat, 4 Apr 2026 20:48:24 +0300 Subject: [PATCH 3/4] =?UTF-8?q?comar=20betiklerini=20py3'e=20d=C3=B6n?= =?UTF-8?q?=C3=BC=C5=9Ft=C3=BCrecek=20betik=20eklendi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit comar betiklerini python3'e dönüştürecek basit bir uygulama eklendi --- CMakeLists.txt | 8 ++- tools/comar_scripts_to_py3.py | 120 ++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 tools/comar_scripts_to_py3.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 9840742..5c7ef09 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -102,11 +102,17 @@ install(FILES config/tr.org.pardus.comar.conf DESTINATION /etc/dbus-1/system.d) -# Install hav to /usr/bin/hav +# Install hav to /usr/bin/hav4 install(PROGRAMS tools/hav.py DESTINATION /usr/bin RENAME "hav${APP_SUFFIX}") +# TODO: Python3 geçişi için eklendi. Geçiş tamamlandığında kaldırılacak +# Install comar_scripts_to_py3 to /usr/bin/comar_scripts_to_py3 +install(PROGRAMS tools/comar_scripts_to_py3.py + DESTINATION /usr/bin + RENAME "comar_scripts_to_py3") + # python2 ile çalışan son comar sürümü 3 olduğundan kaldırıldı # # Install hav to /usr/bin/comar2to3 # install(PROGRAMS tools/comar2to3.py diff --git a/tools/comar_scripts_to_py3.py b/tools/comar_scripts_to_py3.py new file mode 100644 index 0000000..c737c8e --- /dev/null +++ b/tools/comar_scripts_to_py3.py @@ -0,0 +1,120 @@ +#!/usr/bin/python3 +import sys +import re +from argparse import ArgumentParser, RawTextHelpFormatter +from pathlib import Path + +import warnings + +warnings.filterwarnings("ignore", category=DeprecationWarning) + +from lib2to3.main import main as py3fix + + +DESCRIPTION = """ +Bu program python2 ile hazırlanmış comar betiklerini python3'e dönüştürür +ve belirlenen dizine kopyalar. Eğer girdi olarak dizin verilirse alt klasörler +uygun şekilde kopyalanır. + +Örneğin comar3 betiklerini comar4 'e taşımak için aşağıdaki kodu: + +sudo comar_scripts_to_py3 /var/db/comar3/scripts /var/db/comar4/scripts + +ya da herhangi bir betik için aşağıdaki kodu kullanabilirsiniz: + +comar_scripts_to_py3 py2/betik/yolu cikti/dizini +""" + + +def check_comar(): + try: + import comar + except Exception: + return False + return True + + +def main(): + parser = ArgumentParser( + description=DESCRIPTION, + formatter_class=RawTextHelpFormatter, + ) + + parser.add_argument( + "ipath", + type=str, + help="dönüştürülecek dosya veya dizin", + ) + + parser.add_argument( + "opath", + type=str, + default="./py3", + help="çıktı dizini", + ) + + _args = parser.parse_args() + + opath = Path(_args.opath) + ipath = Path(_args.ipath) + + if not ipath.exists(): + print("HATA: Dosya/Dizin yolu mevut değil:", ipath) + return + + if not opath.exists(): + opath.mkdir(parents=True) + + if opath.is_file(): + print("Çıktı parametresi dizin olmak zorunda:", opath) + exit(1) + + is_comar_imported = check_comar() + + if ipath.is_file(): + fix2to3(ipath, opath, is_comar_imported) + else: + for path in ipath.glob("**/*.py"): + fix2to3(path, opath, is_comar_imported, ipath) + + +def get_output_path(path: Path, ipath: Path, opath: Path) -> Path: + sub = opath / str(path).split(str(ipath))[-1][1:] + return sub + + +def fix2to3( + fpath: Path, + opath: Path, + is_comar_imported: bool, + ipath: Path | None = None, +) -> None: + if ipath: + opath = get_output_path(fpath, ipath, opath).parent + if not opath.exists(): + opath.mkdir(parents=True, exist_ok=True) + + py3fix("lib2to3.fixes", args=["-nwW", "-o", str(opath), str(fpath)]) + + import_comar = """import sys + +if "/usr/lib/pisilinux3" not in sys.path: + sys.path.insert(0, "/usr/lib/pisilinux3") + +""" + ofile = opath / fpath.name + with ofile.open() as _file: + code = _file.read() + + # change file function to open + res = re.sub(r"(\W+)(file)(\()", r"\1open\3", code) + + if not is_comar_imported: + res = re.sub(r"((from|import) comar)", f"{import_comar}\\1", res) + + with ofile.open("w") as _file: + print(res, file=_file) + + +if __name__ == "__main__": + main() From b23d2bdc52bb009df1c5749004c4bce836dc7bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Harun=20G=C3=BCltekin?= Date: Sun, 5 Apr 2026 00:15:12 +0300 Subject: [PATCH 4/4] =?UTF-8?q?py3=20ge=C3=A7i=C5=9Fi=20i=C3=A7in=20okuben?= =?UTF-8?q?i=20dosyas=C4=B1=20eklendi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "OKUBEN\304\260.md" | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 "OKUBEN\304\260.md" diff --git "a/OKUBEN\304\260.md" "b/OKUBEN\304\260.md" new file mode 100644 index 0000000..c1f949a --- /dev/null +++ "b/OKUBEN\304\260.md" @@ -0,0 +1,68 @@ +# DİKKAT - 4.0.0-alpha + +Çomar hali hazırda diğer paketler ile sunulan betiklerle birlikte çalışmaktadır. +Dolayısıyla tam potansiyeliyle çalışmayacaktır diğer paketlerdeki comar +betiklerinin kontrol edilmesi gerekmektedir. + +Betiklerin python3'e geçişi için comar_scripts_to_py3 isimli basit bir uygulama hazırlandı. + +Şuan apache, docker servis betikleri python3 geçişi sağlanıp test edildi. Ancak +comar ile yapılacak paket işlemleri pisi python3 geçişi sağlanmadığından çalışmamaktadır. + +## Kurulum + +Aşağıdaki komutlar ile programı derleyip kurabilirsiniz. + +```sh +cmake -S . -B build +cmake --build build +sudo cmake --install build +``` + +Paketlere ait comar betiklerinin önceki sürümden aktarılması için aşağıdaki +komutu çalıştırınız: + +```sh +sudo comar_scripts_to_py3 /var/db/comar3/scripts /var/db/comar4/scripts +``` + +Son olarak comar-api'nin python3 için hazırlanmış olan halininde kurulması gerekmektedir. + +## Çalıştırma + +Comar3 ile çakışma olmaması için program adı comar4 olarak değiştirildi. Bu nedenle +uygulamayı test edebilmek için elle çalıştırılması gerekmektedir. Ayrıca comar uygulaması +çalışıyor ise önce comar'ı durdurun. Daha sonra aşağıdaki komut ile comar4'ü +çalıştırabilirsiniz. Uygulama sonlandırılmadığı sürece arka planda açık kalır. + +```sh +# -g: hata ayıklamayı aktif eder +# -p: çıktıları ekrana yazdırır +sudo comar4 -gp +``` + +Test etmek için yeni bir terminal ekranında comar ile uyumlu olan şu komutları +çalıştırabilirsiniz (Test süresinde yukarıdaki komutu sonlandırmayınız): + +```sh +# örnek komutlar +# hav ile model listeleme +hav4 list-models apache + +# hav ile modelden uygulama listeleme +hav4 list-app System.Manager + +# hav ile method listeleme +hav4 list-method apache System.Service + +# hav ile method çağrısı +hav4 call apache System.Service start +hav4 call apache System.Service info + +# service uygulaması ile servis listeleme +service list + +# açama, kapama gibi işlemler çalıştırılabilir +sudo service apache start +service apache info +```