Пример #1
0
nsresult
nsWifiScannerDBus::SendMessage(const char* aInterface,
                               const char* aPath,
                               const char* aFuncCall)
{
  DBusMessage* msg =
    dbus_message_new_method_call("org.freedesktop.NetworkManager",
                                 aPath, aInterface, aFuncCall);
  if (!msg) {
    return NS_ERROR_FAILURE;
  }

  DBusMessageIter argsIter;
  dbus_message_iter_init_append(msg, &argsIter);

  if (!strcmp(aFuncCall, "Get")) {
    const char* paramInterface = "org.freedesktop.NetworkManager.Device";
    if (!dbus_message_iter_append_basic(&argsIter, DBUS_TYPE_STRING,
                                        &paramInterface)) {
      return NS_ERROR_FAILURE;
    }

    const char* paramDeviceType = "DeviceType";
    if (!dbus_message_iter_append_basic(&argsIter, DBUS_TYPE_STRING,
                                        &paramDeviceType)) {
      return NS_ERROR_FAILURE;
    }
  } else if (!strcmp(aFuncCall, "GetAll")) {
    const char* param = "";
    if (!dbus_message_iter_append_basic(&argsIter, DBUS_TYPE_STRING, &param)) {
      return NS_ERROR_FAILURE;
    }
  }

  DBusError err;
  dbus_error_init(&err);

  // http://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html
  // Refer to function dbus_connection_send_with_reply_and_block.
  const uint32_t DBUS_DEFAULT_TIMEOUT = -1;
  DBusMessage* reply = nullptr;
  reply = dbus_connection_send_with_reply_and_block(mConnection, msg,
                                                    DBUS_DEFAULT_TIMEOUT, &err);
  if (dbus_error_is_set(&err)) {
    dbus_error_free(&err);

    // In the GetAccessPoints case, if there are no access points, error is set.
    // We don't want to error out here.
    if (!strcmp(aFuncCall, "GetAccessPoints")) {
      return NS_OK;
    }
    return NS_ERROR_FAILURE;
  }

  nsresult rv;
  if (!strcmp(aFuncCall, "GetDevices")) {
    rv = IdentifyDevices(reply);
  } else if (!strcmp(aFuncCall, "Get")) {
    rv = IdentifyDeviceType(reply, aPath);
  } else if (!strcmp(aFuncCall, "GetAccessPoints")) {
    rv = IdentifyAccessPoints(reply);
  } else if (!strcmp(aFuncCall, "GetAll")) {
    rv = IdentifyAPProperties(reply);
  } else {
    rv = NS_ERROR_FAILURE;
  }
  dbus_message_unref(reply);
  return rv;
}
Пример #2
0
static void
connect_hook(DBusConnection *connection, void *data)
{
    struct systemd_logind_info *info = data;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t arg;
    char *session = NULL;

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1",
            "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
            "GetSessionByPID");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = getpid();
    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: failed to get session: %s\n",
                   error.message);
        goto cleanup;
    }
    dbus_message_unref(msg);

    if (!dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &session,
                               DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: GetSessionByPID: %s\n",
                   error.message);
        goto cleanup;
    }
    session = XNFstrdup(session);

    dbus_message_unref(reply);
    reply = NULL;


    msg = dbus_message_new_method_call("org.freedesktop.login1",
            session, "org.freedesktop.login1.Session", "TakeControl");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = FALSE; /* Don't forcibly take over over the session */
    if (!dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: TakeControl failed: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',member='PauseDevice'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',member='ResumeDevice'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    /*
     * HdG: This is not useful with systemd <= 208 since the signal only
     * contains invalidated property names there, rather than property, val
     * pairs as it should.  Instead we just use the first resume / pause now.
     */
#if 0
    snprintf(match, sizeof(match),
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='%s'",
        session);
    dbus_bus_add_match(connection, match, &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }
#endif

    if (!dbus_connection_add_filter(connection, message_filter, info, NULL)) {
        LogMessage(X_ERROR, "systemd-logind: could not add filter: %s\n",
                   error.message);
        goto cleanup;
    }

    LogMessage(X_INFO, "systemd-logind: took control of session %s\n",
               session);
    info->conn = connection;
    info->session = session;
    info->vt_active = info->active = TRUE; /* The server owns the vt during init */
    session = NULL;

cleanup:
    free(session);
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);
}
Пример #3
0
int main(int argc, char *argv[]) {
        int r, exit_code = 0;
        DBusConnection *bus = NULL;
        DBusError error;
        _cleanup_close_ int fd = -1;

        dbus_error_init(&error);

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
        if (!bus) {
                log_error("Failed to connect to bus: %s", bus_error_message(&error));
                r = -EIO;
                goto finish;
        }

        if (arg_action == ACTION_LIST) {

                r = print_inhibitors(bus, &error);
                if (r < 0) {
                        log_error("Failed to list inhibitors: %s", bus_error(&error, r));
                        goto finish;
                }

        } else {
                char *w = NULL;
                pid_t pid;

                if (!arg_who)
                        arg_who = w = strv_join(argv + optind, " ");

                fd = inhibit(bus, &error);
                free(w);

                if (fd < 0) {
                        log_error("Failed to inhibit: %s", bus_error(&error, r));
                        r = fd;
                        goto finish;
                }

                pid = fork();
                if (pid < 0) {
                        log_error("Failed to fork: %m");
                        r = -errno;
                        goto finish;
                }

                if (pid == 0) {
                        /* Child */

                        safe_close(fd);
                        close_all_fds(NULL, 0);

                        execvp(argv[optind], argv + optind);
                        log_error("Failed to execute %s: %m", argv[optind]);
                        _exit(EXIT_FAILURE);
                }

                r = wait_for_terminate_and_warn(argv[optind], pid);
                if (r >= 0)
                        exit_code = r;
        }

finish:
        if (bus) {
                dbus_connection_close(bus);
                dbus_connection_unref(bus);
        }

        dbus_error_free(&error);

        return r < 0 ? EXIT_FAILURE : exit_code;
}
Пример #4
0
Error::Error( const char* name, const char* message )
: Dbg::Error( NULL )
{
	dbus_error_init(&_error);
	set(name, message);
}
Пример #5
0
void
systemd_logind_release_fd(int _major, int _minor, int fd)
{
    struct systemd_logind_info *info = &logind_info;
    InputInfoPtr pInfo;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t major = _major;
    dbus_int32_t minor = _minor;
    int matches = 0;

    if (!info->session || major == 0)
        goto close;

    /* Only release the fd if there is only 1 InputInfo left for this major
     * and minor, otherwise other InputInfo's are still referencing the fd. */
    pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs, major, minor);
    while (pInfo) {
        matches++;
        pInfo = systemd_logind_find_info_ptr_by_devnum(pInfo->next, major, minor);
    }
    if (matches > 1) {
        LogMessage(X_INFO, "systemd-logind: not releasing fd for %u:%u, still in use\n", major, minor);
        return;
    }

    LogMessage(X_INFO, "systemd-logind: releasing fd for %u:%u\n", major, minor);

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1", info->session,
            "org.freedesktop.login1.Session", "ReleaseDevice");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &major,
                                       DBUS_TYPE_UINT32, &minor,
                                       DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(info->conn, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply)
        LogMessage(X_ERROR, "systemd-logind: failed to release device: %s\n",
                   error.message);

cleanup:
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);
close:
    if (fd != -1)
        close(fd);
}
Пример #6
0
static void
battery_remove(LibHalContext *ctx, const char *udi)
{
	DBusError error;

	HAL_DEBUG(("battery_remove() enter"));
	dbus_error_init(&error);
	libhal_device_remove_property(ctx, udi, "battery.remaining_time",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.charge_level.percentage", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.charge_level.rate",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.charge_level.last_full", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.charge_level.current", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.voltage.present",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.rate",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.current",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.rechargeable.is_discharging", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.rechargeable.is_charging", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.is_rechargeable",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.charge_level.unit",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.charge_level.granularity_2", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.charge_level.granularity_1", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.charge_level.low",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.charge_level.warning",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.charge_level.design",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.voltage.design",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.reporting.granularity_2", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi,
	    "battery.reporting.granularity_1", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.low",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.warning",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.design",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.last_full",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.unit",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.technology", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.reporting.technology",
	    &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.serial", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.model", &error);
	my_dbus_error_free(&error);
	libhal_device_remove_property(ctx, udi, "battery.vendor", &error);
	my_dbus_error_free(&error);
	HAL_DEBUG(("battery_remove() exit"));
}
Пример #7
0
DBusHandlerResult handle_dbus_message( DBusConnection *connection, DBusMessage *message, void *data )
{
  int eax;
  int esi;
  int msg_type;
  switch ( msg_type )
  {
  default:
    break;
  case 4:
    break;
  case 3:
    break;
  case 2:
    break;
  case 1:
  {
    char *method_name;
    char *interface_name;
    if ( dbus_message_get_member( &message ) )
    {
      if ( interface_name )
      {
        /* phantom */ size_t __s1_len;
        /* phantom */ size_t __s2_len;
        strcmp( "org.seul.geda.pcb", interface_name );
        if ( 1 )
        {
          /* phantom */ size_t __s1_len;
          /* phantom */ size_t __s2_len;
          method_name[0] = dbus_message_get_member( &message );
          strcmp( "GetFilename", dbus_message_get_member( &message ) );
          if ( !1 )
          {
            __fprintf_chk( stderr, 1, "pcb_dbus: Interface '%s' has no method '%s'\n", dbus_message_get_interface( &message ), ebp_184 );
            return 1;
          }
          else
          {
            if ( dbus_message_new_method_return( &message ) )
            {
              dbus_message_iter_init_append( dbus_message_new_method_return( &message ), ebp_112 );
              if ( PCB->Filename )
              {
                if ( lrealpath( &PCB->Filename ) == 0 )
                  goto B38;
                else
                {
                  if ( dbus_message_iter_append_basic( ebp_112, 115, ebp_32 ) )
                  {
                    free( ebp_32 );
                  }
                  else
                  {
                    __fprintf_chk( stderr, 1, "pcb_dbus: Couldn't append return filename string to message reply, Out Of Memory!\n" );
                    free( ebp_32 );
                    dbus_message_unref( &ebx );
                    return 0;
                  }
                }
              }
              else
              {
              }
B38:;
              if ( calloc( 1, 1 ) )
              {
              }
              else
              {
                __fprintf_chk( stderr, 1, ebp_192, ebp_192 );
              }
            }
            else
            {
            }
          }
        }
        else
        {
          /* phantom */ size_t __s1_len;
          /* phantom */ size_t __s2_len;
          strcmp( "org.seul.geda.pcb.actions", interface_name );
          if ( 1 )
          {
            /* phantom */ size_t __s1_len;
            /* phantom */ size_t __s2_len;
            method_name[0] = ebp_140;
            strcmp( "ExecAction", ebp_140 );
            if ( !1 )
            {
              __fprintf_chk( stderr, 1, "pcb_dbus: Interface '%s' has no method '%s'\n", dbus_message_get_interface( &message ), ebp_184 );
            }
            else
            {
              dbus_error_init( ebp_56 );
              if ( dbus_message_get_args( &message, ebp_56, 115, ebp_32, 97, (long long)115, (long long)( ebp_40 ) ) )
              {
                hid_actionv( (char*)calloc( 1, 1 ), ebp_40, ebp_36 );
                dbus_free_string_array( 0 );
                if ( dbus_message_new_method_return( &message ) )
                {
                  dbus_message_iter_init_append( dbus_message_new_method_return( &message ), ebp_112 );
                  if ( dbus_message_iter_append_basic( ebp_112, 117, ebp_28 ) )
                  {
                  }
                  else
                  {
                  }
                }
              }
              else
              {
                __fprintf_chk( stderr, 1, "Failed to read method arguments\n" );
                if ( 0 )
                {
                  dbus_free_string_array( 0 );
                }
              }
            }
          }
          else
          {
            /* phantom */ size_t __s1_len;
            /* phantom */ size_t __s2_len;
            strcmp( "org.freedesktop.DBus.Introspectable", interface_name );
            if ( !1 )
            {
              __fprintf_chk( stderr, 1, "pcb_dbus: Interface '%s' was not recognised\n", dbus_message_iter_append_basic( ebp_112, 117, ebp_28 ) );
            }
          {
            /* phantom */ size_t __s1_len;
            /* phantom */ size_t __s2_len;
            method_name[0] = dbus_message_get_member( &message );
            strcmp( "Introspect", dbus_message_get_member( &message ) );
            if ( !1 )
            {
              __fprintf_chk( stderr, 1, "pcb_dbus: Interface '%s' has no method '%s'\n", dbus_message_get_interface( &message ), ebp_184 );
            }
            else
            {
              if ( dbus_message_new_method_return( &message ) )
              {
                dbus_message_iter_init_append( dbus_message_new_method_return( &message ), ebp_112 );
                if ( dbus_message_iter_append_basic( ebp_112, 115, pcb_dbus_introspect_xml ) )
                {
                  if ( dbus_connection_send( &pcb_dbus_conn, (DBusMessage*)dbus_message_get_interface( &message ), 0 ) )
                  {
                    dbus_message_unref( &ebx );
                    return 0;
                  }
                }
                else
                {
                }
              }
            }
          }
          }
        }
        if ( dbus_connection_send( ebp_200, ebp_200, ebp_196 ) )
        {
          dbus_message_unref( &ebx );
          return 0;
        }
      }
      else
      {
      }
    }
    else
    {
    }
  }
    break;
  }
  __fprintf_chk( stderr, 1, ebp_192, ebp_192 );
}
Пример #8
0
/*****************************************************************************
 * SendToTelepathy
 *****************************************************************************/
static int SendToTelepathy( intf_thread_t *p_intf, const char *psz_msg )
{
    DBusConnection *p_conn;
    DBusMessage *p_msg;
    DBusMessage *p_reply;
    DBusMessageIter args;
    DBusError error;
    dbus_error_init( &error );
    dbus_uint32_t i_status;

    p_conn = p_intf->p_sys->p_conn;

    /* first we need to get the actual status */
    p_msg = dbus_message_new_method_call(
            "org.freedesktop.Telepathy.MissionControl",
           "/org/freedesktop/Telepathy/MissionControl",
            "org.freedesktop.Telepathy.MissionControl",
            "GetPresence" );
    if( !p_msg )
        return VLC_ENOMEM;

    p_reply = dbus_connection_send_with_reply_and_block( p_conn, p_msg,
        50, &error ); /* blocks 50ms maximum */

    dbus_message_unref( p_msg );
    if( p_reply == NULL )
    {   /* MC is not active, or too slow. Better luck next time? */
        return VLC_SUCCESS;
    }

    /* extract the status from the reply */
    if( dbus_message_get_args( p_reply, &error,
            DBUS_TYPE_UINT32, &i_status,
            DBUS_TYPE_INVALID ) == FALSE )
    {
        return VLC_ENOMEM;
    }

    p_msg = dbus_message_new_method_call(
            "org.freedesktop.Telepathy.MissionControl",
           "/org/freedesktop/Telepathy/MissionControl",
            "org.freedesktop.Telepathy.MissionControl",
            "SetPresence" );
    if( !p_msg )
        return VLC_ENOMEM;

    dbus_message_iter_init_append( p_msg, &args );

    /* first argument is the status */
    if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_UINT32, &i_status ) )
    {
        dbus_message_unref( p_msg );
        return VLC_ENOMEM;
    }
    /* second argument is the message */
    if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &psz_msg ) )
    {
        dbus_message_unref( p_msg );
        return VLC_ENOMEM;
    }


    if( !dbus_connection_send( p_conn, p_msg, NULL ) )
        return VLC_ENOMEM;

    dbus_connection_flush( p_conn );
    dbus_message_unref( p_msg );

    return VLC_SUCCESS;
}
Пример #9
0
int virPolkitCheckAuth(const char *actionid,
                       pid_t pid,
                       unsigned long long startTime ATTRIBUTE_UNUSED,
                       uid_t uid,
                       const char **details,
                       bool allowInteraction ATTRIBUTE_UNUSED)
{
    PolKitCaller *pkcaller = NULL;
    PolKitAction *pkaction = NULL;
    PolKitContext *pkcontext = NULL;
    PolKitError *pkerr = NULL;
    PolKitResult pkresult;
    DBusError err;
    DBusConnection *sysbus;
    int ret = -1;

    if (details) {
        virReportError(VIR_ERR_AUTH_FAILED, "%s",
                       _("Details not supported with polkit v0"));
        return -1;
    }

    if (!(sysbus = virDBusGetSystemBus()))
        goto cleanup;

    VIR_INFO("Checking PID %lld running as %d",
             (long long) pid, uid);
    dbus_error_init(&err);
    if (!(pkcaller = polkit_caller_new_from_pid(sysbus,
                                                pid, &err))) {
        VIR_DEBUG("Failed to lookup policy kit caller: %s", err.message);
        dbus_error_free(&err);
        goto cleanup;
    }

    if (!(pkaction = polkit_action_new())) {
        char ebuf[1024];
        VIR_DEBUG("Failed to create polkit action %s",
                  virStrerror(errno, ebuf, sizeof(ebuf)));
        goto cleanup;
    }
    polkit_action_set_action_id(pkaction, actionid);

    if (!(pkcontext = polkit_context_new()) ||
        !polkit_context_init(pkcontext, &pkerr)) {
        char ebuf[1024];
        VIR_DEBUG("Failed to create polkit context %s",
                  (pkerr ? polkit_error_get_error_message(pkerr)
                   : virStrerror(errno, ebuf, sizeof(ebuf))));
        if (pkerr)
            polkit_error_free(pkerr);
        dbus_error_free(&err);
        goto cleanup;
    }

# if HAVE_POLKIT_CONTEXT_IS_CALLER_AUTHORIZED
    pkresult = polkit_context_is_caller_authorized(pkcontext,
                                                   pkaction,
                                                   pkcaller,
                                                   0,
                                                   &pkerr);
    if (pkerr && polkit_error_is_set(pkerr)) {
        VIR_DEBUG("Policy kit failed to check authorization %d %s",
                  polkit_error_get_error_code(pkerr),
                  polkit_error_get_error_message(pkerr));
        goto cleanup;
    }
# else
    pkresult = polkit_context_can_caller_do_action(pkcontext,
                                                   pkaction,
                                                   pkcaller);
# endif
    if (pkresult != POLKIT_RESULT_YES) {
        VIR_DEBUG("Policy kit denied action %s from pid %lld, uid %d, result: %s",
                  actionid, (long long) pid, uid,
                  polkit_result_to_string_representation(pkresult));
        ret = -2;
        goto cleanup;
    }

    VIR_DEBUG("Policy allowed action %s from pid %lld, uid %d",
              actionid, (long long)pid, (int)uid);

    ret = 0;

 cleanup:
    if (ret < 0) {
        virResetLastError();
        virReportError(VIR_ERR_AUTH_FAILED, "%s",
                       _("authentication failed"));
    }
    if (pkcontext)
        polkit_context_unref(pkcontext);
    if (pkcaller)
        polkit_caller_unref(pkcaller);
    if (pkaction)
        polkit_action_unref(pkaction);
    return ret;
}
Пример #10
0
static BusDesktopFile *
desktop_file_for_name (BusConfigParser *parser,
                       const char *name,
                       DBusError  *error)
{
    BusDesktopFile *desktop_file;
    DBusList **service_dirs;
    DBusList *link;
    DBusError tmp_error;
    DBusString full_path;
    DBusString filename;
    const char *dir;

    _DBUS_ASSERT_ERROR_IS_CLEAR (error);

    desktop_file = NULL;

    if (!_dbus_string_init (&filename))
    {
        BUS_SET_OOM (error);
        goto out_all;
    }

    if (!_dbus_string_init (&full_path))
    {
        BUS_SET_OOM (error);
        goto out_filename;
    }

    if (!_dbus_string_append (&filename, name) ||
            !_dbus_string_append (&filename, ".service"))
    {
        BUS_SET_OOM (error);
        goto out;
    }

    service_dirs = bus_config_parser_get_service_dirs (parser);
    for (link = _dbus_list_get_first_link (service_dirs);
            link != NULL;
            link = _dbus_list_get_next_link (service_dirs, link))
    {
        dir = link->data;
        _dbus_verbose ("Looking at '%s'\n", dir);

        dbus_error_init (&tmp_error);

        /* clear the path from last time */
        _dbus_string_set_length (&full_path, 0);

        /* build the full path */
        if (!_dbus_string_append (&full_path, dir) ||
                !_dbus_concat_dir_and_file (&full_path, &filename))
        {
            BUS_SET_OOM (error);
            goto out;
        }

        _dbus_verbose ("Trying to load file '%s'\n", _dbus_string_get_data (&full_path));
        desktop_file = bus_desktop_file_load (&full_path, &tmp_error);
        if (desktop_file == NULL)
        {
            _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
            _dbus_verbose ("Could not load %s: %s: %s\n",
                           _dbus_string_get_const_data (&full_path),
                           tmp_error.name, tmp_error.message);

            /* we may have failed if the file is not found; this is not fatal */
            if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
            {
                dbus_move_error (&tmp_error, error);
                /* we only bail out on OOM */
                goto out;
            }
            dbus_error_free (&tmp_error);
        }

        /* did we find the desktop file we want? */
        if (desktop_file != NULL)
            break;
    }

    /* Didn't find desktop file; set error */
    if (desktop_file == NULL)
    {
        dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND,
                        "The name %s was not provided by any .service files",
                        name);
    }

out:
    _dbus_string_free (&full_path);
out_filename:
    _dbus_string_free (&filename);
out_all:
    return desktop_file;
}
Пример #11
0
/*
   This function communicates with the kernel to check whether or not it should
   allow the access.
   If the machine is in permissive mode it will return ok.  Audit messages will
   still be generated if the access would be denied in enforcing mode.
*/
int selinux_access_check(
                DBusConnection *connection,
                DBusMessage *message,
                const char *path,
                const char *permission,
                DBusError *error) {

        security_context_t scon = NULL, fcon = NULL;
        int r = 0;
        const char *tclass = NULL;
        struct auditstruct audit;

        assert(connection);
        assert(message);
        assert(permission);
        assert(error);

        if (!use_selinux())
                return 0;

        r = selinux_access_init(error);
        if (r < 0)
                return r;

        audit.uid = audit.loginuid = (uid_t) -1;
        audit.gid = (gid_t) -1;
        audit.cmdline = NULL;
        audit.path = path;

        r = get_calling_context(connection, message, &scon, error);
        if (r < 0) {
                log_error("Failed to get caller's security context on: %m");
                goto finish;
        }


        tclass = "service";
        if (path && !strneq(path,"system", strlen("system"))) {
                /* get the file context of the unit file */
                r = getfilecon(path, &fcon);
                if (r < 0) {
                        dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "Failed to get file context on %s.", path);
                        r = -errno;
                        log_error("Failed to get security context on %s: %m",path);
                        goto finish;
                }
        } else {
                if (path)
                        tclass = "system";
                r = getcon(&fcon);
                if (r < 0) {
                        dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "Failed to get current context.");
                        r = -errno;
                        log_error("Failed to get current process context on: %m");
                        goto finish;
                }
        }

        (void) get_audit_data(connection, message, &audit, error);

        errno = 0;
        r = selinux_check_access(scon, fcon, tclass, permission, &audit);
        if (r < 0) {
                dbus_set_error(error, DBUS_ERROR_ACCESS_DENIED, "SELinux policy denies access.");
                r = -errno;
                log_error("SELinux policy denies access.");
        }

        log_debug("SELinux access check scon=%s tcon=%s tclass=%s perm=%s path=%s cmdline=%s: %i", scon, fcon, tclass, permission, path, audit.cmdline, r);

finish:
        free(audit.cmdline);
        freecon(scon);
        freecon(fcon);

        if (r && security_getenforce() != 1) {
                dbus_error_init(error);
                r = 0;
        }

        return r;
}
static int send_dbus_signal(DBusConnection *conn,
			const char *msg_name,
			const char *value) {
	DBusMessage *msg;
	DBusMessageIter args;
	DBusPendingCall *pending;
	int result = 0;

	/* create a signal and check for errors */
	msg = dbus_message_new_method_call(STE_MAD_DBUS_SERVICE,
					STE_MAD_DBUS_OBJECT_NAME,
					STE_MAD_DBUS_TXBO_IF_NAME,
					msg_name);

	if (msg == NULL) {
		ERR("failed to allocate memory\n");
		return -1;
	}

	/* append arguments onto signal */
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &value)) {
		ERR("failed to allocate memory\n");
		result = -1;
		goto exit;
	}

	/* send the message and flush the connection */
	if (!dbus_connection_send_with_reply(conn, msg, &pending, -1)) {
		ERR("DBUS message sending failed\n");
		result = -1;
		goto exit;
	}

	/* send request */
	dbus_connection_flush(conn);
	dbus_message_unref(msg);

	/* wait for ACK from MAD */
	dbus_pending_call_block(pending);
	msg = dbus_pending_call_steal_reply(pending);
	dbus_pending_call_unref(pending);

	if (msg == NULL) {
		ERR("failed to receive MAD's ACK\n");
		goto exit;
	}

	if (dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_ERROR) {
		DBusError err;

		dbus_error_init(&err);
		dbus_set_error_from_message(&err, msg);
		ERR("MAD ACK failed: %s\n", err.message);
		dbus_error_free(&err);
		goto exit;
	}

exit:
	if (msg) {
		dbus_message_unref(msg);
	}
	return result;
}
Пример #13
0
int main (int argc, char **argv)
{
    state     *st;
    GtkWidget *window;
    GtkWidget *drawing_area;

    GError    *error = NULL;

    DBusError dbus_error;

    gtk_set_locale();

    gtk_init_with_args(&argc, &argv,
                       parameter_string,
                       options,
                       "gnome-screensaver",
                       &error);

    if (error != NULL) {
        g_printerr ("%s. See --help for usage information.\n",
                  error->message);
        g_error_free (error);
        return EX_SOFTWARE;
    }

    copy_gifs();
    get_time_str();
    window = gs_theme_window_new();
    drawing_area = gtk_drawing_area_new();
    st = clock_init(window, drawing_area);
    init_weather(st);

    gtk_widget_show(drawing_area);
    gtk_container_add(GTK_CONTAINER (window), drawing_area);

    gtk_widget_show(window);

    loop = g_main_loop_new (NULL, FALSE);

    dbus_error_init (&dbus_error);
    bus = dbus_bus_get (DBUS_BUS_SESSION, &dbus_error);
    if (!bus) {
      g_warning ("Failed to connect to the D-BUS daemon: %s", dbus_error.message);
      dbus_error_free (&dbus_error);
      return 1;
    }
    dbus_connection_setup_with_g_main (bus, NULL);

    /* listening to messages from all objects as no path is specified */
    dbus_bus_add_match (bus, "type='signal',interface='org.freedesktop.MediaPlayer'", &dbus_error);
    dbus_bus_add_match (bus, "type='signal',interface='org.freedesktop.DBus.Properties'", &dbus_error);
    dbus_connection_add_filter (bus, signal_filter, loop, NULL);


    g_signal_connect(G_OBJECT (window), "delete-event",
                     GTK_SIGNAL_FUNC(quit_app), loop);
    g_signal_connect(GTK_OBJECT (drawing_area), "configure_event",
                     GTK_SIGNAL_FUNC (configure_event), st);
    g_signal_connect(GTK_OBJECT (drawing_area), "expose_event",
                     GTK_SIGNAL_FUNC (expose_event), st);

    g_signal_connect(GTK_OBJECT (window), "configure_event",
                     GTK_SIGNAL_FUNC (w_configure_event), st);

    g_random_set_seed(time (NULL));

    st->timer_id = g_timeout_add_seconds(1, clock_timer, st);

    g_main_loop_run (loop);

    clock_free (st);

    return EX_OK;
}
Пример #14
0
dbus_bool_t
dbind_method_call_reentrant_va (DBusConnection *cnx,
                                const char     *bus_name,
                                const char     *path,
                                const char     *interface,
                                const char     *method,
                                DBusError      *opt_error,
                                const char     *arg_types,
                                va_list         args)
{
    dbus_bool_t success = FALSE;
    DBusMessage *msg = NULL, *reply = NULL;
    DBusMessageIter iter;
    DBusError *err, real_err;
    const char *p;
  va_list args_demarshal;

  va_copy (args_demarshal, args);
    if (opt_error)
        err = opt_error;
    else {
        dbus_error_init (&real_err);
        err = &real_err;
    }

    msg = dbus_message_new_method_call (bus_name, path, interface, method);
    if (!msg)
        goto out;

    p = arg_types;
    dbus_message_iter_init_append (msg, &iter);
    dbind_any_marshal_va (&iter, &p, args);

    reply = dbind_send_and_allow_reentry (cnx, msg, err);
    if (!reply)
        goto out;

    if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR)
    {
      const char *name = dbus_message_get_error_name (reply);
      goto out;
    }
    /* demarshal */
    if (p[0] == '=' && p[1] == '>')
    {
        DBusMessageIter iter;
        dbus_message_iter_init (reply, &iter);
        p = arg_types;
        dbind_any_demarshal_va (&iter, &p, args_demarshal);
    }

    success = TRUE;
out:
    if (msg)
        dbus_message_unref (msg);

    if (reply)
        dbus_message_unref (reply);

    if (err == &real_err)
        dbus_error_free (err);

    va_end (args_demarshal);
    return success;
}
Пример #15
0
static void
battery_dynamic_update(LibHalContext *ctx, const char *udi, int fd)
{
	int reporting_rate;
	int reporting_current;
	int reporting_lastfull;
	int design_voltage;
	int present_voltage;
	char *reporting_unit;
	int remaining_time;
	int remaining_percentage;
	gboolean charging;
	gboolean discharging;
	acpi_bst_t bst;
	LibHalChangeSet *cs;
	DBusError error;
	static int counter = 0;

	HAL_DEBUG(("battery_dynamic_update() enter"));
	bzero(&bst, sizeof (bst));
	if (ioctl(fd, BATT_IOC_STATUS, &bst) < 0) {
		return;
	}

	charging = bst.bst_state & BATT_BST_CHARGING ? TRUE : FALSE;
	discharging = bst.bst_state & BATT_BST_DISCHARGING ? TRUE : FALSE;
	/* No need to continue if battery is essentially idle. */
	if (counter && !charging && !discharging) {
		return;
	}
	dbus_error_init(&error);
	libhal_device_set_property_bool(ctx, udi, "battery.is_rechargeable",
	    TRUE, &error);
	my_dbus_error_free(&error);
	if (libhal_device_property_exists(ctx, udi,
	    "battery.charge_level.percentage", &error)) {
		remaining_percentage = libhal_device_get_property_int(ctx, udi,
		    "battery.charge_level.percentage", &error);
		if ((remaining_percentage == 100) && charging) {
			charging = FALSE;
		}
	}
	libhal_device_set_property_bool(ctx, udi,
	    "battery.rechargeable.is_charging", charging, &error);
	my_dbus_error_free(&error);
	libhal_device_set_property_bool(ctx, udi,
	    "battery.rechargeable.is_discharging", discharging, &error);
	my_dbus_error_free(&error);
	reporting_current = bst.bst_rem_cap;
	libhal_device_set_property_int(ctx, udi, "battery.reporting.current",
	    bst.bst_rem_cap, &error);
	my_dbus_error_free(&error);
	reporting_rate = bst.bst_rate;
	libhal_device_set_property_int(ctx, udi, "battery.reporting.rate",
	    bst.bst_rate, &error);
	my_dbus_error_free(&error);
	present_voltage = bst.bst_voltage;
	libhal_device_set_property_int(ctx, udi, "battery.voltage.present",
	    bst.bst_voltage, &error);
	/* get all the data we know */
	my_dbus_error_free(&error);
	reporting_unit = libhal_device_get_property_string(ctx, udi,
	    "battery.reporting.unit", &error);
	my_dbus_error_free(&error);
	reporting_lastfull = libhal_device_get_property_int(ctx, udi,
	    "battery.reporting.last_full", &error);

	/*
	 * Convert mAh to mWh since util_compute_time_remaining() works
	 * for mWh.
	 */
	if (reporting_unit && strcmp(reporting_unit, "mAh") == 0) {
		my_dbus_error_free(&error);
		design_voltage = libhal_device_get_property_int(ctx, udi,
		    "battery.voltage.design", &error);
		/*
		 * If the present_voltage is inaccurate, set it to the
		 * design_voltage.
		 */
		if (((present_voltage * 10) < design_voltage) ||
		    (present_voltage <= 0) ||
		    (present_voltage > design_voltage)) {
			present_voltage = design_voltage;
		}
		reporting_rate = (reporting_rate * present_voltage) / 1000;
		reporting_lastfull = (reporting_lastfull * present_voltage) /
		    1000;
		reporting_current = (reporting_current * present_voltage) /
		    1000;
	}

	/* Make sure the current charge does not exceed the full charge */
	if (reporting_current > reporting_lastfull) {
		reporting_current = reporting_lastfull;
	}
	if (!charging && !discharging) {
		counter++;
		reporting_rate = 0;
	}

	if ((cs = libhal_device_new_changeset(udi)) == NULL) {
		HAL_DEBUG(("Cannot allocate changeset"));
		libhal_free_string(reporting_unit);
		my_dbus_error_free(&error);
		return;
	}

	libhal_changeset_set_property_int(cs, "battery.charge_level.rate",
	    reporting_rate);
	libhal_changeset_set_property_int(cs,
	    "battery.charge_level.last_full", reporting_lastfull);
	libhal_changeset_set_property_int(cs,
	    "battery.charge_level.current", reporting_current);

	remaining_percentage = util_compute_percentage_charge(udi,
	    reporting_current, reporting_lastfull);
	remaining_time = util_compute_time_remaining(udi, reporting_rate,
	    reporting_current, reporting_lastfull, discharging, charging, 0);
	/*
	 * Some batteries give bad remaining_time estimates relative to
	 * the charge level.
	 */
	if (charging && ((remaining_time < 30) || ((remaining_time < 300) &&
	    (remaining_percentage < 95)) || (remaining_percentage > 97))) {
		remaining_time = util_compute_time_remaining(udi,
		    reporting_rate, reporting_current, reporting_lastfull,
		    discharging, charging, 1);
	}

	if (remaining_percentage > 0) {
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.percentage", remaining_percentage);
	} else {
		my_dbus_error_free(&error);
		libhal_device_remove_property(ctx, udi,
		    "battery.charge_level.percentage", &error);
	}
	if ((remaining_percentage == 100) && charging) {
		battery_last_full(cs, fd);
	}
	/*
	 * remaining_percentage is more accurate so we handle cases
	 * where the remaining_time cannot be correct.
	 */
	if ((!charging && !discharging) || ((remaining_percentage == 100) &&
	    !discharging)) {
		remaining_time = 0;
	}
	if (remaining_time < 0) {
		my_dbus_error_free(&error);
		libhal_device_remove_property(ctx, udi,
		    "battery.remaining_time", &error);
	} else if (remaining_time >= 0) {
		libhal_changeset_set_property_int(cs,
		    "battery.remaining_time", remaining_time);
	}

	my_dbus_error_free(&error);
	libhal_device_commit_changeset(ctx, cs, &error);
	libhal_device_free_changeset(cs);
	libhal_free_string(reporting_unit);
	my_dbus_error_free(&error);
	HAL_DEBUG(("battery_dynamic_update() exit"));
}
Пример #16
0
static void
device_added(LibHalContext *hal_ctx, const char *udi)
{
    char **props;
    /* Cleverly, these are currently all leaked. */
    char *path = NULL, *driver = NULL, *name = NULL, *xkb_rules = NULL;
    char *xkb_model = NULL, *xkb_layout = NULL, *xkb_variant = NULL;
    char **xkb_options = NULL;
    DBusError error;
    struct xserver_option *options = NULL;
    int type = TYPE_NONE;
    int i;
    DeviceIntPtr dev = NULL;

    dbus_error_init(&error);

    props = libhal_device_get_property_strlist(hal_ctx, udi,
                                               "info.capabilities", &error);
    if (!props) {
        DebugF("[config/hal] couldn't get capabilities for %s: %s (%s)\n",
               udi, error.name, error.message);
        goto out_error;
    }
    for (i = 0; props[i]; i++) {
        /* input.keys is the new, of which input.keyboard is a subset, but
         * input.keyboard is the old 'we have keys', so we have to keep it
         * around. */
        if (strcmp(props[i], "input.keys") == 0 ||
            strcmp(props[i], "input.keyboard") == 0)
            type |= TYPE_KEYS;
        if (strcmp(props[i], "input.mouse") == 0)
            type |= TYPE_POINTER;
    }
    libhal_free_string_array(props);

    if (!type)
        goto out_error;

    driver = get_prop_string(hal_ctx, udi, "input.x11_driver");
    path = get_prop_string(hal_ctx, udi, "input.device");
    if (!driver || !path) {
        DebugF("[config/hal] no driver or path specified for %s\n", udi);
        goto unwind;
    }
    name = get_prop_string(hal_ctx, udi, "info.product");
    if (!name)
        name = xstrdup("(unnamed)");

    if (type & TYPE_KEYS) {
        xkb_rules = get_prop_string(hal_ctx, udi, "input.xkb.rules");
        xkb_model = get_prop_string(hal_ctx, udi, "input.xkb.model");
        xkb_layout = get_prop_string(hal_ctx, udi, "input.xkb.layout");
        xkb_variant = get_prop_string(hal_ctx, udi, "input.xkb.variant");
        xkb_options = get_prop_string_array(hal_ctx, udi, "input.xkb.options");
    }

    options = xcalloc(sizeof(*options), 1);
    options->key = xstrdup("_source");
    options->value = xstrdup("server/hal");
    if (!options->key || !options->value) {
        ErrorF("[config] couldn't allocate first key/value pair\n");
        goto unwind;
    }

    add_option(&options, "path", path);
    add_option(&options, "driver", driver);
    add_option(&options, "name", name);
    add_option(&options, "hal_udi", udi);

    if (xkb_model)
        add_option(&options, "xkb_model", xkb_model);
    if (xkb_layout)
        add_option(&options, "xkb_layout", xkb_layout);
    if (xkb_variant)
        add_option(&options, "xkb_variant", xkb_variant);
#if 0
    if (xkb_options)
        add_option(&options, "xkb_options", xkb_options);
#endif

    /* Maemo-specific hack.  Ugh. */
    if (type & TYPE_KEYS)
        add_option(&options, "type", "keyboard");
    else
        add_option(&options, "type", "pointer");

    if (NewInputDeviceRequest(options, &dev) != Success) {
        DebugF("[config/hal] NewInputDeviceRequest failed\n");
        goto unwind;
    }

    dbus_error_free(&error);

    return;

unwind:
    if (path)
        xfree(path);
    if (driver)
        xfree(driver);
    if (name)
        xfree(name);
    if (xkb_rules)
        xfree(xkb_rules);
    if (xkb_model)
        xfree(xkb_model);
    if (xkb_layout)
        xfree(xkb_layout);
    if (xkb_options) {
        for (i = 0; xkb_options[i]; i++)
            xfree(xkb_options[i]);
        xfree(xkb_options);
    }

out_error:
    dbus_error_free(&error);

    return;
}
Пример #17
0
static gboolean
battery_static_update(LibHalContext *ctx, const char *udi, int fd)
{
	const char *technology;
	int reporting_design;
	int reporting_warning;
	int reporting_low;
	int reporting_gran1;
	int reporting_gran2;
	int voltage_design;
	char reporting_unit[10];
	acpi_bif_t bif;
	LibHalChangeSet *cs;
	DBusError error;

	HAL_DEBUG(("battery_static_update() enter"));
	bzero(&bif, sizeof (bif));
	if (ioctl(fd, BATT_IOC_INFO, &bif) < 0) {
		return (FALSE);
	}
	if ((cs = libhal_device_new_changeset(udi)) == NULL) {
		HAL_DEBUG(("Cannot allocate changeset"));
		return (FALSE);
	}

	libhal_changeset_set_property_string(cs, "battery.vendor",
	    bif.bif_oem_info);
	technology = bif.bif_type;
	if (technology != NULL) {
		libhal_changeset_set_property_string(cs,
		    "battery.reporting.technology", technology);
		libhal_changeset_set_property_string(cs, "battery.technology",
		    util_get_battery_technology(technology));
	}
	libhal_changeset_set_property_string(cs, "battery.serial",
	    bif.bif_serial);
	libhal_changeset_set_property_string(cs, "battery.model",
	    bif.bif_model);

	if (bif.bif_unit) {
		libhal_changeset_set_property_string(cs,
		    "battery.reporting.unit", "mAh");
		strlcpy(reporting_unit, "mAh", sizeof (reporting_unit));
	} else {
		libhal_changeset_set_property_string(cs,
		    "battery.reporting.unit", "mWh");
		strlcpy(reporting_unit, "mWh", sizeof (reporting_unit));
	}
	libhal_changeset_set_property_int(cs, "battery.reporting.last_full",
	    bif.bif_last_cap);
	libhal_changeset_set_property_int(cs, "battery.reporting.design",
	    bif.bif_design_cap);
	reporting_design = bif.bif_design_cap;
	libhal_changeset_set_property_int(cs, "battery.reporting.warning",
	    bif.bif_warn_cap);
	reporting_warning = bif.bif_warn_cap;
	libhal_changeset_set_property_int(cs, "battery.reporting.low",
	    bif.bif_low_cap);
	reporting_low = bif.bif_low_cap;
	libhal_changeset_set_property_int(cs,
	    "battery.reporting.granularity_1", bif.bif_gran1_cap);
	reporting_gran1 = bif.bif_gran1_cap;
	libhal_changeset_set_property_int(cs,
	    "battery.reporting.granularity_2", bif.bif_gran2_cap);
	reporting_gran2 = bif.bif_gran2_cap;
	libhal_changeset_set_property_int(cs, "battery.voltage.design",
	    bif.bif_voltage);
	voltage_design = bif.bif_voltage;

	if (reporting_unit && strcmp(reporting_unit, "mAh") == 0) {
		/* convert to mWh */
		libhal_changeset_set_property_string(cs,
		    "battery.charge_level.unit", "mWh");
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.design",
		    (reporting_design * voltage_design) / 1000);
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.warning",
		    (reporting_warning * voltage_design) / 1000);
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.low",
		    (reporting_low * voltage_design) / 1000);
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.granularity_1",
		    (reporting_gran1 * voltage_design) / 1000);
		libhal_changeset_set_property_int(cs,
		    "battery.charge_level.granularity_2",
		    (reporting_gran2 * voltage_design) / 1000);
	} else {
		if (reporting_unit && strcmp(reporting_unit, "mWh") == 0) {
			libhal_changeset_set_property_string(cs,
			    "battery.charge_level.unit", "mWh");
		}
		libhal_changeset_set_property_int(cs,
                    "battery.charge_level.design", reporting_design);
                libhal_changeset_set_property_int(cs,
                    "battery.charge_level.warning", reporting_warning);
                libhal_changeset_set_property_int(cs,
                    "battery.charge_level.low", reporting_low);
                libhal_changeset_set_property_int(cs,
                    "battery.charge_level.granularity_1", reporting_gran1);
                libhal_changeset_set_property_int(cs,
                    "battery.charge_level.granularity_2", reporting_gran2);
	}
		

	dbus_error_init(&error);
	libhal_device_commit_changeset(ctx, cs, &error);
	libhal_device_free_changeset(cs);
	my_dbus_error_free(&error);
	HAL_DEBUG(("battery_static_update() exit"));
	return (TRUE);
}
Пример #18
0
static void
connect_hook(DBusConnection *connection, void *data)
{
    DBusError error;
    struct config_hal_info *info = data;
    char **devices;
    int num_devices, i;

    info->system_bus = connection;

    dbus_error_init(&error);

    if (!info->hal_ctx)
        info->hal_ctx = libhal_ctx_new();
    if (!info->hal_ctx) {
        ErrorF("[config/hal] couldn't create HAL context\n");
        goto out_err;
    }

    if (!libhal_ctx_set_dbus_connection(info->hal_ctx, info->system_bus)) {
        ErrorF("[config/hal] couldn't associate HAL context with bus\n");
        goto out_ctx;
    }
    if (!libhal_ctx_init(info->hal_ctx, &error)) {
        ErrorF("[config/hal] couldn't initialise context: %s (%s)\n",
               error.name, error.message);
        goto out_ctx;
    }

    libhal_ctx_set_device_added(info->hal_ctx, device_added);
    libhal_ctx_set_device_removed(info->hal_ctx, device_removed);
    if (!libhal_device_property_watch_all(info->hal_ctx, &error)) {
        ErrorF("[config/hal] couldn't watch all properties: %s (%s)\n",
               error.name, error.message);
        goto out_ctx2;
    }

    devices = libhal_find_device_by_capability(info->hal_ctx, "input",
                                               &num_devices, &error);
    /* FIXME: Get default devices if error is set. */
    for (i = 0; i < num_devices; i++)
        device_added(info->hal_ctx, devices[i]);
    libhal_free_string_array(devices);

    dbus_error_free(&error);

    return;
    
out_ctx2:
    if (!libhal_ctx_shutdown(info->hal_ctx, &error))
        DebugF("[config/hal] couldn't shut down context: %s (%s)\n",
               error.name, error.message);
out_ctx:
    libhal_ctx_free(info->hal_ctx);
out_err:
    dbus_error_free(&error);

    info->hal_ctx = NULL;
    info->system_bus = NULL;

    return;
}
Пример #19
0
//! Validates model file
int
db_validate_model(iks *xml, char *filename)
{
    /*!
     * Validates model file.
     *
     * @xml Iksemel document
     * @return 0 on success, -1 on error
     *
     */

    iks *iface, *met, *arg;

    DBusError bus_error;
    dbus_error_init(&bus_error);

    // Check root tag
    if (iks_strcmp(iks_name(xml), "comarModel") != 0) {
        log_error("Not a valid model XML: %s\n", filename);
        return -1;
    }

    for (iface = iks_first_tag(xml); iface; iface = iks_next_tag(iface)) {
        // Only "interface" tag is allowed
        if (iks_strcmp(iks_name(iface), "interface") != 0) {
            log_error("Unknown tag '%s' in XML: %s\n", iks_name(iface), filename);
            return -1;
        }
        // Interfaces must have a "name" attribute
        if (!iks_strlen(iks_find_attrib(iface, "name"))) {
            log_error("Model with no name in XML: %s\n", filename);
            return -1;
        }

        for (met = iks_first_tag(iface); met; met = iks_next_tag(met)) {
            // Only "method" and "signal" tags are allowed
            if (iks_strcmp(iks_name(met), "method") == 0 || iks_strcmp(iks_name(met), "signal") == 0) {
                // Tags must have a "name" attribute
                if (!iks_strlen(iks_find_attrib(met, "name"))) {
                    log_error("Method/Signal tag without name under '%s' in XML: %s\n", iks_find_attrib(iface, "name"), filename);
                    return -1;
                }
                for (arg = iks_first_tag(met); arg; arg = iks_next_tag(arg)) {
                    if (iks_strcmp(iks_name(arg), "arg") == 0) {
                        // Arguments must have a "name" attribute
                        if (!iks_strlen(iks_find_attrib(arg, "name"))) {
                            log_error("Argument tag with no name under '%s/%s' in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename);
                            return -1;
                        }
                        // Arguments must have a "type" attribute
                        if (!iks_strlen(iks_find_attrib(arg, "type"))) {
                            log_error("Argument tag without type under '%s/%s' in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename);
                            return -1;
                        }
                        // Types must be a valid DBus signature
                        if (!dbus_signature_validate(iks_find_attrib(arg, "type"), &bus_error)) {
                            dbus_error_free(&bus_error);
                            log_error("Argument tag with invalid type (%s/%s/%s) in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), iks_find_attrib(arg, "name"), filename);
                            return -1;
                        }
                        // Types must be single type object
                        if (!dbus_signature_validate_single(iks_find_attrib(arg, "type"), &bus_error)) {
                            dbus_error_free(&bus_error);
                            log_error("Argument tag with a non-single element type (%s/%s/%s) in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), iks_find_attrib(arg, "name"), filename);
                            return -1;
                        }
                    }
                    else if (iks_strcmp(iks_name(arg), "annotation") == 0) {
                        // Attributes must have a "name" attribute
                        if (!iks_strlen(iks_find_attrib(arg, "name"))) {
                            log_error("Annotation tag without name under '%s' in XML: %s\n", iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename);
                            return -1;
                        }
                    }
                    else {
                        log_error("Unknown tag '%s' under '%s/%s' in XML: %s\n", iks_name(arg), iks_find_attrib(iface, "name"), iks_find_attrib(met, "name"), filename);
                        return -1;
                    }
                }
            }
            else {
                log_error("Unknown tag '%s' under '%s' in XML: %s\n", iks_name(met), iks_find_attrib(iface, "name"), filename);
                return -1;
            }
        }
    }

    return 0;
}
Пример #20
0
/*
 * Dump all devices.
 */
int dump_devices(LibHalContext *hal_ctx, char *arg)
{
	int i;
	int num_devices;
	char **device_names;
	DBusError error;
	char *udi = NULL;

	if (arg) {
		if (*arg == '/') {
			udi = arg;
		} else {
#ifdef HAVE_ASPRINTF
			asprintf(&udi, "/org/freedesktop/Hal/devices/%s", arg);
#else
			udi = calloc(1, sizeof ("/org/freedesktop/Hal/devices/%s") + strlen(arg));
			sprintf(udi, "/org/freedesktop/Hal/devices/%s", arg);

#endif
		}
	}

	dbus_error_init(&error);

	if (!udi) {
		if (!(device_names = libhal_get_all_devices(hal_ctx, &num_devices, &error))) {
			fprintf(stderr, "Empty HAL device list.\n");
			LIBHAL_FREE_DBUS_ERROR (&error);
			return 31;
		}
	} else {
		device_names = calloc(2, sizeof *device_names);
		device_names[0] = strdup(udi);
		num_devices = 1;
	}

	for(i = 0; i < num_devices; i++) {
		LibHalPropertySet *props;
		LibHalPropertySetIterator it;
		int type;

		if (!(props = libhal_device_get_all_properties(hal_ctx, device_names[i], &error))) {
			fprintf(stderr, "%s: %s\n", error.name, error.message);
			dbus_error_init(&error);
			continue;
		}

		if (!udi)
			printf("%d: ", i);
		printf("udi = '%s'\n", device_names[i]);

		for(libhal_psi_init(&it, props); libhal_psi_has_more(&it); libhal_psi_next(&it)) {
			type = libhal_psi_get_type(&it);
			switch (type) {
			case LIBHAL_PROPERTY_TYPE_STRING:
				printf("  %s = '%s'  (string)\n",
					libhal_psi_get_key(&it),
					libhal_psi_get_string(&it)
				);
				break;
			case LIBHAL_PROPERTY_TYPE_INT32:
				printf("  %s = %d  (0x%x)  (int)\n",
					libhal_psi_get_key(&it),
					libhal_psi_get_int(&it),
					libhal_psi_get_int(&it)
				);
				break;
			case LIBHAL_PROPERTY_TYPE_UINT64:
				printf("  %s = %lld  (0x%llx)  (uint64)\n",
					libhal_psi_get_key(&it),
					(long long) libhal_psi_get_uint64(&it),
					(long long) libhal_psi_get_uint64(&it)
				);
				break;
			case LIBHAL_PROPERTY_TYPE_DOUBLE:
				printf("  %s = %g  (double)\n",
					libhal_psi_get_key(&it),
					libhal_psi_get_double(&it)
				);
				break;
			case LIBHAL_PROPERTY_TYPE_BOOLEAN:
				printf("  %s = %s  (bool)\n",
					libhal_psi_get_key(&it),
					libhal_psi_get_bool(&it) ? "true" : "false"
				);
				break;
			case LIBHAL_PROPERTY_TYPE_STRLIST:
				{
					char **strlist;

					printf ("  %s = { ", libhal_psi_get_key(&it));
					strlist = libhal_psi_get_strlist(&it);
					while (*strlist) {
						printf("'%s'%s", *strlist, strlist[1] ? ", " : "");
						strlist++;
					}
					printf(" } (string list)\n");
				}
				break;
			default:
				printf("Unknown type %d = 0x%02x\n", type, type);
				break;
			}
		}

		libhal_free_property_set(props);
		printf("\n");
	}

	libhal_free_string_array(device_names);
	dbus_error_free(&error);

	return 0;
}
Пример #21
0
Error::Error()
: Dbg::Error( NULL )
{
	dbus_error_init(&_error);
}
Пример #22
0
int add_udi(LibHalContext *hal_ctx, char *arg)
{
	DBusError error;
	dbus_bool_t dev_exists = FALSE;
	char *udi = NULL, buf[1024];
	lh_prop_t *prop;
	int err;

	if (!arg)
		return 21;

	if (*arg == '/') {
		udi = arg;
	} else {
#ifdef HAVE_ASPRINTF
		asprintf(&udi, "/org/freedesktop/Hal/devices/%s", arg);
#else
		udi = calloc(1, sizeof ("/org/freedesktop/Hal/devices/%s") + strlen(arg));
		sprintf(udi, "/org/freedesktop/Hal/devices/%s", arg);
#endif
	}

	if (udi)
		new_dev.udi = strdup(udi);

	dbus_error_init(&error);

	if (udi)
		dev_exists = libhal_device_exists(hal_ctx, udi, &error);

	if (dev_exists) {
		new_dev.real_udi = strdup(new_dev.udi);
	} else {
		new_dev.real_udi = libhal_new_device(hal_ctx, &error);

		if (!new_dev.real_udi) {
			fprintf(stderr, "%s: %s\n", error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR (&error);
			free(new_dev.real_udi);

			return 22;
		}

		printf("tmp udi: %s\n", new_dev.real_udi);
	}

	prop = NULL;

	while (fgets(buf, sizeof buf, stdin)) {
		process_property(hal_ctx, buf, &prop);
	}

	err = add_properties(hal_ctx, &new_dev, prop);

	prop = free_properties(prop);

	if (!dev_exists) {
		if (!libhal_device_commit_to_gdl(hal_ctx, new_dev.real_udi, new_dev.udi, &error)) {
			fprintf(stderr, "%s: %s\n", error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR (&error);
			free(new_dev.real_udi);

			err = err ? err : 23;
		}
	}

	printf("%s: %s\n", dev_exists ? "merged": "created", new_dev.udi);

	return err;
}
Пример #23
0
/**
 * mafw_proxy_source_new:
 *
 * Creates a new instance of #MafwProxySource.
 *
 * Returns: a new #MafwProxySource object.
 */
GObject *mafw_proxy_source_new(const gchar *uuid, const gchar *plugin,
                               MafwRegistry *registry)
{
	GObject *new_obj = g_object_new(MAFW_TYPE_PROXY_SOURCE,
					"uuid", uuid,
					"plugin", plugin,
					NULL);
	MafwProxySource *source_obj;
	DBusError err;
	gchar *match_str = NULL, *path = NULL;
	DBusObjectPathVTable path_vtable;

	memset(&path_vtable, 0, sizeof(DBusObjectPathVTable));
	path_vtable.message_function =
		(DBusObjectPathMessageFunction)mafw_proxy_source_dispatch_message;

	if (!new_obj)
		return NULL;

	source_obj = MAFW_PROXY_SOURCE(new_obj);


	connection = mafw_dbus_session(NULL);

	if (!connection) goto source_new_error;

	dbus_error_init(&err);

	path = g_strdup_printf(MAFW_SOURCE_OBJECT "/%s", uuid);

	match_str = g_strdup_printf(MAFW_EXTENSION_MATCH, MAFW_SOURCE_INTERFACE,
					path);
	dbus_bus_add_match(connection, match_str, &err);
	g_free(match_str);
	if (dbus_error_is_set(&err)) goto source_new_error;

	if (!dbus_connection_register_object_path(connection,
			path,
			&path_vtable,
			source_obj))
		goto source_new_error;

	g_free(path);
	/* It is harmless to setup the same context multiple times.
	 * On the other hand it is required if someone just calls
	 * mafw_proxy_source_new() without mafw_dbus_discover_init()
	 * for testing purposes. */
	dbus_connection_setup_with_g_main(connection, NULL);

	proxy_extension_attach(G_OBJECT(new_obj), connection, plugin, registry);

	return new_obj;

source_new_error:

	g_free(path);
	if (connection)
		dbus_connection_unref(connection);

	g_object_unref(new_obj);
	return NULL;
}
Пример #24
0
int add_properties(LibHalContext *hal_ctx, new_dev_t *nd, lh_prop_t *prop)
{
	DBusError error;
	lh_prop_t *p;
	char *udi2 = NULL, *udi3 = NULL, **s;
	LibHalPropertyType old_type;

	dbus_error_init(&error);

	for(p = prop; p; p = p->next) {
		if (!strcmp(p->key, "udi") && p->type == LIBHAL_PROPERTY_TYPE_STRING) {
			udi2 = p->v.str_value;
			continue;
		}

		old_type = libhal_device_get_property_type(hal_ctx, nd->real_udi, p->key, &error);
		dbus_error_init(&error);

		if (old_type != LIBHAL_PROPERTY_TYPE_INVALID &&
		    ( p->type != old_type || p->type == LIBHAL_PROPERTY_TYPE_STRLIST)) {
			if (!libhal_device_remove_property(hal_ctx, nd->real_udi, p->key, &error)) {
				fprintf(stderr, "%s: %s\n", error.name, error.message);
				LIBHAL_FREE_DBUS_ERROR (&error);
				return 41;
			}
		}

		switch (p->type) {
			case LIBHAL_PROPERTY_TYPE_INVALID:
				break;
			case LIBHAL_PROPERTY_TYPE_BOOLEAN:
				if (!libhal_device_set_property_bool(hal_ctx, nd->real_udi, p->key, p->v.bool_value, &error)) {
					fprintf(stderr, "%s: %s\n", error.name, error.message);
					LIBHAL_FREE_DBUS_ERROR (&error);
					return 42;
				}
				break;
			case LIBHAL_PROPERTY_TYPE_INT32:
				if (!libhal_device_set_property_int(hal_ctx, nd->real_udi, p->key, p->v.int_value, &error)) {
					fprintf(stderr, "%s: %s\n", error.name, error.message);
					LIBHAL_FREE_DBUS_ERROR (&error);
					return 42;
				}
				break;
			case LIBHAL_PROPERTY_TYPE_UINT64:
				if (!libhal_device_set_property_uint64(hal_ctx, nd->real_udi, p->key, p->v.uint64_value, &error)) {
					fprintf(stderr, "%s: %s\n", error.name, error.message);
					LIBHAL_FREE_DBUS_ERROR (&error);
					return 42;
				}
				break;
			case LIBHAL_PROPERTY_TYPE_DOUBLE:
				if (!libhal_device_set_property_double(hal_ctx, nd->real_udi, p->key, p->v.double_value, &error)) {
					fprintf(stderr, "%s: %s\n", error.name, error.message);
					LIBHAL_FREE_DBUS_ERROR (&error);
					return 42;
				}
				break;
			case LIBHAL_PROPERTY_TYPE_STRING:
				if (!strcmp(p->key, "info.udi")) udi3 = p->v.str_value;
				if (!libhal_device_set_property_string(hal_ctx, nd->real_udi, p->key, p->v.str_value, &error)) {
					fprintf(stderr, "%s: %s\n", error.name, error.message);
					LIBHAL_FREE_DBUS_ERROR (&error);
					return 42;
				}
				break;
			case LIBHAL_PROPERTY_TYPE_STRLIST:
				for(s = p->v.strlist_value; *s; s++) {
					if (!libhal_device_property_strlist_append(hal_ctx, nd->real_udi, p->key, *s, &error)) {
						fprintf(stderr, "%s: %s\n", error.name, error.message);
						LIBHAL_FREE_DBUS_ERROR (&error);
						return 42;
					}
				}
				break;
		}
	}

	if (udi2) udi3 = NULL;
	if (udi3) udi2 = udi3;

	if (udi2 && !nd->udi)
		nd->udi = strdup(udi2);

	return 0;
}
Пример #25
0
static DBusHandlerResult
message_filter(DBusConnection * connection, DBusMessage * message, void *data)
{
    struct systemd_logind_info *info = data;
    struct xf86_platform_device *pdev = NULL;
    InputInfoPtr pInfo = NULL;
    int ack = 0, pause = 0, fd = -1;
    DBusError error;
    dbus_int32_t major, minor;
    char *pause_str;

    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    dbus_error_init(&error);

    if (dbus_message_is_signal(message,
                               "org.freedesktop.DBus", "NameOwnerChanged")) {
        char *name, *old_owner, *new_owner;

        dbus_message_get_args(message, &error,
                              DBUS_TYPE_STRING, &name,
                              DBUS_TYPE_STRING, &old_owner,
                              DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID);
        if (dbus_error_is_set(&error)) {
            LogMessage(X_ERROR, "systemd-logind: NameOwnerChanged: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (name && strcmp(name, "org.freedesktop.login1") == 0)
            FatalError("systemd-logind disappeared (stopped/restarted?)\n");

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (strcmp(dbus_message_get_path(message), info->session) != 0)
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                               "PauseDevice")) {
        if (!dbus_message_get_args(message, &error,
                               DBUS_TYPE_UINT32, &major,
                               DBUS_TYPE_UINT32, &minor,
                               DBUS_TYPE_STRING, &pause_str,
                               DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: PauseDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (strcmp(pause_str, "pause") == 0) {
            pause = 1;
            ack = 1;
        }
        else if (strcmp(pause_str, "force") == 0) {
            pause = 1;
        }
        else if (strcmp(pause_str, "gone") == 0) {
            /* Device removal is handled through udev */
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
        else {
            LogMessage(X_WARNING, "systemd-logind: unknown pause type: %s\n",
                       pause_str);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    }
    else if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                                    "ResumeDevice")) {
        if (!dbus_message_get_args(message, &error,
                                   DBUS_TYPE_UINT32, &major,
                                   DBUS_TYPE_UINT32, &minor,
                                   DBUS_TYPE_UNIX_FD, &fd,
                                   DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: ResumeDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    } else
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    LogMessage(X_INFO, "systemd-logind: got %s for %u:%u\n",
               pause ? "pause" : "resume", major, minor);

    pdev = xf86_find_platform_device_by_devnum(major, minor);
    if (!pdev)
        pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs,
                                                       major, minor);
    if (!pdev && !pInfo) {
        LogMessage(X_WARNING, "systemd-logind: could not find dev %u:%u\n",
                   major, minor);
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (pause) {
        /* Our VT_PROCESS usage guarantees we've already given up the vt */
        info->active = info->vt_active = FALSE;
        /* Note the actual vtleave has already been handled by xf86Events.c */
        if (pdev)
            pdev->flags |= XF86_PDEV_PAUSED;
        else {
            close(pInfo->fd);
            systemd_logind_set_input_fd_for_all_devs(major, minor, -1, FALSE);
        }
        if (ack)
            systemd_logind_ack_pause(info, major, minor);
    }
    else {
        /* info->vt_active gets set by systemd_logind_vtenter() */
        info->active = TRUE;

        if (pdev)
            pdev->flags &= ~XF86_PDEV_PAUSED;
        else
            systemd_logind_set_input_fd_for_all_devs(major, minor, fd,
                                                     info->vt_active);

        /* Always call vtenter(), in case there are only legacy video devs */
        systemd_logind_vtenter();
    }
    return DBUS_HANDLER_RESULT_HANDLED;
}
Пример #26
0
int main(int argc, char **argv)
{
	DBusError error;
	DBusConnection *conn;
	LibHalContext *hal_ctx;
	int i, err;

	opterr = 0;
	opt.list = 1;

	while ((i = getopt_long(argc, argv, "a:hr:", options, NULL)) != -1) {
		switch (i) {
		case 'a':
			opt.add = 1;
			opt.list = 0;
			opt.udi = optarg;
			break;
		case 'r':
			opt.remove = 1;
			opt.list = 0;
			opt.udi = optarg;
			break;
		case 'h':
			help();
			return 0;
		default:
			help();
			return 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;
	}

	/* fprintf(stderr, "connected to: %s\n", dbus_bus_get_unique_name(conn)); */
	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 (opt.list)
		err = dump_devices(hal_ctx, argv[optind]);
	else if (opt.remove)
		err = remove_udi(hal_ctx, opt.udi);
	else if (opt.add)
		err = add_udi(hal_ctx, opt.udi);
	else
		err = 6;

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

	return err;
}
Пример #27
0
int
systemd_logind_take_fd(int _major, int _minor, const char *path,
                       Bool *paused_ret)
{
    struct systemd_logind_info *info = &logind_info;
    InputInfoPtr pInfo;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t major = _major;
    dbus_int32_t minor = _minor;
    dbus_bool_t paused;
    int fd = -1;

    if (!info->session || major == 0)
        return -1;

    /* logind does not support mouse devs (with evdev we don't need them) */
    if (strstr(path, "mouse"))
        return -1;

    /* Check if we already have an InputInfo entry with this major, minor
     * (shared device-nodes happen ie with Wacom tablets). */
    pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs, major, minor);
    if (pInfo) {
        LogMessage(X_INFO, "systemd-logind: returning pre-existing fd for %s %u:%u\n",
               path, major, minor);
        *paused_ret = FALSE;
        return pInfo->fd;
    }

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1", info->session,
            "org.freedesktop.login1.Session", "TakeDevice");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &major,
                                       DBUS_TYPE_UINT32, &minor,
                                       DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(info->conn, msg,
                                                      DBUS_TIMEOUT_USE_DEFAULT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: failed to take device %s: %s\n",
                   path, error.message);
        goto cleanup;
    }

    if (!dbus_message_get_args(reply, &error,
                               DBUS_TYPE_UNIX_FD, &fd,
                               DBUS_TYPE_BOOLEAN, &paused,
                               DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: TakeDevice %s: %s\n",
                   path, error.message);
        goto cleanup;
    }

    *paused_ret = paused;

    LogMessage(X_INFO, "systemd-logind: got fd for %s %u:%u fd %d paused %d\n",
               path, major, minor, fd, paused);

cleanup:
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);

    return fd;
}
Пример #28
0
int main(int argc, char *argv[]) {
        DBusError error;
        DBusConnection *bus = NULL;
        DBusMessage *m = NULL;
        int r = EXIT_FAILURE;

        dbus_error_init(&error);

        if (argc != 2) {
                log_error("Incorrect number of arguments.");
                goto finish;
        }

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        /* We send this event to the private D-Bus socket and then the
         * system instance will forward this to the system bus. We do
         * this to avoid an activation loop when we start dbus when we
         * are called when the dbus service is shut down. */

        bus = dbus_connection_open_private("unix:path=/run/systemd/private", &error);
        if (!bus) {
                log_warning("Failed to get D-Bus connection: %s", bus_error_message(&error));
                goto finish;
        }

        if (bus_check_peercred(bus) < 0) {
                log_error("Bus owner not root.");
                goto finish;
        }

        m = dbus_message_new_signal("/org/freedesktop/systemd1/agent", "org.freedesktop.systemd1.Agent", "Released");
        if (!m) {
                log_error("Could not allocate signal message.");
                goto finish;
        }

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &argv[1],
                                      DBUS_TYPE_INVALID)) {
                log_error("Could not attach group information to signal message.");
                goto finish;
        }

        if (!dbus_connection_send(bus, m, NULL)) {
                log_error("Failed to send signal message on private connection.");
                goto finish;
        }

        r = EXIT_SUCCESS;

finish:
        if (bus) {
                dbus_connection_flush(bus);
                dbus_connection_close(bus);
                dbus_connection_unref(bus);
        }

        if (m)
                dbus_message_unref(m);

        dbus_error_free(&error);
        return r;
}
Пример #29
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" );

    /* Find verbosity from VLC_VERBOSE environment variable */
    {
        char *env = getenv( "VLC_VERBOSE" );
        if( env != NULL )
            priv->i_verbose = atoi( env );
    }

    /* 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 );
    vlc_threads_setup (p_libvlc);

    /* 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 ) )
    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

#define MPRIS_APPEND "/org/mpris/MediaPlayer2/TrackList/Append"
#define MPRIS_BUS_NAME "org.mpris.MediaPlayer2.vlc"
#define MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2"
#define MPRIS_TRACKLIST_INTERFACE "org.mpris.MediaPlayer2.TrackList"

    if( var_InheritBool( p_libvlc, "one-instance" )
    || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
      && var_InheritBool( p_libvlc, "started-from-file" ) ) )
    {
        for( int i = vlc_optind; i < i_argc; i++ )
            if( ppsz_argv[i][0] == ':' )
            {
                msg_Err( p_libvlc, "item option %s incompatible with single instance",
                         ppsz_argv[i] );
                goto dbus_out;
            }

        /* Initialise D-Bus interface, check for other instances */
        dbus_threads_init_default();

        DBusError err;
        dbus_error_init( &err );

        /* connect to the session bus */
        DBusConnection  *conn = dbus_bus_get( DBUS_BUS_SESSION, &err );
        if( conn == NULL )
        {
            msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
                    err.message );
            dbus_error_free( &err );
            goto dbus_out;
        }

        /* 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 */
        /* FIXME: This check is totally brain-dead and buggy. */
        if( !dbus_bus_name_has_owner( conn, MPRIS_BUS_NAME, &err ) )
        {
            dbus_connection_unref( conn );
            if( dbus_error_is_set( &err ) )
            {
                msg_Err( p_libvlc, "D-Bus error: %s", err.message );
            }
            else
                msg_Dbg( p_libvlc, "No media player running. Continuing normally." );
            dbus_error_free( &err );
            goto dbus_out;
        }

        const dbus_bool_t play = !var_InheritBool( p_libvlc, "playlist-enqueue" );

        msg_Warn( p_libvlc, "media player running. Exiting...");
        for( int i = vlc_optind; i < i_argc; i++ )
        {
            DBusMessage *msg = dbus_message_new_method_call(
               MPRIS_BUS_NAME, MPRIS_OBJECT_PATH, MPRIS_TRACKLIST_INTERFACE, "AddTrack" );
            if( unlikely(msg == NULL) )
                continue;

            /* We need to resolve relative paths in this instance */
            char *mrl;
            if( strstr( ppsz_argv[i], "://" ) )
                mrl = strdup( ppsz_argv[i] );
            else
                mrl = vlc_path2uri( ppsz_argv[i], NULL );
            if( mrl == NULL )
            {
                dbus_message_unref( msg );
                continue;
            }

            const char *after_track = MPRIS_APPEND;

            /* append MRLs */
            if( !dbus_message_append_args( msg, DBUS_TYPE_STRING, &mrl,
                                                DBUS_TYPE_STRING, &after_track,
                                                DBUS_TYPE_BOOLEAN, &play,
                                                DBUS_TYPE_INVALID ) )
            {
                 dbus_message_unref( msg );
                 msg = NULL;
            }
            free( mrl );
            if( unlikely(msg == NULL) )
                continue;

            msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl );

            /* send message and get a handle for a reply */
            DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1,
                                                                            &err );
            dbus_message_unref( msg );
            if( reply == NULL )
            {
                msg_Err( p_libvlc, "D-Bus error: %s", err.message );
                continue;
            }
            dbus_message_unref( reply );
        }
        /* we unreference the connection when we've finished with it */
        dbus_connection_unref( conn );
        exit( 1 );
    }
#undef MPRIS_APPEND
#undef MPRIS_BUS_NAME
#undef MPRIS_OBJECT_PATH
#undef MPRIS_TRACKLIST_INTERFACE
dbus_out:
#endif // HAVE_DBUS

    /*
     * 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;
    }
    if( priv->b_color )
        priv->b_color = var_InheritBool( p_libvlc, "color" );

    vlc_CPU_dump( VLC_OBJECT(p_libvlc) );
    vlc_object_set_name( p_libvlc, "main" );

    priv->b_stats = var_InheritBool( p_libvlc, "stats" );

    /*
     * 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" );
        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" );

    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;
}
Пример #30
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;
    char        *psz_val;

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

    vlc_LogPreinit(p_libvlc);

    /* Initialize the module bank and load the configuration of the
     * core module. We need to do this at this stage to be able to display
     * a short help if required by the user. (short help == core 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;
    }

    vlc_threads_setup (p_libvlc);

    /* 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 ) )
    {
        vlc_LogDeinit (p_libvlc);
        module_EndBank (true);
        return VLC_EGENERIC;
    }

    vlc_LogInit(p_libvlc);

    /*
     * Support for gettext
     */
#if defined( ENABLE_NLS ) \
     && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
    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);
        exit(0);
    }

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

#ifdef HAVE_DAEMON
    /* Check for daemon mode */
    if( var_InheritBool( p_libvlc, "daemon" ) )
    {
        if( daemon( 1, 0) != 0 )
        {
            msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
            vlc_LogDeinit (p_libvlc);
            module_EndBank (true);
            return VLC_ENOMEM;
        }

        /* lets check if we need to write the pidfile */
        char *pidfile = var_InheritString( p_libvlc, "pidfile" );
        if( pidfile != NULL )
        {
            FILE *stream = vlc_fopen( pidfile, "w" );
            if( stream != NULL )
            {
                fprintf( stream, "%d", (int)getpid() );
                fclose( stream );
                msg_Dbg( p_libvlc, "written PID file %s", pidfile );
            }
            else
                msg_Err( p_libvlc, "cannot write PID file %s: %s",
                         pidfile, vlc_strerror_c(errno) );
            free( pidfile );
        }
    }
    else
    {
        var_Create( p_libvlc, "pidfile", VLC_VAR_STRING );
        var_SetString( p_libvlc, "pidfile", "" );
    }
#endif

    if( libvlc_InternalDialogInit( p_libvlc ) != VLC_SUCCESS )
    {
        vlc_LogDeinit (p_libvlc);
        module_EndBank (true);
        return VLC_ENOMEM;
    }
    if( libvlc_InternalKeystoreInit( p_libvlc ) != VLC_SUCCESS )
        msg_Warn( p_libvlc, "memory keystore init failed" );

/* FIXME: could be replaced by using Unix sockets */
#ifdef HAVE_DBUS

#define MPRIS_APPEND "/org/mpris/MediaPlayer2/TrackList/Append"
#define MPRIS_BUS_NAME "org.mpris.MediaPlayer2.vlc"
#define MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2"
#define MPRIS_TRACKLIST_INTERFACE "org.mpris.MediaPlayer2.TrackList"

    if( var_InheritBool( p_libvlc, "one-instance" )
    || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
      && var_InheritBool( p_libvlc, "started-from-file" ) ) )
    {
        for( int i = vlc_optind; i < i_argc; i++ )
            if( ppsz_argv[i][0] == ':' )
            {
                msg_Err( p_libvlc, "item option %s incompatible with single instance",
                         ppsz_argv[i] );
                goto dbus_out;
            }

        /* Initialise D-Bus interface, check for other instances */
        dbus_threads_init_default();

        DBusError err;
        dbus_error_init( &err );

        /* connect to the session bus */
        DBusConnection  *conn = dbus_bus_get( DBUS_BUS_SESSION, &err );
        if( conn == NULL )
        {
            msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
                    err.message );
            dbus_error_free( &err );
            goto dbus_out;
        }

        /* 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 */
        /* FIXME: This check is totally brain-dead and buggy. */
        if( !dbus_bus_name_has_owner( conn, MPRIS_BUS_NAME, &err ) )
        {
            dbus_connection_unref( conn );
            if( dbus_error_is_set( &err ) )
            {
                msg_Err( p_libvlc, "D-Bus error: %s", err.message );
            }
            else
                msg_Dbg( p_libvlc, "No media player running. Continuing normally." );
            dbus_error_free( &err );
            goto dbus_out;
        }

        const dbus_bool_t play = !var_InheritBool( p_libvlc, "playlist-enqueue" );

        msg_Warn( p_libvlc, "media player running. Exiting...");
        for( int i = vlc_optind; i < i_argc; i++ )
        {
            DBusMessage *msg = dbus_message_new_method_call(
               MPRIS_BUS_NAME, MPRIS_OBJECT_PATH, MPRIS_TRACKLIST_INTERFACE, "AddTrack" );
            if( unlikely(msg == NULL) )
                continue;

            /* We need to resolve relative paths in this instance */
            char *mrl;
            if( strstr( ppsz_argv[i], "://" ) )
                mrl = strdup( ppsz_argv[i] );
            else
                mrl = vlc_path2uri( ppsz_argv[i], NULL );
            if( mrl == NULL )
            {
                dbus_message_unref( msg );
                continue;
            }

            const char *after_track = MPRIS_APPEND;

            /* append MRLs */
            if( !dbus_message_append_args( msg, DBUS_TYPE_STRING, &mrl,
                                                DBUS_TYPE_OBJECT_PATH, &after_track,
                                                DBUS_TYPE_BOOLEAN, &play,
                                                DBUS_TYPE_INVALID ) )
            {
                 dbus_message_unref( msg );
                 msg = NULL;
                 free( mrl );
                 continue;
            }

            msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl );
            free( mrl );

            /* send message and get a handle for a reply */
            DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1,
                                                                            &err );
            dbus_message_unref( msg );
            if( reply == NULL )
            {
                msg_Err( p_libvlc, "D-Bus error: %s", err.message );
                continue;
            }
            dbus_message_unref( reply );
        }
        /* we unreference the connection when we've finished with it */
        dbus_connection_unref( conn );
        exit( 0 );
    }
#undef MPRIS_APPEND
#undef MPRIS_BUS_NAME
#undef MPRIS_OBJECT_PATH
#undef MPRIS_TRACKLIST_INTERFACE
dbus_out:
#endif // HAVE_DBUS

    vlc_CPU_dump( VLC_OBJECT(p_libvlc) );

    priv->b_stats = var_InheritBool( p_libvlc, "stats" );

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

    /*
     * Meta data handling
     */
    priv->parser = playlist_preparser_New(VLC_OBJECT(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 );
    /* NOTE: Because the playlist and interfaces start before this function
     * returns control to the application (DESIGN BUG!), all these variables
     * must be created (in place of libvlc_new()) and set to VLC defaults
     * (in place of VLC main()) *here*. */
    var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
    var_SetString( p_libvlc, "user-agent",
                   "VLC media player (LibVLC "VERSION")" );
    var_Create( p_libvlc, "http-user-agent", VLC_VAR_STRING );
    var_SetString( p_libvlc, "http-user-agent",
                   "VLC/"PACKAGE_VERSION" LibVLC/"PACKAGE_VERSION );
    var_Create( p_libvlc, "app-icon-name", VLC_VAR_STRING );
    var_SetString( p_libvlc, "app-icon-name", PACKAGE_NAME );
    var_Create( p_libvlc, "app-id", VLC_VAR_STRING );
    var_SetString( p_libvlc, "app-id", "org.VideoLAN.VLC" );
    var_Create( p_libvlc, "app-version", VLC_VAR_STRING );
    var_SetString( p_libvlc, "app-version", PACKAGE_VERSION );

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

#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)
        {
            libvlc_InternalAddIntf( p_libvlc, psz_temp );
            free( psz_temp );
        }
    }
    free( psz_modules );
    free( psz_control );

    if( var_InheritBool( p_libvlc, "network-synchronisation") )
        libvlc_InternalAddIntf( 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

    /*
     * 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 )
    {
        intf_InsertItem( p_libvlc, psz_val, 0, NULL, 0 );
        free( psz_val );
    }

    return VLC_SUCCESS;
}