usb_moded.c 32 KB
Newer Older
1
/**
2 3 4
 * @file usb_moded.c
 *
 * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5
 * Copyright (C) 2012-2019 Jolla. All rights reserved.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * @author: Philippe De Swert <philippe.de-swert@nokia.com>
 * @author: Philippe De Swert <phdeswer@lumi.maa>
 * @author: Philippe De Swert <philippedeswert@gmail.com>
 * @author: Philippe De Swert <philippe.deswert@jollamobile.com>
 * @author: Jonni Rainisto <jonni.rainisto@jollamobile.com>
 * @author: Pekka Lundstrom <pekka.lundstrom@jollamobile.com>
 * @author: Vesa Halttunen <vesa.halttunen@jollamobile.com>
 * @author: Simo Piiroinen <simo.piiroinen@jollamobile.com>
 * @author: Thomas Perl <thomas.perl@jolla.com>
 * @author: Matti Lehtimaki <matti.lehtimaki@gmail.com>
 * @author: Thomas Perl <m@thp.io>
 * @author: Martin Jones <martin.jones@jollamobile.com>
 * @author: Andrew den Exter <andrew.den.exter@jolla.com>
 * @author: Andrew den Exter <andrew.den.exter@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
 */

37
#include "usb_moded.h"
38 39 40 41 42 43

#include "usb_moded-android.h"
#include "usb_moded-appsync.h"
#include "usb_moded-config-private.h"
#include "usb_moded-configfs.h"
#include "usb_moded-control.h"
44
#include "usb_moded-dbus-private.h"
45
#include "usb_moded-devicelock.h"
46 47
#include "usb_moded-log.h"
#include "usb_moded-mac.h"
48 49
#include "usb_moded-modesetting.h"
#include "usb_moded-modules.h"
50
#include "usb_moded-network.h"
51
#include "usb_moded-sigpipe.h"
52
#include "usb_moded-systemd.h"
53 54
#include "usb_moded-trigger.h"
#include "usb_moded-udev.h"
55
#include "usb_moded-worker.h"
56
#include "usb_moded-modes.h"
57

58
#ifdef MEEGOLOCK
59
# include "usb_moded-dsme.h"
60
#endif
61

62 63 64 65 66 67 68 69 70 71
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#ifdef SYSTEMD
# include <systemd/sd-daemon.h>
#endif

72 73 74 75
/* ========================================================================= *
 * Constants
 * ========================================================================= */

76 77 78 79 80
/* Wakelogging is noisy, do not log it by default */
#ifndef  VERBOSE_WAKELOCKING
# define VERBOSE_WAKELOCKING 0
#endif

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
/** Default allowed cable detection delay
 *
 * To comply with USB standards, the delay should be
 * less than 2 seconds to ensure timely enumeration.
 *
 * Any value <= zero means no delay.
 */
#define CABLE_CONNECTION_DELAY_DEFAULT 0

/** Maximum allowed cable detection delay
 *
 * Must be shorter than initial probing delay expected by
 * dsme (currently 5 seconds) to avoid reboot loops in
 * act dead mode.
 *
 * And shorter than USB_MODED_SUSPEND_DELAY_DEFAULT_MS to
 * allow the timer to trigger also in display off scenarios.
 */

#define CABLE_CONNECTION_DELAY_MAXIMUM 4000

102 103 104 105
/* ========================================================================= *
 * Prototypes
 * ========================================================================= */

106 107 108
/* ------------------------------------------------------------------------- *
 * USBMODED
 * ------------------------------------------------------------------------- */
109

110 111 112 113
GList            *usbmoded_get_modelist              (void);
void              usbmoded_load_modelist             (void);
void              usbmoded_free_modelist             (void);
const modedata_t *usbmoded_get_modedata              (const char *modename);
114
modedata_t       *usbmoded_dup_modedata              (const char *modename);
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
bool              usbmoded_get_rescue_mode           (void);
void              usbmoded_set_rescue_mode           (bool rescue_mode);
bool              usbmoded_get_diag_mode             (void);
void              usbmoded_set_diag_mode             (bool diag_mode);
void              usbmoded_set_cable_connection_delay(int delay_ms);
int               usbmoded_get_cable_connection_delay(void);
static gboolean   usbmoded_allow_suspend_timer_cb    (gpointer aptr);
void              usbmoded_allow_suspend             (void);
void              usbmoded_delay_suspend             (void);
bool              usbmoded_can_export                (void);
bool              usbmoded_init_done_p               (void);
void              usbmoded_set_init_done             (bool reached);
void              usbmoded_probe_init_done           (void);
void              usbmoded_exit_mainloop             (int exitcode);
void              usbmoded_handle_signal             (int signum);
static bool       usbmoded_init                      (void);
static void       usbmoded_cleanup                   (void);
static void       usbmoded_usage                     (void);
static void       usbmoded_parse_options             (int argc, char *argv[]);
134

135 136 137 138 139 140
/* ------------------------------------------------------------------------- *
 * MAIN
 * ------------------------------------------------------------------------- */

int main(int argc, char *argv[]);

141
/* ========================================================================= *
142 143
 * Data
 * ========================================================================= */
144

145 146
static int        usbmoded_exitcode       = EXIT_FAILURE;
static GMainLoop *usbmoded_mainloop       = NULL;
147

148 149 150 151
static bool       usbmoded_hw_fallback    = false;
#ifdef SYSTEMD
static bool       usbmoded_systemd_notify = false;
#endif
152
static bool       usbmoded_auto_exit      = false;
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
static pthread_mutex_t  usbmoded_mutex = PTHREAD_MUTEX_INITIALIZER;

#define USBMODED_LOCKED_ENTER do {\
    if( pthread_mutex_lock(&usbmoded_mutex) != 0 ) { \
        log_crit("USBMODED LOCK FAILED");\
        _exit(EXIT_FAILURE);\
    }\
}while(0)

#define USBMODED_LOCKED_LEAVE do {\
    if( pthread_mutex_unlock(&usbmoded_mutex) != 0 ) { \
        log_crit("USBMODED UNLOCK FAILED");\
        _exit(EXIT_FAILURE);\
    }\
}while(0)

170 171 172
/* ========================================================================= *
 * Functions
 * ========================================================================= */
173

174 175 176 177
/* ------------------------------------------------------------------------- *
 * MODELIST
 * ------------------------------------------------------------------------- */

178 179 180 181
/** List of mode data items read from configuration files
 *
 * Note: Worker thread should access this only via #usbmoded_dup_modedata().
 */
182 183
static GList *usbmoded_modelist = 0;

184 185 186 187 188 189
/** Get list of dynamic mode data items
 *
 * Note: This function should be called only from the main thread.
 *
 * @returns List of mode data objects, or NULL
 */
190 191 192
GList *
usbmoded_get_modelist(void)
{
193 194
    LOG_REGISTER_CONTEXT;

195 196 197
    return usbmoded_modelist;
}

198 199 200 201
/** Load dynamic mode data items
 *
 * Note: This function should be called only from the main thread.
 */
202 203 204
void
usbmoded_load_modelist(void)
{
205 206
    LOG_REGISTER_CONTEXT;

207 208
    USBMODED_LOCKED_ENTER;

209 210
    if( !usbmoded_modelist ) {
        log_notice("load modelist");
211
        usbmoded_modelist = modelist_load(usbmoded_get_diag_mode());
212
    }
213 214

    USBMODED_LOCKED_LEAVE;
215 216
}

217 218 219 220
/** Free dynamic mode data items
 *
 * Note: This function should be called only from the main thread.
 */
221 222 223
void
usbmoded_free_modelist(void)
{
224 225
    LOG_REGISTER_CONTEXT;

226 227
    USBMODED_LOCKED_ENTER;

228 229
    if( usbmoded_modelist ) {
        log_notice("free modelist");
230
        modelist_free(usbmoded_modelist),
231 232
            usbmoded_modelist = 0;
    }
233 234

    USBMODED_LOCKED_LEAVE;
235 236
}

237 238 239 240 241 242 243 244
/** Lookup dynamic mode data by name
 *
 * Note: This function should be called only from the main thread.
 *
 * @param modename  Name of mode to lookup
 *
 * @return Mode data object, or NULL
 */
245 246 247
const modedata_t *
usbmoded_get_modedata(const char *modename)
{
248 249
    LOG_REGISTER_CONTEXT;

250 251 252 253 254 255 256 257 258 259 260 261
    modedata_t *modedata = 0;

    for( GList *iter = usbmoded_get_modelist(); iter; iter = g_list_next(iter) ) {
        modedata_t *data = iter->data;
        if( !g_strcmp0(data->mode_name, modename) ) {
            modedata = data;
            break;
        }
    }
    return modedata;
}

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
/** Lookup and clone dynamic mode data by name
 *
 * Note: This function is safe to call from worker thread too.
 *
 * Caller must release the returned object via #modedata_free().
 *
 * @param modename  Name of mode to lookup
 *
 * @return Mode data object, or NULL
 */
modedata_t *
usbmoded_dup_modedata(const char *modename)
{
    LOG_REGISTER_CONTEXT;

    USBMODED_LOCKED_ENTER;

    modedata_t *modedata = modedata_copy(usbmoded_get_modedata(modename));

    USBMODED_LOCKED_LEAVE;

    return modedata;
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299
/* ------------------------------------------------------------------------- *
 * RESCUE_MODE
 * ------------------------------------------------------------------------- */

/** Rescue mode flag
 *
 * When enabled, usb-moded allows developer_mode etc when device is
 * booted up with cable connected without requiring device unlock.
 * Which can be useful if UI for some reason does not come up.
 */
static bool usbmoded_rescue_mode = false;

bool usbmoded_get_rescue_mode(void)
{
300 301
    LOG_REGISTER_CONTEXT;

302 303 304 305 306
    return usbmoded_rescue_mode;
}

void usbmoded_set_rescue_mode(bool rescue_mode)
{
307 308
    LOG_REGISTER_CONTEXT;

309 310 311 312 313 314
    if( usbmoded_rescue_mode != rescue_mode ) {
        log_info("rescue_mode: %d -> %d",  usbmoded_rescue_mode, rescue_mode);
        usbmoded_rescue_mode = rescue_mode;
    }
}

315 316 317 318 319 320 321 322 323 324 325 326 327
/* ------------------------------------------------------------------------- *
 * DIAG_MODE
 * ------------------------------------------------------------------------- */

/** Diagnostic mode active
 *
 * In diag mode usb-moded uses separate mode configuration which
 * should have exactly one mode defined / available.
 */
static bool usbmoded_diag_mode = false;

bool usbmoded_get_diag_mode(void)
{
328 329
    LOG_REGISTER_CONTEXT;

330 331 332 333 334
    return usbmoded_diag_mode;
}

void usbmoded_set_diag_mode(bool diag_mode)
{
335 336
    LOG_REGISTER_CONTEXT;

337 338 339 340 341 342
    if( usbmoded_diag_mode != diag_mode ) {
        log_info("diag_mode: %d -> %d",  usbmoded_diag_mode, diag_mode);
        usbmoded_diag_mode = diag_mode;
    }
}

343 344 345 346
/* ------------------------------------------------------------------------- *
 * CABLE_CONNECT_DELAY
 * ------------------------------------------------------------------------- */

347 348 349 350 351 352 353 354 355
/** PC connection delay
 *
 * Slow cable insert / similar physical issues can lead to a charger
 * getting initially recognized as a pc connection. This defines how
 * long we should wait and see if pc connection gets corrected to a
 * charger kind.
 */
static int usbmoded_cable_connection_delay = CABLE_CONNECTION_DELAY_DEFAULT;

356 357 358 359
/** Helper for setting allowed cable detection delay
 *
 * Used for implementing --max-cable-delay=<ms> option.
 */
360 361
void
usbmoded_set_cable_connection_delay(int delay_ms)
362
{
363 364
    LOG_REGISTER_CONTEXT;

365 366 367 368 369 370 371 372 373
    if( delay_ms > CABLE_CONNECTION_DELAY_MAXIMUM )
        delay_ms = CABLE_CONNECTION_DELAY_MAXIMUM;
    if( delay_ms < 0 )
        delay_ms = 0;

    if( usbmoded_cable_connection_delay != delay_ms ) {
        log_info("cable_connection_delay: %d -> %d",
                 usbmoded_cable_connection_delay,
                 delay_ms);
374
        usbmoded_cable_connection_delay = delay_ms;
375 376 377
    }
}

378 379 380 381 382
/** Helper for getting allowed cable detection delay
 */
int
usbmoded_get_cable_connection_delay(void)
{
383 384
    LOG_REGISTER_CONTEXT;

385 386 387
    return usbmoded_cable_connection_delay;
}

388 389 390 391 392 393 394 395 396 397
/* ------------------------------------------------------------------------- *
 * SUSPEND_BLOCKING
 * ------------------------------------------------------------------------- */

/** Flag for: USB_MODED_WAKELOCK_STATE_CHANGE has been acquired */
static bool usbmoded_blocking_suspend = false;

/** Timer for releasing USB_MODED_WAKELOCK_STATE_CHANGE */
static guint usbmoded_allow_suspend_timer_id = 0;

398
/** Timer callback for releasing wakelock acquired via usbmoded_delay_suspend()
399
 *
400
 * @param aptr callback argument (not used)
401
 */
402
static gboolean usbmoded_allow_suspend_timer_cb(gpointer aptr)
403
{
404 405
    LOG_REGISTER_CONTEXT;

406 407
    (void)aptr;

408
    usbmoded_allow_suspend_timer_id = 0;
409 410 411 412

    usbmoded_allow_suspend();

    return FALSE;
413 414
}

415
/** Release wakelock acquired via usbmoded_delay_suspend()
416
 *
417 418
 * Meant to be called on usb-moded exit so that wakelocks
 * are not left behind.
419
 */
420
void usbmoded_allow_suspend(void)
421
{
422 423
    LOG_REGISTER_CONTEXT;

424 425 426
    if( usbmoded_allow_suspend_timer_id ) {
        g_source_remove(usbmoded_allow_suspend_timer_id),
            usbmoded_allow_suspend_timer_id = 0;
427
    }
428

429 430 431
    if( usbmoded_blocking_suspend ) {
        usbmoded_blocking_suspend = false;
        common_release_wakelock(USB_MODED_WAKELOCK_STATE_CHANGE);
432
    }
433 434 435 436 437 438 439 440 441 442 443 444
}

/** Block suspend briefly
 *
 * Meant to be called in situations usb activity might have woken
 * up the device (cable connect while display is off), or could
 * allow device to suspend (cable disconnect while display is off).
 *
 * Allows usb moded some time to finish asynchronous activity and
 * other processes to receive and process state changes broadcast
 * by usb-moded.
 */
445
void usbmoded_delay_suspend(void)
446
{
447 448
    LOG_REGISTER_CONTEXT;

449 450
    /* Use of automatically terminating wakelocks also means we need
     * to renew the wakelock when extending the suspend delay. */
451
    common_acquire_wakelock(USB_MODED_WAKELOCK_STATE_CHANGE);
452

453
    usbmoded_blocking_suspend = true;
454

455 456
    if( usbmoded_allow_suspend_timer_id )
        g_source_remove(usbmoded_allow_suspend_timer_id);
457

458
    usbmoded_allow_suspend_timer_id =
459 460
        g_timeout_add(USB_MODED_SUSPEND_DELAY_DEFAULT_MS,
                      usbmoded_allow_suspend_timer_cb, 0);
461 462
}

463 464 465 466
/* ------------------------------------------------------------------------- *
 * CAN_EXPORT
 * ------------------------------------------------------------------------- */

467 468 469 470 471 472
/** Check if exposing device data is currently allowed
 *
 * @return true exposing data is ok, or false otherwise
 */
bool usbmoded_can_export(void)
{
473 474
    LOG_REGISTER_CONTEXT;

475 476 477 478 479 480 481 482 483
  bool can_export = true;

#ifdef MEEGOLOCK
    /* Modes that potentially expose data are allowed only when
     * device is running in user mode and device is unlocked */
    can_export = (dsme_in_user_state() &&
                  devicelock_have_export_permission());

    /* Having bootup rescue mode active is an exception */
484
    if( usbmoded_get_rescue_mode() )
485 486 487 488 489 490
        can_export = true;
#endif

    return can_export;
}

491 492 493 494 495 496 497 498 499 500
/* ------------------------------------------------------------------------- *
 * INIT_DONE
 * ------------------------------------------------------------------------- */

/** Path to init-done flag file */
static const char usbmoded_init_done_flagfile[] = "/run/systemd/boot-status/init-done";

/** cached init-done-reached state */
static bool usbmoded_init_done_reached = false;

501 502 503 504
/** Check if system has already been successfully booted up
 *
 * @return true if init-done has been reached, or false otherwise
 */
505
bool usbmoded_init_done_p(void)
506
{
507 508
    LOG_REGISTER_CONTEXT;

509
    return usbmoded_init_done_reached;
510 511 512
}

/** Update cached init-done-reached state */
513
void usbmoded_set_init_done(bool reached)
514
{
515 516
    LOG_REGISTER_CONTEXT;

517 518
    if( usbmoded_init_done_reached != reached ) {
        usbmoded_init_done_reached = reached;
519
        log_warning("init_done -> %s",
520
                    usbmoded_init_done_reached ? "reached" : "not reached");
521
    }
522 523 524
}

/** Check whether init-done flag file exists */
525
void usbmoded_probe_init_done(void)
526
{
527 528
    LOG_REGISTER_CONTEXT;

529
    usbmoded_set_init_done(access(usbmoded_init_done_flagfile, F_OK) == 0);
530 531
}

532 533 534 535
/* ------------------------------------------------------------------------- *
 * MAINLOOP
 * ------------------------------------------------------------------------- */

536 537
/** Request orderly exit from mainloop
 */
538 539
void usbmoded_exit_mainloop(int exitcode)
{
540 541
    LOG_REGISTER_CONTEXT;

542 543
    /* In case multiple exit request get done, retain the
     * highest exit code used. */
544 545
    if( usbmoded_exitcode < exitcode )
        usbmoded_exitcode = exitcode;
546 547

    /* If there is no mainloop to exit, terminate immediately */
548
    if( !usbmoded_mainloop )
549 550
    {
        log_warning("exit requested outside mainloop; exit(%d) now",
551 552
                    usbmoded_exitcode);
        exit(usbmoded_exitcode);
553 554 555
    }

    log_debug("stopping usb-moded mainloop");
556
    g_main_loop_quit(usbmoded_mainloop);
557 558
}

559
void usbmoded_handle_signal(int signum)
560
{
561 562
    LOG_REGISTER_CONTEXT;

563 564 565 566 567 568 569 570 571
    log_debug("handle signal: %s\n", strsignal(signum));

    if( signum == SIGTERM )
    {
        /* Assume: Stopped by init process */
        usbmoded_exit_mainloop(EXIT_SUCCESS);
    }
    else if( signum == SIGHUP )
    {
572 573
        /* Reload mode list */
        log_debug("reloading dynamic mode configuration");
574 575
        usbmoded_free_modelist();
        usbmoded_load_modelist();
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
        /* If default mode selection became invalid,
         * revert setting to "ask" */
        gchar *config = config_get_mode_setting();
        if( g_strcmp0(config, MODE_ASK) &&
            common_valid_mode(config) ) {
            log_warning("default mode '%s' is not valid, reset to '%s'",
                        config, MODE_ASK);
            config_set_mode_setting(MODE_ASK);
        }
        else {
            log_debug("default mode '%s' is still valid", config);
        }
        g_free(config);

        /* If current mode became invalid, select appropriate mode.
         *
         * Use target mode so that we catch also situations where
         * we are making transition to invalid state.
         */
        const char *current = control_get_target_mode();
        if( common_modename_is_internal(current) ) {
            /* Internal modes are not affected by configuration
             * file changes - no changes required. */
            log_debug("current mode '%s' is internal", current);
        }
        else if( common_valid_mode(current) ) {
            /* Dynamic mode that is no longer valid - choose
             * something else. */
            log_warning("current mode '%s' is not valid, re-evaluating",
                        current);
            control_select_usb_mode();
        }
        else {
            /* Dynamic mode that is still valid - do nothing.
             *
             * Note: While the mode details /might/ have changed,
             * skipping immediate usb reprogramming is assumed to
             * be less harmful than potentially cutting developer
             * mode connection during upgrade, etc. */
            log_debug("current mode '%s' is still valid", current);
        }

        /* Signal availability */
        log_debug("broadcast mode availability lists");
621 622
        common_send_supported_modes_signal();
        common_send_available_modes_signal();
623 624 625 626 627 628 629
    }
    else
    {
        usbmoded_exit_mainloop(EXIT_FAILURE);
    }
}

630 631
/* Prepare usb-moded for running the mainloop */
static bool usbmoded_init(void)
632
{
633 634
    LOG_REGISTER_CONTEXT;

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    bool ack = false;

    /* Check if we are in mid-bootup */
    usbmoded_probe_init_done();

    if( !worker_init() ) {
        log_crit("worker thread init failed");
      goto EXIT;
    }

    if( !sigpipe_init() ) {
        log_crit("signal handler init failed");
        goto EXIT;
    }

650 651
    if( usbmoded_get_rescue_mode() && usbmoded_init_done_p() ) {
        usbmoded_set_rescue_mode(false);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        log_warning("init done passed; rescue mode ignored");
    }

    /* Connect to SystemBus */
    if( !umdbus_init_connection() ) {
        log_crit("dbus systembus connection failed");
        goto EXIT;
    }

    /* Start DBus trackers that do async initialization
     * so that initial method calls are on the way while
     * we do initialization actions that might block. */

    /* DSME listener maintains in-user-mode state and is relevant
     * only when MEEGOLOCK configure option has been chosen. */
#ifdef MEEGOLOCK
668
    if( !dsme_start_listener() ) {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        log_crit("dsme tracking could not be started");
        goto EXIT;
    }
#endif

    /* Devicelock listener maintains devicelock state and is relevant
     * only when MEEGOLOCK configure option has been chosen. */
#ifdef MEEGOLOCK
    if( !devicelock_start_listener() ) {
        log_crit("devicelock tracking could not be started");
        goto EXIT;
    }
#endif

    /* Set daemon config/state data to sane state */
    modesetting_init();

686
    /* check config, merge or create if outdated */
687
    if( !config_init() ) {
688 689
        log_crit("Cannot create or find a valid configuration");
        goto EXIT;
690 691 692
    }

#ifdef APP_SYNC
693
    appsync_read_list(usbmoded_get_diag_mode());
694 695 696
#endif

    /* always read dyn modes even if appsync is not used */
697
    usbmoded_load_modelist();
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

    if(config_check_trigger())
        trigger_init();

    /* Set-up mac address before kmod */
    if(access("/etc/modprobe.d/g_ether.conf", F_OK) != 0)
    {
        mac_generate_random_mac();
    }

    /* During bootup the sysfs control structures might
     * not be already in there when usb-moded starts up.
     * Retry few times unless init done is / gets reached
     * while waiting.
     */
    for( int i = 10; ; ) {
714
        if( configfs_init() )
715 716
            break;

717
        if( android_init() )
718 719
            break;

720
        /* Must probe / poll since we're not yet running mainloop */
721 722 723 724 725 726 727 728
        usbmoded_probe_init_done();

        if( usbmoded_init_done_p() || --i <= 0 ) {
            if( !modules_init() )
                log_crit("No supported usb control mechanisms found");
            break;
        }

729
        common_msleep(1000);
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
    /* Allow making systemd control ipc */
    if( !systemd_control_start() ) {
        log_crit("systemd control could not be started");
        goto EXIT;
    }

    /* If usb-moded happens to crash, it could leave appsync processes
     * running. To make sure things are in the order expected by usb-moded
     * force stopping of appsync processes during usb-moded startup.
     *
     * The exception is: When usb-moded starts as a part of bootup. Then
     * we can be relatively sure that usb-moded has not been running yet
     * and therefore no appsync processes have been started and we can
     * skip the blocking ipc required to stop the appsync systemd units. */
#ifdef APP_SYNC
    if( usbmoded_init_done_p() ) {
        log_warning("usb-moded started after init-done; "
                    "forcing appsync stop");
        appsync_stop(true);
    }
#endif

    /* Claim D-Bus service name before proceeding with things that
     * could result in dbus signal broadcasts from usb-moded interface.
     */
    if( !umdbus_init_service() ) {
        log_crit("usb-moded dbus service init failed");
        goto EXIT;
    }

    /* Initialize udev listener. Can cause mode changes.
     *
     * Failing here is allowed if '--fallback' commandline option is used.
     */
    if( !umudev_init() && !usbmoded_hw_fallback ) {
        log_crit("hwal init failed");
        goto EXIT;
    }

    /* Broadcast supported / hidden modes */
    // TODO: should this happen before umudev_init()?
    common_send_supported_modes_signal();
    common_send_available_modes_signal();
    common_send_hidden_modes_signal();
    common_send_whitelisted_modes_signal();

    /* Act on '--fallback' commandline option */
    if( usbmoded_hw_fallback ) {
        log_warning("Forcing USB state to connected always. ASK mode non functional!");
        /* Since there will be no disconnect signals coming from hw the state should not change */
        control_set_cable_state(CABLE_STATE_PC_CONNECTED);
    }

    ack = true;

EXIT:
    return ack;
789 790 791 792 793 794
}

/** Release resources allocated by usbmoded_init()
 */
static void usbmoded_cleanup(void)
{
795 796
    LOG_REGISTER_CONTEXT;

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
    /* Stop the worker thread first to avoid confusion about shared
     * resources we are just about to release. */
    worker_quit();

    /* Detach from SystemBus. Components that hold reference to the
     * shared bus connection can still perform cleanup tasks, but new
     * references can't be obtained anymore and usb-moded method call
     * processing no longer occurs. */
    umdbus_cleanup();

    /* Stop appsync processes that have been started by usb-moded */
#ifdef APP_SYNC
    appsync_stop(false);
#endif

    /* Deny making systemd control ipc */
    systemd_control_stop();

    /* Stop tracking devicelock status */
#ifdef MEEGOLOCK
    devicelock_stop_listener();
#endif

    /* Stop tracking device state */
#ifdef MEEGOLOCK
822
    dsme_stop_listener();
823 824 825 826 827
#endif

    /* Stop udev listener */
    umudev_quit();

828
    /* Do backend specific cleanup */
829
    modules_quit();
830 831
    android_quit();
    configfs_quit();
832 833 834 835

    /* Undo trigger_init() */
    trigger_stop();

836 837
    /* Undo usbmoded_load_modelist() */
    usbmoded_free_modelist();
838 839 840 841 842 843 844

#ifdef APP_SYNC
    /* Undo appsync_read_list() */
    appsync_free_appsync_list();
#endif

    /* Release dynamic memory */
845
    worker_clear_kernel_module();
846 847 848 849
    worker_clear_hardware_mode();
    control_clear_cable_state();
    control_clear_internal_mode();
    control_clear_external_mode();
850
    control_clear_target_mode();
851 852 853 854 855 856 857 858 859 860 861

    modesetting_quit();

    /* Detach from SessionBus connection used for APP_SYNC_DBUS.
     *
     * Can be handled separately from SystemBus side wind down. */
#ifdef APP_SYNC
# ifdef APP_SYNC_DBUS
    dbusappsync_cleanup();
# endif
#endif
862 863 864 865 866 867
}

/* ========================================================================= *
 * MAIN ENTRY
 * ========================================================================= */

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
static const char usbmoded_usage_info[] =
"Usage: usb_moded [OPTION]...\n"
"USB mode daemon\n"
"\n"
"  -a,  --android_usb_broken\n"
"      keep gadget active on broken android kernels\n"
"  -i,  --android_usb_broken_udev_events\n"
"      ignore incorrect disconnect events after mode setting\n"
"  -f,  --fallback       \n"
"      assume always connected\n"
"  -s,  --force-syslog \n"
"      log to syslog\n"
"  -T,  --force-stderr \n"
"      log to stderr\n"
"  -l,  --log-line-info\n"
"      log to stderr and show origin of logging\n"
"  -D,  --debug  \n"
"      turn on debug printing\n"
"  -d,  --diag   \n"
"      turn on diag mode\n"
"  -h,  --help         \n"
"      display this help and exit\n"
"  -r,  --rescue         \n"
"      rescue mode\n"
#ifdef SYSTEMD
"  -n,  --systemd      \n"
"      notify systemd when started up\n"
#endif
"  -v,  --version      \n"
"      output version information and exit\n"
"  -m,  --max-cable-delay=<ms>\n"
"      maximum delay before accepting cable connection\n"
"  -b,  --android-bootup-function=<function>\n"
"      Setup given function during bootup. Might be required\n"
"      on some devices to make enumeration work on the 1st\n"
"      cable connect.\n"
"\n";

static const struct option const usbmoded_long_options[] =
{
    { "android_usb_broken",             no_argument,       0, 'a' },
    { "android_usb_broken_udev_events", no_argument,       0, 'i' },
    { "fallback",                       no_argument,       0, 'd' },
    { "force-syslog",                   no_argument,       0, 's' },
    { "force-stderr",                   no_argument,       0, 'T' },
    { "log-line-info",                  no_argument,       0, 'l' },
    { "debug",                          no_argument,       0, 'D' },
    { "diag",                           no_argument,       0, 'd' },
    { "help",                           no_argument,       0, 'h' },
    { "rescue",                         no_argument,       0, 'r' },
    { "systemd",                        no_argument,       0, 'n' },
    { "version",                        no_argument,       0, 'v' },
    { "max-cable-delay",                required_argument, 0, 'm' },
    { "android-bootup-function",        required_argument, 0, 'b' },
922
    { "auto-exit",                      no_argument,       0, 'Q' },
923 924 925
    { 0, 0, 0, 0 }
};

926
static const char usbmoded_short_options[] = "aifsTlDdhrnvm:b:Q";
927

928 929 930
/* Display usbmoded_usage information */
static void usbmoded_usage(void)
{
931 932
    LOG_REGISTER_CONTEXT;

933
    fprintf(stdout, "%s", usbmoded_usage_info);
934
}
935

936
static void usbmoded_parse_options(int argc, char* argv[])
937
{
938 939
    LOG_REGISTER_CONTEXT;

940
    /* Parse the command-line options */
941 942 943 944 945 946 947 948
    for( ;; ) {
        int opt = getopt_long(argc, argv,
                              usbmoded_short_options,
                              usbmoded_long_options,
                              0);
        if( opt == -1 )
            break;

949 950 951
        switch (opt)
        {
        case 'a':
952
            log_warning("Deprecated option: --android_usb_broken");
953 954
            break;
        case 'i':
955
            log_warning("Deprecated option: --android_usb_broken_udev_events");
956 957
            break;
        case 'f':
958
            usbmoded_hw_fallback = true;
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
            break;
        case 's':
            log_set_type(LOG_TO_SYSLOG);
            break;

        case 'T':
            log_set_type(LOG_TO_STDERR);
            break;

        case 'D':
            log_set_level(LOG_DEBUG);
            break;

        case 'l':
            log_set_type(LOG_TO_STDERR);
            log_set_lineinfo(true);
            break;

        case 'd':
978
            usbmoded_set_diag_mode(true);
979 980 981 982
            break;

        case 'h':
            usbmoded_usage();
983
            exit(EXIT_SUCCESS);
984 985

        case 'r':
986
            usbmoded_set_rescue_mode(true);
987
            break;
988
#ifdef SYSTEMD
989
        case 'n':
990
            usbmoded_systemd_notify = true;
991 992 993 994
            break;
#endif
        case 'v':
            printf("USB mode daemon version: %s\n", VERSION);
995
            exit(EXIT_SUCCESS);
996 997 998 999 1000 1001

        case 'm':
            usbmoded_set_cable_connection_delay(strtol(optarg, 0, 0));
            break;

        case 'b':
1002
            log_warning("Deprecated option: --android-bootup-function");
1003 1004
            break;

1005 1006 1007 1008
        case 'Q':
          usbmoded_auto_exit = true;
          break;

1009 1010
        default:
            usbmoded_usage();
1011
            exit(EXIT_FAILURE);
1012 1013
        }
    }
1014
}
1015

1016 1017
int main(int argc, char* argv[])
{
1018 1019
    LOG_REGISTER_CONTEXT;

1020 1021 1022
    /* Library init calls that should be made before
     * using library functionality.
     */
1023
#if !GLIB_CHECK_VERSION(2, 36, 0)
1024
    g_type_init();
1025
#endif
1026
#if !GLIB_CHECK_VERSION(2, 31, 0)
1027
    g_thread_init(NULL);
1028
#endif
1029 1030
    dbus_threads_init_default();

1031 1032 1033
    /* - - - - - - - - - - - - - - - - - - - *
     * OPTIONS
     * - - - - - - - - - - - - - - - - - - - */
1034

1035 1036 1037
    /* Set logging defaults */
    log_init();
    log_set_name(basename(*argv));
1038

1039 1040
    /* Parse command line options */
    usbmoded_parse_options(argc, argv);
1041

1042 1043
    fprintf(stderr, "usb_moded %s starting\n", VERSION);
    fflush(stderr);
1044

1045 1046
    /* Silence common_system() calls */
    if( log_get_type() != LOG_TO_STDERR && log_get_level() != LOG_DEBUG )
1047
    {
1048 1049 1050 1051 1052 1053
        if( !freopen("/dev/null", "a", stdout) ) {
            log_err("can't redirect stdout: %m");
        }
        if( !freopen("/dev/null", "a", stderr) ) {
            log_err("can't redirect stderr: %m");
        }
1054
    }
1055

1056 1057 1058
    /* - - - - - - - - - - - - - - - - - - - *
     * INITIALIZE
     * - - - - - - - - - - - - - - - - - - - */
1059

1060
    if( !usbmoded_init() )
1061 1062 1063 1064 1065 1066 1067
        goto EXIT;

    /* - - - - - - - - - - - - - - - - - - - *
     * EXECUTE
     * - - - - - - - - - - - - - - - - - - - */

    /* Tell systemd that we have started up */
1068
#ifdef SYSTEMD
1069 1070
    if( usbmoded_systemd_notify ) {
        log_debug("notifying systemd");
1071 1072
        sd_notify(0, "READY=1");
    }
1073 1074
#endif

1075
    /* init succesful, run main loop */
1076
    usbmoded_exitcode = EXIT_SUCCESS;
1077 1078 1079 1080

    if( usbmoded_auto_exit )
        goto EXIT;

1081
    usbmoded_mainloop = g_main_loop_new(NULL, FALSE);
1082

1083
    log_debug("enter usb-moded mainloop");
1084
    g_main_loop_run(usbmoded_mainloop);
1085
    log_debug("leave usb-moded mainloop");
1086

1087 1088
    g_main_loop_unref(usbmoded_mainloop),
        usbmoded_mainloop = 0;
1089

1090 1091 1092
    /* - - - - - - - - - - - - - - - - - - - *
     * CLEANUP
     * - - - - - - - - - - - - - - - - - - - */
1093
EXIT:
1094
    usbmoded_cleanup();
1095

1096 1097 1098
    /* Memory leak debugging - instruct libdbus to flush resources. */
#if 0
    dbus_shutdown();
1099 1100
#endif

1101 1102 1103 1104
    /* - - - - - - - - - - - - - - - - - - - *
     * EXIT
     * - - - - - - - - - - - - - - - - - - - */

1105 1106 1107
    /* Must be done just before exit to make sure no more wakelocks
     * are taken and left behind on exit path */
    usbmoded_allow_suspend();
1108

1109
    log_debug("usb-moded return from main, with exit code %d",
1110 1111
              usbmoded_exitcode);
    return usbmoded_exitcode;
1112
}