Ejemplo n.º 1
0
int keyzen_dbus_get_pid_of_name(DBusConnection *connection, const char *name, pid_t *pid)
{
	int result;
	DBusError error;
	DBusMessage *message, *reply;
	dbus_bool_t b;
    dbus_uint32_t u32;

	assert(connection);
	assert(name);
	assert(pid);

	/* look at cache */
	if (read_cache(name, pid))
		return 0;

	/* create the message */
	message = dbus_message_new_method_call(
				DBUS_SERVICE_DBUS, 
				DBUS_PATH_DBUS, 
				DBUS_INTERFACE_DBUS, 
				get_pid_method);

	if (message == NULL) {
		result = -ENOMEM; /* can't create the message */
	} else {
		/* fulfill the message with the name */
		b = dbus_message_append_args(
				message, 
				DBUS_TYPE_STRING, 
				&name, 
				DBUS_TYPE_INVALID);
		if (b != TRUE) {
			result = -ENOMEM; /* can't fullfill the message */
		} else {
			dbus_error_init(&error);
			reply = dbus_connection_send_with_reply_and_block(
							connection, 
							message, 
							timeout, 
							&error);
			if (!reply) {
				result = -ENOTSUP; /* got no reply */
			} else {
				if (dbus_message_get_type(reply)
						!= DBUS_MESSAGE_TYPE_METHOD_RETURN) {
					result = -ENOTSUP; /* unexpected answer kind */
				} else {
					dbus_error_init(&error);
					b = dbus_message_get_args(
								reply, 
								&error, 
								DBUS_TYPE_UINT32, 
								&u32, 
								DBUS_TYPE_INVALID);
					if (b != TRUE) {
						result = -ENOTSUP; /* unexpected argument types */
					} else {
						*pid = (pid_t)u32;
						result = 0;
						add_cache(name, (pid_t)u32);
					}
				}
				dbus_message_unref(reply);
			}
		}
		dbus_message_unref(message);
	}
	return result;
}
Ejemplo n.º 2
0
int ccgi_dbus_eag_conf_vlanmaping(DBusConnection *conn, dbus_vlan_conf vlan_conf)
{
	DBusMessage *query, *reply;
    DBusError err;
    int ret_vlan = -1;

    query = dbus_message_new_method_call(
                                    EAG_AURO_SERVER,
                                    EAG_AURO_CONF_OBJECT,
						            INTERFACE_AURO_VLANMAPING, 
						            METHOD_VLANMAPING );
	if (NULL == query) {
      fprintf(stderr, "dbus_eag_conf_vlanmaping:dbus_message_new_method_call==Null\n");
    }

    dbus_error_init(&err);

	//fprintf(stderr,"eag_auto_conf v_wlan_begin_id=%d,v_wlan_end_id=%d,v_wtp_begin_id=%u,v_wtp_end_id=%u",\
	//			vlan_conf.v_wlan_begin_id,vlan_conf.v_wlan_end_id,vlan_conf.v_wtp_begin_id,vlan_conf.v_wtp_end_id);
	
	const char * tmp_wlan_begin_id = vlan_conf.v_wlan_begin_id;
	const char * tmp_wlan_end_id = vlan_conf.v_wlan_end_id;
	const char * tmp_wtp_begin_id = vlan_conf.v_wtp_begin_id;
	const char * tmp_wtp_end_id = vlan_conf.v_wtp_end_id;
	const char * nasportid = vlan_conf.nasportid;
	const char * tmp_attz = vlan_conf.v_attz;
	
	dbus_message_append_args(   query,
								DBUS_TYPE_INT32,  &vlan_conf.v_flag,
								DBUS_TYPE_INT32,  &vlan_conf.v_strategy_id,
								DBUS_TYPE_STRING, &tmp_wlan_begin_id,
								DBUS_TYPE_STRING, &tmp_wlan_end_id,
								DBUS_TYPE_STRING, &tmp_wtp_begin_id,
								DBUS_TYPE_STRING, &tmp_wtp_end_id,
								DBUS_TYPE_STRING, &nasportid,
								DBUS_TYPE_STRING, &tmp_attz,
					            DBUS_TYPE_INVALID );
	
    reply = dbus_connection_send_with_reply_and_block ( conn, query, -1, &err );
    dbus_message_unref(query);
    
    if ( NULL == reply )
    {
        if (dbus_error_is_set(&err))
        {
        	//fprintf(stderr, "dbus_message_new_method_call Error:%s\n", err.message);
            dbus_error_free(&err);
        }
        ret_vlan = ERR_DBUS_REPLY_NULL;
    }
    else
    {
        dbus_message_get_args( reply,
                                &err,
                                DBUS_TYPE_INT32, &ret_vlan,
                                DBUS_TYPE_INVALID );
		dbus_message_unref(reply);
    }       
    
	return ret_vlan;
}
Ejemplo n.º 3
0
/*ifname的长度要小于16 */
int create_ac_ip_list_cmd(int instance_id,char *ID,char *ifname)/*返回0表示失败,返回1表示成功,返回-1表示unknown id format*/
																   /*返回-2表示id should be 1 to ACIPLIST_NUM-1,返回-3表示ifname is too long,out of the limit of 16*/
																   /*返回-4表示id exist,返回-5表示error,返回-6表示interface has be binded in other hansi*/
{
	if((NULL == ID)||(NULL == ifname))
		return 0;
	
	int ret,len;
	unsigned char isAdd;	
	unsigned char id;
	char *name;
	DBusMessage *query, *reply;	
	DBusMessageIter	 iter;
	DBusError err;
	isAdd = 1;
	int retu;
	
	ret = parse_char_ID((char*)ID, &id);
	if(ret != WID_DBUS_SUCCESS){
		return -1;
	}	
	if(id >= ACIPLIST_NUM || id == 0){
		return -2;
	}
	len = strlen(ifname);
	if(len > 16){		
		return -3;
	}
	name = (char*)malloc(strlen(ifname)+1);
	if(NULL == name)
		return 0;
	memset(name, 0, strlen(ifname)+1);
	memcpy(name, ifname, strlen(ifname));		
	
	int index;
	char BUSNAME[PATH_LEN];
	char OBJPATH[PATH_LEN];
	char INTERFACE[PATH_LEN];
	/*if(vty->node == CONFIG_NODE){
		index = 0;
	}else if(vty->node == HANSI_NODE){
		index = vty->index;
	}*/
	index = instance_id;
	
	ReInitDbusPath(index,WID_DBUS_BUSNAME,BUSNAME);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_OBJPATH,OBJPATH);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_INTERFACE,INTERFACE);
	query = dbus_message_new_method_call(BUSNAME,OBJPATH,INTERFACE,WID_DBUS_ACIPLIST_METHOD_ADD_AC_IP_LIST_GROUP);

/*	query = dbus_message_new_method_call(WID_DBUS_BUSNAME,WID_DBUS_ACIPLIST_OBJPATH,\
						WID_DBUS_ACIPLIST_INTERFACE,WID_DBUS_ACIPLIST_METHOD_ADD_AC_IP_LIST_GROUP);*/
	dbus_error_init(&err);

	dbus_message_append_args(query,
						DBUS_TYPE_BYTE,&id,
						DBUS_TYPE_STRING,&name,
						DBUS_TYPE_INVALID);

	reply = dbus_connection_send_with_reply_and_block (ccgi_dbus_connection,query,-1, &err);
	
	dbus_message_unref(query);
	
	if (NULL == reply) {
		if (dbus_error_is_set(&err)) {
			dbus_error_free(&err);
		}
		if(name)
		{
			free(name);
			name = NULL;
		}
		return 0;
	}
	dbus_message_iter_init(reply,&iter);
	dbus_message_iter_get_basic(&iter,&ret);

	if(ret == 0)
		retu = 1;
	else if(ret == WLAN_ID_BE_USED)
		retu = -4;
	else if(ret == IF_BINDING_FLAG)
		retu = -6;
	else
		retu = -5;

	dbus_message_unref(reply);
	FREE_OBJECT(name);
	return retu;	
}
Ejemplo n.º 4
0
static dbus_bool_t dbus_bus_get_unix_process_id(DBusConnection* conn,
                                                const char*     name,
                                                pid_t*          pid)
{
  DBusMessage*  msg;
  DBusMessage*  reply;
  DBusError     err;
  dbus_uint32_t pid_arg;

  msg = dbus_message_new_method_call("org.freedesktop.DBus",
                                     "/org/freedesktop/DBus",
                                     "org.freedesktop.DBus",
                                     "GetConnectionUnixProcessID");
  if (!msg) {
      dsme_log(LOG_DEBUG, "Unable to allocate new message");
      return FALSE;
  }

  if (!dbus_message_append_args(msg,
                                DBUS_TYPE_STRING,
                                &name,
                                DBUS_TYPE_INVALID))
  {
      dsme_log(LOG_DEBUG, "Unable to append arguments to message");
      dbus_message_unref(msg);
      return FALSE;
  }

  // TODO: it is risky that we are blocking
  dbus_error_init(&err);
  reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
  if (dbus_error_is_set(&err)) {
      dsme_log(LOG_DEBUG,
               "Sending GetConnectionUnixProcessID failed: %s",
               err.message);
      dbus_error_free(&err);
      dbus_message_unref(msg);
      return FALSE;
  }

  dbus_error_init(&err);
  dbus_message_get_args(reply,
                        &err,
                        DBUS_TYPE_UINT32,
                        &pid_arg,
                        DBUS_TYPE_INVALID);
  if (dbus_error_is_set(&err)) {
      dsme_log(LOG_DEBUG,
               "Getting GetConnectionUnixProcessID args failed: %s",
               err.message);
      dbus_error_free(&err);
      dbus_message_unref(msg);
      dbus_message_unref(reply);
      return FALSE;
  }

  *pid = pid_arg;

  dbus_message_unref(msg);
  dbus_message_unref(reply);

  return TRUE;
}
static DBusHandlerResult
nds_filter_function(DBusConnection *connection, DBusMessage *message,
		void *user_data)
{
	LibHalContext *ctx = user_data;
	DBusMessage *reply;
	DBusError error;
	const char *member = dbus_message_get_member(message);
	const char *path = dbus_message_get_path(message);
	int rc = -1;

	dbus_error_init(&error);

	HAL_DEBUG(("DBus message: %s, %s ", member, path));

	if (dbus_message_is_method_call(message,
				DBUS_INTERFACE, "EnablePrinterScanningViaSNMP")) {
		int interval = -1;
		char *udi = getenv("UDI");
		char *community = "public";
		char *network = "0.0.0.0";

		dbus_message_get_args(message, &error,
				DBUS_TYPE_INT32, &interval,
				DBUS_TYPE_STRING, &community,
				DBUS_TYPE_STRING, &network,
				DBUS_TYPE_INVALID);

		if (strcmp(network, "0.0.0.0") == 0)
			network = NULL;

		rc = nds_EnablePrinterScanningViaSNMP(ctx, udi, interval,
				community, network);
	} else if (dbus_message_is_method_call(message,
				DBUS_INTERFACE, "ScanForPrintersViaSNMP")) {
		int interval = -1;
		char *udi = getenv("UDI");
		char *community = "public";
		char *network = "0.0.0.0";

		dbus_message_get_args(message, &error,
				DBUS_TYPE_STRING, &community,
				DBUS_TYPE_STRING, &network,
				DBUS_TYPE_INVALID);

		if (strcmp(network, "0.0.0.0") == 0)
			network = NULL;

		rc = nds_ScanForPrintersViaSNMP(ctx, udi, community, network);
	} else if (dbus_message_is_method_call(message,
				DBUS_INTERFACE, "DisablePrinterScanningViaSNMP")) {
		rc = nds_DisablePrinterScanningViaSNMP(ctx);
	} else {
		/* bypass not-handled messages */
		HAL_WARNING(("Unknown DBus message: %s, %s ", member, path));
		return (DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
	}

	if (dbus_error_is_set(&error))
		dbus_error_free(&error);

	if ((reply = dbus_message_new_method_return(message)) == NULL) {
		HAL_WARNING(("Could not allocate memory for the DBus reply"));
		return (FALSE);
	}

	dbus_message_append_args(reply, DBUS_TYPE_INT32, &rc,
			DBUS_TYPE_INVALID);

	if (!dbus_connection_send(connection, reply, NULL)) {
		HAL_WARNING(("Could not sent reply"));
	}
	dbus_connection_flush(connection);
	dbus_message_unref(reply);

	return (DBUS_HANDLER_RESULT_HANDLED);
}
Ejemplo n.º 6
0
static void 
force_unmount (LibHalContext *ctx, const char *udi)
{
	DBusError error;
	DBusMessage *msg = NULL;
	DBusMessage *reply = NULL;
	char **options = NULL;
	unsigned int num_options = 0;
	DBusConnection *dbus_connection;
	char *device_file;

	dbus_connection = libhal_ctx_get_dbus_connection (ctx);

	msg = dbus_message_new_method_call ("org.freedesktop.Hal", udi,
					    "org.freedesktop.Hal.Device.Volume",
					    "Unmount");
	if (msg == NULL) {
		HAL_ERROR (("Could not create dbus message for %s", udi));
		goto out;
	}


	options = calloc (1, sizeof (char *));
	if (options == NULL) {
		HAL_ERROR (("Could not allocate options array"));
		goto out;
	}

	options[0] = "lazy";
	num_options = 1;

	device_file = libhal_device_get_property_string (ctx, udi, "block.device", NULL);
	if (device_file != NULL) {
		HAL_INFO(("forcibly attempting to lazy unmount %s as media was removed", device_file));
		libhal_free_string (device_file);
	}

	if (!dbus_message_append_args (msg, 
				       DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &options, num_options,
				       DBUS_TYPE_INVALID)) {
		HAL_ERROR (("Could not append args to dbus message for %s", udi));
		goto out;
	}
	
	dbus_error_init (&error);
	if (!(reply = dbus_connection_send_with_reply_and_block (dbus_connection, msg, -1, &error))) {
		HAL_ERROR (("Unmount failed for %s: %s : %s\n", udi, error.name, error.message));
		dbus_error_free (&error);
		goto out;
	}

	if (dbus_error_is_set (&error)) {
		HAL_ERROR (("Unmount failed for %s\n%s : %s\n", udi, error.name, error.message));
		dbus_error_free (&error);
		goto out;
	}

	HAL_DEBUG (("Succesfully unmounted udi '%s'", udi));

out:
	if (options != NULL)
		free (options);
	if (msg != NULL)
		dbus_message_unref (msg);
	if (reply != NULL)
		dbus_message_unref (reply);
}
Ejemplo n.º 7
0
static void
check_hello_from_self_reply (DBusPendingCall *pcall, 
                             void *user_data)
{
  DBusMessage *reply;
  DBusMessage *echo_message, *echo_reply = NULL;
  DBusError error;
  DBusConnection *connection;
  
  int type;
  
  dbus_error_init (&error);
 
  connection = dbus_bus_get (DBUS_BUS_STARTER, &error);
  if (connection == NULL)
    {
      fprintf (stderr, "*** Failed to open connection to activating message bus: %s\n",
               error.message);
      dbus_error_free (&error);
      die("no memory");
    }

  
  echo_message = (DBusMessage *)user_data;
    
  reply = dbus_pending_call_steal_reply (pcall);
    
  type = dbus_message_get_type (reply);
    
  if (type == DBUS_MESSAGE_TYPE_METHOD_RETURN)
    {
      const char *s;
      printf ("Reply from HelloFromSelf received\n");
     
      if (!dbus_message_get_args (echo_message,
                              &error,
                              DBUS_TYPE_STRING, &s,
                              DBUS_TYPE_INVALID))
        {
            echo_reply = dbus_message_new_error (echo_message,
                                      error.name,
                                      error.message);

            if (echo_reply == NULL)
              die ("No memory\n");

        } 
      else
        {  
          echo_reply = dbus_message_new_method_return (echo_message);
          if (echo_reply == NULL)
            die ("No memory\n");
  
          if (!dbus_message_append_args (echo_reply,
                                 DBUS_TYPE_STRING, &s,
                                 DBUS_TYPE_INVALID))
            die ("No memory");
        }
        
      if (!dbus_connection_send (connection, echo_reply, NULL))
        die ("No memory\n");
      
      dbus_message_unref (echo_reply);
    }
  else if (type == DBUS_MESSAGE_TYPE_ERROR)
    {
      dbus_set_error_from_message (&error, reply);
      printf ("Error type in reply: %s\n", error.message);

      if (strcmp (error.name, DBUS_ERROR_NO_MEMORY) != 0)
        {
            echo_reply = dbus_message_new_error (echo_reply,
                                      error.name,
                                      error.message);

            if (echo_reply == NULL)
              die ("No memory\n");

            if (!dbus_connection_send (connection, echo_reply, NULL))
              die ("No memory\n");

            dbus_message_unref (echo_reply);
        }
      dbus_error_free (&error);
    }
  else
     _dbus_assert_not_reached ("Unexpected message received\n");

  hello_from_self_reply_received = TRUE;
  
  dbus_message_unref (reply);
  dbus_message_unref (echo_message);
  dbus_pending_call_unref (pcall);
  dbus_connection_unref (connection);
}
Ejemplo n.º 8
0
int tool_cmd_joiner(int argc, char* argv[])
{
	int ret = 0;
	int c;
	int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000;
	DBusConnection* connection = NULL;
	DBusMessage *message = NULL;
	DBusMessage *reply = NULL;
	DBusMessageIter iter;
	DBusMessageIter dict_iter;
	DBusError error;
	const char *empty_string = "";
	const char *psk = NULL;
	const char *provisioning_url = NULL;
	const char *vendor_name = NULL;
	const char *vendor_model = NULL;
	const char *vendor_sw_version = NULL;
	const char *vendor_data = NULL;
	const char *property_joiner_state = kWPANTUNDProperty_ThreadJoinerState;
	dbus_bool_t action = false;

	dbus_error_init(&error);

	if (argc == 1) {
		fprintf(stderr, "%s: error: Missing command.\n", argv[0]);
		print_arg_list_help(joiner_option_list,
				argv[0], joiner_cmd_syntax);
		goto bail;
	}

	while (1) {
		static struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"timeout", required_argument, 0, 't'},
			{"start", no_argument, 0, 'e'},
			{"stop", no_argument, 0, 'd'},
			{"attach", no_argument, 0, 'a'},
			{"state", no_argument, 0, 's'},
			{0, 0, 0, 0}
		};

		int option_index = 0;
		c = getopt_long(argc, argv, "hst:eda", long_options,
						&option_index);
		if (c == -1) {
			break;
		}

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

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

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

			connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);

			ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_PROP_GET);
			require_action(ret == 0, bail, print_error_diagnosis(ret));

			dbus_message_append_args(
				message,
				DBUS_TYPE_STRING, &property_joiner_state,
				DBUS_TYPE_INVALID
			);

			reply = dbus_connection_send_with_reply_and_block(
				connection,
				message,
				timeout,
				&error
			);

			if (!reply) {
				fprintf(stderr, "%s: error: %s\n", argv[0], error.message);
				ret = ERRORCODE_TIMEOUT;
				goto bail;
			}

			dbus_message_iter_init(reply, &iter);

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

			if (ret) {
				const char* error_cstr = NULL;

				// Try to see if there is an error explanation we can extract
				dbus_message_iter_next(&iter);
				if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRING) {
					dbus_message_iter_get_basic(&iter, &error_cstr);
				}

				if(!error_cstr || error_cstr[0] == 0) {
					error_cstr = (ret<0)?strerror(-ret):"Get failed";
				}

				fprintf(stderr, "%s: %s (%d)\n", property_joiner_state, error_cstr, ret);
				goto bail;
			}

			// Move to the property
			dbus_message_iter_next(&iter);

			uint8_t state;
			dbus_message_iter_get_basic(&iter, &state);
			fprintf(stdout, "%d (%s)\n", state, joiner_state_int2str(state));
			goto bail;

		case 'a':
			// joiner attaches to commissioned thread network
			connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);

			ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_ATTACH);
			require_action(ret == 0, bail, print_error_diagnosis(ret));

			reply = dbus_connection_send_with_reply_and_block(
				connection,
				message,
				timeout,
				&error
			);

			if (!reply) {
				fprintf(stderr, "%s: error: %s\n", argv[0], error.message);
				ret = ERRORCODE_TIMEOUT;
				goto bail;
			}

			dbus_message_get_args(reply, &error,
					DBUS_TYPE_INT32, &ret,
					DBUS_TYPE_INVALID
					);

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

		case 'e':
			// start commissioning

			if (optind < argc) {
				psk = argv[optind];
				optind++;
			}

			if (!psk) {
				fprintf(stderr, "%s: error: Missing PSK value.\n", argv[0]);
				ret = ERRORCODE_BADARG;
				goto bail;
			}

			ret = check_psk_format(psk);
			if (ret != 0) {
				fprintf(stderr, "%s: error: Invalid PSKd %d\n", argv[0], ret);
				goto bail;
			}

			if (optind < argc) {
				size_t len;

				provisioning_url = argv[optind++];
				len = strnlen(provisioning_url, (COMMR_PROVIISIONING_URL_MAX_LENGTH + 1));

				if (len > COMMR_PROVIISIONING_URL_MAX_LENGTH) {
					fprintf(stderr, "%s: error: Provisioning URL is too long, must be maximum %d characters\n",
						argv[0], COMMR_PROVIISIONING_URL_MAX_LENGTH);
					ret = ERRORCODE_BADARG;
					goto bail;
				}
			}

			if (optind < argc) {
				vendor_name = argv[optind++];
			}

			if (optind < argc) {
				vendor_model = argv[optind++];
			}

			if (optind < argc) {
				vendor_sw_version = argv[optind++];
			}

			if (optind < argc) {
				vendor_data = argv[optind++];
			}

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

			connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);

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

			ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_START);
			require_action(ret == 0, bail, print_error_diagnosis(ret));

			dbus_message_iter_init_append(message, &iter);

			// Open a container as "Array of Dictionary entries from String to Variants" (dbus type "a{sv}")
			dbus_message_iter_open_container(
				&iter,
				DBUS_TYPE_ARRAY,
				DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
					DBUS_TYPE_STRING_AS_STRING
					DBUS_TYPE_VARIANT_AS_STRING
				DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
				&dict_iter
			);

			// Append dictionary entries

			append_dbus_dict_entry_basic(
				&dict_iter,
				kWPANTUNDValueMapKey_Joiner_PSKd,
				DBUS_TYPE_STRING, &psk
			);

			if (provisioning_url) {
				append_dbus_dict_entry_basic(
					&dict_iter,
					kWPANTUNDValueMapKey_Joiner_ProvisioningUrl,
					DBUS_TYPE_STRING, &provisioning_url
				);
			}

			if (vendor_name) {
				append_dbus_dict_entry_basic(
					&dict_iter,
					kWPANTUNDValueMapKey_Joiner_VendorName,
					DBUS_TYPE_STRING, &vendor_name
				);
			}

			if (vendor_model) {
				append_dbus_dict_entry_basic(
					&dict_iter,
					kWPANTUNDValueMapKey_Joiner_VendorModel,
					DBUS_TYPE_STRING, &vendor_model
				);
			}

			if (vendor_sw_version) {
				append_dbus_dict_entry_basic(
					&dict_iter,
					kWPANTUNDValueMapKey_Joiner_VendorSwVersion,
					DBUS_TYPE_STRING, &vendor_sw_version
				);
			}

			if (vendor_data) {
				append_dbus_dict_entry_basic(
					&dict_iter,
					kWPANTUNDValueMapKey_Joiner_VendorData,
					DBUS_TYPE_STRING, &vendor_data
				);
			}

			dbus_message_iter_close_container(&iter, &dict_iter);

			// Send DBus message and parse the DBus reply

			reply = dbus_connection_send_with_reply_and_block(connection, message, timeout, &error);

			if (!reply) {
				fprintf(stderr, "%s: error: %s\n", argv[0], error.message);
				ret = ERRORCODE_TIMEOUT;
				goto bail;
			}

			dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID);

			if (ret) {
				fprintf(stderr, "Failed to start Joiner Commissioning - error %d. %s\n", ret, wpantund_status_to_cstr(ret));
				print_error_diagnosis(ret);
				goto bail;
			}

			fprintf(stdout, "Started joiner commissioning, PSKd:\"%s\"", psk);

			if (provisioning_url) {
				fprintf(stdout, ", ProvisioningURL:\"%s\"", provisioning_url);
			}

			if (vendor_name) {
				fprintf(stdout, ", VendorName:\"%s\"", vendor_name);
			}

			if (vendor_model) {
				fprintf(stdout, ", VendorModel:\"%s\"", vendor_model);
			}

			if (vendor_sw_version) {
				fprintf(stdout, ", VendorSwVersion:\"%s\"", vendor_sw_version);
			}

			if (vendor_data) {
				fprintf(stdout, ", VendorData:\"%s\"", vendor_data);
			}

			fprintf(stdout, "\n", psk);

			goto bail;

		case 'd':
			// stop commissioning

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

			connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);

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

			ret = create_new_wpan_dbus_message(&message, WPANTUND_IF_CMD_JOINER_STOP);
			require_action(ret == 0, bail, print_error_diagnosis(ret));

			reply = dbus_connection_send_with_reply_and_block(connection, message, timeout, &error);

			if (!reply) {
				fprintf(stderr, "%s: error: %s\n", argv[0], error.message);
				ret = ERRORCODE_TIMEOUT;
				goto bail;
			}

			dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID);

			if (ret) {
				fprintf(stderr, "Failed to stop joiner commissioning - error %d. %s\n", ret, wpantund_status_to_cstr(ret));
				print_error_diagnosis(ret);
				goto bail;
			}

			fprintf(stdout, "Stopped joiner commissioning\n");
			goto bail;
		}
	}

bail:
	if (connection) {
		dbus_connection_unref(connection);
	}

	if (message) {
		dbus_message_unref(message);
	}

	if (reply) {
		dbus_message_unref(reply);
	}

	dbus_error_free(&error);

	return ret;
}
Ejemplo n.º 9
0
DBusHandlerResult message_handler(DBusConnection *connection, 
				  DBusMessage *message, 
				  void *user_data)
{
  char *method = (char *)dbus_message_get_member(message);
  DBusMessage *reply = NULL;
  int clear_cache = 0, new_servers = 0;
    
  if (dbus_message_is_method_call(message, DBUS_INTERFACE_INTROSPECTABLE, "Introspect"))
    {
      /* string length: "%s" provides space for termination zero */
      if (!introspection_xml && 
	  (introspection_xml = whine_malloc(strlen(introspection_xml_template) + strlen(daemon->dbus_name))))
	sprintf(introspection_xml, introspection_xml_template, daemon->dbus_name);
    
      if (introspection_xml)
	{
	  reply = dbus_message_new_method_return(message);
	  dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection_xml, DBUS_TYPE_INVALID);
	}
    }
  else if (strcmp(method, "GetVersion") == 0)
    {
      char *v = VERSION;
      reply = dbus_message_new_method_return(message);
      
      dbus_message_append_args(reply, DBUS_TYPE_STRING, &v, DBUS_TYPE_INVALID);
    }
#ifdef HAVE_LOOP
  else if (strcmp(method, "GetLoopServers") == 0)
    {
      reply = dbus_reply_server_loop(message);
    }
#endif
  else if (strcmp(method, "SetServers") == 0)
    {
      dbus_read_servers(message);
      new_servers = 1;
    }
  else if (strcmp(method, "SetServersEx") == 0)
    {
      reply = dbus_read_servers_ex(message, 0);
      new_servers = 1;
    }
  else if (strcmp(method, "SetDomainServers") == 0)
    {
      reply = dbus_read_servers_ex(message, 1);
      new_servers = 1;
    }
  else if (strcmp(method, "SetFilterWin2KOption") == 0)
    {
      reply = dbus_set_bool(message, OPT_FILTER, "filterwin2k");
    }
  else if (strcmp(method, "SetBogusPrivOption") == 0)
    {
      reply = dbus_set_bool(message, OPT_BOGUSPRIV, "bogus-priv");
    }
  else if (strcmp(method, "ClearCache") == 0)
    clear_cache = 1;
  else
    return (DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
   
  if (new_servers)
    {
      my_syslog(LOG_INFO, _("setting upstream servers from DBus"));
      check_servers();
      if (option_bool(OPT_RELOAD))
	clear_cache = 1;
    }

  if (clear_cache)
    clear_cache_and_reload(dnsmasq_time());
  
  method = user_data; /* no warning */

  /* If no reply or no error, return nothing */
  if (!reply)
    reply = dbus_message_new_method_return(message);

  if (reply)
    {
      dbus_connection_send (connection, reply, NULL);
      dbus_message_unref (reply);
    }

  return (DBUS_HANDLER_RESULT_HANDLED);
}
Ejemplo n.º 10
0
Device* DeviceHandler::takeDeviceDBus(const std::string& path, int flags)
{
	int fd = 0;
	struct stat st;
    if(stat(path.c_str(), &st) < 0 || !S_ISCHR(st.st_mode))
    {
		ny::sendWarning("DeviceHandler::takeDeviceDBus: failed to get stat struct for path");
        return nullptr;
    }

    unsigned int majr = major(st.st_rdev);
    unsigned int minr = minor(st.st_rdev);

    DBusMessage* msg;
	DBusError error;
	dbus_error_init(&error);
	std::string errStr = "no dbus error available";

    if(!(msg = dbus_message_new_method_call("org.freedesktop.login1", sessionPath().c_str(), 
		"org.freedesktop.login1.Session", "TakeDevice")))
    {
		ny::sendWarning("DeviceHandler::takeDeviceDBus: dbus_message_new_method_call failed");
        dbus_message_unref(msg);
        return nullptr;
    }

    if(!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &majr, DBUS_TYPE_UINT32, &minr, 
		DBUS_TYPE_INVALID))
    {
		ny::sendWarning("DH::takeDeviceDBus: dbus_message_append_args failed");
        dbus_message_unref(msg);
        return nullptr;
    }

    DBusMessage *reply;
    if(!(reply = dbus_connection_send_with_reply_and_block(&dbusHandler()->dbusConnection(), msg, 
		-1, &error)))
    {
		DBusHandler::checkError(error, errStr);
		ny::sendWarning("DH::takeDevDBus: dbus_connection_send_with_reply_and_block: ", errStr);
        dbus_message_unref(msg);
        return nullptr;
    }

    dbus_bool_t paused;
    if(!dbus_message_get_args(reply, nullptr, DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_BOOLEAN, 
		&paused, DBUS_TYPE_INVALID))
    {
		ny::sendWarning("DH::takeDeviceDBus: dbus_message_get_args failed");
        dbus_message_unref(reply);
        dbus_message_unref(msg);
        return nullptr;
    }

    int fl;
    if((fl = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFD, fl | FD_CLOEXEC) < 0)
    {
		ny::sendWarning("DH::takeDeviceDBus: invalid fd");
        close(fd);
        dbus_message_unref(reply);
        dbus_message_unref(msg);
        return nullptr;
    }

    dbus_message_unref(reply);
    dbus_message_unref(msg);

	auto dev = std::make_unique<Device>();
	dev->fd_ = fd;
	dev->active_ = !paused;
	dev->handler_ = this;
	dev->path_ = path;

	auto* ret = dev.get();
	devices_.push_back(std::move(dev));

	return ret;
}
Ejemplo n.º 11
0
/* DBus filter function */
static DBusHandlerResult
filter_function (DBusConnection *connection, DBusMessage *message, void *userdata)
{
	DBusError err;
	DBusMessage *reply;

	if (!check_priv (halctx, connection, message, dbus_message_get_path (message),
	                 "org.freedesktop.hal.power-management.lcd-panel")) {
		return DBUS_HANDLER_RESULT_HANDLED;
	}

#ifdef DEBUG_OMAP_BL
	dbg ("filter_function: sender=%s destination=%s obj_path=%s interface=%s method=%s",
	     dbus_message_get_sender (message),
	     dbus_message_get_destination (message),
	     dbus_message_get_path (message),
	     dbus_message_get_interface (message),
	     dbus_message_get_member (message));
#endif
	reply = NULL;
	dbus_error_init (&err);

	if (dbus_message_is_method_call (message,
					 "org.freedesktop.Hal.Device.LaptopPanel",
					 "SetBrightness")) {
		int brightness;

		if (dbus_message_get_args (message,
					   &err,
					   DBUS_TYPE_INT32, &brightness,
					   DBUS_TYPE_INVALID)) {
			if (brightness < 0 || brightness > 228) {
				reply = dbus_message_new_error (message,
								"org.freedesktop.Hal.Device.LaptopPanel.Invalid",
								"Brightness has to be between 0 and 228!");
			} else {
				int return_code;

				bl_data.set_backlight_level (&bl_data, brightness);

				reply = dbus_message_new_method_return (message);
				if (reply == NULL)
					goto error;

				return_code = 0;
				dbus_message_append_args (reply,
							  DBUS_TYPE_INT32, &return_code,
							  DBUS_TYPE_INVALID);
			}

			dbus_connection_send (connection, reply, NULL);
		}
	} else if (dbus_message_is_method_call (message,
						"org.freedesktop.Hal.Device.LaptopPanel",
						"GetBrightness")) {
		int brightness;

		if (dbus_message_get_args (message,
					   &err,
					   DBUS_TYPE_INVALID)) {

			brightness = bl_data.get_backlight_level (&bl_data);
			if (brightness < bl_data.bl_min)
				brightness = bl_data.bl_min;
			if (brightness > bl_data.bl_max)
				brightness = bl_data.bl_max;

			/* dbg ("getting brightness, it's %d", brightness); */

			reply = dbus_message_new_method_return (message);
			if (reply == NULL)
				goto error;

			dbus_message_append_args (reply,
						  DBUS_TYPE_INT32, &brightness,
						  DBUS_TYPE_INVALID);
			dbus_connection_send (connection, reply, NULL);
		}
	}

error:
	if (reply != NULL)
		dbus_message_unref (reply);

	LIBHAL_FREE_DBUS_ERROR (&err);

	return DBUS_HANDLER_RESULT_HANDLED;
}
static dbus_bool_t
generate_special (DBusMessageDataIter   *iter,
                  DBusString            *data,
                  DBusValidity          *expected_validity)
{
  int item_seq;
  DBusMessage *message;
  int pos;
  dbus_int32_t v_INT32;

  _dbus_assert (_dbus_string_get_length (data) == 0);
  
  message = NULL;
  pos = -1;
  v_INT32 = 42;
  item_seq = iter_get_sequence (iter);

  if (item_seq == 0)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      /* set an invalid typecode */
      _dbus_string_set_byte (data, pos + 1, '$');

      *expected_validity = DBUS_INVALID_UNKNOWN_TYPECODE;
    }
  else if (item_seq == 1)
    {
      char long_sig[DBUS_MAXIMUM_TYPE_RECURSION_DEPTH+2];
      const char *v_STRING;
      int i;
      
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");

      i = 0;
      while (i < (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH + 1))
        {
          long_sig[i] = DBUS_TYPE_ARRAY;
          ++i;
        }
      long_sig[i] = DBUS_TYPE_INVALID;

      v_STRING = long_sig;
      if (!_dbus_header_set_field_basic (&message->header,
                                         DBUS_HEADER_FIELD_SIGNATURE,
                                         DBUS_TYPE_SIGNATURE,
                                         &v_STRING))
        _dbus_assert_not_reached ("oom");
      
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_EXCEEDED_MAXIMUM_ARRAY_RECURSION;
    }
  else if (item_seq == 2)
    {
      char long_sig[DBUS_MAXIMUM_TYPE_RECURSION_DEPTH*2+4];
      const char *v_STRING;
      int i;
      
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");

      i = 0;
      while (i <= (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH + 1))
        {
          long_sig[i] = DBUS_STRUCT_BEGIN_CHAR;
          ++i;
        }

      long_sig[i] = DBUS_TYPE_INT32;
      ++i;

      while (i < (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH*2 + 3))
        {
          long_sig[i] = DBUS_STRUCT_END_CHAR;
          ++i;
        }
      long_sig[i] = DBUS_TYPE_INVALID;
      
      v_STRING = long_sig;
      if (!_dbus_header_set_field_basic (&message->header,
                                         DBUS_HEADER_FIELD_SIGNATURE,
                                         DBUS_TYPE_SIGNATURE,
                                         &v_STRING))
        _dbus_assert_not_reached ("oom");
      
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_EXCEEDED_MAXIMUM_STRUCT_RECURSION;
    }
  else if (item_seq == 3)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, pos + 1, DBUS_STRUCT_BEGIN_CHAR);
      
      *expected_validity = DBUS_INVALID_STRUCT_STARTED_BUT_NOT_ENDED;
    }
  else if (item_seq == 4)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, pos + 1, DBUS_STRUCT_END_CHAR);
      
      *expected_validity = DBUS_INVALID_STRUCT_ENDED_BUT_NOT_STARTED;
    }
  else if (item_seq == 5)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, pos + 1, DBUS_STRUCT_BEGIN_CHAR);
      _dbus_string_set_byte (data, pos + 2, DBUS_STRUCT_END_CHAR);
      
      *expected_validity = DBUS_INVALID_STRUCT_HAS_NO_FIELDS;
    }
  else if (item_seq == 6)
    {
      message = simple_method_call ();
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, TYPE_OFFSET, DBUS_MESSAGE_TYPE_INVALID);
      
      *expected_validity = DBUS_INVALID_BAD_MESSAGE_TYPE;
    }
  else if (item_seq == 7)
    {
      /* Messages of unknown type are considered valid */
      message = simple_method_call ();
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, TYPE_OFFSET, 100);
      
      *expected_validity = DBUS_VALID;
    }
  else if (item_seq == 8)
    {
      message = simple_method_call ();
      generate_from_message (data, expected_validity, message);
      
      _dbus_marshal_set_uint32 (data, BODY_LENGTH_OFFSET,
                                DBUS_MAXIMUM_MESSAGE_LENGTH / 2 + 4,
                                message->byte_order);
      _dbus_marshal_set_uint32 (data, FIELDS_ARRAY_LENGTH_OFFSET,
                                DBUS_MAXIMUM_MESSAGE_LENGTH / 2 + 4,
                                message->byte_order);
      *expected_validity = DBUS_INVALID_MESSAGE_TOO_LONG;
    }
  else if (item_seq == 9)
    {
      const char *v_STRING = "not a valid bus name";
      message = simple_method_call ();

      if (!_dbus_header_set_field_basic (&message->header,
                                         DBUS_HEADER_FIELD_SENDER,
                                         DBUS_TYPE_STRING, &v_STRING))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);

      *expected_validity = DBUS_INVALID_BAD_SENDER;
    }
  else if (item_seq == 10)
    {
      message = simple_method_call ();

      if (!dbus_message_set_interface (message, DBUS_INTERFACE_LOCAL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);

      *expected_validity = DBUS_INVALID_USES_LOCAL_INTERFACE;
    }
  else if (item_seq == 11)
    {
      message = simple_method_call ();

      if (!dbus_message_set_path (message, DBUS_PATH_LOCAL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);

      *expected_validity = DBUS_INVALID_USES_LOCAL_PATH;
    }
  else if (item_seq == 12)
    {
      /* Method calls don't have to have interface */
      message = simple_method_call ();

      if (!dbus_message_set_interface (message, NULL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_VALID;
    }
  else if (item_seq == 13)
    {
      /* Signals require an interface */
      message = simple_signal ();

      if (!dbus_message_set_interface (message, NULL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_MISSING_INTERFACE;
    }
  else if (item_seq == 14)
    {
      message = simple_method_return ();

      if (!_dbus_header_delete_field (&message->header, DBUS_HEADER_FIELD_REPLY_SERIAL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_MISSING_REPLY_SERIAL;
    }
  else if (item_seq == 15)
    {
      message = simple_error ();

      if (!dbus_message_set_error_name (message, NULL))
        _dbus_assert_not_reached ("oom");
      
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_MISSING_ERROR_NAME;
    }
  else if (item_seq == 16)
    {
      char long_sig[DBUS_MAXIMUM_TYPE_RECURSION_DEPTH*4+10];
      const char *v_STRING;
      int i;
      int n_begins;
      
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");

      i = 0;
      while (i <= (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH*3 + 3))
        {
          long_sig[i] = DBUS_TYPE_ARRAY;
          ++i;
          long_sig[i] = DBUS_DICT_ENTRY_BEGIN_CHAR;
          ++i;
          long_sig[i] = DBUS_TYPE_INT32;
          ++i;
        }
      n_begins = i / 3;

      long_sig[i] = DBUS_TYPE_INT32;
      ++i;
      
      while (n_begins > 0)
        {
          long_sig[i] = DBUS_DICT_ENTRY_END_CHAR;
          ++i;
          n_begins -= 1;
        }
      long_sig[i] = DBUS_TYPE_INVALID;
      
      v_STRING = long_sig;
      if (!_dbus_header_set_field_basic (&message->header,
                                         DBUS_HEADER_FIELD_SIGNATURE,
                                         DBUS_TYPE_SIGNATURE,
                                         &v_STRING))
        _dbus_assert_not_reached ("oom");
      
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      *expected_validity = DBUS_INVALID_EXCEEDED_MAXIMUM_DICT_ENTRY_RECURSION;
    }
  else if (item_seq == 17)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);

      _dbus_string_set_byte (data, pos + 1, DBUS_TYPE_ARRAY);
      _dbus_string_set_byte (data, pos + 2, DBUS_DICT_ENTRY_BEGIN_CHAR);
      
      *expected_validity = DBUS_INVALID_DICT_ENTRY_STARTED_BUT_NOT_ENDED;
    }
  else if (item_seq == 18)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);
      
      _dbus_string_set_byte (data, pos + 1, DBUS_DICT_ENTRY_END_CHAR);
      
      *expected_validity = DBUS_INVALID_DICT_ENTRY_ENDED_BUT_NOT_STARTED;
    }
  else if (item_seq == 19)
    {
      message = simple_method_call ();
      if (!dbus_message_append_args (message,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INT32, &v_INT32,
                                     DBUS_TYPE_INVALID))
        _dbus_assert_not_reached ("oom");
                                     
      _dbus_header_get_field_raw (&message->header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  NULL, &pos);
      generate_from_message (data, expected_validity, message);

      _dbus_string_set_byte (data, pos + 1, DBUS_TYPE_ARRAY);
      _dbus_string_set_byte (data, pos + 2, DBUS_DICT_ENTRY_BEGIN_CHAR);
      _dbus_string_set_byte (data, pos + 3, DBUS_DICT_ENTRY_END_CHAR);
      
      *expected_validity = DBUS_INVALID_DICT_ENTRY_HAS_NO_FIELDS;
    }
  else
    {
      return FALSE;
    }

  if (message)
    dbus_message_unref (message);

  iter_next (iter);
  return TRUE;
}
Ejemplo n.º 13
0
Archivo: fsck.c Proyecto: adsr/systemd
static void start_target(const char *target, bool isolate) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        const char *mode, *basic_target = "basic.target";
        DBusConnection *bus = NULL;

        assert(target);

        dbus_error_init(&error);

        if (bus_connect(DBUS_BUS_SYSTEM, &bus, NULL, &error) < 0) {
                log_error("Failed to get D-Bus connection: %s", bus_error_message(&error));
                goto finish;
        }

        if (isolate)
                mode = "isolate";
        else
                mode = "replace";

        log_info("Running request %s/start/%s", target, mode);

        if (!(m = dbus_message_new_method_call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartUnitReplace"))) {
                log_error("Could not allocate message.");
                goto finish;
        }

        /* Start these units only if we can replace base.target with it */

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &basic_target,
                                      DBUS_TYPE_STRING, &target,
                                      DBUS_TYPE_STRING, &mode,
                                      DBUS_TYPE_INVALID)) {
                log_error("Could not attach target and flag information to message.");
                goto finish;
        }

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {

                /* Don't print a warning if we aren't called during
                 * startup */
                if (!dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_JOB))
                        log_error("Failed to start unit: %s", bus_error_message(&error));

                goto finish;
        }

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

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

        dbus_error_free(&error);
}
Ejemplo n.º 14
0
void PulseAudioControl::update()
{
    openConnection();

    if (dbusConnection == NULL) {
        return;
    }

    DBusError error;
    dbus_error_init(&error);

    DBusMessage *reply = NULL;
    DBusMessage *msg = dbus_message_new_method_call(VOLUME_SERVICE, VOLUME_PATH, "org.freedesktop.DBus.Properties", "GetAll");
    if (msg != NULL) {
        dbus_message_append_args(msg, DBUS_TYPE_STRING, &VOLUME_INTERFACE, DBUS_TYPE_INVALID);

        reply = dbus_connection_send_with_reply_and_block(dbusConnection, msg, -1, &error);

        DBUS_ERR_CHECK (error);

        dbus_message_unref(msg);
    }

    int currentStep = -1, stepCount = -1;
    if (reply != NULL) {
        if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN) {
            DBusMessageIter iter;
            dbus_message_iter_init(reply, &iter);
            // Recurse into the array [array of dicts]
            while (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INVALID) {
                DBusMessageIter dict_entry;
                dbus_message_iter_recurse(&iter, &dict_entry);

                // Recurse into the dict [ dict_entry (string, variant(int)) ]
                while (dbus_message_iter_get_arg_type(&dict_entry) != DBUS_TYPE_INVALID) {
                    DBusMessageIter in_dict;
                    // Recurse into the dict_entry [ string, variant(int) ]
                    dbus_message_iter_recurse(&dict_entry, &in_dict);
                    {
                        char *prop_name = NULL;
                        // Get the string value, "property name"
                        dbus_message_iter_get_basic(&in_dict, &prop_name);

                        dbus_message_iter_next(&in_dict);

                        DBusMessageIter variant;
                        // Recurse into the variant [ variant(int) ]
                        dbus_message_iter_recurse(&in_dict, &variant);

                        quint32 value;
                        // Get the variant value which is uint32
                        dbus_message_iter_get_basic(&variant, &value);

                        if (prop_name && strcmp(prop_name, "StepCount") == 0) {
                            stepCount = value;
                        } else if (prop_name && strcmp(prop_name, "CurrentStep") == 0) {
                            currentStep = value;
                        }
                    }

                    dbus_message_iter_next(&dict_entry);
                }
                dbus_message_iter_next(&iter);
            }
        }
        dbus_message_unref(reply);
    }

    if (currentStep != -1 && stepCount != -1) {
        setSteps(currentStep, stepCount);
    }
}
/**
 * wpa_supplicant_dbus_notify_state_change - Send a state change signal
 * @wpa_s: %wpa_supplicant network interface data
 * @new_state: new state wpa_supplicant is entering
 * @old_state: old state wpa_supplicant is leaving
 * Returns: 0 on success, -1 on failure
 *
 * Notify listeners that wpa_supplicant has changed state
 */
void wpa_supplicant_dbus_notify_state_change(struct wpa_supplicant *wpa_s,
					     wpa_states new_state,
					     wpa_states old_state)
{
	struct ctrl_iface_dbus_priv *iface;
	DBusMessage *signal = NULL;
	const char *path;
	const char *new_state_str, *old_state_str;

	/* Do nothing if the control interface is not turned on */
	if (wpa_s->global == NULL)
		return;
	iface = wpa_s->global->dbus_ctrl_iface;
	if (iface == NULL)
		return;

	/* Only send signal if state really changed */
	if (new_state == old_state)
		return;

	path = wpa_supplicant_get_dbus_path(wpa_s);
	if (path == NULL) {
		perror("wpa_supplicant_dbus_notify_state_change[dbus]: "
		       "interface didn't have a dbus path");
		wpa_printf(MSG_ERROR,
		           "wpa_supplicant_dbus_notify_state_change[dbus]: "
		           "interface didn't have a dbus path; can't send "
		           "signal.");
		return;
	}
	signal = dbus_message_new_signal(path, WPAS_DBUS_IFACE_INTERFACE,
					 "StateChange");
	if (signal == NULL) {
		perror("wpa_supplicant_dbus_notify_state_change[dbus]: "
		       "couldn't create dbus signal; likely out of memory");
		wpa_printf(MSG_ERROR,
		           "wpa_supplicant_dbus_notify_state_change[dbus]: "
		           "couldn't create dbus signal; likely out of "
		           "memory.");
		return;
	}

	new_state_str = wpa_supplicant_state_txt(new_state);
	old_state_str = wpa_supplicant_state_txt(old_state);
	if (new_state_str == NULL || old_state_str == NULL) {
		perror("wpa_supplicant_dbus_notify_state_change[dbus]: "
		       "couldn't convert state strings");
		wpa_printf(MSG_ERROR,
		           "wpa_supplicant_dbus_notify_state_change[dbus]: "
		           "couldn't convert state strings.");
		goto out;
	}

	if (!dbus_message_append_args(signal,
	                              DBUS_TYPE_STRING, &new_state_str,
	                              DBUS_TYPE_STRING, &old_state_str,
	                              DBUS_TYPE_INVALID)) {
		perror("wpa_supplicant_dbus_notify_state_change[dbus]: "
		       "not enough memory to construct state change signal.");
		wpa_printf(MSG_ERROR,
		           "wpa_supplicant_dbus_notify_state_change[dbus]: "
		           "not enough memory to construct state change "
		           "signal.");
		goto out;
	}
	dbus_connection_send(iface->con, signal, NULL);

out:
	dbus_message_unref(signal);
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
    DBusError err;
    DBusConnection *c;
    int rc = 0, async = 0;
    struct stat dirstat;
    char *dir;

    if (argc < 2) {

        fprintf(stderr, 
            "Usage: %s <directory name> [%s]\n\n"
            "\tstores screenshots of all VMs in <directory name>,\n"
            "\t%s: do not wait for completion, return as soon as the request has been sent\n",
            argv[0], ASYNCFLAG, ASYNCFLAG);

        return 1;
    }

    // TODO: getopt if any more options!
    if ((argc == 3) && !strncmp (argv[2], ASYNCFLAG, strlen (ASYNCFLAG))) {
        async = 1;
    }

    dir = argv[1];

    if (stat (dir, &dirstat)) {
        fprintf (stderr, "failed to stat %s: %s", dir, strerror (errno));
        return 2;
    }

    if (! S_ISDIR(dirstat.st_mode)) {
        fprintf (stderr, "%s is not a directory\n", dir);
        return 3;
    }

    fprintf(stderr, 
         "Saving screenshots for all screens, all domains in directory %s\n",
         dir);

    dbus_error_init(&err);

    c = dbus_bus_get(DBUS_BUS_SYSTEM, &err);

    if (!c) {
        fprintf(stderr, "Can't get connection to dbus service: %s\n",
                err.message);
        return 1;
    }

    DBusMessage *m = dbus_message_new_method_call("com.citrix.xenclient.surfman",
                                                  "/",
                                                  "com.citrix.xenclient.surfman",
                                                  "dump_all_screens");

    if (!m) {
        fprintf(stderr, "Can't allocate dbus message\n");
        rc = 1;
        goto unref_conn;
    }

    dbus_message_append_args(m, DBUS_TYPE_STRING, &dir, DBUS_TYPE_INVALID);

    dbus_connection_send(c, m, NULL);
    dbus_message_unref(m);

    if (!async) {
        int timeout = 10; // seconds we allow surfman to write the screenshots
        int done = 0;
        const int inactivity = 3; // mtime seconds after which a file is 
                                  // considered not being written to anymore

        /* now wait until time is up or no more changes are being made in dir */
        do {
            sleep (1);
            timeout--;

            if (age_of_latest_modification (dir) > inactivity) {
                done = 1;
            }
        } while (!done && (timeout > 0));
    }

unref_conn:
    dbus_connection_unref(c);
    return rc;
}
/**
 * thunar_dbus_client_bulk_rename:
 * @working_directory : the default working directory for the bulk rename dialog.
 * @filenames         : the list of files that should be displayed by default or
 *                      the empty list to start with an empty bulk rename dialog.
 * @standalone        : whether to run the bulk renamer in standalone mode.
 * @screen            : the #GdkScreen on which to display the dialog or %NULL to
 *                      use the default #GdkScreen.
 * @error             : return location for errors or %NULL.
 *
 * Tries to invoke the BulkRename() method on a running Thunar instance, that is
 * registered with the current D-BUS session bus. Returns %TRUE if the method was
 * successfully invoked, else %FALSE.
 *
 * If %TRUE is returned, the current process may afterwards just terminate, as
 * all @filenames will be handled by the remote instance.
 *
 * Return value: %TRUE on success, else %FALSE.
 **/
gboolean
thunar_dbus_client_bulk_rename (const gchar *working_directory,
                                gchar      **filenames,
                                gboolean     standalone,
                                GdkScreen   *screen,
                                GError     **error)
{
  DBusConnection *connection;
  DBusMessage    *message;
  DBusMessage    *result;
  DBusError       derror;
  gchar          *display_name;

  _thunar_return_val_if_fail (screen == NULL || GDK_IS_SCREEN (screen), FALSE);
  _thunar_return_val_if_fail (g_path_is_absolute (working_directory), FALSE);
  _thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  _thunar_return_val_if_fail (filenames != NULL, FALSE);

  /* initialize the DBusError struct */
  dbus_error_init (&derror);

  /* fallback to default screen if no other is specified */
  if (G_LIKELY (screen == NULL))
    screen = gdk_screen_get_default ();

  /* try to connect to the session bus */
  connection = dbus_bus_get (DBUS_BUS_SESSION, &derror);
  if (G_UNLIKELY (connection == NULL))
    {
      dbus_set_g_error (error, &derror);
      dbus_error_free (&derror);
      return FALSE;
    }

  /* determine the display name for the screen */
  display_name = gdk_screen_make_display_name (screen);

  /* generate the BulkRename() method (disable activation!) */
  message = dbus_message_new_method_call ("org.xfce.Thunar", "/org/xfce/FileManager", "org.xfce.Thunar", "BulkRename");
  dbus_message_set_auto_start (message, FALSE);
  dbus_message_append_args (message,
                            DBUS_TYPE_STRING, &working_directory,
                            DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &filenames, g_strv_length (filenames),
                            DBUS_TYPE_BOOLEAN, &standalone,
                            DBUS_TYPE_STRING, &display_name,
                            DBUS_TYPE_INVALID);

  /* release the display name */
  g_free (display_name);

  /* send the message and release our references on connection and message */
  result = dbus_connection_send_with_reply_and_block (connection, message, -1, &derror);
  dbus_message_unref (message);

  /* check if no reply was received */
  if (G_UNLIKELY (result == NULL))
    {
      dbus_set_g_error (error, &derror);
      dbus_error_free (&derror);
      return FALSE;
    }

  /* but maybe we received an error */
  if (dbus_message_get_type (result) == DBUS_MESSAGE_TYPE_ERROR)
    {
      dbus_set_error_from_message (&derror, result);
      dbus_set_g_error (error, &derror);
      dbus_message_unref (result);
      dbus_error_free (&derror);
      return FALSE;
    }

  /* let's asume that it worked */
  dbus_message_unref (result);
  return TRUE;
}
Ejemplo n.º 18
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();

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

    /*
     * 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.");
        module_EndBank (true);
        vlc_LogDeinit (p_libvlc);
        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" );
            module_EndBank (true);
            vlc_LogDeinit (p_libvlc);
            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

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

#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" );
    }
    else
#endif
        if( var_InheritBool( p_libvlc, "file-logging" ) )
            intf_Create( p_libvlc, "logger,none" );

    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( pl_Get(p_libvlc), psz_val, NULL, PLAYLIST_INSERT, 0,
                         -1, 0, NULL, 0, true, pl_Unlocked );
        free( psz_val );
    }

    return VLC_SUCCESS;
}
nsresult
GetDefaultAdapterPathInternal(nsCString& aAdapterPath)
{
  DBusMessage *msg = NULL, *reply = NULL;
  DBusError err;
  const char *device_path = NULL;
  int attempt = 0;

  for (attempt = 0; attempt < 1000 && reply == NULL; attempt ++) {
    msg = dbus_message_new_method_call("org.bluez", "/",
                                       "org.bluez.Manager", "DefaultAdapter");
    if (!msg) {
      LOG("%s: Can't allocate new method call for get_adapter_path!",
             __FUNCTION__);
      return NS_ERROR_FAILURE;
    }
    dbus_message_append_args(msg, DBUS_TYPE_INVALID);
    dbus_error_init(&err);
    reply = dbus_connection_send_with_reply_and_block(
      sDBusConnection->mConnection, msg, -1, &err);

    if (!reply) {
      if (dbus_error_is_set(&err)) {
        if (dbus_error_has_name(&err,
                                "org.freedesktop.DBus.Error.ServiceUnknown")) {
          // bluetoothd is still down, retry
          LOG("Service unknown\n");
          dbus_error_free(&err);
          //usleep(10000); // 10 ms
          continue;
        } else if (dbus_error_has_name(&err,
                                       "org.bluez.Error.NoSuchAdapter")) {
          LOG("No adapter found\n");
          dbus_error_free(&err);
          goto failed;
        } else {
          // Some other error we weren't expecting
          LOG("other error\n");
          dbus_error_free(&err);
        }
      }
    }
  }
  if (attempt == 1000) {
    LOG("timeout\n");
    //printfE("Time out while trying to get Adapter path, is bluetoothd up ?");
    goto failed;
  }

  if (!dbus_message_get_args(reply, &err, DBUS_TYPE_OBJECT_PATH,
                             &device_path, DBUS_TYPE_INVALID)
      || !device_path) {
    if (dbus_error_is_set(&err)) {
      dbus_error_free(&err);
    }
    goto failed;
  }
  dbus_message_unref(msg);
  aAdapterPath = nsDependentCString(device_path);
  return NS_OK;
failed:
  dbus_message_unref(msg);
  return NS_ERROR_FAILURE;
}
Ejemplo n.º 20
0
static void show_notification (DB_playItem_t *track) {
    char title[1024];
    char content[1024];

    char format[200];
    char format_content[200];
    deadbeef->conf_get_str ("notify.format", NOTIFY_DEFAULT_TITLE, format, sizeof (format));
    deadbeef->conf_get_str ("notify.format_content", NOTIFY_DEFAULT_CONTENT, format_content, sizeof (format_content));
    deadbeef->pl_format_title (track, -1, title, sizeof (title), -1, format);
    deadbeef->pl_format_title (track, -1, content, sizeof (content), -1, format_content);

    // escape &
//    char esc_title[1024];
    char esc_content[1024];
//    esc_xml (title, esc_title, sizeof (esc_title));
    esc_xml (content, esc_content, sizeof (esc_content));
    DBusMessage *msg = dbus_message_new_method_call (E_NOTIFICATION_BUS_NAME, E_NOTIFICATION_PATH, E_NOTIFICATION_INTERFACE, "Notify");

    deadbeef->pl_lock ();
    if (last_track) {
        deadbeef->pl_item_unref (last_track);
        last_track = 0;
    }
    last_track = track;
    deadbeef->pl_item_ref (last_track);
    request_timer = time (NULL);
    deadbeef->pl_unlock ();

    const char *v_appname = "DeaDBeeF";
    dbus_uint32_t v_id = 0;
    char *v_iconname = NULL;
    if (deadbeef->conf_get_int("notify.albumart", 0) && artwork_plugin) {
        deadbeef->pl_lock ();
        const char *album = deadbeef->pl_find_meta (track, "album");
        const char *artist = deadbeef->pl_find_meta (track, "artist");
        const char *fname = deadbeef->pl_find_meta (track, ":URI");
        if (!album || !*album) {
            album = deadbeef->pl_find_meta (track, "title");
        }
        v_iconname = artwork_plugin->get_album_art (fname, artist, album, deadbeef->conf_get_int ("notify.albumart_size", 64), cover_avail_callback, NULL);
        deadbeef->pl_unlock ();
    }
    if (!v_iconname) {
        v_iconname = strdup ("deadbeef");
    }
    const char *v_summary = title;
    const char *v_body = esc_content;
    dbus_int32_t v_timeout = -1;

    dbus_message_append_args (msg
            , DBUS_TYPE_STRING, &v_appname
            , DBUS_TYPE_UINT32, &replaces_id
            , DBUS_TYPE_STRING, &v_iconname
            , DBUS_TYPE_STRING, &v_summary
            , DBUS_TYPE_STRING, &v_body
            , DBUS_TYPE_INVALID
            );

    DBusMessageIter iter, sub;
    // actions
    dbus_message_iter_init_append(msg, &iter);
    dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub);
    dbus_message_iter_close_container(&iter, &sub);
    // hints
    dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub);
    dbus_message_iter_close_container(&iter, &sub);

    dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT32, &v_timeout);

    intptr_t tid = 0;
    if ((tid=deadbeef->thread_start(notify_thread, msg)) != 0) {
        dbus_message_ref (msg);
        deadbeef->thread_detach (tid);  
    }
    dbus_message_unref (msg);
    if (v_iconname) {
        free (v_iconname);
    }
}
Ejemplo n.º 21
0
static DBusHandlerResult
path_message_func (DBusConnection  *connection,
                   DBusMessage     *message,
                   void            *user_data)
{
  if (dbus_message_is_method_call (message,
                                   "org.freedesktop.TestSuite",
                                   "Echo"))
    return handle_echo (connection, message);
  else if (dbus_message_is_method_call (message,
                                        "org.freedesktop.TestSuite",
                                        "DelayEcho"))
    return handle_delay_echo (connection, message);
  else if (dbus_message_is_method_call (message,
                                        "org.freedesktop.TestSuite",
                                        "Exit"))
    {
      quit ();
      return DBUS_HANDLER_RESULT_HANDLED;
    }
  else if (dbus_message_is_method_call (message,
                                        "org.freedesktop.TestSuite",
                                        "EmitFoo"))
    {
      /* Emit the Foo signal */
      DBusMessage *signal;
      double v_DOUBLE;

      _dbus_verbose ("emitting signal Foo\n");
      
      signal = dbus_message_new_signal ("/org/freedesktop/TestSuite",
                                        "org.freedesktop.TestSuite",
                                        "Foo");
      if (signal == NULL)
        die ("No memory\n");

      v_DOUBLE = 42.6;
      if (!dbus_message_append_args (signal,
                                     DBUS_TYPE_DOUBLE, &v_DOUBLE,
                                     DBUS_TYPE_INVALID))
        die ("No memory");
  
      if (!dbus_connection_send (connection, signal, NULL))
        die ("No memory\n");
      
      return DBUS_HANDLER_RESULT_HANDLED;
    }
    
  else if (dbus_message_is_method_call (message,
                                   "org.freedesktop.TestSuite",
                                   "RunHelloFromSelf"))
    {
      return handle_run_hello_from_self (connection, message);
    }
  else if (dbus_message_is_method_call (message,
                                        "org.freedesktop.TestSuite",
                                        "HelloFromSelf"))
    {
        DBusMessage *reply;
        printf ("Received the HelloFromSelf message\n");
        
        reply = dbus_message_new_method_return (message);
        if (reply == NULL)
          die ("No memory");
        
        if (!dbus_connection_send (connection, reply, NULL))
          die ("No memory");

        return DBUS_HANDLER_RESULT_HANDLED;
    }
  else
    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
Ejemplo n.º 22
0
char *
pcmk_dbus_get_property(
    DBusConnection *connection, const char *target, const char *obj, const gchar * iface, const char *name,
    void (*callback)(const char *name, const char *value, void *userdata), void *userdata, DBusPendingCall **pending,
    int timeout)
{
    DBusMessage *msg;
    const char *method = "GetAll";
    char *output = NULL;

    struct db_getall_data *query_data = NULL;

    /* char *state = pcmk_dbus_get_property(systemd_proxy, BUS_NAME, unit, BUS_NAME ".Unit", "ActiveState"); */

    crm_debug("Calling: %s on %s", method, target);
    msg = dbus_message_new_method_call(target, // target for the method call
                                       obj, // object to call on
                                       BUS_PROPERTY_IFACE, // interface to call on
                                       method); // method name

    if (NULL == msg) {
        crm_err("Call to %s failed: No message", method);
        return NULL;
    }

    CRM_LOG_ASSERT(dbus_message_append_args(msg, DBUS_TYPE_STRING, &iface, DBUS_TYPE_INVALID));

    query_data = malloc(sizeof(struct db_getall_data));
    if(query_data == NULL) {
        crm_err("Call to %s failed: malloc failed", method);
        return NULL;
    }

    query_data->target = strdup(target);
    query_data->object = strdup(obj);
    query_data->callback = callback;
    query_data->userdata = userdata;
    query_data->name = NULL;

    if(name) {
        query_data->name = strdup(name);
    }

    if(query_data->callback) {
        DBusPendingCall* _pending;
        _pending = pcmk_dbus_send(msg, connection, pcmk_dbus_lookup_cb, query_data, timeout);
        if (pending != NULL) {
            *pending = _pending;
        }

    } else {
        DBusMessage *reply = pcmk_dbus_send_recv(msg, connection, NULL, timeout);

        output = pcmk_dbus_lookup_result(reply, query_data);

        if(reply) {
            dbus_message_unref(reply);
        }
    }

    dbus_message_unref(msg);

    return output;
}
Ejemplo n.º 23
0
static int request_lookup(struct connman_service *service, const char *url)
{
	DBusMessage *msg;
	DBusPendingCall *call;
	dbus_bool_t result;
	char *host;
	struct proxy_data *data;

	DBG("");

	if (daemon_running == FALSE)
		return -EINVAL;

	msg = dbus_message_new_method_call(PACRUNNER_SERVICE,
						PACRUNNER_CLIENT_PATH,
						PACRUNNER_CLIENT_INTERFACE,
						"FindProxyForURL");
	if (msg == NULL)
		return -1;

	host = parse_url(url);
	if (host == NULL) {
		dbus_message_unref(msg);
		return -EINVAL;
	}

	data = g_try_new0(struct proxy_data, 1);
	if (data == NULL) {
		dbus_message_unref(msg);
		g_free(host);
		return -ENOMEM;
	}

	data->url = g_strdup(url);
	data->service = connman_service_ref(service);

	dbus_message_set_auto_start(msg, FALSE);

	dbus_message_append_args(msg, DBUS_TYPE_STRING, &url,
					DBUS_TYPE_STRING, &host,
					DBUS_TYPE_INVALID);

	result = dbus_connection_send_with_reply(connection, msg,
							&call, DBUS_TIMEOUT);

	dbus_message_unref(msg);

	if (result == FALSE || call == NULL) {
		g_free(host);
		g_free(data->url);
		g_free(data);
		return -EINVAL;
	}

	dbus_pending_call_set_notify(call, request_lookup_reply,
							data, NULL);

	dbus_pending_call_unref(call);
	g_free(host);

	return 0;
}
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{
	DBusConnection *conn;
	DBusError error;
	DBusMessage *msg;
	DBusMessageIter iter, dict;
	char **envp, *busname, *interface, *path, *reason;
	int ret = 0;

	openlog(basename(argv[0]), LOG_NDELAY | LOG_PID, LOG_DAEMON);

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

	reason = getenv("script_type");

	if (!busname || !interface || !path || !reason) {
		print("Required environment variables not set");
		ret = 1;
		goto out;
	}
	dbus_error_init(&error);

	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (!conn) {
		if (dbus_error_is_set(&error)) {
			print("%s", error.message);
			dbus_error_free(&error);
		} else
			print("Failed to get on system bus");

		goto out;
	}

	msg = dbus_message_new_method_call(busname, path,
						interface, "notify");
	if (!msg) {
		dbus_connection_unref(conn);
		print("Failed to allocate method call");
		goto out;
	}

	dbus_message_set_no_reply(msg, TRUE);

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

	dbus_message_iter_init_append(msg, &iter);

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

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

	dbus_message_iter_close_container(&iter, &dict);

	if (!dbus_connection_send(conn, msg, NULL)) {
		print("Failed to send message");
		goto out;
	}

	dbus_connection_flush(conn);

	dbus_message_unref(msg);

	dbus_connection_unref(conn);

out:
	closelog();

	return ret;
}
Ejemplo n.º 25
0
int ccgi_dbus_eag_conf_nas(DBusConnection *conn, dbus_nas_conf nas_conf)
{
	DBusMessage *query, *reply;
    DBusError err;
    int ret_nas = -1;

    query = dbus_message_new_method_call(
                                    EAG_AURO_SERVER,
                                    EAG_AURO_CONF_OBJECT,
						            INTERFACE_AURO_NAS, 
						            METHOD_NAS );
	if (NULL == query) {
      fprintf(stderr, "ccgi_dbus_eag_conf_nas:Message Null\n");
    }
	
    dbus_error_init(&err);

	const char * tmp_n_nastype = nas_conf.n_nastype;
	const char * tmp_n_start = nas_conf.n_start;
	const char * tmp_n_end = nas_conf.n_end;
	
	const char * tmp_n_nasid = nas_conf.n_nasid;
	const char * tmp_n_syntaxis = nas_conf.n_syntaxis;
	const char * tmp_n_attz = nas_conf.n_attz;
	//fprintf(stderr,"eag_auto_conf n_flag=%d,n_default=%d,n_plotid=%u,n_nastype=%s,n_start=%s,n_end=%s,n_nasid=%u,n_syntaxis=%u",\
	//			nas_conf.n_flag,nas_conf.n_default,nas_conf.n_plotid,tmp_n_nastype,tmp_n_start,tmp_n_end,nas_conf.n_nasid,nas_conf.n_syntaxis);
	
	dbus_message_append_args(   query,
								DBUS_TYPE_INT32,  &nas_conf.n_flag,
								DBUS_TYPE_INT32,  &nas_conf.n_default,
								DBUS_TYPE_INT32,  &nas_conf.n_plotid,
								DBUS_TYPE_STRING, &tmp_n_nastype,
								DBUS_TYPE_STRING, &tmp_n_start,
								DBUS_TYPE_STRING, &tmp_n_end,
								DBUS_TYPE_STRING, &tmp_n_nasid,
								DBUS_TYPE_STRING, &tmp_n_syntaxis,
								DBUS_TYPE_STRING, &tmp_n_attz,
					            DBUS_TYPE_INVALID );
	
    reply = dbus_connection_send_with_reply_and_block ( conn, query, -1, &err );
    dbus_message_unref(query);
    
    if ( NULL == reply )
    {
        if (dbus_error_is_set(&err))
        {
        	fprintf(stderr, "ccgi_dbus_eag_conf_nas:send_with_reply_and_block Error:(%s)\n", err.message);
            dbus_error_free(&err);
        }
        ret_nas = ERR_DBUS_REPLY_NULL;
    }
    else
    {
        dbus_message_get_args( reply,
                                &err,
                                DBUS_TYPE_INT32, &ret_nas,
                                DBUS_TYPE_INVALID );
		dbus_message_unref(reply);
    }       
    
	return ret_nas;
}
Ejemplo n.º 26
0
void ofono_ussd_notify(struct ofono_ussd *ussd, int status, int dcs,
			const unsigned char *data, int data_len)
{
	DBusConnection *conn = ofono_dbus_get_connection();
	const char *ussdstr = "USSD";
	char *utf8_str = NULL;
	const char *str;
	const char sig[] = { DBUS_TYPE_STRING, 0 };
	DBusMessage *reply;
	DBusMessageIter iter;
	DBusMessageIter variant;

	DBG("status: %d %s, state: %d %s",
		status, ussd_status_name(status),
		ussd->state, ussd_state_name(ussd->state));

	if (ussd->req &&
			(status == OFONO_USSD_STATUS_NOTIFY ||
			status == OFONO_USSD_STATUS_TERMINATED ||
			status == OFONO_USSD_STATUS_TIMED_OUT ||
			status == OFONO_USSD_STATUS_NOT_SUPPORTED)) {
		ussd_request_finish(ussd, ussd_status_to_failure_code(status),
					dcs, data, data_len);

		ussd_change_state(ussd, USSD_STATE_IDLE);
		return;
	}

	if (status == OFONO_USSD_STATUS_TERMINATED) {
		ussd_change_state(ussd, USSD_STATE_IDLE);

		if (ussd->pending == NULL)
			return;

		reply = __ofono_error_network_terminated(ussd->pending);
		goto out;
	}

	if (status == OFONO_USSD_STATUS_NOT_SUPPORTED) {
		ussd_change_state(ussd, USSD_STATE_IDLE);

		if (ussd->pending == NULL)
			return;

		reply = __ofono_error_not_supported(ussd->pending);
		goto out;
	}

	if (status == OFONO_USSD_STATUS_TIMED_OUT) {
		ussd_change_state(ussd, USSD_STATE_IDLE);

		if (ussd->pending == NULL)
			return;

		reply = __ofono_error_timed_out(ussd->pending);
		goto out;
	}

	if (data && data_len > 0)
		utf8_str = ussd_decode(dcs, data_len, data);

	str = utf8_str;

	/* TODO: Rework this in the Agent framework */
	if (ussd->state == USSD_STATE_ACTIVE) {

		reply = dbus_message_new_method_return(ussd->pending);

		if (str == NULL)
			str = "";

		dbus_message_iter_init_append(reply, &iter);

		dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
						&ussdstr);

		dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, sig,
							&variant);

		dbus_message_iter_append_basic(&variant, DBUS_TYPE_STRING,
						&str);

		dbus_message_iter_close_container(&iter, &variant);

		if (status == OFONO_USSD_STATUS_ACTION_REQUIRED)
			ussd_change_state(ussd, USSD_STATE_USER_ACTION);
		else
			ussd_change_state(ussd, USSD_STATE_IDLE);

	} else if (ussd->state == USSD_STATE_RESPONSE_SENT) {
		reply = dbus_message_new_method_return(ussd->pending);

		if (str == NULL)
			str = "";

		dbus_message_append_args(reply, DBUS_TYPE_STRING, &str,
						DBUS_TYPE_INVALID);

		if (status == OFONO_USSD_STATUS_ACTION_REQUIRED)
			ussd_change_state(ussd, USSD_STATE_USER_ACTION);
		else
			ussd_change_state(ussd, USSD_STATE_IDLE);
	} else if (ussd->state == USSD_STATE_IDLE) {
		const char *signal_name;
		const char *path = __ofono_atom_get_path(ussd->atom);
		int new_state;

		if (status == OFONO_USSD_STATUS_ACTION_REQUIRED) {
			new_state = USSD_STATE_USER_ACTION;
			signal_name = "RequestReceived";
		} else {
			new_state = USSD_STATE_IDLE;
			signal_name = "NotificationReceived";
		}

		if (str == NULL)
			str = "";

		g_dbus_emit_signal(conn, path,
			OFONO_SUPPLEMENTARY_SERVICES_INTERFACE, signal_name,
				DBUS_TYPE_STRING, &str, DBUS_TYPE_INVALID);

		ussd_change_state(ussd, new_state);
		goto free;
	} else {
		ofono_error("Received an unsolicited USSD but can't handle.");
		DBG("USSD is: status: %d, %s", status, str);

		goto free;
	}

out:
	g_dbus_send_message(conn, reply);

	dbus_message_unref(ussd->pending);
	ussd->pending = NULL;

free:
	g_free(utf8_str);
}
Ejemplo n.º 27
0
int set_ac_ip_diffnum_banlance_cmd(int instance_id,char *id,char *value)/*返回0表示失败,返回1表示成功,返回-1表示unknown id format*/
																			   /*返回-2表示wlan id does not exist,返回-3表示interface does not exist*/
																			   /*返回-4表示wlan is enable,please disable it first,返回-5表示error*/
{
	if((NULL == id)||(NULL == value))
		return 0;
	
	int ret;
	unsigned char ID = 0;
	unsigned int diffnum = 0;
	DBusMessage *query, *reply;	
	DBusMessageIter	 iter;
	DBusError err;
	int retu;
	
	ret = parse_int_ID((char*)value, &diffnum);
	if(ret != WID_DBUS_SUCCESS){
		return -1;
	}	

	
	int index;
	char BUSNAME[PATH_LEN];
	char OBJPATH[PATH_LEN];
	char INTERFACE[PATH_LEN];
	/*if(vty->node == ACIPLIST_NODE){
		index = 0;			
		ID = (int)vty->index;
	}else if(vty->node == HANSI_ACIPLIST_NODE){
		index = vty->index; 		
		ID = (int)vty->index_sub;
	}*/
	index = instance_id;			
	ID = id;
	
	ReInitDbusPath(index,WID_DBUS_BUSNAME,BUSNAME);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_OBJPATH,OBJPATH);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_INTERFACE,INTERFACE);
	query = dbus_message_new_method_call(BUSNAME,OBJPATH,INTERFACE,WID_DBUS_ACIPLIST_METHOD_SET_AC_IP_DIFF_BANLANCE);
		

	dbus_error_init(&err);

	dbus_message_append_args(query,
							 DBUS_TYPE_BYTE,&ID,
							 DBUS_TYPE_UINT32,&diffnum,
							 DBUS_TYPE_INVALID);

	reply = dbus_connection_send_with_reply_and_block (ccgi_dbus_connection,query,-1, &err);
	
	dbus_message_unref(query);
	
	if (NULL == reply)
	{
		if (dbus_error_is_set(&err))
		{
			dbus_error_free(&err);
		}
		return 0;
	}
	
	dbus_message_iter_init(reply,&iter);
	dbus_message_iter_get_basic(&iter,&ret);

	if(ret == 0)
		retu = 1;
	else if(ret == WLAN_ID_NOT_EXIST)
		retu = -2;
	else if(ret == APPLY_IF_FAIL)
		retu = -3;
	else if(ret == WLAN_BE_ENABLE)
		retu = -4;
	else
		retu = -5;
		
	dbus_message_unref(reply);
	return retu;
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
#endif
{
	gboolean opt_force_online = FALSE;
	gboolean opt_help = FALSE;
	gboolean opt_login = FALSE;
	gboolean opt_nologin = FALSE;
	gboolean opt_version = FALSE;
	gboolean opt_si = TRUE;     /* Check for single instance? */
	char *opt_config_dir_arg = NULL;
	char *opt_login_arg = NULL;
	char *opt_session_arg = NULL;
	char *search_path;
	GList *accounts;
#ifdef HAVE_SIGNAL_H
	int sig_indx;	/* for setting up signal catching */
	sigset_t sigset;
	char errmsg[BUFSIZ];
	GIOChannel *signal_channel;
	GIOStatus signal_status;
	guint signal_channel_watcher;
#ifndef DEBUG
	char *segfault_message_tmp;
#endif
	GError *error;
#endif
	int opt;
	gboolean gui_check;
	gboolean debug_enabled;
	gboolean migration_failed = FALSE;
	GList *active_accounts;

	struct option long_options[] = {
		{"config",       required_argument, NULL, 'c'},
		{"debug",        no_argument,       NULL, 'd'},
		{"force-online", no_argument,       NULL, 'f'},
		{"help",         no_argument,       NULL, 'h'},
		{"login",        optional_argument, NULL, 'l'},
		{"multiple",     no_argument,       NULL, 'm'},
		{"nologin",      no_argument,       NULL, 'n'},
		{"session",      required_argument, NULL, 's'},
		{"version",      no_argument,       NULL, 'v'},
		{"display",      required_argument, NULL, 'D'},
		{"sync",         no_argument,       NULL, 'S'},
		{0, 0, 0, 0}
	};

#ifdef DEBUG
	debug_enabled = TRUE;
#else
	debug_enabled = FALSE;
#endif

#if !GLIB_CHECK_VERSION(2, 32, 0)
	/* GLib threading system is automaticaly initialized since 2.32.
	 * For earlier versions, it have to be initialized before calling any
	 * Glib or GTK+ functions.
	 */
	g_thread_init(NULL);
#endif

	g_set_prgname("Pidgin");

#ifdef ENABLE_NLS
	bindtextdomain(PACKAGE, LOCALEDIR);
	bind_textdomain_codeset(PACKAGE, "UTF-8");
	textdomain(PACKAGE);
#endif

#ifdef HAVE_SETLOCALE
	/* Locale initialization is not complete here.  See gtk_init_check() */
	setlocale(LC_ALL, "");
#endif

#ifdef HAVE_SIGNAL_H

#ifndef DEBUG
		/* We translate this here in case the crash breaks gettext. */
		segfault_message_tmp = g_strdup_printf(_(
			"%s %s has segfaulted and attempted to dump a core file.\n"
			"This is a bug in the software and has happened through\n"
			"no fault of your own.\n\n"
			"If you can reproduce the crash, please notify the developers\n"
			"by reporting a bug at:\n"
			"%ssimpleticket/\n\n"
			"Please make sure to specify what you were doing at the time\n"
			"and post the backtrace from the core file.  If you do not know\n"
			"how to get the backtrace, please read the instructions at\n"
			"%swiki/GetABacktrace\n"),
			PIDGIN_NAME, DISPLAY_VERSION, PURPLE_DEVEL_WEBSITE, PURPLE_DEVEL_WEBSITE
		);

		/* we have to convert the message (UTF-8 to console
		   charset) early because after a segmentation fault
		   it's not a good practice to allocate memory */
		error = NULL;
		segfault_message = g_locale_from_utf8(segfault_message_tmp,
						      -1, NULL, NULL, &error);
		if (segfault_message != NULL) {
			g_free(segfault_message_tmp);
		}
		else {
			/* use 'segfault_message_tmp' (UTF-8) as a fallback */
			g_warning("%s\n", error->message);
			g_error_free(error);
			segfault_message = segfault_message_tmp;
		}
#else
		/* Don't mark this for translation. */
		segfault_message = g_strdup(
			"Hi, user.  We need to talk.\n"
			"I think something's gone wrong here.  It's probably my fault.\n"
			"No, really, it's not you... it's me... no no no, I think we get along well\n"
			"it's just that.... well, I want to see other people.  I... what?!?  NO!  I \n"
			"haven't been cheating on you!!  How many times do you want me to tell you?!  And\n"
			"for the last time, it's just a rash!\n"
		);
#endif

	/*
	 * Create a socket pair for receiving unix signals from a signal
	 * handler.
	 */
	if (socketpair(AF_UNIX, SOCK_STREAM, 0, signal_sockets) < 0) {
		perror("Failed to create sockets for GLib signal handling");
		exit(1);
	}
	signal_channel = g_io_channel_unix_new(signal_sockets[1]);

	/*
	 * Set the channel encoding to raw binary instead of the default of
	 * UTF-8, because we'll be sending integers across instead of strings.
	 */
	error = NULL;
	signal_status = g_io_channel_set_encoding(signal_channel, NULL, &error);
	if (signal_status != G_IO_STATUS_NORMAL) {
		fprintf(stderr, "Failed to set the signal channel to raw "
				"binary: %s", error->message);
		exit(1);
	}
	signal_channel_watcher = g_io_add_watch(signal_channel, G_IO_IN, mainloop_sighandler, NULL);
	g_io_channel_unref(signal_channel);

	/* Let's not violate any PLA's!!!! */
	/* jseymour: whatever the fsck that means */
	/* Robot101: for some reason things like gdm like to block     *
	 * useful signals like SIGCHLD, so we unblock all the ones we  *
	 * declare a handler for. thanks JSeymour and Vann.            */
	if (sigemptyset(&sigset)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't initialise empty signal set");
		perror(errmsg);
	}
	for(sig_indx = 0; catch_sig_list[sig_indx] != -1; ++sig_indx) {
		if(signal(catch_sig_list[sig_indx], sighandler) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d for catching",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
		if(sigaddset(&sigset, catch_sig_list[sig_indx])) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't include signal %d for unblocking",
				catch_sig_list[sig_indx]);
			perror(errmsg);
		}
	}
	for(sig_indx = 0; ignore_sig_list[sig_indx] != -1; ++sig_indx) {
		if(signal(ignore_sig_list[sig_indx], SIG_IGN) == SIG_ERR) {
			snprintf(errmsg, sizeof(errmsg), "Warning: couldn't set signal %d to ignore",
				ignore_sig_list[sig_indx]);
			perror(errmsg);
		}
	}

	if (sigprocmask(SIG_UNBLOCK, &sigset, NULL)) {
		snprintf(errmsg, sizeof(errmsg), "Warning: couldn't unblock signals");
		perror(errmsg);
	}
#endif

	/* scan command-line options */
	opterr = 1;
	while ((opt = getopt_long(argc, argv,
#ifndef _WIN32
				  "c:dfhmnl::s:v",
#else
				  "c:dfhmnl::v",
#endif
				  long_options, NULL)) != -1) {
		switch (opt) {
		case 'c':	/* config dir */
			g_free(opt_config_dir_arg);
			opt_config_dir_arg = g_strdup(optarg);
			break;
		case 'd':	/* debug */
			debug_enabled = TRUE;
			break;
		case 'f':	/* force-online */
			opt_force_online = TRUE;
			break;
		case 'h':	/* help */
			opt_help = TRUE;
			break;
		case 'n':	/* no autologin */
			opt_nologin = TRUE;
			break;
		case 'l':	/* login, option username */
			opt_login = TRUE;
			g_free(opt_login_arg);
			if (optarg != NULL)
				opt_login_arg = g_strdup(optarg);
			break;
		case 's':	/* use existing session ID */
			g_free(opt_session_arg);
			opt_session_arg = g_strdup(optarg);
			break;
		case 'v':	/* version */
			opt_version = TRUE;
			break;
		case 'm':   /* do not ensure single instance. */
			opt_si = FALSE;
			break;
		case 'D':   /* --display */
		case 'S':   /* --sync */
			/* handled by gtk_init_check below */
			break;
		case '?':	/* show terse help */
		default:
			show_usage(argv[0], TRUE);
#ifdef HAVE_SIGNAL_H
			g_free(segfault_message);
#endif
			return 0;
			break;
		}
	}

	/* show help message */
	if (opt_help) {
		show_usage(argv[0], FALSE);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}
	/* show version message */
	if (opt_version) {
		printf("%s %s (libpurple %s)\n", PIDGIN_NAME, DISPLAY_VERSION,
		                                 purple_core_get_version());
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* set a user-specified config directory */
	if (opt_config_dir_arg != NULL) {
		purple_util_set_user_dir(opt_config_dir_arg);
	}

	/*
	 * We're done piddling around with command line arguments.
	 * Fire up this baby.
	 */

	purple_debug_set_enabled(debug_enabled);

	/* If we're using a custom configuration directory, we
	 * do NOT want to migrate, or weird things will happen. */
	if (opt_config_dir_arg == NULL)
	{
		if (!purple_core_migrate())
		{
			migration_failed = TRUE;
		}
	}

	search_path = g_build_filename(purple_user_dir(), "gtkrc-2.0", NULL);
	gtk_rc_add_default_file(search_path);
	g_free(search_path);

	gui_check = gtk_init_check(&argc, &argv);
	if (!gui_check) {
		char *display = gdk_get_display();

		printf("%s %s\n", PIDGIN_NAME, DISPLAY_VERSION);

		g_warning("cannot open display: %s", display ? display : "unset");
		g_free(display);
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif

		return 1;
	}

	g_set_application_name(PIDGIN_NAME);

#ifdef _WIN32
	winpidgin_init(hint);
#endif

	if (migration_failed)
	{
		char *old = g_strconcat(purple_home_dir(),
		                        G_DIR_SEPARATOR_S ".gaim", NULL);
		const char *text = _(
			"%s encountered errors migrating your settings "
			"from %s to %s. Please investigate and complete the "
			"migration by hand. Please report this error at http://developer.pidgin.im");
		GtkWidget *dialog;

		dialog = gtk_message_dialog_new(NULL,
		                                0,
		                                GTK_MESSAGE_ERROR,
		                                GTK_BUTTONS_CLOSE,
		                                text, PIDGIN_NAME,
		                                old, purple_user_dir());
		g_free(old);

		g_signal_connect_swapped(dialog, "response",
		                         G_CALLBACK(gtk_main_quit), NULL);

		gtk_widget_show_all(dialog);

		gtk_main();

#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	purple_core_set_ui_ops(pidgin_core_get_ui_ops());
	purple_eventloop_set_ui_ops(pidgin_eventloop_get_ui_ops());

	/*
	 * Set plugin search directories. Give priority to the plugins
	 * in user's home directory.
	 */
	search_path = g_build_filename(purple_user_dir(), "plugins", NULL);
	if (g_mkdir(search_path, S_IRUSR | S_IWUSR | S_IXUSR) != 0 && errno != EEXIST)
		fprintf(stderr, "Couldn't create plugins dir\n");
	purple_plugins_add_search_path(search_path);
	g_free(search_path);
	purple_plugins_add_search_path(LIBDIR);

	if (!purple_core_init(PIDGIN_UI)) {
		fprintf(stderr,
				"Initialization of the libpurple core failed. Dumping core.\n"
				"Please report this!\n");
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		abort();
	}

	if (opt_si && !purple_core_ensure_single_instance()) {
#ifdef HAVE_DBUS
		DBusConnection *conn = purple_dbus_get_connection();
		DBusMessage *message = dbus_message_new_method_call(DBUS_SERVICE_PURPLE, DBUS_PATH_PURPLE,
				DBUS_INTERFACE_PURPLE, "PurpleBlistSetVisible");
		gboolean tr = TRUE;
		dbus_message_append_args(message, DBUS_TYPE_INT32, &tr, DBUS_TYPE_INVALID);
		dbus_connection_send_with_reply_and_block(conn, message, -1, NULL);
		dbus_message_unref(message);
#endif
		gdk_notify_startup_complete();
		purple_core_quit();
		g_printerr(_("Exiting because another libpurple client is already running.\n"));
#ifdef HAVE_SIGNAL_H
		g_free(segfault_message);
#endif
		return 0;
	}

	/* TODO: Move blist loading into purple_blist_init() */
	purple_set_blist(purple_blist_new());
	purple_blist_load();

	/* load plugins we had when we quit */
	purple_plugins_load_saved(PIDGIN_PREFS_ROOT "/plugins/loaded");

	/* TODO: Move pounces loading into purple_pounces_init() */
	purple_pounces_load();

	ui_main();

#ifdef USE_SM
	pidgin_session_init(argv[0], opt_session_arg, opt_config_dir_arg);
#endif
	if (opt_session_arg != NULL) {
		g_free(opt_session_arg);
		opt_session_arg = NULL;
	}
	if (opt_config_dir_arg != NULL) {
		g_free(opt_config_dir_arg);
		opt_config_dir_arg = NULL;
	}

	/* This needs to be before purple_blist_show() so the
	 * statusbox gets the forced online status. */
	if (opt_force_online)
		purple_network_force_online();

	/*
	 * We want to show the blist early in the init process so the
	 * user feels warm and fuzzy (not cold and prickley).
	 */
	purple_blist_show();

	if (purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/debug/enabled"))
		pidgin_debug_window_show();

	if (opt_login) {
		/* disable all accounts */
		for (accounts = purple_accounts_get_all(); accounts != NULL; accounts = accounts->next) {
			PurpleAccount *account = accounts->data;
			purple_account_set_enabled(account, PIDGIN_UI, FALSE);
		}
		/* honor the startup status preference */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		/* now enable the requested ones */
		dologin_named(opt_login_arg);
		if (opt_login_arg != NULL) {
			g_free(opt_login_arg);
			opt_login_arg = NULL;
		}
	} else if (opt_nologin)	{
		/* Set all accounts to "offline" */
		PurpleSavedStatus *saved_status;

		/* If we've used this type+message before, lookup the transient status */
		saved_status = purple_savedstatus_find_transient_by_type_and_message(
							PURPLE_STATUS_OFFLINE, NULL);

		/* If this type+message is unique then create a new transient saved status */
		if (saved_status == NULL)
			saved_status = purple_savedstatus_new(NULL, PURPLE_STATUS_OFFLINE);

		/* Set the status for each account */
		purple_savedstatus_activate(saved_status);
	} else {
		/* Everything is good to go--sign on already */
		if (!purple_prefs_get_bool("/purple/savedstatus/startup_current_status"))
			purple_savedstatus_activate(purple_savedstatus_get_startup());
		purple_accounts_restore_current_statuses();
	}

	if ((active_accounts = purple_accounts_get_all_active()) == NULL)
	{
		pidgin_accounts_window_show();
	}
	else
	{
		g_list_free(active_accounts);
	}

	/* GTK clears the notification for us when opening the first window,
	 * but we may have launched with only a status icon, so clear the it
	 * just in case. */
	gdk_notify_startup_complete();

#ifdef _WIN32
	winpidgin_post_init();
#endif

	gtk_main();

#ifdef HAVE_SIGNAL_H
	g_free(segfault_message);
	g_source_remove(signal_channel_watcher);
	close(signal_sockets[0]);
	close(signal_sockets[1]);
#endif

#ifdef _WIN32
	winpidgin_cleanup();
#endif

	return 0;
}
Ejemplo n.º 29
0
/*ID的范围是1至ACIPLIST_NUM-1*/
int del_ac_ip_list_cmd(int instance_id,char *ID)/*返回0表示失败,返回1表示成功,返回-1表示unknown id format*/
												   /*返回-2表示id should be 1 to ACIPLIST_NUM-1,返回-3表示wlan id does not exist*/
												   /*返回-4表示wlan is enable,please disable it first,返回-5表示error*/
{
	if(NULL == ID)
		return 0;
	
	int ret;
	unsigned char id;
	DBusMessage *query, *reply;	
	DBusMessageIter	 iter;
	DBusError err;	
	int retu;
		
	ret = parse_char_ID((char*)ID, &id);
	if(ret != WID_DBUS_SUCCESS){
		return -1;
	}	
	if(id >= ACIPLIST_NUM || id == 0){
		return -2;
	}
	
	int index;
	char BUSNAME[PATH_LEN];
	char OBJPATH[PATH_LEN];
	char INTERFACE[PATH_LEN];
	/*if(vty->node == CONFIG_NODE){
		index = 0;
	}else if(vty->node == HANSI_NODE){
		index = vty->index;
	}*/
	index = instance_id;
	ReInitDbusPath(index,WID_DBUS_BUSNAME,BUSNAME);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_OBJPATH,OBJPATH);
	ReInitDbusPath(index,WID_DBUS_ACIPLIST_INTERFACE,INTERFACE);
	query = dbus_message_new_method_call(BUSNAME,OBJPATH,INTERFACE,WID_DBUS_ACIPLIST_METHOD_DEL_AC_IP_LIST_GROUP);

/*	query = dbus_message_new_method_call(WID_DBUS_BUSNAME,WID_DBUS_ACIPLIST_OBJPATH,\
						WID_DBUS_ACIPLIST_INTERFACE,WID_DBUS_ACIPLIST_METHOD_DEL_AC_IP_LIST_GROUP);*/
	dbus_error_init(&err);

	dbus_message_append_args(query,
						DBUS_TYPE_BYTE,&id,
						DBUS_TYPE_INVALID);

	reply = dbus_connection_send_with_reply_and_block (ccgi_dbus_connection,query,-1, &err);
	
	dbus_message_unref(query);
	
	if (NULL == reply) {
		if (dbus_error_is_set(&err)) {
			dbus_error_free(&err);
		}
		return 0;
	}
	dbus_message_iter_init(reply,&iter);
	dbus_message_iter_get_basic(&iter,&ret);

		if(ret == 0)
			retu = 1;
		else if(ret == WLAN_ID_NOT_EXIST)
			retu = -3;
		else if(ret == WLAN_BE_ENABLE)
			retu = -4;
		else
			retu = -5;

	dbus_message_unref(reply);
	return retu;	
}
Ejemplo n.º 30
0
int tool_cmd_scan(int argc, char *argv[])
{
	int ret = 0;
	int c;
	int timeout = DEFAULT_TIMEOUT_IN_SECONDS * 1000;
	const char *method_name;
	DBusConnection* connection = NULL;
	DBusMessage *message = NULL;
	DBusMessage *reply = NULL;
	DBusPendingCall *pending = NULL;
	DBusError error;
	int32_t scan_period = 0;
	uint32_t channel_mask = 0;
	dbus_bool_t joiner_flag = FALSE;
	dbus_bool_t enable_filtering = FALSE;
	uint16_t pan_id_filter = 0xffff;

	dbus_error_init(&error);

	sEnergyScan = false;
	sMleDiscoverScan = false;

	while (1) {
		static struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"timeout", required_argument, 0, 't'},
			{"channel", required_argument, 0, 'c'},
			{"energy", no_argument, 0, 'e'},
			{"discover", no_argument, 0, 'd'},
			{"joiner-only", no_argument, 0, 'j'},
			{"enable-filtering", no_argument, 0, 'f'},
			{"panid-filtering", required_argument, 0, 'p'},
			{0, 0, 0, 0}
		};

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

		if (c == -1)
			break;

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

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

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

		case 'e':
			sEnergyScan = true;
			break;

		case 'd':
			sMleDiscoverScan = true;
			break;

		case 'j':
			joiner_flag = TRUE;
			break;

		case 'f':
			enable_filtering = TRUE;
			break;

		case 'p':
			pan_id_filter = strtol(optarg, NULL, 0);
			break;
		}
	}

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

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

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

	connection = dbus_bus_get(DBUS_BUS_STARTER, &error);

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

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

	dbus_bus_add_match(connection, gDBusObjectManagerMatchString, &error);

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

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

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

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

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

		if (sEnergyScan) {
			method_name = WPANTUND_IF_CMD_ENERGY_SCAN_START;
		} else {
			if (sMleDiscoverScan) {
				method_name = WPANTUND_IF_CMD_DISCOVER_SCAN_START;
			} else {
				method_name = WPANTUND_IF_CMD_NET_SCAN_START;
			}
		}

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

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

		if (sMleDiscoverScan) {
			dbus_message_append_args(
				message,
				DBUS_TYPE_BOOLEAN, &joiner_flag,
				DBUS_TYPE_BOOLEAN, &enable_filtering,
				DBUS_TYPE_UINT16, &pan_id_filter,
				DBUS_TYPE_INVALID
			);
		}

		print_scan_header();

		if (!sEnergyScan) {
			gScannedNetworkCount = 0;
		}

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

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

		reply = dbus_pending_call_steal_reply(pending);

		require(reply != NULL, bail);


		dbus_message_iter_init(reply, &iter);

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

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

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


bail:

	if (reply) {
		dbus_message_unref(reply);
	}

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

	if (message) {
		dbus_message_unref(message);
	}

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

	dbus_error_free(&error);

	return ret;
}