Exemple #1
0
void Preferences::registerService()
{
	bool ret;
	LSError error;
	LSErrorInit(&error);

	ret = LSRegister(NULL, &m_lsHandle, &error);
	if (!ret) {
		g_critical("Failed to register handler: %s", error.message);
		LSErrorFree(&error);
		exit(1);
	}

	ret = LSGmainAttach(m_lsHandle, HostBase::instance()->mainLoop(), &error);
	if (!ret) {
		g_critical("Failed to attach service to main loop: %s", error.message);
		LSErrorFree(&error);
		exit(1);
	}

	ret = LSCall(m_lsHandle, "palm://com.palm.lunabus/signal/registerServerStatus",
				 "{\"serviceName\":\"com.palm.systemservice\"}",
				 serverConnectCallback, this, &m_serverStatusToken, &error);
	if (!ret) {
		g_critical("Failed in calling palm://com.palm.lunabus/signal/registerServerStatus: %s",
					  error.message);
		LSErrorFree(&error);
		exit(1);
	}
	
}
bool cbGetStatus(LSHandle *handle, LSMessage *message, void *user_data)
{
	SUBSCRIBE_SCHEMA_RETURN(handle, message);

	bool success = true;
	LSError error;
	json_object* json = json_object_new_object();
	bool subscribed = false;
	bool firstUse = false;
	std::string stateStr;

	LSErrorInit(&error);

	if (LSMessageIsSubscription(message)) {
		if (!LSSubscriptionProcess(handle, message, &subscribed, &error)) {
			LSErrorFree (&error);
			goto done;
		}
	}

	stateStr = bootStateToStr(BootManager::instance()->currentState());
	json_object_object_add(json, "state", json_object_new_string(stateStr.c_str()));

done:
	json_object_object_add(json, "returnValue", json_object_new_boolean(success));
	json_object_object_add(json, "subscribed", json_object_new_boolean(subscribed));

	if (!LSMessageReply(handle, message, json_object_to_json_string(json), &error))
		LSErrorFree (&error);

	json_object_put(json);

	return true;
}
void BootManager::startService()
{
	bool result;
	LSError error;
	LSErrorInit(&error);

	GMainLoop *mainLoop = HostBase::instance()->mainLoop();

	g_message("BootManager starting...");

	if (!LSRegister("org.webosports.bootmgr", &m_service, &error)) {
		g_warning("Failed in BootManager: %s", error.message);
		LSErrorFree(&error);
		return;
	}

	if (!LSRegisterCategory(m_service, "/", s_methods, NULL, NULL, &error)) {
		g_warning("Failed in BootManager: %s", error.message);
		LSErrorFree(&error);
		return;
	}

	if (!LSGmainAttach(m_service, mainLoop, &error)) {
		g_warning("Failed in BootManager: %s", error.message);
		LSErrorFree(&error);
		return;
	}

	if (!LSRegisterServerStatus(m_service, "org.webosports.luna",
				cbCompositorAvailable, NULL, &error)) {
		g_warning("Failed to register for compositor status");
		LSErrorFree(&error);
	}
}
Exemple #4
0
//
// Return a polite response.
// Called directly from webOS, and returns directly to webOS.
//
bool set_debug_log_method(LSHandle* lshandle, LSMessage *message, void *ctx)
{
	log("set_debug_log_method");

	LSError lserror;
	LSErrorInit(&lserror);

	// Extract the id argument from the message
	json_t *object = json_parse_document(LSMessageGetPayload(message));
	json_t *enableDebugLogging = json_find_first_label(object, "enableDebugLogging");
               
	if(enableDebugLogging)
	{
		if(enableDebugLogging->child->type == JSON_TRUE)
		{
			log("enableDebugLogging: JSON_TRUE");
			g_debugLoggingEnabled = true;
		}
		else if(enableDebugLogging->child->type == JSON_FALSE)
		{
			log("enableDebugLogging: JSON_FALSE");
			g_debugLoggingEnabled = false;
			remove(LOG_FILE);
		}
		else
		{
			log("enableDebugLogging: %d", enableDebugLogging->child->type);
		}
	}
	else
	{
		if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing parameters\"}", &lserror))
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);

			return false;
		}
	}

	// Local buffer to store the reply
	char reply[MAXLINLEN];
	sprintf(reply, "{\"returnValue\": true, \"debugLoggingEnabled\": %s}", g_debugLoggingEnabled ? "true" : "false");
	log(reply);
	
	if (!LSMessageReply(lshandle, message, reply, &lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);

		return false;
	}

	return true;
}
Exemple #5
0
static bool 
timingServiceResponse(LSHandle *sh, LSMessage *reply, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);
    LSMessageToken token;

    const char *payload;
    
    clock_gettime(CLOCK_MONOTONIC, &stopTime);

    token = LSMessageGetResponseToken(reply);
    payload = LSMessageGetPayload(reply);
    
    double duration = ((double)stopTime.tv_sec + (((double)stopTime.tv_nsec)/1000000000.0)) -
                     ((double)startTime.tv_sec + (((double)startTime.tv_nsec)/1000000000.0));
    
    roundtripTime += duration;
    roundtripCount++;
    rcvdBytes += strlen(payload);
    sentBytes += url ? strlen(url) : 0;
    sentBytes += message ? strlen(message) : 0;

    g_message("%s Got response: duration %.02f ms, token %ld, payload %s", __FUNCTION__, duration * 1000.0, token, payload);

    if (--count > 0)
    {
        // resend the message!
        LSMessageToken sessionToken;

        clock_gettime(CLOCK_MONOTONIC, &startTime);
        
        /* Basic sending */
        bool retVal = LSCallFromApplication(sh, url, message, appId,
                     timingServiceResponse, ctx, &sessionToken, &lserror);
        if (!retVal)
        {
            LSErrorPrint (&lserror, stderr);
            LSErrorFree (&lserror);
        }
    } else {
        bool retVal = LSCallCancel (sh, token, &lserror);
        if (!retVal)
        {
            LSErrorPrint (&lserror, stderr);
            LSErrorFree (&lserror);
        }
        g_timeout_add (300, goodbye, ctx);
        return true;
    }

    return true;
}
static bool handle_get_info_command(LSHandle *sh, LSMessage *message, void* context)
{
	jvalue_ref reply = jobject_create();
	LSError lserror;
	LSErrorInit(&lserror);
	char wifi_mac_address[32]={0}, wired_mac_address[32]={0};

	jobject_put(reply, J_CSTR_TO_JVAL("returnValue"), jboolean_create(true));

	if(get_wifi_mac_address(CONNMAN_WIFI_INTERFACE_NAME, wifi_mac_address) == 0)
	{
		jvalue_ref wifi_info = jobject_create();
		jobject_put(wifi_info, J_CSTR_TO_JVAL("macAddress"),jstring_create(wifi_mac_address));
		jobject_put(reply, J_CSTR_TO_JVAL("wifiInfo"), wifi_info);
	}
	else
		WCA_LOG_ERROR("Error in fetching mac address for wifi interface");


	if(get_wifi_mac_address(CONNMAN_WIRED_INTERFACE_NAME, wired_mac_address) == 0)
	{
		jvalue_ref wired_info = jobject_create();
		jobject_put(wired_info, J_CSTR_TO_JVAL("macAddress"),jstring_create(wired_mac_address));
		jobject_put(reply, J_CSTR_TO_JVAL("wiredInfo"), wired_info);
	}
	else
		WCA_LOG_ERROR("Error in fetching mac address for wired interface");

	jschema_ref response_schema = jschema_parse (j_cstr_to_buffer("{}"), DOMOPT_NOOPT, NULL);
	if(!response_schema)
	{
		LSMessageReplyErrorUnknown(sh,message);
		goto cleanup;
	}

	if (!LSMessageReply(sh, message, jvalue_tostring(reply, response_schema), &lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	jschema_release(&response_schema);

cleanup:
	if (LSErrorIsSet(&lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	j_release(&reply);
	return true;
}
bool ImageServices::init(MainLoopProvider * p)
{
	if (p == NULL)
		return false;
	
	//grab the main loop ptr from the provider
	m_p_mainloop = p->getMainLoopPtr();
	if (m_p_mainloop == NULL)
		return false;
	
	//register the service
	LSError lsError;
	bool result;

	LSErrorInit(&lsError);

	// Register the service
	result = LSRegisterPalmService("com.palm.image", &m_service, &lsError);
	if (!result) {
		g_warning("Failed to register service: com.palm.image");
		return false;
	}

	m_serviceHandlePublic = LSPalmServiceGetPublicConnection(m_service);
	m_serviceHandlePrivate = LSPalmServiceGetPrivateConnection(m_service);
	result = LSGmainAttachPalmService(m_service, m_p_mainloop, &lsError);
	if (!result) {
		g_warning("Failed to attach service handle to main loop");
		LSErrorFree(&lsError);
		LSErrorInit(&lsError);
		result = LSUnregisterPalmService(m_service,&lsError);
		if (!result)
			LSErrorFree(&lsError);
		return false;
	}
	
	//register methods
	result = LSPalmServiceRegisterCategory( m_service, "/", s_methods_public, s_methods_private,
			NULL, this, &lsError);
	if (!result) {
		g_warning("Failed in registering handler methods on /: %s", lsError.message);
		LSErrorFree(&lsError);
		result = LSUnregisterPalmService(m_service,&lsError);
		if (!result)
			LSErrorFree(&lsError);
		return false;
	}

	return true;

}
bool _test0(LSHandle* lshandle,LSMessage *message, void *user_data)
{
	const char* str = LSMessageGetPayload(message);
	if( !str )
		return false;

	QtJsonAbstract * j = QtJsonAbstract::jsonParse(QString(str));
	if (j)
	{
		QList<QPair<QString,QVariant> > allContents = j->extractAll();
		for (QtJsonAbstract::ContentsListIterator it = allContents.begin();
				it != allContents.end();++it)
		{
			//qDebug() << "key = " << it->first;
//			if ((QMetaType::Type)(it->second.userType()) == qMetaTypeId<QtJsonAbstractVariant>())
				//qDebug() << "\tval = " << it->second.value<QtJsonAbstractVariant>();
//			else
				//qDebug() << "\tval = " << it->second << " , usertype =  " << (QMetaType::Type)(it->second.userType()) << " , mytype = " << qMetaTypeId<QtJsonAbstractVariant>();
		}
		QtJsonAbstract::throwAway(j);

		QtJsonAbstract * reply = QtJsonAbstract::create();
		reply->add("returnValue",true);

		LSError lserror;
		LSErrorInit(&lserror);

		if (!LSMessageReply( lshandle, message,ccstr(reply->toString()), &lserror )) {
			LSErrorPrint (&lserror, stderr);
			LSErrorFree(&lserror);
		}
		QtJsonAbstract::throwAway(reply);
	}
	else
	{
		QtJsonAbstract * reply = QtJsonAbstract::create();
		reply->add("returnValue",true);

		LSError lserror;
		LSErrorInit(&lserror);

		if (!LSMessageReply( lshandle, message,ccstr(reply->toString()), &lserror )) {
			LSErrorPrint (&lserror, stderr);
			LSErrorFree(&lserror);
		}
		QtJsonAbstract::throwAway(reply);
	}

	return true;
}
struct property_service* property_service_create()
{
	struct property_service *service;
	LSError error;

	service = g_try_new0(struct property_service, 1);
	if (!service)
		return NULL;

	LSErrorInit(&error);

	if (!LSRegisterPubPriv("com.android.properties", &service->handle, false, &error)) {
		g_error("Failed to register the luna service: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSRegisterCategory(service->handle, "/", property_service_methods,
			NULL, NULL, &error)) {
		g_error("Could not register service category: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSCategorySetData(service->handle, "/", service, &error)) {
		g_error("Could not set daa for service category: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSGmainAttach(service->handle, event_loop, &error)) {
		g_error("Could not attach service handle to mainloop: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	return service;

error:
	if (service->handle != NULL) {
		LSUnregister(service->handle, &error);
		LSErrorFree(&error);
	}

	g_free(service);

	return NULL;
}
Exemple #10
0
bool luna_service_message_validate_and_send(LSHandle *handle, LSMessage *message, jvalue_ref reply_obj)
{
	jschema_ref response_schema = NULL;
	LSError lserror;
	bool success = true;

	LSErrorInit(&lserror);

	response_schema = jschema_parse (j_cstr_to_buffer("{}"), DOMOPT_NOOPT, NULL);
	if(!response_schema) {
		luna_service_message_reply_error_internal(handle, message);
		return false;
	}

	if (!LSMessageReply(handle, message,
					jvalue_tostring(reply_obj, response_schema), &lserror)) {
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
		success = false;
	}

	jschema_release(&response_schema);

	return success;
}
bool service_register(const char *name)
{
	bool rc;
	LSError err;
	LSErrorInit(&err);

	loop = g_main_loop_new(NULL, FALSE);

	if(loop == NULL)
		goto end;

	rc = LSRegisterPalmService(name, &handle, &err);
	if(rc)
	{
		pub = LSPalmServiceGetPublicConnection(handle);
		prv = LSPalmServiceGetPrivateConnection(handle);
	}
	else
		goto end;

	rc = LSPalmServiceRegisterCategory(handle, "/", methods, NULL, NULL,
					   NULL, &err);
	LSGmainAttachPalmService(handle, loop, &err);
	if(!rc)
		goto end;
end:
	if(LSErrorIsSet(&err))
	{
		LSErrorPrint(&err, stderr);
		LSErrorFree(&err);
		puts("servece startup error...");
	}
	return rc;
}
Exemple #12
0
static int
_power_timeout_init(void)
{
    /* Set up luna service */


    psh = GetPalmService();

    LSError lserror;
    LSErrorInit(&lserror);
    if (!LSPalmServiceRegisterCategory(psh,
                "/timeout", timeout_methods /*public*/, NULL /*private*/, NULL, NULL, &lserror)) {
        POWERDLOG(LOG_ERR, "%s could not register category: %s",
                __FUNCTION__, lserror.message);
        LSErrorFree(&lserror);
        goto error;
    }

    if (!LSRegisterCategory(GetLunaServiceHandle(),
          "/time", time_methods, NULL, NULL, &lserror))
      {
          goto error;
      }

    UEventListen("/com/palm/powerd/timechange/uevent", _timechange_callback);

    return 0;

error:
    return -1;
}
Exemple #13
0
static void
test_LSErrorLog(TestData *fixture, gconstpointer user_data)
{
    LSError lserror;
    LSErrorInit(&lserror);
    _LSErrorSetNoPrint(&lserror, LS_ERROR_CODE_UNKNOWN_ERROR, LS_ERROR_TEXT_UNKNOWN_ERROR);

    if (g_test_trap_fork(0, G_TEST_TRAP_SILENCE_STDERR))
    {
        LOG_LSERROR("LS_TEST_ERROR", &lserror);
        exit(0);
    }
    gchar *expected_stderr = g_strdup_printf("{\"ERROR_CODE\":%d,\"ERROR\":\"%s\",\"FUNC\":\"%s\",\"FILE\":\"%s\",\"LINE\":%d"
                                             "} LUNASERVICE ERROR\n",
                                             lserror.error_code, lserror.message, lserror.func, lserror.file, lserror.line);
    g_test_trap_assert_stderr(expected_stderr);
    g_free(expected_stderr);

    if (g_test_trap_fork(0, G_TEST_TRAP_SILENCE_STDERR))
    {
        LOG_LSERROR("LS_TEST_ERROR", NULL);
        exit(0);
    }
    g_test_trap_assert_stderr("lserror is NULL. Did you pass in a LSError?\n");

    LSErrorFree(&lserror);
}
Exemple #14
0
void AlertWebApp::startPowerdActivity()
{
	if (!m_isPowerdActivityRunning) {
		LSHandle* lshandle = WebAppManager::instance()->getStatsServiceHandle();
		LSError lsError;
		LSErrorInit(&lsError);

		gchar* activityId = g_strdup_printf("com.palm.lunastats-alert-%p", this);
		g_message ("%s: starting powerd activity for %s", __PRETTY_FUNCTION__, activityId);
		gchar* params = g_strdup_printf("{\"id\": \"%s\", \"duration_ms\": %d}", activityId, kAlertActivityDuration);

		bool ret = LSCall(lshandle, "palm://com.palm.power/com/palm/power/activityStart",
				params, NULL, NULL, NULL, &lsError);

		g_free (activityId);
		g_free (params);

		if (!ret) {
			g_warning("%s: Failed to call powerd activityStart: %s", __PRETTY_FUNCTION__, lsError.message);
			LSErrorFree(&lsError);
			return;
		}
		m_isPowerdActivityRunning = true;
	}
}
Exemple #15
0
bool
chargerStatusQuery(LSHandle *sh,
                   LSMessage *message, void *user_data)
{
	nyx_charger_status_t status;
	if(!nyxDev)
		return false;
	nyx_error_t err = nyx_charger_query_charger_status(nyxDev,&status);

	if(err != NYX_ERROR_NONE)
	{
		POWERDLOG(LOG_ERR,"%s: nyx_charger_query_battery_status returned with error : %d",__func__,err);
	}

	LSError lserror;
	LSErrorInit(&lserror);

	char *payload = g_strdup_printf("{\"DockConnected\":%s,\"DockPower\":%s,\"DockSerialNo\":\"%s\","
				"\"USBConnected\":%s,\"USBName\":\"%s\",\"Charging\":%s}",(status.connected & NYX_CHARGER_INDUCTIVE_CONNECTED) ? "true" : "false",
				(status.powered & NYX_CHARGER_INDUCTIVE_POWERED) ? "true" :"false",(strlen(status.dock_serial_number)) ? status.dock_serial_number : "NULL",
				(status.powered & NYX_CHARGER_USB_POWERED) ? "true" : "false",ChargerNameToString(status.connected),
				(status.is_charging) ? "true":"false");

	POWERDLOG(LOG_DEBUG,"%s: Sending payload : %s",__func__,payload);
	bool retVal = LSMessageReply(sh, message, payload,NULL);
	if (!retVal)
	{

		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}
	g_free(payload);
	return TRUE;
}
Exemple #16
0
/** 
* @brief Cleanup all IPC.
*/
void
_PowerdClientIPCStop(void)
{
    if (gMainLoop)
    {
        if (!gOwnMainLoop)
            g_main_loop_quit(gMainLoop);

        g_main_loop_unref(gMainLoop);

        gMainLoop = NULL;
        gOwnMainLoop = false;
    }

    if (gServiceHandle && !gOwnLunaService)
    {
        bool retVal;
        LSError lserror;
        LSErrorInit(&lserror);

        retVal = LSUnregister(gServiceHandle, &lserror);
        if (!retVal)
        {
            LSErrorPrint(&lserror, stderr);
            LSErrorFree(&lserror);
        }
    }
    gServiceHandle = NULL;
    gOwnLunaService = false;
}
bool version_method(LSHandle* lshandle, LSMessage *message, void *ctx) {

  bool returnVal = true;
  char line[MAXLINELEN];
  // %%% MAGIC NUMBER ALERT %%%
  char version[16];

  LSError lserror;
  LSErrorInit(&lserror);

  char *jsonResponse = 0;
  int len = 0;

  FILE *fp = popen("/sbin/initctl version", "r");
  if (fp) {
    while ( fgets( line, sizeof line, fp)) {
      // %%% MAGIC NUMBER ALERT %%%
      if (sscanf(line, "init (upstart %15s)\n", (char*)&version) == 1) {
	len = asprintf(&jsonResponse, "{\"returnValue\":true,\"version\":\"%s\"}", version);
      }
    }
    // %%% IGNORING RETURN ALERT %%%
    pclose(fp);
  }

  if (jsonResponse) {
    LSMessageReply(lshandle, message, jsonResponse, &lserror);
    free(jsonResponse);
  } else
    LSMessageReply(lshandle, message, "{\"returnValue\":false,\"errorCode\":-1,\"errorText\":\"Generic error\"}", &lserror);
 
  LSErrorFree(&lserror);

  return returnVal;
}
Exemple #18
0
bool getFilecacheType_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  if (access_denied(message)) return true;

  char filename[MAXLINLEN];

  // Extract the id argument from the message
  json_t *object = json_parse_document(LSMessageGetPayload(message));
  json_t *type = json_find_first_label(object, "type");               
  if (!type || (type->child->type != JSON_STRING) || (strspn(type->child->text, ALLOWED_CHARS) != strlen(type->child->text))) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing type\"}",
			&lserror)) goto error;
    return true;
  }

  sprintf(filename, "/etc/palm/filecache_types/%s", type->child->text);

  return read_file(message, filename, true);

 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemple #19
0
/**
 * Destructor: Stop anything we have going & disconnect proxy listener
 */
SoundPlayer::~SoundPlayer()
{
	PRINTF_BLUE("SoundPlayer::~SoundPlayer(%s)", getStateName());
	if (m_state == eState_PlayPending || m_state == eState_Playing)
		stop();

	if (m_player.get()) {
		m_player->removeMediaPlayerChangeListener(m_mediaPlayerChangeListener);
		m_player.reset((media::MediaPlayer*) 0);
	}
	
	// Important: Make sure to call this before the service handle destuction
	if (m_mediaPlayerChangeListener.get())
		m_mediaPlayerChangeListener.reset((media::MediaPlayerChangeListener*)0);

	if (m_serviceHandle) {
		LSError lserror;
		LSErrorInit(&lserror);
		if (!LSUnregisterPalmService(m_serviceHandle, &lserror)) {
	        LSErrorPrint (&lserror, stderr);
	        LSErrorFree (&lserror);
		}

		m_serviceHandle = 0;
	}
}
Exemple #20
0
/**
 * Simply start the healthCheck timer with a single refresh setting
 * Also start activity if necessary
 */
void SoundPlayer::startTimer()
{
	if (!m_timer.running())
	{
		m_timer.start(1000, false);
		m_activityID = ++m_activityCount;

	    gchar * request = g_strdup_printf("{\"id\":\"com.palm.sysmgr.soundplayer.%i\",\"duration_ms\":60000}", m_activityID);

	    LSError lserror;
	    LSErrorInit(&lserror);
	    bool activityStartRequestSuccess = LSCall(getServiceHandle(), "palm://com.palm.power/com/palm/power/activityStart", request, NULL, NULL, NULL, &lserror);
	    if (!activityStartRequestSuccess)
	    {
	    	CRITICAL("SoundPlayer::startTimer: activity '%s' Start failed", request);
	        LSErrorPrint (&lserror, stderr);
	        LSErrorFree (&lserror);
	    }
	    else
	    	DEBUG("SoundPlayer::startTimer: booked activity '%s'...", request);

	    g_free(request);
	}
	m_lastPlayingTime = currentTime();
}
Exemple #21
0
static bool
shutdownServicesRegister(LSHandle *sh, LSMessage *message,
                             void *user_data)
{
    struct json_object *object =
        json_tokener_parse(LSMessageGetPayload(message));
    if (is_error(object)) goto end;

    const char *clientId = LSMessageGetUniqueToken(message);
    const char *clientName = json_object_get_string(json_object_object_get(
        object, "clientName"));

    client_new_service(clientId, clientName);

    bool retVal;
    LSError lserror;
    LSErrorInit(&lserror);

    retVal = LSSubscriptionAdd(sh, "shutdownClient",
                             message, &lserror);
    if (!retVal)
    {
        g_critical("LSSubscriptionAdd failed.");
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    send_reply(sh, message, "{\"clientId\":\"%s\"}", clientId);

    json_object_put(object);
end:
    return true;
}
Exemple #22
0
//
// Return a polite response.
// Called directly from webOS, and returns directly to webOS.
//
bool query_adhoc_state_method(LSHandle* lshandle, LSMessage *message, void *ctx)
{
	log("query_adhoc_state_method");

	LSError lserror;
	LSErrorInit(&lserror);

	// Local buffer to store the reply
	char reply[MAXLINLEN];	

	if(g_adhocAddress != NULL)
	{
		sprintf(reply, "{\"returnValue\": true, \"connected\": true, \"address\": \"%s\"}", g_adhocAddress);
	}
	else
	{
		sprintf(reply, "{\"returnValue\": true, \"connected\": false}");
	}

	log(reply);

	if (!LSMessageReply(lshandle, message, reply, &lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);

		return false;
	}

	return true;	
}
bool luna_service_initialize(const char *dbusAddress) {

  bool returnVal = FALSE;

  LSError lserror;
  LSErrorInit(&lserror);

  loop = g_main_loop_new(NULL, FALSE);
  if (loop==NULL)
    goto end;

  returnVal = LSRegisterPalmService(dbusAddress, &serviceHandle, &lserror);
  if (returnVal) {
    pub_serviceHandle = LSPalmServiceGetPublicConnection(serviceHandle);
    priv_serviceHandle = LSPalmServiceGetPrivateConnection(serviceHandle);
  } else
    goto end;

  returnVal =  register_methods(serviceHandle, lserror);
  if (returnVal) {
    LSGmainAttachPalmService(serviceHandle, loop, &lserror);
  }

 end:
  if (LSErrorIsSet(&lserror)) {
    LSErrorPrint(&lserror, stderr);
    LSErrorFree(&lserror);
  }

  return returnVal;
}
Exemple #24
0
static int
shutdown_init(void)
{
    sClientList = g_new0(ShutdownClientList, 1);
    sClientList->applications = g_hash_table_new_full(g_str_hash, g_str_equal,
                        NULL, (GDestroyNotify)client_free);
    sClientList->services = g_hash_table_new_full(g_str_hash, g_str_equal,
                        NULL, (GDestroyNotify)client_free);
    sClientList->num_ack = 0;
    sClientList->num_nack = 0;

    shutdown_timer = g_timer_new();

    gCurrentState = &kStateMachine[kPowerShutdownNone];
    
    LSError lserror;
    LSErrorInit(&lserror);

    if (!LSRegisterCategory(GetLunaServiceHandle(),
            "/shutdown", shutdown_methods, shutdown_signals, NULL, &lserror))
    {
        goto error;
    }

    return 0;

error:
    LSErrorPrint(&lserror, stderr);
    LSErrorFree(&lserror);
    return -1;
}
Exemple #25
0
//
// Run ls-monitor --capture and provide the output back to Mojo
//
bool ls2Monitor_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  if (ls2MonitorThread) {
    syslog(LOG_NOTICE, "Ls2 thread already running\n");
    if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"ouroboros\": true, \"stage\": \"failed\"}", &lserror)) goto error;
    return true;
  }

  syslog(LOG_DEBUG, "Create ls2 thread, ref message %p\n", message);

  // Ref and save the message for use in ls2 thread
  LSMessageRef(message);

  if (pthread_create(&ls2MonitorThread, NULL, ls2_monitor, (void*)message)) {
    syslog(LOG_ERR, "Creating ls2 thread failed (0x%x)\n", ls2MonitorThread);
    // Report that the ls2 operation was not able to start
    if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"ouroboros\": true, \"errorCode\": -1, \"errorText\": \"Unable to start ls2 thread\"}", &lserror)) goto error;
  }
  else {
    syslog(LOG_DEBUG, "Created ls2 thread successfully (0x%x)\n", ls2MonitorThread);
    // Report that the ls2 operation has begun
    if (!LSMessageReply(lshandle, message, "{\"returnValue\": true, \"ouroboros\": true, \"stage\": \"start\"}", &lserror)) goto error;
  }

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemple #26
0
//
// Return a polite response.
// Called directly from webOS, and returns directly to webOS.
//
bool stop_adhoc_method(LSHandle* lshandle, LSMessage *message, void *ctx)
{
	log("stop_adhoc_method");

	LSError lserror;
	LSErrorInit(&lserror);

	// Local buffer to store the reply
	char reply[MAXLINLEN];

	restartNetworkCard();
	resetDns();
	startPalmWifiService();
	g_adhocAddress = NULL;

	sprintf(reply, "{\"returnValue\": true}");
	log(reply);

	if (!LSMessageReply(lshandle, message, reply, &lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);

		return false;
	}

	return true;	
}
Exemple #27
0
static void
test_LSErrorPrint(TestData *fixture, gconstpointer user_data)
{
    LSError error;
    LSErrorInit(&error);
    _LSErrorSetNoPrint(&error, LS_ERROR_CODE_UNKNOWN_ERROR, LS_ERROR_TEXT_UNKNOWN_ERROR);

    if (g_test_trap_fork(0, G_TEST_TRAP_SILENCE_STDERR))
    {
        LSErrorPrint(&error, stderr);
        exit(0);
    }
    gchar *expected_stderr = g_strdup_printf("LUNASERVICE ERROR %d: %s (%s @ %s:%d)\n",
             error.error_code, error.message, error.func, error.file, error.line);
    g_test_trap_assert_stderr(expected_stderr);
    g_free(expected_stderr);

    if (g_test_trap_fork(0, G_TEST_TRAP_SILENCE_STDERR))
    {
        LSErrorPrint(NULL, stderr);
        exit(0);
    }
    g_test_trap_assert_stderr("LUNASERVICE ERROR: lserror is NULL. Did you pass in a LSError?");

    LSErrorFree(&error);
}
Exemple #28
0
static void
test_LSErrorSetFunc(TestData *fixture, gconstpointer user_data)
{
    LSError error;
    LSErrorInit(&error);

    const char *file = __FILE__;
    const int line = __LINE__;
    const char *func = __FUNCTION__;
    const int error_code = LS_ERROR_CODE_UNKNOWN_ERROR;

    g_assert(_LSErrorSetFunc(&error, file, line, func, error_code, LS_ERROR_TEXT_OOM));
    g_assert_cmpstr(error.file, ==, file);
    g_assert_cmpint(error.line, ==, line);
    g_assert_cmpstr(error.func, ==, func);
    g_assert_cmpint(error.error_code, ==, error_code);
    g_assert_cmpstr(error.message, ==, LS_ERROR_TEXT_OOM);

    // error already set, should not touch given error, but just return true
    g_assert(_LSErrorSetFunc(&error, "file", 0, "func", LS_ERROR_CODE_UNKNOWN_ERROR, "msg"));
    g_assert_cmpstr(error.file, ==, file);
    g_assert_cmpint(error.line, ==, line);
    g_assert_cmpstr(error.func, ==, func);
    g_assert_cmpint(error.error_code, ==, error_code);
    g_assert_cmpstr(error.message, ==, LS_ERROR_TEXT_OOM);

    LSErrorFree(&error);

    // NULL error case (should return true)
    g_assert(_LSErrorSetFunc(NULL, file, line, func, error_code, LS_ERROR_TEXT_OOM));
}
int main(int argc, char **argv)
{
	LSError lserror;

	g_type_init();

	g_log_set_handler (NULL, G_LOG_LEVEL_MASK, log_handler, NULL);

	signal(SIGTERM, signal_term_handler);
	signal(SIGINT, signal_term_handler);

	mainloop = g_main_loop_new(NULL, FALSE);

	LSErrorInit(&lserror);

	if (!LSRegisterPalmService("org.webosinternals.service.update", &palm_service_handle, &lserror)) {
		g_error("Failed to initialize the Luna Palm service: %s", lserror.message);
		LSErrorFree(&lserror);
		goto cleanup;
	}

	if (!LSGmainAttachPalmService(palm_service_handle, mainloop, &lserror)) {
		g_error("Failed to attach to glib mainloop for palm service: %s", lserror.message);
		LSErrorFree(&lserror);
		goto cleanup;
	}

	private_service_handle = LSPalmServiceGetPrivateConnection(palm_service_handle);

	initialize_luna_service();

	g_main_loop_run(mainloop);

cleanup:
	shutdown_luna_service();

	if (palm_service_handle != NULL && LSUnregisterPalmService(palm_service_handle, &lserror) < 0) {
		g_error("Could not unregister palm service: %s", lserror.message);
		LSErrorFree(&lserror);
	}

	g_source_remove(signal);

	g_main_loop_unref(mainloop);

	return 0;
}
Exemple #30
0
void AppEffector::remove(const QString& webosAppId,const QUuid& iconUid)
{
	WebOSApp * pWebOSapp = AppMonitor::appMonitor()->webosAppByAppId(webosAppId);
	if (!pWebOSapp)
	{
		qDebug() << __FUNCTION__ << ": didn't find a webos app with appId ["<<webosAppId<<"]";
		return;
	}

	ApplicationDescription * pAppDesc = ApplicationManager::instance()->getAppById(StringTranslator::outputString(pWebOSapp->appId()));
	if (!pAppDesc)
	{
		return;
	}

	//if the app is a sysmgr builtin, then ignore
	if (pAppDesc->type() == ApplicationDescription::Type_SysmgrBuiltin)
	{
		return;
	}

	//check to see if the icon that triggered this is an auxiliary launch point or the main one

	WOAppIconType::Enum type;
	QString launchPointId = pWebOSapp->launchpointIdOfIcon(iconUid,&type);

	if (type == WOAppIconType::Auxiliary)
	{
		//yes, auxiliary...delegate to removeLaunchpoint
		g_message("%s: The remove was on one of the app's auxiliary icons (launchpoints)...delegating to another function to do that removal",
				__FUNCTION__);
		return removeLaunchpoint(webosAppId,launchPointId);
	}

	g_message("%s: The remove is on the app's main icon; the whole app will be removed from the system",__FUNCTION__);
	//else, it's the main icon, so the app removal procedure needs to take place

	pWebOSapp->m_stateBeingRemoved = true;		//this is set in case at some point the removal process needs to go async

	//I'm going to hijack ApplicationManager's LS handle to make a call to remove an app
	json_object* payload = json_object_new_object();
	LSError lserror;
	LSErrorInit(&lserror);

	///TODO: do I want to track remove status???
	json_object_object_add(payload, "id", json_object_new_string(pWebOSapp->appId().toAscii().constData()));
	if (!LSCall(ApplicationManager::instance()->m_serviceHandlePrivate,
			"palm://com.palm.appInstallService/remove",json_object_to_json_string(payload),
			NULL, NULL, NULL, &lserror)) {
		LSErrorFree(&lserror);
	}
	json_object_put(payload);
	//!...this HAS TO BE THE LAST CALL IN THIS FUNCTION!!! and also, make sure nothing much happens up the chain either
#if defined(TARGET_DESKTOP)
	LauncherObject::primaryInstance()->slotAppPreRemove(*pWebOSapp,DimensionsSystemInterface::AppMonitorSignalType::AppManSourced);
#endif

	return;
}