mce-dbus.c 142 KB
Newer Older
1 2 3 4 5
/**
 * @file mce-dbus.c
 * D-Bus handling code for the Mode Control Entity
 * <p>
 * Copyright © 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
6
 * Copyright (C) 2012-2019 Jolla Ltd.
7 8 9
 * <p>
 * @author David Weinehall <david.weinehall@nokia.com>
 * @author Ismo Laitinen <ismo.laitinen@nokia.com>
10
 * @author Santtu Lakkala <ext-santtu.1.lakkala@nokia.com>
spiiroin's avatar
spiiroin committed
11
 * @author Simo Piiroinen <simo.piiroinen@jollamobile.com>
12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * mce is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * mce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with mce.  If not, see <http://www.gnu.org/licenses/>.
 */
25

26
#include "mce-dbus.h"
27

28 29
#include "mce.h"
#include "mce-log.h"
30
#include "mce-lib.h"
31
#include "mce-wakelock.h"
32

33 34
#include "systemui/dbus-names.h"

35 36
#include <sys/stat.h>

spiiroin's avatar
spiiroin committed
37
#include <stdio.h>
38 39 40
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
41
#include <dlfcn.h>
42 43
#include <grp.h>
#include <pwd.h>
44

45
#include "dbus-gmain/dbus-gmain.h"
46

47
#include <mce/dbus-names.h>
48
#include <dsme/thermalmanager_dbus_if.h>
49

50 51 52 53
/* ========================================================================= *
 * TYPES & CONSTANTS
 * ========================================================================= */

54 55 56
/** How long to block late suspend when mce is sending dbus messages */
#define MCE_DBUS_SEND_SUSPEND_BLOCK_MS 1000

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
/** Placeholder value for invalid/unknown process id */
#define PEERINFO_NO_PID ((pid_t)-1)

/** Placeholder value for invalid/unknown user id */
#define PEERINFO_NO_UID ((uid_t)-1)

/** Placeholder value for invalid/unknown group id */
#define PEERINFO_NO_GID ((gid_t)-1)

/** Root user id */
#define PEERINFO_ROOT_UID ((uid_t)0)

/** Root group id */
#define PEERINFO_ROOT_GID ((gid_t)0)

/** D-Bus handler callback function */
typedef gboolean (*handler_callback_t)(DBusMessage *const msg);

/** D-Bus handler structure */
typedef struct
{
    handler_callback_t  callback;   /**< Handler callback */
    gchar              *sender;     /**< Service name to match */
    gchar              *interface;  /**< The interface to listen on */
    gchar              *rules;      /**< Additional matching rules */
    gchar              *name;       /**< Method call or signal name */
    gchar              *args;       /**< Introspect XML data */
    int                 type;       /**< DBUS_MESSAGE_TYPE */
    bool                privileged; /**< Allowed for privileged users only */
} handler_struct_t;

/** Possible values for "privileged" peer checks */
typedef enum
{
    /** Client/service is not available / details are not known yet */
    PRIVILEGED_UNKNOWN = -1,

    /** Client/service is on D-Bus and it is not a privileged process */
    PRIVILEGED_NO,

    /** Client/service is on D-Bus and it is a privileged process */
    PRIVILEGED_YES,
} privileged_t;

/** Notification details for client exit tracking */
typedef struct peerquit_t peerquit_t;

/** Callback function type for notifying client exits */
typedef gboolean  (*peerquit_fn)(DBusMessage *const msg);

struct peerquit_t
{
    peerinfo_t *pq_peerinfo;
    peerquit_fn pq_callback;
};

113 114 115 116 117 118 119 120 121 122 123 124
/** Notification details for client state tracking */
typedef struct peernotify_t peernotify_t;

struct peernotify_t
{
    peerinfo_t    *pn_peerinfo;
    peernotify_fn  pn_callback;
    gpointer       pn_userdata;
    GDestroyNotify pn_userfree;
    guint          pn_idle_id;
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
struct peerinfo_t
{
    /** Availability / property query IPC state */
    peerstate_t      pi_state;

    /** D-Bus name to track */
    gchar           *pi_name;

    /** Unique bus name of the name owner */
    gchar           *pi_owner_name;

    /** Signal match that has been sent to D-Bus daemon */
    gchar           *pi_rule;

    /** Process id of the D-Bus name owner */
    pid_t            pi_owner_pid;

    /** Cached effective user id of the D-Bus name owner */
    uid_t            pi_owner_uid;

    /** Cached effective group id of the D-Bus name owner */
    gid_t            pi_owner_gid;

    /** Cached command line of the Bus name owner */
    gchar           *pi_owner_cmd;

    /** Optional datapipe to use for service availability signaling */
152
    datapipe_t      *pi_datapipe;
153 154 155 156

    /** Client exit notifications for this D-Bus name */
    GQueue           pi_quit_callbacks; // -> peerquit_t *

157 158 159
    /** Client stat notifications for this D-Bus name */
    GQueue           pi_notifications; // -> peernotify_t

160 161 162 163 164 165 166 167 168
    /** Queue of privileged method calls waiting for peer details */
    GQueue           pi_priv_methods; // -> DBusMessage *

    /** Pending org.freedesktop.DBus.GetNameOwner method call */
    DBusPendingCall *pi_name_owner_pc;

    /** Pending org.freedesktop.DBus.GetConnectionUnixProcessID method call */
    DBusPendingCall *pi_name_pid_pc;

169
    /** Timer for delayed delete after hitting PEERSTATE_STOPPED */
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    guint            pi_delete_id;

    /** Fixed size buffer for providing peer details for debugging purposes */
    char             pi_repr[128];
};

/* ========================================================================= *
 * FUNCTIONALITY
 * ========================================================================= */

/* ------------------------------------------------------------------------- *
 * SUSPEND_PROOFING
 * ------------------------------------------------------------------------- */

static void               mdb_callgate_detach_cb               (void *aptr);
static void               mdb_callgate_attach                  (DBusPendingCall *pc);
void                      mce_dbus_pending_call_blocks_suspend (DBusPendingCall *pc);

/* ------------------------------------------------------------------------- *
 * DEBUG_HELPERS
 * ------------------------------------------------------------------------- */

static dbus_bool_t        mce_dbus_message_repr_any            (FILE *file, DBusMessageIter *iter);
char                     *mce_dbus_message_iter_repr           (DBusMessageIter *iter);
char                     *mce_dbus_message_repr                (DBusMessage *const msg);

/* ------------------------------------------------------------------------- *
 * HANDLER_STRUCT_T
 * ------------------------------------------------------------------------- */

static inline void        handler_struct_set_sender            (handler_struct_t *self, const char *val);
static inline void        handler_struct_set_type              (handler_struct_t *self, int val);
static inline void        handler_struct_set_interface         (handler_struct_t *self, const char *val);
static inline void        handler_struct_set_args              (handler_struct_t *self, const char *val);
static inline void        handler_struct_set_name              (handler_struct_t *self, const char *val);
static inline void        handler_struct_set_rules             (handler_struct_t *self, const char *val);
static inline void        handler_struct_set_callback          (handler_struct_t *self, handler_callback_t val);
static inline void        handler_struct_set_privileged        (handler_struct_t *self, bool val);

static void               handler_struct_delete                (handler_struct_t *self);
static handler_struct_t  *handler_struct_create                (void);

/* ------------------------------------------------------------------------- *
 * PEERSTATE_T
 * ------------------------------------------------------------------------- */

216
const char              *peerstate_repr                        (peerstate_t state);
217 218 219 220 221 222 223 224 225 226

/* ------------------------------------------------------------------------- *
 * PEERQUIT_T
 * ------------------------------------------------------------------------- */

static peerquit_t       *peerquit_create                       (peerinfo_t *parent, peerquit_fn callback);
static void              peerquit_delete                       (peerquit_t *self);

static void              peerquit_notify                       (peerquit_t *self, DBusMessage *msg);

227 228 229 230 231 232 233 234 235 236 237
/* ------------------------------------------------------------------------- *
 * PEERNOTIFY_T
 * ------------------------------------------------------------------------- */

static gboolean          peernotify_idle_cb                    (gpointer aptr);
static void              peernotify_schedule                   (peernotify_t *self);
static void              peernotify_unschedule                 (peernotify_t *self);
static void              peernotify_execute                    (peernotify_t *self);
static peernotify_t     *peernotify_create                     (peerinfo_t *peerinfo, peernotify_fn callback, gpointer userdata, GDestroyNotify userfree);
static void              peernotify_delete                     (peernotify_t *self);

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
/* ------------------------------------------------------------------------- *
 * PEERINFO_T
 * ------------------------------------------------------------------------- */

static gchar            *peerinfo_guess_cmd                    (pid_t pid);

static inline void       peerinfo_ctor                         (peerinfo_t *self, const char *name);
static inline void       peerinfo_dtor                         (peerinfo_t *self);
peerinfo_t              *peerinfo_create                       (const char *name);
void                     peerinfo_delete                       (peerinfo_t *self);
void                     peerinfo_delete_cb                    (void *self);

static void              peerinfo_enter_state                  (peerinfo_t *self);
static void              peerinfo_leave_state                  (peerinfo_t *self);
static void              peerinfo_set_state                    (peerinfo_t *self, peerstate_t state);
253
peerstate_t              peerinfo_get_state                    (const peerinfo_t *self);
254

255 256 257
static const char       *peerinfo_repr                         (peerinfo_t *self);
const char              *peerinfo_name                         (const peerinfo_t *self);
const char              *peerinfo_get_owner_name               (const peerinfo_t *self);
258
static bool              peerinfo_set_owner_name               (peerinfo_t *self, const char *name);
259
pid_t                    peerinfo_get_owner_pid                (const peerinfo_t *self);
260
static void              peerinfo_set_owner_pid                (peerinfo_t *self, pid_t pid);
261
uid_t                    peerinfo_get_owner_uid                (const peerinfo_t *self);
262
static void              peerinfo_set_owner_uid                (peerinfo_t *self, uid_t uid);
263
gid_t                    peerinfo_get_owner_gid                (const peerinfo_t *self);
264
static void              peerinfo_set_owner_gid                (peerinfo_t *self, gid_t gid);
265
const char              *peerinfo_get_owner_cmd                (const peerinfo_t *self);
266 267
static void              peerinfo_set_owner_cmd                (peerinfo_t *self, const char *cmd);
static privileged_t      peerinfo_get_privileged               (const peerinfo_t *self, bool no_caching);
268
static void              peerinfo_set_datapipe                 (peerinfo_t *self, datapipe_t *datapipe);
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

static void              peerinfo_query_owner_ign              (peerinfo_t *self);
static void              peerinfo_query_owner_rsp              (DBusPendingCall *pc, void *aptr);
static void              peerinfo_query_owner_req              (peerinfo_t *self);

static void              peerinfo_query_pid_ign                (peerinfo_t *self);
static void              peerinfo_query_pid_rsp                (DBusPendingCall *pc, void *aptr);
static void              peerinfo_query_pid_req                (peerinfo_t *self);

static void              peerinfo_query_delete_ign             (peerinfo_t *self);
static gboolean          peerinfo_query_delete_tmo             (gpointer aptr);
static void              peerinfo_query_delete_req             (peerinfo_t *self);

static peerquit_t       *peerinfo_add_quit_callback            (peerinfo_t *self, peerquit_fn callback);
static void              peerinfo_remove_quit_callback         (peerinfo_t *self, peerquit_t *quit);
static void              peerinfo_execute_quit_callbacks       (peerinfo_t *self);
static void              peerinfo_flush_quit_callbacks         (peerinfo_t *self);

287 288 289 290 291 292
static GList            *peerinfo_find_notify_slot             (peerinfo_t *self, peernotify_fn callback, gpointer userdata);
static void              peerinfo_flush_notify_callbacks       (peerinfo_t *self);
static void              peerinfo_execute_notify_callbacks     (peerinfo_t *self);
static void              peerinfo_add_notify_callback          (peerinfo_t *self, peernotify_fn callback, gpointer userdata, GDestroyNotify userfree);
static void              peerinfo_remove_notify_callback       (peerinfo_t *self, peernotify_fn callback, gpointer userdata);

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
static void              peerinfo_queue_method                 (peerinfo_t *self, DBusMessage *req);
static void              peerinfo_flush_methods                (peerinfo_t *self);
static void              peerinfo_handle_methods               (peerinfo_t *self);

/* ------------------------------------------------------------------------- *
 * PEER_TRACKING
 * ------------------------------------------------------------------------- */

static DBusHandlerResult mce_dbus_peerinfo_filter_cb           (DBusConnection *con, DBusMessage *msg, void *user_data);
static void              mce_dbus_init_peerinfo                (void);
static void              mce_dbus_quit_peerinfo                (void);
peerinfo_t              *mce_dbus_get_peerinfo                 (const char *name);
peerinfo_t              *mce_dbus_add_peerinfo                 (const char *name);
void                     mce_dbus_update_peerinfo              (const char *name, const char *owner);
void                     mce_dbus_del_peerinfo                 (const char *name);
const char              *mce_dbus_get_peerdesc                 (const char *name);

/* ------------------------------------------------------------------------- *
 * MESSAGE_SENDING
 * ------------------------------------------------------------------------- */

DBusConnection          *dbus_connection_get                   (void);
DBusMessage             *dbus_new_signal                       (const gchar *const path, const gchar *const interface, const gchar *const name);
static DBusMessage      *dbus_new_error                        (DBusMessage *req, const char *err, const char *fmt, ...);
DBusMessage             *dbus_new_method_call                  (const gchar *const service, const gchar *const path, const gchar *const interface, const gchar *const name);
DBusMessage             *dbus_new_method_reply                 (DBusMessage *const message);
gboolean                 dbus_send_message                     (DBusMessage *const msg);
static gboolean          dbus_send_message_with_reply_handler  (DBusMessage *const msg, DBusPendingCallNotifyFunction callback, int timeout, void *user_data, DBusFreeFunction user_free, DBusPendingCall **ppc);
static gboolean          dbus_send_va                          (const char *service, const char *path, const char *interface, const char *name, DBusPendingCallNotifyFunction callback, int timeout, void *user_data, DBusFreeFunction user_free, DBusPendingCall **ppc, int first_arg_type, va_list va);
gboolean                 dbus_send_ex                          (const char *service, const char *path, const char *interface, const char *name, DBusPendingCallNotifyFunction callback, void *user_data, DBusFreeFunction user_free, DBusPendingCall **ppc, int first_arg_type, ...);
gboolean                 dbus_send_ex2                         (const char *service, const char *path, const char *interface, const char *name, DBusPendingCallNotifyFunction callback, int timeout, void *user_data, DBusFreeFunction user_free, DBusPendingCall **ppc, int first_arg_type, ...);
gboolean                 dbus_send                             (const gchar *const service, const gchar *const path, const gchar *const interface, const gchar *const name, DBusPendingCallNotifyFunction callback, int first_arg_type, ...);

/* ------------------------------------------------------------------------- *
 * METHOD_CALL_HANDLERS
 * ------------------------------------------------------------------------- */

static gboolean          version_get_dbus_cb                   (DBusMessage *const msg);
static gboolean          suspend_stats_get_dbus_cb             (DBusMessage *const req);
static gboolean          verbosity_get_dbus_cb                 (DBusMessage *const req);
static gboolean          config_get_dbus_cb                    (DBusMessage *const msg);
static gboolean          verbosity_set_dbus_cb                 (DBusMessage *const req);
static gboolean          config_get_all_dbus_cb                (DBusMessage *const req);
static gboolean          config_reset_dbus_cb                  (DBusMessage *const msg);
static gboolean          config_set_dbus_cb                    (DBusMessage *const msg);
static gboolean          introspect_dbus_cb                    (DBusMessage *const req);

/* ------------------------------------------------------------------------- *
 * CONFIG_VALUES
 * ------------------------------------------------------------------------- */

static const char      **string_array_from_gconf_value         (GConfValue *conf, int *pcount);
static dbus_int32_t     *int_array_from_gconf_value            (GConfValue *conf, int *pcount);
static dbus_bool_t      *bool_array_from_gconf_value           (GConfValue *conf, int *pcount);
static double           *float_array_from_gconf_value          (GConfValue *conf, int *pcount);
static const char       *type_signature                        (GConfValueType type);
static const char       *value_signature                       (GConfValue *conf);
static bool              append_gconf_value_to_dbus_iterator   (DBusMessageIter *iter, GConfValue *conf);
static bool              append_gconf_entry_to_dbus_iterator   (DBusMessageIter *iter, GConfEntry *entry);
static bool              append_gconf_entries_to_dbus_iterator (DBusMessageIter *iter, GSList *entries);
static bool              append_gconf_value_to_dbus_message    (DBusMessage *reply, GConfValue *conf);
void                     mce_dbus_send_config_notification     (GConfEntry *entry);
static void              value_list_free                       (GSList *list);
static GSList           *value_list_from_string_array          (DBusMessageIter *iter);
static GSList           *value_list_from_int_array             (DBusMessageIter *iter);
static GSList           *value_list_from_bool_array            (DBusMessageIter *iter);
static GSList           *value_list_from_float_array           (DBusMessageIter *iter);

/* ------------------------------------------------------------------------- *
 * MESSAGE_DISPATCH
 * ------------------------------------------------------------------------- */

static gboolean          check_rules                           (DBusMessage *const msg, const char *rules);
static gchar            *mce_dbus_build_signal_match           (const gchar *sender, const gchar *interface, const gchar *name, const gchar *rules);
static void              mce_dbus_squeeze_slist                (GSList **list);
static bool              mce_dbus_match                        (const char *msg_val, const char *hnd_val);
static DBusHandlerResult msg_handler                           (DBusConnection *const connection, DBusMessage *const msg, gpointer const user_data);
static gconstpointer     mce_dbus_handler_add_ex               (const gchar *const sender, const gchar *const interface, const gchar *const name, const gchar *const args, const gchar *const rules, const guint type, gboolean (*callback)(DBusMessage *const msg), bool privileged);
static void              mce_dbus_handler_remove               (gconstpointer cookie);
static void              mce_dbus_handler_remove_cb            (gpointer handler, gpointer user_data);
void                     mce_dbus_handler_register             (mce_dbus_handler_t *self);
void                     mce_dbus_handler_unregister           (mce_dbus_handler_t *self);
void                     mce_dbus_handler_register_array       (mce_dbus_handler_t *array);
void                     mce_dbus_handler_unregister_array     (mce_dbus_handler_t *array);

/* ------------------------------------------------------------------------- *
 * OWNER_MONITORING
 * ------------------------------------------------------------------------- */

static peerquit_t       *find_monitored_service                (const gchar *service, GSList *monitor_list);
gssize                   mce_dbus_owner_monitor_add            (const gchar *service, gboolean (*callback)(DBusMessage *const msg), GSList **monitor_list, gssize max_num);
gssize                   mce_dbus_owner_monitor_remove         (const gchar *service, GSList **monitor_list);
void                     mce_dbus_owner_monitor_remove_all     (GSList **monitor_list);

/* ------------------------------------------------------------------------- *
 * SERVICE_MANAGEMENT
 * ------------------------------------------------------------------------- */

static gboolean          dbus_acquire_services                 (void);
static void              dbus_quit_message_handler             (void);
static gboolean          dbus_init_message_handler             (void);

/* ------------------------------------------------------------------------- *
 * MESSAGE_ITER
 * ------------------------------------------------------------------------- */

const char              *mce_dbus_type_repr                    (int type);
bool                     mce_dbus_iter_at_end                  (DBusMessageIter *iter);
401 402
bool                     mce_dbus_iter_req_type                (DBusMessageIter *iter, int want);
bool                     mce_dbus_iter_get_basic               (DBusMessageIter *iter, void *pval, int type);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
bool                     mce_dbus_iter_get_object              (DBusMessageIter *iter, const char **pval);
bool                     mce_dbus_iter_get_string              (DBusMessageIter *iter, const char **pval);
bool                     mce_dbus_iter_get_bool                (DBusMessageIter *iter, bool *pval);
bool                     mce_dbus_iter_get_int32               (DBusMessageIter *iter, dbus_int32_t *pval);
bool                     mce_dbus_iter_get_uint32              (DBusMessageIter *iter, dbus_uint32_t *pval);
static bool              mce_dbus_iter_get_container           (DBusMessageIter *iter, DBusMessageIter *sub, int type);
bool                     mce_dbus_iter_get_array               (DBusMessageIter *iter, DBusMessageIter *sub);
bool                     mce_dbus_iter_get_struct              (DBusMessageIter *iter, DBusMessageIter *sub);
bool                     mce_dbus_iter_get_entry               (DBusMessageIter *iter, DBusMessageIter *sub);
bool                     mce_dbus_iter_get_variant             (DBusMessageIter *iter, DBusMessageIter *sub);

/* ------------------------------------------------------------------------- *
 * PEER_IDENTITY
 * ------------------------------------------------------------------------- */

const char              *mce_dbus_get_name_owner_ident         (const char *name);
const char              *mce_dbus_get_message_sender_ident     (DBusMessage *msg);

/* ------------------------------------------------------------------------- *
 * INTROSPECT_SUPPORT
 * ------------------------------------------------------------------------- */

static void              introspect_add_methods                (FILE *file, const char *interface);
static void              introspect_add_signals                (FILE *file, const char *interface);
static void              introspect_add_defaults               (FILE *file);
static void              introspect_com_nokia_mce_request      (FILE *file);
static void              introspect_com_nokia_mce_signal       (FILE *file);
static void              introspect_com_nokia_mce              (FILE *file);
static void              introspect_com_nokia                  (FILE *file);
static void              introspect_com                        (FILE *file);
static void              introspect_root                       (FILE *file);
static bool              introspectable_signal                 (const char *interface, const char *member);

/* ------------------------------------------------------------------------- *
 * DBUS_NAME_OWNER_TRACKING
 * ------------------------------------------------------------------------- */

const char              *mce_dbus_nameowner_get                (const char *name);
static char             *mce_dbus_nameowner_watch              (const char *name);
static void              mce_dbus_nameowner_unwatch            (char *rule);

/* ------------------------------------------------------------------------- *
 * MODULE_INIT_QUIT
 * ------------------------------------------------------------------------- */

DBusConnection          *dbus_bus_get                          (DBusBusType type, DBusError *err);
DBusConnection          *dbus_bus_get_private                  (DBusBusType type, DBusError *err);
static void              mce_dbus_init_privileged_uid          (void);
static void              mce_dbus_init_privileged_gid          (void);
gboolean                 mce_dbus_init                         (const gboolean systembus);
void                     mce_dbus_exit                         (void);

/* ========================================================================= *
 * DATA
 * ========================================================================= */

/** Pointer to the DBusConnection */
static DBusConnection *dbus_connection = NULL;

/** List of all D-Bus handlers */
static GSList *dbus_handlers = NULL; // -> handler_struct_t *

/** Cached UID for "privileged" user; assume root only */
static uid_t mce_dbus_privileged_uid = PEERINFO_ROOT_UID;

/** Cached GID for "privileged" group; assume root only */
static gid_t mce_dbus_privileged_gid = PEERINFO_ROOT_GID;

/* ========================================================================= *
 * SUSPEND_PROOFING
 * ========================================================================= */

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
/** Pending call callgate slot destry callback function
 *
 * Called when pending call ref count drops to zero.
 *
 * Releases the ultiplexed wakelock that has been attached
 * to the pending call object via mdb_callgate_attach().
 *
 * @param aptr Name of the attached wakelock
 */
static void mdb_callgate_detach_cb(void  *aptr)
{
	char *name = aptr;

	mce_log(LL_DEBUG, "detach %s", name);
	mce_wakelock_release(name);
	g_free(name);
}

/** Block suspend while mce is waiting for a reply to a method call
 *
 * Take advantage of the fact that custom data attached to a pending
 * call object gets destroyed along with the object itself and create
 * unique wakelock that is used for blocking the device from entering
 * suspend until:
 *
 * a) the wait for pending call is canceled
 * b) mce has received and processed the reply message
 *
 * @param pc Pending call object to suspend proof
 */
static void mdb_callgate_attach(DBusPendingCall *pc)
{
	static dbus_int32_t  slot = -1;
	static unsigned      uniq = 0;

	gchar               *name = 0;

	if( !pc )
		goto EXIT;

	if( slot == -1 && !dbus_pending_call_allocate_data_slot(&slot) )
		goto EXIT;

	if( !(name = g_strdup_printf("dbus_call_%u", ++uniq)) )
		goto EXIT;

	mce_log(LL_DEBUG, "attach %s", name);

	if( dbus_pending_call_set_data(pc, slot, name, mdb_callgate_detach_cb) ) {
		mce_wakelock_obtain(name, -1);
		name = 0;
	}

EXIT:
	g_free(name);
}

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
/** Public function for making dbus method calls suspend proof
 *
 * NOTE: We would not need this function if all of the mce code base
 *       would use dbus_send_ex() based method call handling.
 *
 * FIXME: Fix all code that uses dbus_connection_send_with_reply()
 *        so that dbus_send_ex() is used instead.
 *
 * @param pc  Pending call object to protect
 */
void mce_dbus_pending_call_blocks_suspend(DBusPendingCall *pc)
{
	mdb_callgate_attach(pc);
}

547 548 549
/* ========================================================================= *
 * DEBUG_HELPERS
 * ========================================================================= */
550

spiiroin's avatar
spiiroin committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
/** Emit one iterm from dbus message iterator to file
 *
 * @param file output file
 * @param iter dbus message parse position
 *
 * @return TRUE if more items can be parsed, FALSE otherwise
 */
static dbus_bool_t
mce_dbus_message_repr_any(FILE *file, DBusMessageIter *iter)
{
	dbus_any_t val = { .u64 = 0 };
	DBusMessageIter sub;

	switch( dbus_message_iter_get_arg_type(iter) ) {
	case DBUS_TYPE_INVALID:
		return FALSE;
	default:
	case DBUS_TYPE_UNIX_FD:
		fprintf(file, " ???");
		return FALSE;
	case DBUS_TYPE_BYTE:
		dbus_message_iter_get_basic(iter, &val.o);
		fprintf(file, " byte:%d", val.o);
		break;
	case DBUS_TYPE_BOOLEAN:
		dbus_message_iter_get_basic(iter, &val.b);
		fprintf(file, " bool:%d", val.b);
		break;
	case DBUS_TYPE_INT16:
		dbus_message_iter_get_basic(iter, &val.i16);
		fprintf(file, " i16:%d", val.i16);
		break;
	case DBUS_TYPE_INT32:
		dbus_message_iter_get_basic(iter, &val.i32);
		fprintf(file, " i32:%d", val.i32);
		break;
	case DBUS_TYPE_INT64:
		dbus_message_iter_get_basic(iter, &val.i64);
		fprintf(file, " i64:%lld", (long long)val.i64);
		break;
	case DBUS_TYPE_UINT16:
		dbus_message_iter_get_basic(iter, &val.u16);
		fprintf(file, " u16:%u", val.u16);
		break;
	case DBUS_TYPE_UINT32:
		dbus_message_iter_get_basic(iter, &val.u32);
		fprintf(file, " u32:%u", val.u32);
		break;
	case DBUS_TYPE_UINT64:
		dbus_message_iter_get_basic(iter, &val.u64);
		fprintf(file, " u64:%llu", (unsigned long long)val.u64);
		break;
	case DBUS_TYPE_DOUBLE:
		dbus_message_iter_get_basic(iter, &val.d);
		fprintf(file, " dbl:%g", val.d);
		break;
	case DBUS_TYPE_STRING:
		dbus_message_iter_get_basic(iter, &val.s);
		fprintf(file, " str:\"%s\"", val.s);
		break;
	case DBUS_TYPE_OBJECT_PATH:
		dbus_message_iter_get_basic(iter, &val.s);
		fprintf(file, " obj:\"%s\"", val.s);
		break;
	case DBUS_TYPE_SIGNATURE:
		dbus_message_iter_get_basic(iter, &val.s);
		fprintf(file, " sgn:\"%s\"", val.s);
		break;
	case DBUS_TYPE_ARRAY:
		dbus_message_iter_recurse(iter, &sub);
		fprintf(file, " [");
		while( mce_dbus_message_repr_any(file, &sub) ) {}
		fprintf(file, " ]");
		break;
	case DBUS_TYPE_VARIANT:
		dbus_message_iter_recurse(iter, &sub);
		fprintf(file, " var");
		mce_dbus_message_repr_any(file, &sub);
		break;
	case DBUS_TYPE_STRUCT:
		dbus_message_iter_recurse(iter, &sub);
		fprintf(file, " {");
		while( mce_dbus_message_repr_any(file, &sub) ) {}
		fprintf(file, " }");
		break;
	case DBUS_TYPE_DICT_ENTRY:
		dbus_message_iter_recurse(iter, &sub);
		fprintf(file, " key");
		mce_dbus_message_repr_any(file, &sub);
		fprintf(file, " val");
		mce_dbus_message_repr_any(file, &sub);
		break;
	}

	return dbus_message_iter_next(iter);
}

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
/** Convert dbus message read iterator to string
 *
 * Caller must release returned string with free().
 *
 * @param iter dbus message iterator
 *
 * @returns representation of the iterator, or NULL
 */
char *
mce_dbus_message_iter_repr(DBusMessageIter *iter)
{
	size_t  size = 0;
	char   *data = 0;
	FILE   *file = open_memstream(&data, &size);

	if( !iter )
		goto EXIT;

	while( mce_dbus_message_repr_any(file, iter) ) {}
EXIT:
	fclose(file);
	return data;
}

/** Convert dbus message to string
 *
 * Caller must release returned string with free().
 *
 * @param msg dbus message
 *
 * @returns representation of the dbus message, or NULL
 */
char *
mce_dbus_message_repr(DBusMessage *const msg)
{
	size_t  size = 0;
	char   *data = 0;
	FILE   *file = open_memstream(&data, &size);

	const char *iface = dbus_message_get_interface(msg);
	const char *member = dbus_message_get_member(msg);
	int type = dbus_message_get_type(msg);
	const char *tname = dbus_message_type_to_string(type);
	const char *sender = dbus_message_get_sender(msg);

	fprintf(file, "%s", tname);

	if( sender ) fprintf(file, " from %s", sender);
	if( iface )  fprintf(file, " %s", iface);
	if( member ) fprintf(file, " %s", member);

	DBusMessageIter iter;
	dbus_message_iter_init(msg, &iter);
	if( dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_INVALID )
		goto EXIT;

	fprintf(file, ":");

	while( mce_dbus_message_repr_any(file, &iter) ) {}
EXIT:
	fclose(file);
	return data;
}

/* ========================================================================= *
 * HANDLER_STRUCT_T
 * ========================================================================= */

/** Set sender for D-Bus handler structure */
static inline void handler_struct_set_sender(handler_struct_t *self, const char *val)
{
	g_free(self->sender), self->sender = val ? g_strdup(val) : 0;
}

/** Set handler type for D-Bus handler structure */
static inline void handler_struct_set_type(handler_struct_t *self, int val)
{
	self->type = val;
}

/** Set interface name for D-Bus handler structure */
static inline void handler_struct_set_interface(handler_struct_t *self, const char *val)
{
	g_free(self->interface), self->interface = val ? g_strdup(val) : 0;
}

/** Set introspect args for D-Bus handler structure */
static inline void handler_struct_set_args(handler_struct_t *self, const char *val)
{
	g_free(self->args), self->args = val ? g_strdup(val) : 0;
}

/** Set member name for D-Bus handler structure */
static inline void handler_struct_set_name(handler_struct_t *self, const char *val)
{
	g_free(self->name), self->name = val ? g_strdup(val) : 0;
}

/** Set custom rules for D-Bus handler structure */
static inline void handler_struct_set_rules(handler_struct_t *self, const char *val)
{
	g_free(self->rules), self->rules = val ? g_strdup(val) : 0;
}

/** Set callback function for D-Bus handler structure */
static inline void handler_struct_set_callback(handler_struct_t *self,
					       handler_callback_t val)
{
	self->callback = val;
}

/** Set privileged requirement for D-Bus handler structure */
static inline void handler_struct_set_privileged(handler_struct_t *self, bool val)
{
	self->privileged = val;
}

/** Release D-Bus handler structure */
static void handler_struct_delete(handler_struct_t *self)
{
	if( !self )
		goto EXIT;

	g_free(self->args);
	g_free(self->name);
	g_free(self->rules);
	g_free(self->interface);
	g_free(self->sender);
	g_free(self);

EXIT:
	return;
}

/** Allocate D-Bus handler structure */
static handler_struct_t *handler_struct_create(void)
{
	handler_struct_t *self = g_malloc0(sizeof *self);

	self->sender     = 0;
	self->interface  = 0;
	self->rules      = 0;
	self->name       = 0;
	self->args       = 0;
	self->type       = DBUS_MESSAGE_TYPE_INVALID;
	self->privileged = false;

	return self;
}

/* ========================================================================= *
 * PEERSTATE_T
 * ========================================================================= */

802
const char *
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
peerstate_repr(peerstate_t state)
{
    const char *repr = "PEERSTATE_INVALID";

    switch( state ) {
    case PEERSTATE_INITIAL:       repr = "PEERSTATE_INITIAL";     break;
    case PEERSTATE_QUERY_OWNER:   repr = "PEERSTATE_QUERY_OWNER"; break;
    case PEERSTATE_QUERY_PID:     repr = "PEERSTATE_QUERY_PID";   break;
    case PEERSTATE_RUNNING:       repr = "PEERSTATE_RUNNING";     break;
    case PEERSTATE_STOPPED:       repr = "PEERSTATE_STOPPED";     break;
    default: break;
    }

    return repr;
}

/* ========================================================================= *
 * PEERQUIT_T
 * ========================================================================= */

static peerquit_t *
peerquit_create(peerinfo_t *parent, peerquit_fn callback)
{
    peerquit_t *self = g_malloc0(sizeof *self);

    self->pq_peerinfo = parent;
    self->pq_callback = callback;

    mce_log(LL_DEBUG, "create quit notify: %s -> %p",
	    peerinfo_name(self->pq_peerinfo),
	    self->pq_callback);

    return self;
}

static void
peerquit_delete(peerquit_t *self)
{
    if( self )
    {
	mce_log(LL_DEBUG, "delete quit notify: %s -> %p",
		peerinfo_name(self->pq_peerinfo),
		self->pq_callback);

	g_free(self);
    }
}

static void
peerquit_notify(peerquit_t *self, DBusMessage *msg)
{
    mce_log(LL_DEBUG, "execute quit notify: %s -> %p",
	    peerinfo_name(self->pq_peerinfo),
	    self->pq_callback);
    self->pq_callback(msg);
}

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
/* ========================================================================= *
 * PEERNOTIFY_T
 * ========================================================================= */

/** Callback for Notifying initial peer state
 *
 * @param aptr  peernotify_t object as void pointer
 *
 * @return FALSE to stop idle callback from being repeated
 */
static gboolean
peernotify_idle_cb(gpointer aptr)
{
    peernotify_t *self = aptr;

    if( self->pn_idle_id ) {
	self->pn_idle_id = 0;
	peernotify_execute(self);
    }

    return FALSE;
}

/** Schedule initial state notification for freshly added tracker
 *
 * Is called as a consequence of peerinfo_add_notify_callback() call.
 *
 * @param self  peernotify_t object
 */
static void
peernotify_schedule(peernotify_t *self)
{
    if( !self->pn_idle_id ) {
	self->pn_idle_id  = g_idle_add(peernotify_idle_cb, self);
    }
}

/** Cancel initial state notification for freshly added tracker
 *
 * Is called a part of notify object cleanup / if the tracking
 * state change notification gets emitted before idle callback
 * gets a chance to get dispatched.
 *
 * @param self  peernotify_t object
 */
static void
peernotify_unschedule(peernotify_t *self)
{
    if( self->pn_idle_id ) {
	g_source_remove(self->pn_idle_id), self->pn_idle_id = 0;
    }
}

/** Notify peer tracking state change
 *
 * @param self  peernotify_t object
 */
static void
peernotify_execute(peernotify_t *self)
{
    peernotify_unschedule(self);

    if( self->pn_callback ) {
	self->pn_callback(self->pn_peerinfo, self->pn_userdata);
    }
}

/** Create peer state tracking object
 *
 * @param peerinfo  D-Bus client being tracked
 * @param callback  Notification function to call on state change
 * @param userdata  A pointer that should be passed to notification callback
 * @param userfree  free() like function to call on userdata on cleanup
 *
 * @param self  peernotify_t object
 */
static peernotify_t *
peernotify_create(peerinfo_t       *peerinfo,
		  peernotify_fn     callback,
		  gpointer          userdata,
		  GDestroyNotify    userfree)
{
    peernotify_t *self = calloc(1, sizeof *self);

    self->pn_peerinfo = peerinfo;
    self->pn_callback = callback;
    self->pn_userdata = userdata;
    self->pn_userfree = userfree;
    self->pn_idle_id  = 0;

    peernotify_schedule(self);

    return self;
}

/** Delete peer state tracking object
 *
 * @param self  peernotify_t object, or NULL
 */
static void
peernotify_delete(peernotify_t *self)
{
    if( self != 0 )
    {
	peernotify_unschedule(self);

	if( self->pn_userdata && self->pn_userfree )
	    self->pn_userfree(self->pn_userdata);

	self->pn_peerinfo = 0;
	self->pn_callback = 0;
	self->pn_userdata = 0;
	self->pn_userfree = 0;

	free(self);
    }
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
/* ========================================================================= *
 * PEERINFO_T
 * ========================================================================= */

/* ------------------------------------------------------------------------- *
 * misc helpers
 * ------------------------------------------------------------------------- */

static gchar *
peerinfo_guess_cmd(pid_t pid)
{
    gchar *cmd  = 0;
    int    file = -1;

    char path[256];
    unsigned char text[64];

    snprintf(path, sizeof path, "/proc/%d/cmdline", (int)pid);
    if( (file = open(path, O_RDONLY)) == -1 ) {
	mce_log(LL_ERR, "%s: open: %m", path);
	goto EXIT;
    }

    int n = read(file, text, sizeof text - 1);
    if( n == -1 ) {
	mce_log(LL_ERR, "%s: read: %m", path);
	goto EXIT;
    }
    text[n] = 0;

    for( int i = 0; i < n; ++i ) {
	if( text[i] < 32 )
	    text[i] = ' ';
    }

    cmd = g_strdup((char *)text);

EXIT:
    if( file != -1 ) close(file);

    return cmd;
}

/* ------------------------------------------------------------------------- *
 * create / delete
 * ------------------------------------------------------------------------- */

static inline void
peerinfo_ctor(peerinfo_t *self, const char *name)
{
    self->pi_state         = PEERSTATE_INITIAL;
    self->pi_name          = g_strdup(name);
    self->pi_owner_name    = 0;
    self->pi_owner_pid     = PEERINFO_NO_PID;
    self->pi_owner_uid     = PEERINFO_NO_UID;
    self->pi_owner_gid     = PEERINFO_NO_GID;
    self->pi_owner_cmd     = 0;
    self->pi_datapipe      = 0;
    self->pi_name_owner_pc = 0;
    self->pi_name_pid_pc   = 0;
    self->pi_delete_id     = 0;

    g_queue_init(&self->pi_quit_callbacks);
1041
    g_queue_init(&self->pi_notifications);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    g_queue_init(&self->pi_priv_methods);

    mce_log(LL_DEBUG, "[%s] create", peerinfo_name(self));

    self->pi_rule = mce_dbus_nameowner_watch(peerinfo_name(self));

    peerinfo_set_state(self, PEERSTATE_QUERY_OWNER);
}

static inline void
peerinfo_dtor(peerinfo_t *self)
{
    mce_log(LL_DEBUG, "[%s] delete", peerinfo_name(self));

    mce_dbus_nameowner_unwatch(self->pi_rule),
	self->pi_rule = 0;

    peerinfo_flush_quit_callbacks(self);
1060
    peerinfo_flush_notify_callbacks(self);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    peerinfo_flush_methods(self);

    peerinfo_set_owner_name(self, 0);
    peerinfo_set_owner_pid(self, PEERINFO_NO_PID);
    peerinfo_set_owner_uid(self, PEERINFO_NO_UID);
    peerinfo_set_owner_gid(self, PEERINFO_NO_GID);

    peerinfo_query_owner_ign(self);
    peerinfo_query_pid_ign(self);
    peerinfo_query_delete_ign(self);

    g_free(self->pi_name),
	self->pi_name = 0;
}

peerinfo_t *
peerinfo_create(const char *name)
{
    peerinfo_t *self = g_malloc0(sizeof *self);
    peerinfo_ctor(self, name);
    return self;
}

void
peerinfo_delete(peerinfo_t *self)
{
    if( self != 0 )
    {
	peerinfo_dtor(self);
	g_free(self);
    }
}

void
peerinfo_delete_cb(void *self)
{
    peerinfo_delete(self);
}

/* ------------------------------------------------------------------------- *
 * state management
 * ------------------------------------------------------------------------- */

static void
peerinfo_enter_state(peerinfo_t *self)
{
    switch( self->pi_state ) {
    case PEERSTATE_INITIAL:
	break;

    case PEERSTATE_QUERY_OWNER:
	if( *peerinfo_name(self) == ':' ) {
	    peerinfo_set_owner_name(self, peerinfo_name(self));
	    peerinfo_set_state(self, PEERSTATE_QUERY_PID);
	}
	else {
1117
	    peerinfo_set_owner_name(self, 0);
1118 1119 1120 1121 1122
	    peerinfo_query_owner_req(self);
	}
	break;

    case PEERSTATE_QUERY_PID:
1123 1124 1125
	peerinfo_set_owner_pid(self, PEERINFO_NO_PID);
	peerinfo_set_owner_uid(self, PEERINFO_NO_UID);
	peerinfo_set_owner_gid(self, PEERINFO_NO_GID);
1126 1127 1128 1129
	peerinfo_query_pid_req(self);
	break;

    case PEERSTATE_RUNNING:
1130 1131 1132 1133 1134
	/* Make sure any previously logged ipc without process
	 * details can be mapped to something useful when
	 * debugging -> emit details now that we have them. */
	mce_log(LL_DEVEL, "%s", peerinfo_repr(self));

1135
	if( self->pi_datapipe ) {
1136
	    datapipe_exec_full(self->pi_datapipe,
1137
			       GINT_TO_POINTER(SERVICE_STATE_RUNNING));
1138 1139 1140 1141 1142
	}
	peerinfo_handle_methods(self);
	break;

    case PEERSTATE_STOPPED:
1143 1144 1145 1146
	if( self->pi_datapipe ) {
	    datapipe_exec_full(self->pi_datapipe,
			       GINT_TO_POINTER(SERVICE_STATE_STOPPED));
	}
1147 1148 1149 1150
	peerinfo_flush_methods(self);
	peerinfo_execute_quit_callbacks(self);

	/* Private names do not come back, delete from cache */
1151 1152
	if( *peerinfo_name(self) == ':' )
	    peerinfo_query_delete_req(self);
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
	break;

    default:
	mce_abort();
    }
}

static void
peerinfo_leave_state(peerinfo_t *self)
{
    switch( self->pi_state ) {
    case PEERSTATE_INITIAL:
	break;

    case PEERSTATE_QUERY_OWNER:
	peerinfo_query_owner_ign(self);
	break;

    case PEERSTATE_QUERY_PID:
	peerinfo_query_pid_ign(self);
	break;

    case PEERSTATE_RUNNING:
	break;

    case PEERSTATE_STOPPED:
1179
	peerinfo_query_delete_ign(self);
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
	break;

    default:
	mce_abort();
    }
}

static void
peerinfo_set_state(peerinfo_t *self, peerstate_t state)
{
    if( self->pi_state == state )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] state: %s -> %s",
	    peerinfo_name(self),
	    peerstate_repr(self->pi_state),
	    peerstate_repr(state));

    peerinfo_leave_state(self);
    self->pi_state = state;
    peerinfo_enter_state(self);

1202 1203
    peerinfo_execute_notify_callbacks(self);

1204 1205 1206 1207
EXIT:
    return;
}

1208
peerstate_t
1209 1210 1211 1212 1213 1214 1215 1216 1217
peerinfo_get_state(const peerinfo_t *self)
{
    return self->pi_state;
}

/* ------------------------------------------------------------------------- *
 * property accessors
 * ------------------------------------------------------------------------- */

1218
static const char *
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
peerinfo_repr(peerinfo_t *self)
{
    const char *desc = 0;

    if( !self )
	goto EXIT;

    snprintf(self->pi_repr, sizeof self->pi_repr,
	     "name=%s owner=%s pid=%d uid=%d gid=%d priv=%d cmd=%s",
	     peerinfo_name (self),
	     peerinfo_get_owner_name(self) ?: "NULL",
	     (int)peerinfo_get_owner_pid(self),
	     (int)peerinfo_get_owner_uid(self),
	     (int)peerinfo_get_owner_gid(self),
	     peerinfo_get_privileged(self, false),
	     peerinfo_get_owner_cmd(self) ?: "NULL");

    desc = self->pi_repr;

EXIT:
    return desc;
}

1242
const char *
1243 1244 1245 1246 1247
peerinfo_name(const peerinfo_t *self)
{
    return self->pi_name;
}

1248
const char *
1249 1250 1251 1252 1253
peerinfo_get_owner_name(const peerinfo_t *self)
{
    return self->pi_owner_name;
}

1254
static bool
1255 1256
peerinfo_set_owner_name(peerinfo_t *self, const char *name)
{
1257 1258 1259 1260 1261
    bool changed = false;

    if( name && !*name )
	name = 0;

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    if( !g_strcmp0(self->pi_owner_name, name) )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner name: %s -> %s",
	    peerinfo_name(self),
	    self->pi_owner_name ?: "NULL",
	    name          ?: "NULL");

    g_free(self->pi_owner_name),
	self->pi_owner_name = name ? g_strdup(name) : 0;

1273
    changed = true;
1274 1275

EXIT:
1276
    return changed;
1277 1278
}

1279
pid_t
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
peerinfo_get_owner_pid(const peerinfo_t *self)
{
    return self->pi_owner_pid;
}

static void
peerinfo_set_owner_pid(peerinfo_t *self, pid_t pid)
{
    if( self->pi_owner_pid == pid )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner pid: %d -> %d",
	    peerinfo_name(self),
	    (int)self->pi_owner_pid,
	    (int)pid);

    self->pi_owner_pid = pid;

    gchar *cmd = 0;
    if( pid != PEERINFO_NO_PID )
	cmd = peerinfo_guess_cmd(pid);
    peerinfo_set_owner_cmd(self, cmd);
    g_free(cmd);

    if( pid != PEERINFO_NO_PID ) {
	char path[256];
	snprintf(path, sizeof path, "/proc/%d", (int)pid);

	struct stat st;
	memset(&st, 0, sizeof st);
	if( stat(path, &st) == 0 ) {
	    peerinfo_set_owner_uid(self, st.st_uid);
	    peerinfo_set_owner_gid(self, st.st_gid);
	}
    }

EXIT:
    return;
}

1320
uid_t
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
peerinfo_get_owner_uid(const peerinfo_t *self)
{
    return self->pi_owner_uid;
}

static void
peerinfo_set_owner_uid(peerinfo_t *self, uid_t uid)
{
    if( self->pi_owner_uid == uid )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner uid: %d -> %d",
	    peerinfo_name(self),
	    (int)self->pi_owner_uid,
	    (int)uid);

    self->pi_owner_uid = uid;

EXIT:
    return;
}

1343
gid_t
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
peerinfo_get_owner_gid(const peerinfo_t *self)
{
    return self->pi_owner_gid;
}

static void
peerinfo_set_owner_gid(peerinfo_t *self, gid_t gid)
{
    if( self->pi_owner_gid == gid )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner gid: %d -> %d",
	    peerinfo_name(self),
	    (int)self->pi_owner_gid,
	    (int)gid);

    self->pi_owner_gid = gid;

EXIT:
    return;
}

1366
const char *
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
peerinfo_get_owner_cmd(const peerinfo_t *self)
{
    return self->pi_owner_cmd;
}

static void
peerinfo_set_owner_cmd(peerinfo_t *self, const char *cmd)
{
    if( !g_strcmp0(self->pi_owner_cmd, cmd) )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner cmd: %s -> %s",
	    peerinfo_name(self),
	    self->pi_owner_cmd ?: "NULL",
	    cmd                ?: "NULL");

    g_free(self->pi_owner_cmd),
	self->pi_owner_cmd = cmd ? g_strdup(cmd) : 0;

EXIT:
    return;
}

static privileged_t
peerinfo_get_privileged(const peerinfo_t *self, bool no_caching)
{
    privileged_t privileged = PRIVILEGED_NO;

    if( !self )
	goto EXIT;

    pid_t pid = peerinfo_get_owner_pid(self);
    if( pid == PEERINFO_NO_PID ) {
	privileged = PRIVILEGED_UNKNOWN;
	goto EXIT;
    }

    uid_t uid = PEERINFO_NO_UID;
    gid_t gid = PEERINFO_NO_GID;

    if( no_caching ) {

	/* The owner / group of /proc/PID directory reflects
	 * the current euid / egid of the process. */

	char path[256];
	struct stat st;

	memset(&st, 0, sizeof st);
	snprintf(path, sizeof path, "/proc/%d", (int)pid);

	if( stat(path, &st) == -1 )
	    goto EXIT;

	uid = st.st_uid;
	gid = st.st_gid;
    }
    else {
	uid = peerinfo_get_owner_uid(self);
	gid = peerinfo_get_owner_gid(self);
    }

    if( uid == PEERINFO_ROOT_UID ||
	uid == mce_dbus_privileged_uid ||
	gid == mce_dbus_privileged_gid ) {
	privileged = PRIVILEGED_YES;
    }

EXIT:
    return privileged;
}

static void
1440
peerinfo_set_datapipe(peerinfo_t *self, datapipe_t *datapipe)
1441 1442 1443 1444 1445 1446 1447
{
    mce_log(LL_DEBUG, "[%s] datapipe: %p -> %p",
	    peerinfo_name(self),
	    self->pi_datapipe,
	    datapipe);

    if( (self->pi_datapipe = datapipe) ) {
1448 1449 1450
	/* Report immediately if the state is already known */
	switch( peerinfo_get_state(self) ) {
	case PEERSTATE_RUNNING:
1451
	    datapipe_exec_full(self->pi_datapipe,
1452
			       GINT_TO_POINTER(SERVICE_STATE_RUNNING));
1453 1454 1455 1456 1457 1458 1459
	    break;
	case PEERSTATE_STOPPED:
	    datapipe_exec_full(self->pi_datapipe,
			       GINT_TO_POINTER(SERVICE_STATE_STOPPED));
	    break;
	default:
	    break;
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	}
    }
}

/* ------------------------------------------------------------------------- *
 * async owner name query
 * ------------------------------------------------------------------------- */

static void
peerinfo_query_owner_ign(peerinfo_t *self)
{
    if( !self->pi_name_owner_pc )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner query canceled", peerinfo_name(self));

    dbus_pending_call_cancel(self->pi_name_owner_pc);
    dbus_pending_call_unref(self->pi_name_owner_pc),
	self->pi_name_owner_pc = 0;

EXIT:
    return;
}

static void
peerinfo_query_owner_rsp(DBusPendingCall *pc, void *aptr)
{
    peerinfo_t  *self  = aptr;
    const char  *owner = 0;
    DBusMessage *rsp   = 0;
    DBusError    err   = DBUS_ERROR_INIT;

    mce_log(LL_DEBUG, "[%s] owner query replied", peerinfo_name(self));

    if( self->pi_name_owner_pc != pc )
	goto EXIT;

    dbus_pending_call_unref(self->pi_name_owner_pc),
	self->pi_name_owner_pc = 0;

1500 1501 1502 1503
    if( !(rsp = dbus_pending_call_steal_reply(pc)) ) {
	mce_log(LL_WARN, "null reply");
    }
    else if( dbus_set_error_from_message(&err, rsp) ) {
1504
	if( strcmp(err.name, DBUS_ERROR_NAME_HAS_NO_OWNER) ) {
1505
	    mce_log(LL_WARN, "error reply: %s: %s", err.name, err.message);
1506 1507
	}
    }
1508 1509 1510 1511 1512
    else if( !dbus_message_get_args(rsp, &err,
				    DBUS_TYPE_STRING, &owner,
				    DBUS_TYPE_INVALID) ) {
	mce_log(LL_WARN, "parse error: %s: %s", err.name, err.message);
    }
1513 1514 1515

    if( owner ) {
	peerinfo_set_owner_name(self, owner);
1516
	peerinfo_set_state(self, PEERSTATE_QUERY_PID);
1517 1518
    }
    else {
1519
	peerinfo_set_state(self, PEERSTATE_STOPPED);
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    }

EXIT:
    if( rsp ) dbus_message_unref(rsp);
    dbus_error_free(&err);
}

static void
peerinfo_query_owner_req(peerinfo_t *self)
{
    if( peerinfo_get_state(self) != PEERSTATE_QUERY_OWNER )
	goto EXIT;

    if( self->pi_name_owner_pc )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] owner query ...", peerinfo_name(self));

    const char *name = peerinfo_name(self);

    dbus_send_ex(DBUS_SERVICE_DBUS,
		 DBUS_PATH_DBUS,
		 DBUS_INTERFACE_DBUS,
		 "GetNameOwner",
		 peerinfo_query_owner_rsp,
		 self, 0,
		 &self->pi_name_owner_pc,
		 DBUS_TYPE_STRING, &name,
		 DBUS_TYPE_INVALID);

EXIT:
    return;
}

/* ------------------------------------------------------------------------- *
 * async owner pid query
 * ------------------------------------------------------------------------- */

static void
peerinfo_query_pid_ign(peerinfo_t *self)
{
    if( !self->pi_name_pid_pc )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] pid query canceled", peerinfo_name(self));

    dbus_pending_call_cancel(self->pi_name_pid_pc);
    dbus_pending_call_unref(self->pi_name_pid_pc),
	self->pi_name_pid_pc = 0;

EXIT:
    return;
}

static void
peerinfo_query_pid_rsp(DBusPendingCall *pc, void *aptr)
{
    peerinfo_t  *self  = aptr;
    dbus_uint32_t pid  = 0;
    DBusMessage *rsp   = 0;
    DBusError    err   = DBUS_ERROR_INIT;

    mce_log(LL_DEBUG, "[%s] pid query replied", peerinfo_name(self));

    if( self->pi_name_pid_pc != pc )
	goto EXIT;

    dbus_pending_call_unref(self->pi_name_pid_pc),
	self->pi_name_pid_pc = 0;

1590 1591 1592 1593 1594 1595 1596
    if( !(rsp = dbus_pending_call_steal_reply(pc)) ) {
	mce_log(LL_WARN, "null reply");
    }
    else if( dbus_set_error_from_message(&err, rsp) ) {
	mce_log(LL_WARN, "error reply: %s: %s", err.name, err.message);
    }
    else if( !dbus_message_get_args(rsp, &err,
1597
			       DBUS_TYPE_UINT32, &pid,
1598 1599
			       DBUS_TYPE_INVALID) ) {
	mce_log(LL_WARN, "parse error: %s: %s", err.name, err.message);
1600 1601 1602 1603 1604 1605 1606
    }

    if( pid ) {
	peerinfo_set_owner_pid(self, pid);
	peerinfo_set_state(self, PEERSTATE_RUNNING);
    }
    else {
1607
	peerinfo_set_state(self, PEERSTATE_STOPPED);
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
    }

EXIT:
    if( rsp ) dbus_message_unref(rsp);
    dbus_error_free(&err);
}

static void
peerinfo_query_pid_req(peerinfo_t *self)
{
    if( peerinfo_get_state(self) != PEERSTATE_QUERY_PID )
	goto EXIT;

    if( self->pi_name_pid_pc )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] pid query send", peerinfo_name(self));

    const char *name = peerinfo_name(self);

    dbus_send_ex(DBUS_SERVICE_DBUS,
		 DBUS_PATH_DBUS,
		 DBUS_INTERFACE_DBUS,
		 "GetConnectionUnixProcessID",
		 peerinfo_query_pid_rsp,
		 self, 0,
		 &self->pi_name_pid_pc,
		 DBUS_TYPE_STRING, &name,
		 DBUS_TYPE_INVALID);

EXIT:
    return;
}

/* ------------------------------------------------------------------------- *
 * delete timer
 * ------------------------------------------------------------------------- */

static void
peerinfo_query_delete_ign(peerinfo_t *self)
{
    if( !self->pi_delete_id )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] delete timer canceled", peerinfo_name(self));

    g_source_remove(self->pi_delete_id),
	self->pi_delete_id = 0;

EXIT:
    return;
}

static gboolean
peerinfo_query_delete_tmo(gpointer aptr)
{
    peerinfo_t  *self  = aptr;

    mce_log(LL_DEBUG, "[%s] delete timer triggered", peerinfo_name(self));

    if( !self->pi_delete_id )
	goto EXIT;

    self->pi_delete_id = 0;

1673 1674 1675 1676 1677
    /* Execute any quit callbacks that might have been queued
     * while peerinfo is already in PEERSTATE_STOPPED state.
     */
    peerinfo_execute_quit_callbacks(self);

1678 1679 1680 1681 1682 1683 1684 1685 1686
    mce_dbus_del_peerinfo(peerinfo_name(self));

EXIT:
    return FALSE;
}

static void
peerinfo_query_delete_req(peerinfo_t *self)
{
1687
    if( peerinfo_get_state(self) != PEERSTATE_STOPPED )
1688 1689 1690 1691 1692 1693 1694
	goto EXIT;

    if( self->pi_delete_id )
	goto EXIT;

    mce_log(LL_DEBUG, "[%s] delete timer scheduled", peerinfo_name(self));

1695
    self->pi_delete_id = g_timeout_add(500, peerinfo_query_delete_tmo, self);
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

EXIT:

    return;
}

/* ------------------------------------------------------------------------- *
 * quit notifications
 * ------------------------------------------------------------------------- */

static peerquit_t *
peerinfo_add_quit_callback(peerinfo_t *self, peerquit_fn callback)
{
    peerquit_t *quit = peerquit_create(self, callback);
    g_queue_push_tail(&self->pi_quit_callbacks, quit);
    return quit;
}

static void
peerinfo_remove_quit_callback(peerinfo_t *self, peerquit_t *quit)
{
    if( g_queue_remove(&self->pi_quit_callbacks, quit) )
	peerquit_delete(quit);
}

static void
peerinfo_execute_quit_callbacks(peerinfo_t *self)
{
    const char  *name  = peerinfo_name(self);
    const char  *owner = "";
    DBusMessage *faked = 0;

    peerquit_t *quit;

    mce_log(LL_DEBUG, "[%s] run quit notifications", peerinfo_name(self));

    while( (quit = g_queue_pop_head(&self->pi_quit_callbacks)) ) {
	if( !faked ) {
	    faked = dbus_message_new_signal("/org/freedesktop/DBus",
					    "org.freedesktop.DBus",
					    "NameOwnerChanged");
	    if( !faked )
		break;

	    dbus_message_append_args(faked,
				     DBUS_TYPE_STRING, &name,
				     DBUS_TYPE_STRING, &name,
				     DBUS_TYPE_STRING, &owner,
				     DBUS_TYPE_INVALID);
	}
	peerquit_notify(quit, faked);
	peerquit_delete(quit);
    }

    if( faked )
	dbus_message_unref(faked);
}

static void
peerinfo_flush_quit_callbacks(peerinfo_t *self)
{
    peerquit_t *quit;

    while( (quit = g_queue_pop_head(&self->pi_quit_callbacks)) )
	peerquit_delete(quit);
}

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
/* ------------------------------------------------------------------------- *
 * state change notifications
 * ------------------------------------------------------------------------- */

/** Find a peernotify_t slot related to a given notification callback
 *
 * Can be used both as a predicate for notification callback already
 * exist and accessing/removing the existing peernotify_t object.
 *
 * @param self      peerinfo_t object
 * @param callback  tracking state change notification callback
 * @param userdata  user data pointer that is passed to the callback
 *
 * @return GSlist entry that has notification data, or NULL if not present
 */
static GList *
peerinfo_find_notify_slot(peerinfo_t     *self,
			  peernotify_fn   callback,
			  gpointer        userdata)
{
    GList *slot = 0;

    for( GList *item = self->pi_notifications.head; item; item = item->next ) {
	peernotify_t *peernotify = item->data;
	if( !peernotify )
	    continue;
	if( peernotify->pn_callback != callback )
	    continue;
	if( peernotify->pn_userdata != userdata )
	    continue;
	slot = item;
	break;
    }

    return slot;
}

/** Remove all tracking state callbacks installed to peerinfo_t object
 *
 * @param self peerinfo_t object
 */
static void
peerinfo_flush_notify_callbacks(peerinfo_t *self)
{
    while( self->pi_notifications.head ) {
	peernotify_t *peernotify = g_queue_pop_head(&self->pi_notifications);
	peernotify_delete(peernotify);
    }
}

/** Execute all tracking state callbacks installed to peerinfo_t object
 *
 * @param self peerinfo_t object
 */
static void
peerinfo_execute_notify_callbacks(peerinfo_t *self)
{
    mce_log(LL_DEBUG, "[%s] run state notifications", peerinfo_name(self));

    bool flush = false;

    for( GList *item = self->pi_notifications.head; item; item = item->next ) {
	peernotify_t *peernotify = item->data;
	if( peernotify )
	    peernotify_execute(peernotify);

	/* Note: The callback might have removed itself */
	if( !item->data )
	    flush = true;
    }

    if( flush ) {
	g_queue_remove_all(&self->pi_notifications, 0);
    }
}

/** Add tracking state callback to peerinfo_t object
 *
 * @param self      peerinfo_t object
 * @param callback  Notification function to call on state change
 * @param userdata  A pointer that should be passed to notification callback
 * @param userfree  free() like function to call on userdata on cleanup
 */
static void
peerinfo_add_notify_callback(peerinfo_t     *self,
			     peernotify_fn   callback,
			     gpointer        userdata,
			     GDestroyNotify  userfree)
{
    GList *slot = peerinfo_find_notify_slot(self, callback, userdata);

    if( slot )
	goto EXIT;

    peernotify_t *peernotify = peernotify_create(self, callback,
						 userdata, userfree);

    g_queue_push_tail(&self->pi_notifications, peernotify);

EXIT:
    return;
}

/** Remove tracking state callback from peerinfo_t object
 *
 * @param self      peerinfo_t object
 * @param callback  Notification function to call on state change
 * @param userdata  A pointer that should be passed to notification callback
 */
static void
peerinfo_remove_notify_callback(peerinfo_t    *self,
				peernotify_fn  callback,
				gpointer       userdata)
{
    GList *slot = peerinfo_find_notify_slot(self, callback, userdata);

    if( !slot )
	goto EXIT;

    /* Note: To allow safe removal from notification callback,
     *       we just sever the item from queue without modifying
     *       the queue itself. The null links are left behind to
     *       be cleaned when peerinfo_execute_notify_callbacks()
     *       gets called the next time.
     */

    peernotify_t *peernotify = slot->data;
    slot->data = 0;
    peernotify_delete(peernotify);

EXIT:
    return;
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
/* ------------------------------------------------------------------------- *
 * waiting priviledged calls
 * ------------------------------------------------------------------------- */

static void
peerinfo_queue_method(peerinfo_t *self, DBusMessage *req)
{
    if( req ) {
	mce_log(LL_DEBUG, "queue %s call from %s",
		dbus_message_get_member(req),
		peerinfo_repr(self));
	g_queue_push_tail(&self->pi_priv_methods, dbus_message_ref(req));
    }
}

static void
peerinfo_flush_methods(peerinfo_t *self)
{
    DBusMessage *req;

    while( (req = g_queue_pop_head(&self->pi_priv_methods)) ) {
	mce_log(LL_WARN, "dropped %s call from %s",
		dbus_message_get_member(req),
		peerinfo_repr(self));
	dbus_message_unref(req);
    }
}

static void
peerinfo_handle_methods(peerinfo_t *self)
{
    DBusMessage *req;

    while( (req = g_queue_pop_head(&self->pi_priv_methods)) ) {
	mce_log(LL_DEBUG, "retry %s call from %s",
		dbus_message_get_member(req),
		peerinfo_repr(self));
	msg_handler(0, req, 0);
	dbus_message_unref(req);
    }
}

/* ========================================================================= *
 * PEER_TRACKING
 * ========================================================================= */

/** Lookup table of D-Bus names to watch */
static struct
{
1946 1947
    const char  *name;
    datapipe_t  *datapipe;
1948 1949 1950 1951 1952

} mce_dbus_nameowner_lut[] =
{
    {
	.name     = DSME_DBUS_SERVICE,
1953
	.datapipe = &dsme_service_state_pipe,
1954
    },
1955 1956 1957 1958
    {
	.name     = thermalmanager_service,
	.datapipe = &thermalmanager_service_state_pipe,
    },
1959 1960
    {
	.name     = "org.bluez",
1961
	.datapipe = &bluez_service_state_pipe,
1962 1963 1964
    },
    {
	.name     = COMPOSITOR_SERVICE,
1965
	.datapipe = &compositor_service_state_pipe,
1966 1967 1968 1969 1970
    },
    {
	/* Note: due to lipstick==compositor assumption lipstick
	 *       service name must be probed after compositor */
	.name     = LIPSTICK_SERVICE,
1971
	.datapipe = &lipstick_service_state_pipe,
1972 1973 1974
    },
    {
	.name     = DEVICELOCK_SERVICE,
1975
	.datapipe = &devicelock_service_state_pipe,
1976 1977 1978
    },
    {
	.name     = USB_MODED_DBUS_SERVICE,
1979
	.datapipe = &usbmoded_service_state_pipe,
1980
    },
1981 1982 1983 1984
    {
	.name     = FINGERPRINT1_DBUS_SERVICE,
	.datapipe = &fpd_service_state_pipe,
    },
1985 1986
    {
	.name     = "com.nokia.NonGraphicFeedback1.Backend",
1987
	.datapipe = &ngfd_service_state_pipe,
1988 1989 1990 1991 1992 1993 1994
    },
    {
	.name = 0,
    }
};

/** D-Bus message filter for handling NameOwnerChanged signals
spiiroin's avatar
spiiroin committed
1995
 *
1996 1997 1998
 * @param con       (not used)
 * @param msg       message to be acted upon
 * @param user_data (not used)
spiiroin's avatar
spiiroin committed
1999
 *
2000
 * @return DBUS_HANDLER_RESULT_NOT_YET_HANDLED (other filters see the msg too)
spiiroin's avatar
spiiroin committed
2001
 */
2002 2003 2004
static
DBusHandlerResult
mce_dbus_peerinfo_filter_cb(DBusConnection *con, DBusMessage *msg, void *user_data)
spiiroin's avatar
spiiroin committed
2005
{
2006 2007
    (void)user_data;
    (void)con;
spiiroin's avatar
spiiroin committed
2008

2009
    DBusHandlerResult res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
spiiroin's avatar
spiiroin committed
2010

2011 2012 2013
    const char *name = 0;
    const char *prev = 0;
    const char *curr = 0;
spiiroin's avatar
spiiroin committed
2014

2015
    DBusError err = DBUS_ERROR_INIT;
spiiroin's avatar
spiiroin committed
2016

2017 2018 2019
    if( !dbus_message_is_signal(msg, DBUS_INTERFACE_DBUS,
				"NameOwnerChanged") )
	goto EXIT;
spiiroin's avatar
spiiroin committed
2020

2021 2022 2023 2024 2025 2026 2027 2028
    if( !dbus_message_get_args(msg, &err,
			       DBUS_TYPE_STRING, &name,
			       DBUS_TYPE_STRING, &prev,
			       DBUS_TYPE_STRING, &curr,
			       DBUS_TYPE_INVALID) ) {
	mce_log(LL_WARN, "%s: %s", err.name, err.message);
	goto EXIT;
    }
spiiroin's avatar
spiiroin committed
2029

2030
    mce_dbus_update_peerinfo(name, curr);
spiiroin's avatar
spiiroin committed
2031 2032

EXIT:
2033 2034
    dbus_error_free(&err);
    return res;
spiiroin's avatar
spiiroin committed
2035 2036
}

2037 2038
/** D-Bus name to peerinfo_t object look up table */
static GHashTable *mce_dbus_peerinfo_lut = 0;
2039

2040 2041 2042 2043
/** Initialize peerinfo lookup table and seed it with essential services
 */
static void
mce_dbus_init_peerinfo(void)
2044
{
2045 2046 2047
    if( !mce_dbus_peerinfo_lut ) {
	mce_dbus_peerinfo_lut = g_hash_table_new_full(g_str_hash, g_str_equal,
						      g_free, peerinfo_delete_cb);
2048

2049 2050
	dbus_connection_add_filter(dbus_connection,
				   mce_dbus_peerinfo_filter_cb, 0, 0);
2051

2052 2053 2054 2055 2056
	for( int i = 0; mce_dbus_nameowner_lut[i].name; ++i ) {
	    peerinfo_t *info = mce_dbus_add_peerinfo(mce_dbus_nameowner_lut[i].name);
	    peerinfo_set_datapipe(info, mce_dbus_nameowner_lut[i].datapipe);
	}
    }
2057 2058
}

2059 2060 2061 2062
/** Cleanup peerinfo lookup table
 */
static void
mce_dbus_quit_peerinfo(void)
2063
{
2064 2065 2066
    if( mce_dbus_peerinfo_lut ) {
	dbus_connection_remove_filter(dbus_connection,
				      mce_dbus_peerinfo_filter_cb, 0);
2067

2068 2069 2070
	g_hash_table_unref(mce_dbus_peerinfo_lut),
	    mce_dbus_peerinfo_lut = 0;
    }
2071 2072
}

2073 2074 2075 2076
/** Lookup already existing peerinfo based on D-Bus name
 */
peerinfo_t *
mce_dbus_get_peerinfo(const char *name)
2077
{
2078 2079 2080 2081 2082 2083 2084 2085 2086
    peerinfo_t *info = 0;

    if( !mce_dbus_peerinfo_lut )
	goto EXIT;

    info = g_hash_table_lookup(mce_dbus_peerinfo_lut, name);

EXIT:
    return info;
2087 2088
}

2089 2090 2091 2092
/** Lookup / create peerinfo based on D-Bus name
 */
peerinfo_t *
mce_dbus_add_peerinfo(const char *name)
2093
{
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
    peerinfo_t *info = 0;

    if( !mce_dbus_peerinfo_lut )
	goto EXIT;

    if( !(info = g_hash_table_lookup(mce_dbus_peerinfo_lut, name)) ) {
	info = peerinfo_create(name);
	g_hash_table_replace(mce_dbus_peerinfo_lut,
			     g_strdup(name), info);
    }

EXIT:
    return info;
2107 2108
}

2109 2110 2111 2112
/** Update name owner in already existing peerinfo object
 */
void
mce_dbus_update_peerinfo(const char *name, const char *owner)
2113
{
2114 2115 2116 2117 2118
    peerinfo_t *info = mce_dbus_get_peerinfo(name);

    if( !info )
	goto EXIT;

2119
    if( peerinfo_set_owner_name(info, owner) ) {
2120 2121
	peerinfo_set_state(info, PEERSTATE_STOPPED);

2122 2123 2124 2125
	if( peerinfo_get_owner_name(info) ) {
	    peerinfo_set_state(info, PEERSTATE_QUERY_PID);
	}
    }
2126 2127 2128

EXIT:
    return;
2129 2130
}

2131 2132 2133 2134
/** Remove peerinfo based on D-Bus name
 */
void
mce_dbus_del_peerinfo(const char *name)
2135
{
2136 2137
    if( !mce_dbus_peerinfo_lut )
	goto EXIT;
2138

2139
    g_hash_table_remove(mce_dbus_peerinfo_lut, name);
2140 2141

EXIT:
2142
    return;
2143
}
2144

2145 2146 2147 2148
/** Get useful-for-debugging description of process owning D-Bus name
 */
const char *
mce_dbus_get_peerdesc(const char *name)
2149
{
2150
    return peerinfo_repr(mce_dbus_add_peerinfo(name));
2151
}
2152

2153 2154 2155 2156
/* ========================================================================= *
 * MESSAGE_SENDING
 * ========================================================================= */

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
/** Return reference to dbus connection cached at mce-dbus module
 *
 * For use in situations where the abstraction provided by mce-dbus
 * makes things too complicated.
 *
 * Caller must release non-null return values with dbus_connection_unref().
 *
 * @return DBusConnection, or NULL if mce has no dbus connection
 */
DBusConnection *dbus_connection_get(void)
{
	if( !dbus_connection ) {
		mce_log(LL_WARN, "no dbus connection");
		return NULL;
	}
	return dbus_connection_ref(dbus_connection);
}

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
/**
 * Create a new D-Bus signal, with proper error checking
 * will exit the mainloop if an error occurs
 *
 * @param path The signal path
 * @param interface The signal interface
 * @param name The name of the signal to send
 * @return A new DBusMessage
 */
DBusMessage *dbus_new_signal(const gchar *const path,
			     const gchar *const interface,
			     const gchar *const name)
{
2188 2189 2190 2191
	DBusMessage *msg = dbus_message_new_signal(path, interface, name);

	if( !msg )
		mce_abort();
2192

2193 2194 2195
	if( !introspectable_signal(interface, name) ) {
		mce_log(LL_ERR, "sending non-introspectable signal: %s.%s",
			interface, name);
2196 2197 2198 2199 2200 2201 2202 2203 2204
	}

	return msg;
}

/**
 * Create a new D-Bus error message, with proper error checking
 * will exit the mainloop if an error occurs
 *
2205 2206 2207 2208 2209
 * @param req  Method call message for which to create an error reply
 * @param err  D-Bus error name
 * @param fmt  Error message format string
 * @param ...  Arguments required by the format string
 *
2210 2211
 * @return A new DBusMessage
 */
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221

static DBusMessage *dbus_new_error(DBusMessage *req,
				   const char *err,
				   const char *fmt,
				   ...) __attribute__((format(printf, 3, 4)));

static DBusMessage *dbus_new_error(DBusMessage *req,
				   const char *err,
				   const char *fmt,
				   ...)
2222
{
2223
	char *msg = 0;
2224

2225 2226 2227 2228 2229 2230 2231
	va_list va;
	va_start(va, fmt);
	if( vasprintf(&msg, fmt, va) < 0 )
		msg = 0;
	va_end(va);

	DBusMessage *rsp = dbus_message_new_error(req, err, msg);
2232

2233 2234 2235 2236 2237
	if( !rsp )
		mce_abort();

	free(msg);
	return rsp;
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
}

/**
 * Create a new D-Bus method call, with proper error checking
 * will exit the mainloop if an error occurs
 *
 * @param service The method call service
 * @param path The method call path
 * @param interface The method call interface
 * @param name The name of the method to call
 * @return A new DBusMessage
 */
DBusMessage *dbus_new_method_call(const gchar *const service,
				  const gchar *const path,
				  const gchar *const interface,
				  const gchar *const name)
{
2255 2256 2257 2258
	DBusMessage *msg = dbus_message_new_method_call(service, path,
							interface, name);
	if( !msg )
		mce_abort();
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271

	return msg;
}

/**
 * Create a new D-Bus method call reply, with proper error checking
 * will exit the mainloop if an error occurs
 *
 * @param message The DBusMessage to reply to
 * @return A new DBusMessage
 */
DBusMessage *dbus_new_method_reply(DBusMessage *const message)
{
2272
	DBusMessage *msg = dbus_message_new_method_return(message);
2273

2274 2275
	if( !msg )
		mce_abort();
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290

	return msg;
}

/**
 * Send a D-Bus message
 * Side-effects: frees msg
 *
 * @param msg The D-Bus message to send
 * @return TRUE on success, FALSE on out of memory
 */
gboolean dbus_send_message(DBusMessage *const msg)
{
	gboolean status = FALSE;

2291 2292
	mce_wakelock_obtain("dbus_send", MCE_DBUS_SEND_SUSPEND_BLOCK_MS);

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
	if (dbus_connection_send(dbus_connection, msg, NULL) == FALSE) {
		mce_log(LL_CRIT,
			"Out of memory when sending D-Bus message");
		goto EXIT;
	}

	status = TRUE;

EXIT:
	dbus_message_unref(msg);

	return status;
}

/**
 * Send a D-Bus message and setup a reply callback
 * Side-effects: frees msg
 *
 * @param msg The D-Bus message to send
 * @param callback The reply callback
2313 2314
 * @param user_data Data to pass to callback
 * @param user_free Delete callback for user_data
2315 2316
 * @return TRUE on success, FALSE on failure
 */
2317 2318 2319
static gboolean
dbus_send_message_with_reply_handler(DBusMessage *const msg,
				     DBusPendingCallNotifyFunction</