usb_moded-dsme.c 22.8 KB
Newer Older
1
/**
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * @file usb_moded-dsme.c
 *
 * Copyright (C) 2013-2018 Jolla. All rights reserved.
 *
 * @author: Philippe De Swert <philippe.deswert@jollamobile.com>
 * @author: Jonni Rainisto <jonni.rainisto@jollamobile.com>
 * @author: Simo Piiroinen <simo.piiroinen@jollamobile.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Lesser GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * This program 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
 * General Public License for more details.
 *
 * You should have received a copy of the Lesser GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */
24 25

#include "usb_moded-dsme.h"
26 27

#include "usb_moded-control.h"
28
#include "usb_moded-dbus-private.h"
29
#include "usb_moded-log.h"
30 31 32 33
#include "usb_moded-modesetting.h"

#include <stdlib.h>
#include <unistd.h>
34

35 36 37 38
#include <dsme/state.h>
#include <dsme/protocol.h>
#include <dsme/processwd.h>

39
/* ========================================================================= *
40
 * DSME D-Bus Constants
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 * ========================================================================= */

#define DSME_DBUS_SERVICE               "com.nokia.dsme"

#define DSME_DBUS_REQUEST_PATH          "/com/nokia/dsme/request"
#define DSME_DBUS_REQUEST_IFACE         "com.nokia.dsme.request"
#define DSME_DBUS_GET_STATE_REQ         "get_state"

#define DSME_DBUS_SIGNAL_PATH           "/com/nokia/dsme/signal"
#define DSME_DBUS_SIGNAL_IFACE          "com.nokia.dsme.signal"
#define DSME_STATE_CHANGE_SIG           "state_change_ind"

#define DSME_STATE_CHANGE_MATCH\
     "type='signal'"\
     ",interface='"DSME_DBUS_SIGNAL_IFACE"'"\
     ",member='"DSME_STATE_CHANGE_SIG"'"

#define DSME_OWNER_CHANGE_MATCH\
     "type='signal'"\
     ",interface='"DBUS_INTERFACE_DBUS"'"\
     ",member='"DBUS_NAME_OWNER_CHANGED_SIG"'"\
     ",arg0='"DSME_DBUS_SERVICE"'"

/* ========================================================================= *
65
 * Functionality
66 67
 * ========================================================================= */

68 69 70
/* ------------------------------------------------------------------------- *
 * DSME_STATE_TRACKING
 * ------------------------------------------------------------------------- */
71

72 73 74 75 76 77 78 79 80 81 82
static const char        *dsme_state_repr                       (dsme_state_t state);
static dsme_state_t       dsme_state_parse                      (const char *name);

static void               dsme_state_update                     (dsme_state_t state);
static bool               dsme_state_is_shutdown                (void);
static bool               dsme_state_is_user                    (void);

/* ------------------------------------------------------------------------- *
 * DSME_SOCKET_IPC
 * ------------------------------------------------------------------------- */

83
static bool               dsme_socket_send_message              (void *msg);
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 113 114 115 116 117 118 119 120 121
static void               dsme_socket_processwd_pong            (void);
static void               dsme_socket_processwd_init            (void);
static void               dsme_socket_processwd_quit            (void);
static void               dsme_socket_query_state               (void);

static gboolean           dsme_socket_recv_cb                   (GIOChannel *source, GIOCondition condition, gpointer data);
static bool               dsme_socket_is_connected              (void);
static bool               dsme_socket_connect                   (void);
static void               dsme_socket_disconnect                (void);

/* ------------------------------------------------------------------------- *
 * DSME_DBUS_IPC
 * ------------------------------------------------------------------------- */

static void               dsme_dbus_device_state_update         (const char *state);
static void               dsme_dbus_device_state_query_cb       (DBusPendingCall *pending, void *aptr);
static void               dsme_dbus_device_state_query          (void);
static void               dsme_dbus_device_state_cancel         (void);
static void               dsme_dbus_device_state_signal         (DBusMessage *msg);

static bool               dsme_dbus_name_owner_available        (void);
static void               dsme_dbus_name_owner_update           (const char *owner);
static void               dsme_dbus_name_owner_query_cb         (const char *owner);
static void               dsme_dbus_name_owner_query            (void);
static void               dsme_dbus_name_owner_cancel           (void);
static void               dsme_dbus_name_owner_signal           (DBusMessage *msg);

static DBusHandlerResult  dsme_dbus_filter_cb                   (DBusConnection *con, DBusMessage *msg, void *user_data);

static bool               dsme_dbus_init                        (void);
static void               dsme_dbus_quit                        (void);

/* ------------------------------------------------------------------------- *
 * MODULE_API
 * ------------------------------------------------------------------------- */

gboolean                  dsme_listener_start                   (void);
void                      dsme_listener_stop                    (void);
122
gboolean                  dsme_in_user_state                    (void);
123 124 125 126 127 128 129 130 131 132 133 134 135

/* ========================================================================= *
 * DSME_STATE_TRACKING
 * ========================================================================= */

/** Lookup table for dsme state name <-> state enum conversion */
static const struct
{
    const char   *name;
    dsme_state_t  state;
} dsme_states[] =
{
#define DSME_STATE(NAME, VALUE) { #NAME, DSME_STATE_##NAME },
136
#include <dsme/state_states.h> // NOTRIM
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 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
#undef  DSME_STATE
};

/* Cached dsme state */
static dsme_state_t dsme_state_val = DSME_STATE_NOT_SET;

/* Flag for: dsme_state_val is USER */
static bool dsme_user_state = false;

/* Flag for: dsme_state_val is SHUTDOWN | REBOOT */
static bool dsme_shutdown_state = false;

/** Convert dsme state enum value to string
 */
static const char *
dsme_state_repr(dsme_state_t state)
{
    const char *repr = "DSME_STATE_UNKNOWN";

    for( size_t i = 0; i < G_N_ELEMENTS(dsme_states); ++i ) {
        if( dsme_states[i].state == state ) {
            repr = dsme_states[i].name;
            break;
        }
    }

    return repr;
}

/** Convert dsme state name to enum value
 */
static dsme_state_t
dsme_state_parse(const char *name)
{
    dsme_state_t state = DSME_STATE_NOT_SET;

    for( size_t i = 0; i < G_N_ELEMENTS(dsme_states); ++i ) {
        if( !strcmp(dsme_states[i].name, name) ) {
            state = dsme_states[i].state;
            break;
        }
    }

    return state;
}

/** Update cached dsme state
 */
static void
dsme_state_update(dsme_state_t state)
{
    /* Handle state change */
    if( dsme_state_val != state ) {
        log_debug("dsme_state: %s -> %s",
                  dsme_state_repr(dsme_state_val),
                  dsme_state_repr(state));
        dsme_state_val = state;
    }

    /* Handle entry to / exit from USER state */
    bool user_state = (state == DSME_STATE_USER);

    if( dsme_user_state != user_state ) {
        dsme_user_state = user_state;
        log_debug("in user state: %s", dsme_user_state ? "true" : "false");

203
        control_rethink_usb_charging_fallback();
204 205 206 207 208 209 210 211 212 213
    }

    /* Handle entry to / exit from SHUTDOWN / REBOOT state */
    bool shutdown_state = (state == DSME_STATE_SHUTDOWN ||
                           state == DSME_STATE_REBOOT);

    if( dsme_shutdown_state != shutdown_state ) {
        dsme_shutdown_state = shutdown_state;
        log_debug("in shutdown: %s", dsme_shutdown_state ? "true" : "false");

214 215 216
        /* Re-evaluate dsmesock connection */
        if( !dsme_shutdown_state )
            dsme_socket_connect();
217 218 219 220
    }
}

/** Checks if the device is shutting down (or rebooting)
221
 *
222
 * @return true if device is shutting down, false otherwise
223
 */
224 225
static bool
dsme_state_is_shutdown(void)
226
{
227
    return dsme_shutdown_state;
228 229 230 231 232 233 234 235 236 237
}

/** Checks if the device is is USER-state.
 *
 * @return true if device is in USER-state, false otherwise
 */
static bool
dsme_state_is_user(void)
{
    return dsme_user_state;
238 239 240
}

/* ========================================================================= *
241
 * DSME_SOCKET_IPC
242 243
 * ========================================================================= */

244 245 246 247 248 249 250 251 252 253 254
/* Connection object for libdsme based ipc with dsme */
static dsmesock_connection_t *dsme_socket_con = NULL;

/** I/O watch for dsme_socket_con */
static guint dsme_socket_iowatch = 0;

/** Generic send function for dsmesock messages
 *
 * @param msg A pointer to the message to send
 */
static bool
255
dsme_socket_send_message(gpointer msg)
256 257 258 259 260
{
    bool res = false;

    if( !dsme_socket_con ) {
        log_warning("failed to send %s to dsme; %s",
261
                    dsmemsg_name(msg),"not connected");
262 263 264 265 266
        goto EXIT;
    }

    if( dsmesock_send(dsme_socket_con, msg) == -1) {
        log_err("failed to send %s to dsme; %m",
267
                dsmemsg_name(msg));
268 269
    }

270
    log_debug("%s sent to DSME", dsmemsg_name(msg));
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

    res = true;

EXIT:
    return res;
}

/** Send process watchdog pong message to DSME
 */
static void
dsme_socket_processwd_pong(void)
{
    DSM_MSGTYPE_PROCESSWD_PONG msg =
        DSME_MSG_INIT(DSM_MSGTYPE_PROCESSWD_PONG);

    msg.pid = getpid();

288
    dsme_socket_send_message(&msg);
289 290 291 292 293 294 295 296 297 298 299 300
}

/** Register to DSME process watchdog
 */
static void
dsme_socket_processwd_init(void)
{
    DSM_MSGTYPE_PROCESSWD_CREATE msg =
        DSME_MSG_INIT(DSM_MSGTYPE_PROCESSWD_CREATE);

    msg.pid = getpid();

301
    dsme_socket_send_message(&msg);
302 303 304 305 306 307 308 309 310 311 312 313
}

/** Unregister from DSME process watchdog
 */
static void
dsme_socket_processwd_quit(void)
{
    DSM_MSGTYPE_PROCESSWD_DELETE msg =
        DSME_MSG_INIT(DSM_MSGTYPE_PROCESSWD_DELETE);

    msg.pid = getpid();

314
    dsme_socket_send_message(&msg);
315 316 317 318 319 320 321 322 323 324
}

/** Query current DSME state
 */
static void
dsme_socket_query_state(void)
{
    DSM_MSGTYPE_STATE_QUERY msg =
        DSME_MSG_INIT(DSM_MSGTYPE_STATE_QUERY);

325
    dsme_socket_send_message(&msg);
326 327 328 329 330 331 332 333 334 335 336 337 338 339
}

/** Callback for pending I/O from dsmesock
 *
 * @param source     (not used)
 * @param condition  I/O condition that caused the callback to be called
 * @param data       (not used)
 *
 * @return TRUE if iowatch is to be kept, or FALSE if it should be removed
 */
static gboolean
dsme_socket_recv_cb(GIOChannel *source,
                    GIOCondition condition,
                    gpointer data)
340
{
341 342
    gboolean keep_going = TRUE;
    dsmemsg_generic_t *msg = 0;
343

344
    DSM_MSGTYPE_STATE_CHANGE_IND *msg2;
345

346 347 348 349 350 351 352
    (void)source;
    (void)data;

    if( condition & (G_IO_ERR | G_IO_HUP | G_IO_NVAL) ) {
        if( !dsme_state_is_shutdown() )
            log_crit("DSME socket hangup/error");
        keep_going = FALSE;
353
        goto EXIT;
354
    }
355

356 357
    if( !(msg = dsmesock_receive(dsme_socket_con)) )
        goto EXIT;
358

359 360 361 362 363 364 365 366 367
    if( DSMEMSG_CAST(DSM_MSGTYPE_CLOSE, msg) ) {
        if( !dsme_state_is_shutdown() )
            log_warning("DSME socket closed");
        keep_going = FALSE;
    }
    else if( DSMEMSG_CAST(DSM_MSGTYPE_PROCESSWD_PING, msg) ) {
        dsme_socket_processwd_pong();

        /* Do heartbeat actions here */
368
        modesetting_verify_values();
369 370 371 372 373
    }
    else if( (msg2 = DSMEMSG_CAST(DSM_MSGTYPE_STATE_CHANGE_IND, msg)) ) {
        dsme_state_update(msg2->state);
    }
    else {
374 375
        log_debug("Unhandled %s message received from DSME",
                  dsmemsg_name(msg));
376
    }
377 378

EXIT:
379 380 381 382 383
    free(msg);

    if( !keep_going ) {
        if( !dsme_state_is_shutdown() ) {
            log_warning("DSME i/o notifier disabled;"
384
                        " assuming dsme was stopped");
385 386 387 388 389 390 391 392 393 394
        }

        /* mark notifier as removed */
        dsme_socket_iowatch = 0;

        /* close and wait for possible dsme restart */
        dsme_socket_disconnect();
    }

    return keep_going;
395 396
}

397 398 399 400 401 402 403 404 405
/** Predicate for: socket connection to dsme exists
 *
 * @return true if connected, false otherwise
 */
static bool
dsme_socket_is_connected(void)
{
    return dsme_socket_iowatch;
}
406

407 408 409 410 411 412
/** Initialise dsmesock connection
 *
 * @return true on success, false on failure
 */
static bool
dsme_socket_connect(void)
413
{
414 415
    GIOChannel *iochan = NULL;

416 417 418 419 420 421
    /* No new connections during shutdown */
    if( dsme_state_is_shutdown() )
        goto EXIT;

    /* No new connections uness dsme dbus service is available */
    if( !dsme_dbus_name_owner_available() )
422
        goto EXIT;
423

424 425 426 427 428 429 430 431 432
    /* Already connected ? */
    if( dsme_socket_iowatch )
        goto EXIT;

    log_debug("Opening DSME socket");

    if( !(dsme_socket_con = dsmesock_connect()) ) {
        log_err("Failed to open DSME socket");
        goto EXIT;
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

    log_debug("Adding DSME socket notifier");

    if( !(iochan = g_io_channel_unix_new(dsme_socket_con->fd)) ) {
        log_err("Failed to set up I/O channel for DSME socket");
        goto EXIT;
    }

    dsme_socket_iowatch =
        g_io_add_watch(iochan,
                       G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
                       dsme_socket_recv_cb, NULL);

    /* Register with DSME's process watchdog */
    dsme_socket_processwd_init();

    /* Query current state */
    dsme_socket_query_state();

EXIT:
    if( iochan ) g_io_channel_unref(iochan);

    /* All or nothing */
    if( !dsme_socket_iowatch )
        dsme_socket_disconnect();

    return dsme_socket_is_connected();
}

/** Close dsmesock connection
 */
static void
dsme_socket_disconnect(void)
{
    if( dsme_socket_iowatch ) {
        log_debug("Removing DSME socket notifier");
        g_source_remove(dsme_socket_iowatch);
        dsme_socket_iowatch = 0;
472 473 474 475 476

        /* Still having had a live socket notifier means we have
         * initiated the dsmesock disconnect and need to deactivate
         * the process watchdog before actually disconnecting */
        dsme_socket_processwd_quit();
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    }

    if( dsme_socket_con ) {
        log_debug("Closing DSME socket");
        dsmesock_close(dsme_socket_con);
        dsme_socket_con = 0;
    }
}

/* ========================================================================= *
 * DSME_DBUS_IPC
 * ========================================================================= */

/* SystemBus connection ref used for dsme dbus ipc */
static DBusConnection *dsme_dbus_con = NULL;

/* ------------------------------------------------------------------------- *
 * device state tracking
 * ------------------------------------------------------------------------- */

static void
dsme_dbus_device_state_update(const char *state)
{
    dsme_state_update(dsme_state_parse(state));
501 502
}

503 504 505 506
static DBusPendingCall *dsme_dbus_device_state_query_pc = 0;

static void
dsme_dbus_device_state_query_cb(DBusPendingCall *pending, void *aptr)
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 532 533
{
    DBusMessage *rsp = 0;
    const char  *dta = 0;
    DBusError    err = DBUS_ERROR_INIT;

    (void)aptr;

    if( !(rsp = dbus_pending_call_steal_reply(pending)) ) {
        log_err("did not get reply");
        goto EXIT;
    }

    if( dbus_set_error_from_message(&err, rsp) )
    {
        log_err("error reply: %s: %s", err.name, err.message);
        goto EXIT;
    }

    if( !dbus_message_get_args(rsp, &err,
                               DBUS_TYPE_STRING, &dta,
                               DBUS_TYPE_INVALID) )
    {
        if( strcmp(err.name, DBUS_ERROR_NAME_HAS_NO_OWNER) )
            log_err("parse error: %s: %s", err.name, err.message);
        goto EXIT;
    }

534
    dsme_dbus_device_state_update(dta);
535 536 537 538 539 540 541

EXIT:

    if( rsp ) dbus_message_unref(rsp);

    dbus_error_free(&err);

542 543
    dbus_pending_call_unref(dsme_dbus_device_state_query_pc),
        dsme_dbus_device_state_query_pc = 0;
544 545
}

546 547
static void
dsme_dbus_device_state_query(void)
548
{
549 550 551
    DBusMessage     *req = NULL;
    DBusPendingCall *pc  = 0;

552
    dsme_dbus_device_state_cancel();
553

554
    if( !dsme_dbus_con ) {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        log_err("not connected to system bus; skip device state query");
        goto EXIT;
    }

    req = dbus_message_new_method_call(DSME_DBUS_SERVICE,
                                       DSME_DBUS_REQUEST_PATH,
                                       DSME_DBUS_REQUEST_IFACE,
                                       DSME_DBUS_GET_STATE_REQ);
    if( !req ) {
        log_err("failed to construct %s.%s request",
                DSME_DBUS_REQUEST_IFACE,
                DSME_DBUS_GET_STATE_REQ);
        goto EXIT;
    }

570
    if( !dbus_connection_send_with_reply(dsme_dbus_con, req, &pc, -1) )
571 572 573 574 575
        goto EXIT;

    if( !pc )
        goto EXIT;

576
    if( !dbus_pending_call_set_notify(pc, dsme_dbus_device_state_query_cb, 0, 0) )
577 578
        goto EXIT;

579
    dsme_dbus_device_state_query_pc = pc, pc = 0;
580 581 582 583 584 585 586

EXIT:

    if( pc  ) dbus_pending_call_unref(pc);
    if( req ) dbus_message_unref(req);
}

587 588 589 590 591 592 593 594 595 596 597 598
static void
dsme_dbus_device_state_cancel(void)
{
    if( dsme_dbus_device_state_query_pc ) {
        dbus_pending_call_cancel(dsme_dbus_device_state_query_pc);
        dbus_pending_call_unref(dsme_dbus_device_state_query_pc),
            dsme_dbus_device_state_query_pc = 0;
    }
}

static void
dsme_dbus_device_state_signal(DBusMessage *msg)
599 600 601 602 603 604 605
{
    DBusError   err = DBUS_ERROR_INIT;
    const char *dta = 0;

    if( !dbus_message_get_args(msg, &err,
                               DBUS_TYPE_STRING, &dta,
                               DBUS_TYPE_INVALID) )
606
    {
607 608 609 610 611
        log_err("failed to parse signal: %s: %s",
                err.name, err.message);
    }
    else
    {
612
        dsme_dbus_device_state_update(dta);
613 614
    }
    dbus_error_free(&err);
615 616
}

617
/* ------------------------------------------------------------------------- *
618
 * dsme name owner tracking
619
 * ------------------------------------------------------------------------- */
620

621 622
/* Flag for: dsme is available on system bus */
static gchar *dsme_dbus_name_owner_val = 0;
623

624 625 626 627 628
static bool
dsme_dbus_name_owner_available(void)
{
    return dsme_dbus_name_owner_val != 0;
}
629

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
static void
dsme_dbus_name_owner_update(const char *owner)
{
    if( owner && !*owner )
        owner = 0;

    if( g_strcmp0(dsme_dbus_name_owner_val, owner) ) {
        log_debug("dsme dbus name owner: %s -> %s",
                  dsme_dbus_name_owner_val ?: "none",
                  owner                    ?: "none");

        g_free(dsme_dbus_name_owner_val),
            dsme_dbus_name_owner_val = owner ? g_strdup(owner) : 0;

        /* Query current state on dsme startup and initiate
         * dsmesock connection for process watchdog activity.
         */
        if( dsme_dbus_name_owner_val ) {
            dsme_dbus_device_state_query();
            dsme_socket_connect();
650 651 652 653
        }
    }
}

654
static DBusPendingCall *dsme_dbus_name_owner_query_pc = 0;
655

656 657
static void
dsme_dbus_name_owner_query_cb(const char *owner)
658
{
659
    dsme_dbus_name_owner_update(owner);
660

661 662
    dbus_pending_call_unref(dsme_dbus_name_owner_query_pc),
        dsme_dbus_name_owner_query_pc = 0;
663 664
}

665 666
static void
dsme_dbus_name_owner_query(void)
667
{
668 669
    dsme_dbus_name_owner_cancel();

670 671 672
    umdbus_get_name_owner_async(DSME_DBUS_SERVICE,
                                dsme_dbus_name_owner_query_cb,
                                &dsme_dbus_name_owner_query_pc);
673 674
}

675 676
static void
dsme_dbus_name_owner_cancel(void)
677
{
678 679 680 681 682 683
    if( dsme_dbus_name_owner_query_pc )
    {
        dbus_pending_call_cancel(dsme_dbus_name_owner_query_pc);
        dbus_pending_call_unref(dsme_dbus_name_owner_query_pc),
            dsme_dbus_name_owner_query_pc = 0;
    }
684 685
}

686 687
static void
dsme_dbus_name_owner_signal(DBusMessage *msg)
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
{
    DBusError   err  = DBUS_ERROR_INIT;
    const char *name = 0;
    const char *prev = 0;
    const char *curr = 0;

    if( !dbus_message_get_args(msg, &err,
                               DBUS_TYPE_STRING, &name,
                               DBUS_TYPE_STRING, &prev,
                               DBUS_TYPE_STRING, &curr,
                               DBUS_TYPE_INVALID) )
    {
        log_err("failed to parse signal: %s: %s",
                err.name, err.message);
    }
    else if( !strcmp(name, DSME_DBUS_SERVICE) )
    {
705
        dsme_dbus_name_owner_update(curr);
706 707 708 709
    }
    dbus_error_free(&err);
}

710 711 712
/* ------------------------------------------------------------------------- *
 * dbus connection management
 * ------------------------------------------------------------------------- */
713 714 715 716 717 718 719 720 721 722 723

static DBusHandlerResult
dsme_dbus_filter_cb(DBusConnection *con, DBusMessage *msg, void *user_data)
{
    (void)con;
    (void)user_data;

    if( dbus_message_is_signal(msg,
                               DSME_DBUS_SIGNAL_IFACE,
                               DSME_STATE_CHANGE_SIG) )
    {
724
        dsme_dbus_device_state_signal(msg);
725 726 727 728 729
    }
    else if( dbus_message_is_signal(msg,
                                    DBUS_INTERFACE_DBUS,
                                    DBUS_NAME_OWNER_CHANGED_SIG) )
    {
730
        dsme_dbus_name_owner_signal(msg);
731 732 733 734 735
    }

    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

736 737
static bool
dsme_dbus_init(void)
738
{
739
    bool ack = false;
740 741

    /* Get connection ref */
742
    if( (dsme_dbus_con = umdbus_get_connection()) == 0 )
743 744 745 746 747 748
    {
        log_err("Could not connect to dbus for dsme\n");
        goto cleanup;
    }

    /* Add filter callback */
749
    if( !dbus_connection_add_filter(dsme_dbus_con,
750 751 752 753 754 755
                                    dsme_dbus_filter_cb , 0, 0) )
    {
        log_err("adding system dbus filter for dsme failed");
        goto cleanup;
    }

756 757 758
    /* Add matches without blocking / error checking */
    dbus_bus_add_match(dsme_dbus_con, DSME_STATE_CHANGE_MATCH, 0);
    dbus_bus_add_match(dsme_dbus_con, DSME_OWNER_CHANGE_MATCH, 0);
759 760

    /* Initiate async dsme name owner query */
761
    dsme_dbus_name_owner_query();
762

763
    ack = true;
764 765 766 767 768 769

cleanup:

    return ack;
}

770 771
static void
dsme_dbus_quit(void)
772
{
773 774 775
    /* Cancel any pending dbus queries */
    dsme_dbus_name_owner_cancel();
    dsme_dbus_device_state_cancel();
776

777 778
    /* Detach from SystemBus */
    if(dsme_dbus_con)
779 780
    {
        /* Remove filter callback */
781
        dbus_connection_remove_filter(dsme_dbus_con,
782 783
                                      dsme_dbus_filter_cb, 0);

784 785 786 787
        if( dbus_connection_get_is_connected(dsme_dbus_con) ) {
            /* Remove matches without blocking / error checking */
            dbus_bus_remove_match(dsme_dbus_con, DSME_STATE_CHANGE_MATCH, 0);
            dbus_bus_remove_match(dsme_dbus_con, DSME_OWNER_CHANGE_MATCH, 0);
788 789 790
        }

        /* Let go of connection ref */
791 792
        dbus_connection_unref(dsme_dbus_con),
            dsme_dbus_con = 0;
793
    }
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

    /* Release dynamic resources */
    g_free(dsme_dbus_name_owner_val),
        dsme_dbus_name_owner_val = 0;
}

/* ========================================================================= *
 * MODULE_API
 * ========================================================================= */

gboolean
dsme_listener_start(void)
{
    return dsme_dbus_init();
}

void
dsme_listener_stop(void)
{
    dsme_dbus_quit();
    dsme_socket_disconnect();
}

/** Checks if the device is is USER-state.
 *
 * @return 1 if it is in USER-state, 0 for not
 */
gboolean
822
dsme_in_user_state(void)
823 824
{
    return dsme_state_is_user();
825
}