Beispiel #1
0
//
// Kill the currently running commands
//
bool killDBusCapture_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  if (!dbusCaptureThread) {
    syslog(LOG_NOTICE, "DBus thread 0x%x not running\n", dbusCaptureThread);
    if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"ouroboros\": true, \"stage\": \"failed\"}", &lserror)) goto error;
    return true;
  }

  syslog(LOG_DEBUG, "Killing dbus thread 0x%x\n", dbusCaptureThread);
  
  pthread_cancel(dbusCaptureThread);
  dbusCaptureThread = 0;

  if (!LSMessageReply(lshandle, message, "{\"returnValue\": true, \"ouroboros\": true, \"stage\": \"completed\"}", &lserror)) goto error;

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Beispiel #2
0
bool batteryStatusQuery(LSHandle *sh,
                   LSMessage *message, void *user_data)
{
	nyx_battery_status_t status;
	if(!battDev)
		return false;

	nyx_error_t err = nyx_battery_query_battery_status(battDev,&status);

	if(err != NYX_ERROR_NONE)
	{
		POWERDLOG(LOG_ERR,"%s: nyx_charger_query_battery_status returned with error : %d",__func__,err);
	}
	int percent_ui = getUiPercent(status.percentage);


	POWERDLOG(LOG_INFO,
			"(%fmAh, %d%%, %d%%_ui, %dC, %dmA, %dmV)\n",
			status.capacity, status.percentage,
			percent_ui,
			status.temperature,
			status.current, status.voltage);

	GString *buffer = g_string_sized_new(500);
	g_string_append_printf(buffer,"{\"percent\":%d,\"percent_ui\":%d,"
				"\"temperature_C\":%d,\"current_mA\":%d,\"voltage_mV\":%d,"
				"\"capacity_mAh\":%f}",
		status.percentage,
		percent_ui,
		status.temperature,
		status.current,
		status.voltage,
		status.capacity);

	char *payload = g_string_free(buffer, FALSE);

	POWERDLOG(LOG_DEBUG,"%s: Sending payload : %s",__func__,payload);
	LSError lserror;
	LSErrorInit(&lserror);
    bool retVal = LSMessageReply(sh, message, payload,NULL);
	if (!retVal)
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}
	g_free(payload);
	return TRUE;
}
Beispiel #3
0
// callback
static bool
listContacts(LSHandle *sh, LSMessage *message, void *categoryContext)
{
    bool retVal;
    LSError lserror;
    LSErrorInit(&lserror);

    retVal = LSMessageReply(sh, message, "{ JSON REPLY PAYLOAD }", &lserror);
    if (!retVal)
    {
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    return retVal;
}
Beispiel #4
0
//
// A dummy method, useful for unimplemented functions or as a status function.
// Called directly from webOS, and returns directly to webOS.
//
bool dummy_method(LSHandle* lshandle, LSMessage *message, void *ctx)
{
	log("dummy_method");

	LSError lserror;
	LSErrorInit(&lserror);

	if (!LSMessageReply(lshandle, message, "{\"returnValue\": true}", &lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);

		return false;
	}

	return true;
}
Beispiel #5
0
void luna_service_message_reply_custom_error(LSHandle *handle, LSMessage *message, const char *error_text)
{
	bool ret;
	LSError lserror;
	char *payload;

	LSErrorInit(&lserror);

	payload = g_strdup_printf("{\"returnValue\":false, \"errorText\":\"%s\"}", error_text);

	ret = LSMessageReply(handle, message, payload, &lserror);
	if (!ret) {
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	g_free(payload);
}
static bool handle_get_status_command(LSHandle* sh, LSMessage *message, void* context)
{

	jvalue_ref reply = jobject_create();
	LSError lserror;
	LSErrorInit(&lserror);
	bool subscribed = false;

	if (LSMessageIsSubscription(message))
	{
		if (!LSSubscriptionProcess(sh, message, &subscribed, &lserror))
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);
		}
		jobject_put(reply, J_CSTR_TO_JVAL("subscribed"), jboolean_create(subscribed));
		if(!connman_manager_is_manager_available(manager))
			goto response;
	}
	if(!connman_status_check(manager, sh, message))
		goto cleanup;

	send_connection_status(&reply);

response:
	{
		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:
	j_release(&reply);
	return true;
}
Beispiel #7
0
//
// Send a standard format command failure message back to webOS.
// The command will be escaped.  The output argument should be a JSON array and is not escaped.
// The additional text  will not be escaped.
// The return value is from the LSMessageReply call, not related to the command execution.
//
static bool report_command_failure(LSHandle* lshandle, LSMessage *message, char *command, char *stdErrText, char *additional) {
  LSError lserror;
  LSErrorInit(&lserror);

  char buffer[MAXBUFLEN];
  char esc_buffer[MAXBUFLEN];

  // Include the command that was executed, in escaped form.
  snprintf(buffer, MAXBUFLEN,
	   "{\"errorText\": \"Unable to run command: %s\"",
	   json_escape_str(command, esc_buffer));

  // Include any stderr fields from the command.
  if (stdErrText) {
    strcat(buffer, ", \"stdErr\": ");
    strcat(buffer, stdErrText);
  }

  // Report that an error occurred.
  strcat(buffer, ", \"returnValue\": false, \"errorCode\": -1");

  // Add any additional JSON fields.
  if (additional) {
    strcat(buffer, ", ");
    strcat(buffer, additional);
  }

  // Terminate the JSON reply message ...
  strcat(buffer, "}");

  // fprintf(stderr, "Message is %s\n", buffer);

  // and send it.
  if (!LSMessageReply(lshandle, message, buffer, &lserror)) goto error;

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Beispiel #8
0
static bool
suspend_ipc_method_cb(LSHandle *sh, LSMessage *message, void *ctx)
{
	bool retVal;
	LSMessage *replyMessage = (LSMessage *)ctx;

	POWERDLOG(LOG_INFO,"%s: response with payload %s", __FUNCTION__, LSMessageGetPayload(message));
	if(replyMessage && LSMessageGetConnection(replyMessage))
	{
		retVal = LSMessageReply(LSMessageGetConnection(replyMessage), replyMessage, LSMessageGetPayload(message), NULL);
		if (!retVal)
		{
			POWERDLOG(LOG_WARNING, "%s could not send reply.", __FUNCTION__);
		}
		LSMessageUnref(replyMessage);
	}
	else
		POWERDLOG(LOG_CRIT,"%s: replyMessage is NULL",__func__);
    return true;
}
Beispiel #9
0
static void
send_reply(LSHandle *sh, LSMessage *message,
           const char *format, ...)
{
    bool retVal;
    char *payload;
    va_list vargs;

    va_start(vargs, format);
    payload = g_strdup_vprintf(format, vargs);
    va_end(vargs);

    retVal = LSMessageReply(sh, message, payload, NULL);
    if (!retVal)
    {
        g_critical("Could not send reply with payload %s",
            payload);
    }

    g_free(payload);
}
Beispiel #10
0
static bool
state_shutdown_action(ShutdownEvent *event, ShutdownState *next)
{
    bool retVal =
        LSMessageReply(GetLunaServiceHandle(), shutdown_message,
            "{\"success\":true}", NULL);
    if (!retVal)
    {
        g_critical("%s: Could not send shutdown success message",
                __FUNCTION__);
    }

    if (shutdown_message)
    {
        LSMessageUnref(shutdown_message);
        shutdown_message = NULL;
    }

    nyx_system_set_alarm(GetNyxSystemDevice(),0,NULL,NULL);

    return false;  
}
Beispiel #11
0
//
// Return the current API version of the service.
// Called directly from webOS, and returns directly to webOS.
//
bool version_method(LSHandle* lshandle, LSMessage *message, void *ctx)
{
	log("version_method");

	LSError lserror;
	LSErrorInit(&lserror);

	// Local buffer to store the reply
	char reply[MAXLINLEN];
	sprintf(reply, "{\"returnValue\": true, \"version\": \"%s\", \"apiVersion\": \"%s\"}", VERSION, API_VERSION);
	log(reply);

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

		return false;
	}

	return true;
}
bool
_LSPrivateGetSubscriptions(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    const char *sender = LSMessageGetSenderServiceName(message);

    if (!sender || strcmp(sender, MONITOR_NAME) != 0)
    {
        g_critical("WARNING: subscription debug method not called by monitor;"
                   " ignoring (service name: %s, unique_name: %s)",
                   sender, LSMessageGetSender(message));
        return true;
    }

    struct json_object *ret_obj = NULL;
    bool json_ret = _LSSubscriptionGetJson(sh, &ret_obj, &lserror);
    if (!json_ret)
    {
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
        return true;
    }

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending subscription info failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    json_object_put(ret_obj);
    
    return true;

}
Beispiel #13
0
bool InputManager::processSubscription(LSHandle* handle, LSMessage* msg, void* userData)
{
    SUBSCRIBE_SCHEMA_RETURN(handle, msg);

	// process subscriptions for a group of keys
	bool retVal = false;
	LSError lserror;
	LSErrorInit(&lserror);
	bool subscribed = false;
	json_object* json = json_object_new_object();

	if (LSMessageIsSubscription(msg)) {
		retVal = LSSubscriptionProcess(handle, msg, &subscribed, &lserror);
		if (!retVal) {
			LSErrorPrint (&lserror, stderr);
			LSErrorFree (&lserror);
			goto Error;
		}
	} else {
		json_object_object_add(json, "errorCode", json_object_new_int(-1));
		json_object_object_add(json, "errorText", json_object_new_string("We were expecting a subscribe type message, but we did not recieve one."));
	}

Error:

	json_object_object_add(json, "returnValue", json_object_new_boolean(retVal));
	json_object_object_add(json, "subscribed", json_object_new_boolean(subscribed));
	

	if (!LSMessageReply(handle, msg, json_object_to_json_string(json), &lserror)) {
		LSErrorPrint(&lserror, stderr);
		LSErrorFree (&lserror);
	}
	json_object_put(json);

	return true;	// message has been processed, don't call the callback anymore
}
Beispiel #14
0
/**
* @brief Sends a message to subscription list with name 'key'.
*
* @param  sh
* @param  key
* @param  payload
* @param  lserror
*
* @retval
*/
bool
LSSubscriptionReply(LSHandle *sh, const char *key,
                    const char *payload, LSError *lserror)
{
    LSHANDLE_VALIDATE(sh);

    bool retVal = true;
    _Catalog *catalog = sh->catalog;

    _CatalogLock(catalog);

    _SubList *tokens = _CatalogGetSubList_unlocked(catalog, key);
    if (!tokens)
    {
        retVal = true;
        goto cleanup;
    }

    int i;
    for (i = 0; i < tokens->len; i++)
    {
        char *tok = g_ptr_array_index(tokens, i);

        _Subscription *subs =
            g_hash_table_lookup(catalog->token_map, tok);
        if (!subs) continue;

        LSMessage *message = subs->message;

        retVal = LSMessageReply(sh, message, payload, lserror);
        if (!retVal) goto cleanup;
    }
cleanup:
    _CatalogUnlock(catalog);
    return retVal;
}
Beispiel #15
0
//
// Run a simple shell command, and return the output to webOS.
//
static bool simple_command(LSHandle* lshandle, LSMessage *message, char *command) {
  LSError lserror;
  LSErrorInit(&lserror);

  char run_command_buffer[MAXBUFLEN];

  // Initialise the output buffer
  strcpy(run_command_buffer, "{\"stdOut\": [");

  // Run the command
  if (run_command(command, true, run_command_buffer)) {

    // Finalise the message ...
    strcat(run_command_buffer, "], \"returnValue\": true}");

    // fprintf(stderr, "Message is %s\n", run_command_buffer);

    // and send it to webOS.
    if (!LSMessageReply(lshandle, message, run_command_buffer, &lserror)) goto error;
  }
  else {

    // Finalise the command output ...
    strcat(run_command_buffer, "]");

    // and use it in a failure report message.
    if (!report_command_failure(lshandle, message, command, run_command_buffer+11, NULL)) goto end;
  }

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
bool list_method(LSHandle* lshandle, LSMessage *message, void *ctx) {

  bool returnVal = true;
  char line[MAXLINELEN];
  // %%% MAGIC NUMBERS ALERT %%%
  char name[128];
  char state[16];
  char status[128];

  LSError lserror;
  LSErrorInit(&lserror);

  char *jsonResponse = 0;
  int len = 0;

  json_t *response = json_new_object();

  FILE *fp = popen("/sbin/initctl list", "r");
  if (fp) {
    json_t *array = json_new_array();
    while ( fgets( line, sizeof line, fp)) {
      // %%% MAGIC NUMBERS ALERT %%%
      if (sscanf(line, "%127s (start) %127c",
		 (char*)&name, (char *)&status) == 2) {
	// %%% HACK ALERT %%%
	*strchr(status,'\n') = 0;
	json_t *object = json_new_object();
	// %%% IGNORING RETURN ALERT %%%
	json_insert_pair_into_object(object, "name", json_new_string(name));
	json_insert_pair_into_object(object, "state", json_new_string("start"));
	json_insert_pair_into_object(object, "status", json_new_string(status));
	json_insert_child(array, object);
      }
      // %%% MAGIC NUMBERS ALERT %%%
      else if (sscanf(line, "%127s (stop) %127c",
		 (char*)&name, (char *)&status) == 2) {
	// %%% HACK ALERT %%%
	*strchr(status,'\n') = 0;
	json_t *object = json_new_object();
	// %%% IGNORING RETURN ALERT %%%
	json_insert_pair_into_object(object, "name", json_new_string(name));
	json_insert_pair_into_object(object, "state", json_new_string("stop"));
	json_insert_pair_into_object(object, "status", json_new_string(status));
	json_insert_child(array, object);
      }
    }
    if (!pclose(fp)) {
      // %%% IGNORING RETURN ALERT %%%
      json_insert_pair_into_object(response, "returnValue", json_new_true());
      json_insert_pair_into_object(response, "jobs", array);
      json_tree_to_string(response, &jsonResponse);
    }
  }

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

  return returnVal;
}
Beispiel #17
0
/**
* @brief Query for set of alarms identified by 'serviceName' & 'key'.
*
* {"serviceName":"com.palm.X", "key":"calendarAlarm"}
*
* Response:
*
* {"alarms":
*   [{"alarmId":1,"key":"calendarAlarm"},
*    {"alarmId":2,"key":"calendarAlarm"},
*   ]}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmQuery(LSHandle *sh, LSMessage *message, void *ctx)
{
	bool retVal;
	const char *serviceName, *key;
	struct json_object *object;
	GString *alarm_str = NULL;
	GString *buf = NULL;

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));
	key = json_object_get_string(
	          json_object_object_get(object, "key"));

	if (!serviceName || !key)
	{
		goto invalid_format;
	}

	alarm_str = g_string_sized_new(512);

	if (!alarm_str)
	{
		goto cleanup;
	}

	bool first = true;
	GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms);

	while (!g_sequence_iter_is_end(iter))
	{
		_Alarm *alarm = (_Alarm *)g_sequence_get(iter);
		GSequenceIter *next = g_sequence_iter_next(iter);

		if (alarm && alarm->serviceName && alarm->key &&
		        (strcmp(alarm->serviceName, serviceName) == 0) &&
		        (strcmp(alarm->key, key) == 0))
		{
			g_string_append_printf(alarm_str,
			                       "%s{\"alarmId\":%d,\"key\":\"%s\"}",
			                       first ? "" : "\n,",
			                       alarm->id, alarm->key);
			first = false;
		}

		iter = next;
	}

	buf = g_string_sized_new(512);
	g_string_append_printf(buf, "{\"alarms\": [%s]}", alarm_str->str);

	LSError lserror;
	LSErrorInit(&lserror);
	retVal = LSMessageReply(sh, message, buf->str, &lserror);

	if (!retVal)
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	goto cleanup;

invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"alarmQuery parameters are missing.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (alarm_str)
	{
		g_string_free(alarm_str, TRUE);
	}

	if (buf)
	{
		g_string_free(buf, TRUE);
	}

	if (!is_error(object))
	{
		json_object_put(object);
	}

	return true;
}
Beispiel #18
0
static bool read_file(LSHandle* lshandle, LSMessage *message, char *filename, bool subscribed) {
  LSError lserror;
  LSErrorInit(&lserror);

  FILE * file = fopen(filename, "r");
  if (!file) {
    sprintf(file_buffer,
	    "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Cannot open %s\"}",
	    filename);
    
    if (!LSMessageReply(lshandle, message, file_buffer, &lserror)) goto error;
    return true;
  }
  
  char chunk[CHUNKSIZE];
  int chunksize = CHUNKSIZE;

  syslog(LOG_DEBUG, "Reading file %s\n", filename);

  fseek(file, 0, SEEK_END);
  int filesize = ftell(file);
  fseek(file, 0, SEEK_SET);

  if (subscribed) {
    if (sprintf(file_buffer,
		"{\"returnValue\": true, \"filesize\": %d, \"chunksize\": %d, \"stage\": \"start\"}",
		filesize, chunksize)) {

      if (!LSMessageReply(lshandle, message, file_buffer, &lserror)) goto error;

    }
  }
  else if (filesize < chunksize) {
    chunksize = filesize;
  }

  int size;
  int datasize = 0;
  while ((size = fread(chunk, 1, chunksize, file)) > 0) {
    datasize += size;
    chunk[size] = '\0';
    sprintf(file_buffer, "{\"returnValue\": true, \"size\": %d, \"contents\": \"", size);
    strcat(file_buffer, json_escape_str(chunk, file_esc_buffer));
    strcat(file_buffer, "\"");
    if (subscribed) {
      strcat(file_buffer, ", \"stage\": \"middle\"");
    }
    strcat(file_buffer, "}");

    if (!LSMessageReply(lshandle, message, file_buffer, &lserror)) goto error;

  }

  if (!fclose(file)) {
    if (subscribed) {
      sprintf(file_buffer, "{\"returnValue\": true, \"datasize\": %d, \"stage\": \"end\"}", datasize);

      if (!LSMessageReply(lshandle, message, file_buffer, &lserror)) goto error;

    }
  }
  else {
    sprintf(file_buffer, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Cannot close file\"}");

    if (!LSMessageReply(lshandle, message, file_buffer, &lserror)) goto error;

  }

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

	LSError lserror;
	LSErrorInit(&lserror);

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

	// Extract the id argument from the message
	json_t *object = json_parse_document(LSMessageGetPayload(message));
	json_t *ssid = json_find_first_label(object, "ssid");
	json_t *preferedDNS = json_find_first_label(object, "preferedDNS");
	json_t *alternateDNS = json_find_first_label(object, "alternateDNS");
               
	log("ssid: %s, preferedDNS: %s, alternateDNS: %s", ssid->child->text, preferedDNS->child->text, alternateDNS->child->text);

	if (!ssid || (ssid->child->type != JSON_STRING) ||
		!preferedDNS || (preferedDNS->child->type != JSON_STRING) ||
		!alternateDNS || (alternateDNS->child->type != JSON_STRING))
	{
		if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing parameters\"}", &lserror))
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);

			return false;
		}
	}

	stopPalmWifiService();
	detectHardware();
	restartNetworkCard();
	if(configureWifiInterface(ssid->child->text) == true)
	{
		const char* address = getDhcpAddress();

		// If we got an IP address then update the DNS
		if(address != NULL)
		{
			// If the user passed in both dns options blank, then we'll use the obtained IP address for dns forwarding
			if(strlen(preferedDNS->child->text) == 0 && strlen(alternateDNS->child->text) == 0)
			{
				updateDns(address);
			}
			else
			{
				if(strlen(preferedDNS->child->text) > 0)
				{
					updateDns(preferedDNS->child->text);
				}

				if(strlen(alternateDNS->child->text) > 0)
				{
					updateDns(alternateDNS->child->text);
				}
			}
			sprintf(reply, "{\"returnValue\": true, \"address\": \"%s\"}", address);
		}
		else
		{
			// We didn't managed to get an IP address from the Ad-Hoc access point, so retart the Palm Wi-Fi Service
			startPalmWifiService();
			sprintf(reply, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Unable to obtain IP address\"}");
		}
	}
	else
	{
		// We didn't managed to configure the network interface
		startPalmWifiService();
		sprintf(reply, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Error configuring network interface\"}");
	}

	log(reply);

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

		return false;
	}

	return true;
}
bool AmbientLightSensor::controlStatus(LSHandle *sh, LSMessage *message, void *ctx)
{
#if defined (TARGET_DEVICE)
    LSError lserror;
    LSErrorInit(&lserror);
    bool result = true;

    AmbientLightSensor *als = (AmbientLightSensor*)ctx;

    // {"subscribe":boolean, "disableALS" : boolean}
    VALIDATE_SCHEMA_AND_RETURN(sh,
                               message,
                               SCHEMA_2(REQUIRED(subscribe, boolean), REQUIRED(disableALS, boolean)));

    g_debug ("%s: received '%s;", __PRETTY_FUNCTION__, LSMessageGetPayload(message));

    bool subscribed = false;

    result = LSSubscriptionProcess (sh, message, &subscribed, &lserror);
    if(!result)
    {
        LSErrorFree (&lserror);
        result = true;
        subscribed = false;
    }

    if (subscribed)
    {
        als->m_alsSubscriptions++;
        als->on ();

		bool disable = false;
		const char* str = LSMessageGetPayload(message);
		if (str) {
			json_object* root = json_tokener_parse(str);
			if (root && !is_error(root)) {
				result = true;
	    	    disable = json_object_get_boolean(json_object_object_get(root, "disableALS"));
				json_object_put(root);
			}
		}

        if (disable)
            als->m_alsDisabled++;
    }

    int ptr = (als->m_alsPointer + als->m_alsSamplesNeeded - 1) % als->m_alsSamplesNeeded;
    gchar *status = g_strdup_printf ("{\"returnValue\":true,\"current\":%i,\"average\":%i,\"disabled\":%s,\"subscribed\":%s}",
            als->m_alsValue[ptr], als->m_alsSum / als->m_alsSamplesNeeded, als->m_alsDisabled > 0 ? "true" : "false", 
            subscribed ? "true" : "false");

    if (NULL != status)
        result = LSMessageReply(sh, message, status, &lserror);
    if(!result)
    {
        LSErrorPrint (&lserror, stderr);
        LSErrorFree (&lserror);
    }

    g_free(status);
#endif
    return true;
}
//static 
bool ImageServices::lsConvertImage(LSHandle* lsHandle, LSMessage* message,void* user_data)
{
	LSError lserror;
	LSErrorInit(&lserror);
	std::string errorText;
	json_object * root = NULL;
	json_object * label = NULL;
	const char* str;
	int rc;
	bool specOn = false;
	std::string srcfile;
	std::string destfile;
	std::string desttype;
	double focusX = -1;
	double focusY = -1;
	double scale = -1;
	uint32_t cropW = 0;
	uint32_t cropH = 0;

    // {"src": string, "dest": string, "destType": string, "focusX": double, "focusY": double, "scale": double, "cropW": double, "cropH": double}
    VALIDATE_SCHEMA_AND_RETURN(lsHandle,
                               message,
                               SCHEMA_8(REQUIRED(src, string), REQUIRED(dest, string), REQUIRED(destType, string), REQUIRED(focusX, double), REQUIRED(focusY, double), REQUIRED(scale, double), REQUIRED(cropW, double), REQUIRED(cropH, double)));

	
	ImageServices * pImgSvc = instance();
	if (pImgSvc == NULL) {
		errorText = "Image Service has not started";
		goto Done_lsConvertImage;
	}

	if (pImgSvc->isValid() == false) {
		errorText = "Image Service has not started (failed init)";
		goto Done_lsConvertImage;
	}
	
	str = LSMessageGetPayload( message );
	if (!str) {
		errorText = "No payload provided";
		goto Done_lsConvertImage;
	}

	root = json_tokener_parse( str );
	if (!root || is_error(root)) {
		errorText = "Malformed JSON detected in payload";
		root = 0;
		goto Done_lsConvertImage;
	}
	
	if (Utils::extractFromJson(root,"src",srcfile) == false) {
		errorText = "'src' parameter missing";
		goto Done_lsConvertImage;
	}
	if (Utils::extractFromJson(root,"dest",destfile) == false) {
		errorText = "'dest' parameter missing";
		goto Done_lsConvertImage;
	}
	if (Utils::extractFromJson(root,"destType",desttype) == false) {
		errorText = "'destType' parameter missing";
		goto Done_lsConvertImage;
	}

	if ((label = Utils::JsonGetObject(root,"focusX")) != NULL) {
		focusX = json_object_get_double(label);
		if ((focusX < 0) || (focusX > 1)) {
			errorText = "'focusX' parameter out of range (must be [0.0,1.0] )";
			goto Done_lsConvertImage;
		}
		specOn = true;
	}
	if ((label = Utils::JsonGetObject(root,"focusY")) != NULL) {
		focusY = json_object_get_double(label);
		if ((focusY < 0) || (focusY > 1)) {
			errorText = "'focusY' parameter out of range (must be [0.0,1.0] )";
			goto Done_lsConvertImage;
		}
		specOn = true;
	}
	if ((label = Utils::JsonGetObject(root,"scale")) != NULL) {
		scale = json_object_get_double(label);
		if (scale <= 0) {
			errorText = "'scale' parameter out of range ( must be > 0.0 )";
			goto Done_lsConvertImage;
		}
		specOn = true;
	}
	if ((label = Utils::JsonGetObject(root,"cropW")) != NULL) {
		cropW = json_object_get_double(label);
		if (cropW < 0) {
			errorText = "'cropW' parameter out of range (must be > 0 )";
			goto Done_lsConvertImage;
		}
		specOn = true;
	}
	if ((label = Utils::JsonGetObject(root,"cropH")) != NULL) {
		cropH = json_object_get_double(label);
		if (cropH < 0) {
			errorText = "'cropH' parameter out of range (must be > 0 )";
			goto Done_lsConvertImage;
		}
		specOn = true;
	}
	
	/*
	 * 
	 * bool convertImage(const std::string& pathToSourceFile,
			const std::string& pathToDestFile,int destType,
			double focusX,double focusY,double scale,
			uint32_t widthFinal,uint32_t heightFinal,
			std::string& r_errorText);
	
	bool convertImage(const std::string& pathToSourceFile,
			const std::string& pathToDestFile,int destType,
			std::string& r_errorText);
			
	 * 
	 */
    if (specOn) {
        rc = ImageServices::instance()->convertImage(srcfile, destfile, desttype.c_str(),
                                                     focusX, focusY,
                                                     scale,
                                                     cropW, cropH,
                                                     errorText);
    }
    else {
        // the "just transcode" version of convert is called
        rc = ImageServices::instance()->convertImage(srcfile, destfile, desttype.c_str(), errorText);
    }
	
Done_lsConvertImage:

	if (root)
		json_object_put(root);

	json_object * reply = json_object_new_object();
	json_object_object_add(reply, "subscribed", json_object_new_boolean(false));
	if (errorText.size() > 0) {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(false));
		json_object_object_add(reply, "errorCode", json_object_new_string(errorText.c_str()));
	}
	else {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(true));
	}

	if (!LSMessageReply(lsHandle, message, json_object_to_json_string(reply), &lserror))
		LSErrorFree (&lserror);

	json_object_put(reply);

	return true;
}
//static
bool ImageServices::lsEzResize(LSHandle* lsHandle, LSMessage* message,void* user_data)
{
	LSError lserror;
	LSErrorInit(&lserror);
	std::string errorText;
	json_object * root = NULL;
	json_object * label = NULL;
	const char* str;
	std::string srcfile;
	std::string destfile;
	std::string desttype;
	uint32_t destSizeW = 0;
	uint32_t destSizeH = 0;

    // {"src": string, "dest": string, "destType": string, "destSizeW": integer, "destSizeH": integer}
    VALIDATE_SCHEMA_AND_RETURN(lsHandle,
                               message,
                               SCHEMA_5(REQUIRED(src, string), REQUIRED(dest, string), REQUIRED(destType, string), REQUIRED(destSizeW, integer), REQUIRED(destSizeH, integer)));

	ImageServices * pImgSvc = instance();
	if (pImgSvc == NULL) {
		errorText = "Image Service has not started";
		goto Done_ezResize;
	}

	if (pImgSvc->isValid() == false) {
		errorText = "Image Service has not started (failed init)";
		goto Done_ezResize;
	}

	str = LSMessageGetPayload( message );
	if (!str) {
		errorText = "No payload provided";
		goto Done_ezResize;
	}

	root = json_tokener_parse( str );
	if (!root || is_error(root)) {
		errorText = "Malformed JSON detected in payload";
		root = 0;
		goto Done_ezResize;
	}

	if (Utils::extractFromJson(root,"src",srcfile) == false) {
		errorText = "'src' parameter missing";
		goto Done_ezResize;
	}
	if (Utils::extractFromJson(root,"dest",destfile) == false) {
		errorText = "'dest' parameter missing";
		goto Done_ezResize;
	}
	if (Utils::extractFromJson(root,"destType",desttype) == false) {
		errorText = "'destType' parameter missing";
		goto Done_ezResize;
	}

	if ((label = Utils::JsonGetObject(root,"destSizeW")) != NULL)
	{
		destSizeW = json_object_get_int(label);
	}
	else
	{
		errorText = "'destSizeW' missing";
		goto Done_ezResize;
	}
	if ((label = Utils::JsonGetObject(root,"destSizeH")) != NULL)
	{
		destSizeH = json_object_get_int(label);
	}
	else
	{
		errorText = "'destSizeH' missing";
		goto Done_ezResize;
	}

    (void)ImageServices::instance()->ezResize(srcfile, destfile, desttype.c_str(), destSizeW, destSizeH, errorText);

Done_ezResize:

	if (root)
		json_object_put(root);

	json_object * reply = json_object_new_object();
	json_object_object_add(reply, "subscribed", json_object_new_boolean(false));
	if (errorText.size() > 0) {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(false));
		json_object_object_add(reply, "errorCode", json_object_new_string(errorText.c_str()));
	}
	else {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(true));
	}

	if (!LSMessageReply(lsHandle, message, json_object_to_json_string(reply), &lserror))
		LSErrorFree (&lserror);

	json_object_put(reply);

	return true;
}
Beispiel #23
0
/**
* @brief Remove an alarm by id.
*
* {"alarmId":1}
*
* Response:
*
* {"returnValue":true}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmRemove(LSHandle *sh, LSMessage *message, void *ctx)
{
	LSError lserror;
	LSErrorInit(&lserror);

	bool found = false;
	bool retVal;

	const char *payload = LSMessageGetPayload(message);
	struct json_object *object = json_tokener_parse(payload);

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("alarmRemove() : %s", LSMessageGetPayload(message));

	int alarmId =
	    json_object_get_int(json_object_object_get(object, "alarmId"));

	GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms);

	while (!g_sequence_iter_is_end(iter))
	{
		_Alarm *alarm = (_Alarm *)g_sequence_get(iter);
		GSequenceIter *next = g_sequence_iter_next(iter);

		if (alarm && alarm->id == alarmId)
		{
			char *timeout_key = g_strdup_printf("%s-%d", alarm->key, alarm->id);
			_timeout_clear("com.palm.sleep", timeout_key,
			               false /*public_bus*/);
			g_free(timeout_key);

			g_sequence_remove(iter);
			found = true;
		}

		iter = next;
	}

	const char *response;

	if (found)
	{
		alarm_write_db();
		response = "{\"returnValue\":true}";
	}
	else
	{
		response = "{\"returnValue\":false}";
	}

	retVal = LSMessageReply(sh, message, response, &lserror);

	if (!retVal)
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	return true;
}
//static
bool ImageServices::lsImageInfo(LSHandle* lsHandle, LSMessage* message,void* user_data)
{
	LSError lserror;
	LSErrorInit(&lserror);
	std::string errorText;
	json_object * root = NULL;
	const char* str;
	std::string srcfile;
	int srcWidth;
	int srcHeight;
	int srcBpp;
    const char* srcType;
    // {"src": string}
    VALIDATE_SCHEMA_AND_RETURN(lsHandle,
                               message,
                               SCHEMA_1(REQUIRED(src, string)));

	ImageServices * pImgSvc = instance();
	if (pImgSvc == NULL) {
		errorText = "Image Service has not started";
		goto Done_lsImageInfo;
	}

	if (pImgSvc->isValid() == false) {
		errorText = "Image Service has not started (failed init)";
		goto Done_lsImageInfo;
	}

	str = LSMessageGetPayload( message );
	if (!str) {
		errorText = "No payload provided";
		goto Done_lsImageInfo;
	}

	root = json_tokener_parse( str );
	if (!root || is_error(root)) {
		errorText = "Malformed JSON detected in payload";
		root = 0;
		goto Done_lsImageInfo;
	}

	if (Utils::extractFromJson(root,"src",srcfile) == false) {
		errorText = "'src' parameter missing";
		goto Done_lsImageInfo;
	}

    {
        QImageReader reader(QString::fromStdString(srcfile));
        if(!reader.canRead()) {
            errorText = reader.errorString().toStdString();
            return false;
            goto Done_lsImageInfo;
        }
        srcWidth = reader.size().width();
        srcHeight = reader.size().height();
        // QImageReader probably won't return all of these, but just to make sure we cover all cases
        switch(reader.imageFormat()) {
            case QImage::Format_ARGB32_Premultiplied:
            case QImage::Format_ARGB32:
            case QImage::Format_RGB32:
            srcBpp = 32; break;
            case QImage::Format_RGB888:
            case QImage::Format_RGB666:
            case QImage::Format_ARGB8565_Premultiplied:
            case QImage::Format_ARGB6666_Premultiplied:
            case QImage::Format_ARGB8555_Premultiplied:
            srcBpp = 24; break;
            case QImage::Format_RGB444:
            case QImage::Format_ARGB4444_Premultiplied:
            case QImage::Format_RGB16:
            case QImage::Format_RGB555:
            srcBpp = 16; break;
            case QImage::Format_Indexed8:
            srcBpp = 8; break;
            case QImage::Format_Mono:
            case QImage::Format_MonoLSB:
            srcBpp = 1; break;
            default:
            srcBpp = 0;
        }
       srcType = reader.format(); // png/jpg etc
    }

Done_lsImageInfo:

	if (root)
		json_object_put(root);

	json_object * reply = json_object_new_object();
	json_object_object_add(reply, "subscribed", json_object_new_boolean(false));
	if (errorText.size() > 0) {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(false));
		json_object_object_add(reply, "errorCode", json_object_new_string(errorText.c_str()));
	}
	else {
		json_object_object_add(reply, "returnValue", json_object_new_boolean(true));
		json_object_object_add(reply, "width",json_object_new_int(srcWidth));
		json_object_object_add(reply, "height",json_object_new_int(srcHeight));
		json_object_object_add(reply, "bpp",json_object_new_int(srcBpp));
		json_object_object_add(reply, "type", json_object_new_string(srcType));
	}

	if (!LSMessageReply(lsHandle, message, json_object_to_json_string(reply), &lserror))
		LSErrorFree (&lserror);

	json_object_put(reply);

	return true;
}
Beispiel #25
0
/**
* @brief Set a calendar event.
*
* luna://com.palm.sleep/time/alarmAddCalendar
*
* Message:
* Set alarm to expire at a fixed calendar time in UTC. Response will be sent
* as a call to "luna://com.palm.X/alarm".
*
* {"key":"calendarAlarm", "serviceName":"com.palm.X",
*  "date":"01-02-2009", "time":"13:40:03"}
*
* Subscribing indicates that you want the alarm message as a response to
* the current call.
*
* {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X",
*  "date":"01-02-2009", "time":"13:40:03"}
*
* Response:
*
* Alarm is sucessfully registered for calendar date
* {"alarmId":1}
*
* Subscribe case:
* {"alarmId":1,"subscribed":true}
* {"alarmId":1,"fired":true}
*
* Alarm failed to be registered:
*
* {"returnValue":false, ...}
* {"returnValue":false,"serivceName":"com.palm.sleep",
*  "errorText":"com.palm.sleep is not running"}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmAddCalendar(LSHandle *sh, LSMessage *message, void *ctx)
{
	int alarm_id;
	struct json_object *object;
	const char *key, *serviceName, *applicationName, *cal_date, *cal_time;
	struct tm gm_time;
	bool subscribe;
	bool retVal = false;
	gchar **cal_date_str;

	time_t alarm_time = 0;

	LSError lserror;
	LSErrorInit(&lserror);

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("alarmAddCalendar() : %s", LSMessageGetPayload(message));

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));

	applicationName = LSMessageGetApplicationID(message);

	key = json_object_get_string(json_object_object_get(object, "key"));

	cal_date = json_object_get_string(
	               json_object_object_get(object, "date"));
	cal_time = json_object_get_string(
	               json_object_object_get(object, "time"));


	if (!cal_date || !cal_time)
	{
		goto invalid_format;
	}

	int hour, min, sec;
	int month, day, year;

	if (!ConvertJsonTime(cal_time, &hour, &min, &sec))
	{
		goto invalid_format;
	}

	cal_date_str = g_strsplit(cal_date, "-", 3);

	if ((NULL == cal_date_str[0]) || (NULL == cal_date_str[1]) ||
	        (NULL == cal_date_str[2]))
	{
		goto invalid_format;
	}

	month = atoi(cal_date_str[0]);
	day = atoi(cal_date_str[1]);
	year = atoi(cal_date_str[2]);
	g_strfreev(cal_date_str);

	if (hour < 0 || hour > 24 || min < 0 || min > 59 ||
	        sec < 0 || sec > 59 ||
	        month < 1 || month > 12 || day < 1 || day > 31 || year < 0)
	{
		goto invalid_format;
	}

	SLEEPDLOG_DEBUG("alarmAddCalendar() : (%s %s %s) at %s %s", serviceName,
	                applicationName, key, cal_date, cal_time);

	struct json_object *subscribe_json =
	    json_object_object_get(object, "subscribe");

	subscribe = json_object_get_boolean(subscribe_json);

	memset(&gm_time, 0, sizeof(struct tm));

	gm_time.tm_hour = hour;
	gm_time.tm_min = min;
	gm_time.tm_sec = sec;
	gm_time.tm_mon = month - 1; // month-of-year [0-11]
	gm_time.tm_mday = day;      // day-of-month [1-31]
	gm_time.tm_year = year - 1900;

	/* timegm converts time(GMT) -> seconds since epoch */
	alarm_time = timegm(&gm_time);

	if (alarm_time < 0)
	{
		goto invalid_format;
	}

	retVal = alarm_queue_new(key, true, alarm_time,
	                         serviceName, applicationName, subscribe, message, &alarm_id);

	if (!retVal)
	{
		goto error;
	}

	/*****************
	 * Use new timeout API
	 */
	{
		char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id);
		_AlarmTimeout timeout;
		_timeout_create(&timeout, "com.palm.sleep", timeout_key,
		                "luna://com.palm.sleep/time/internalAlarmFired",
		                "{}",
		                false /*public bus*/,
		                true /*wakeup*/,
		                "" /*activity_id*/,
		                0 /*activity_duration_ms*/,
		                true /*calendar*/,
		                alarm_time);

		retVal = _timeout_set(&timeout);

		g_free(timeout_key);

		if (!retVal)
		{
			goto error;
		}
	}
	/*****************/

	/* Send alarm id of sucessful alarm add. */
	GString *reply = g_string_sized_new(512);
	g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id);

	if (subscribe_json)
	{
		g_string_append_printf(reply, ",\"subscribed\":%s",
		                       subscribe ? "true" : "false");
	}

	g_string_append_printf(reply, "}");

	retVal = LSMessageReply(sh, message, reply->str, &lserror);

	g_string_free(reply, TRUE);

	goto cleanup;
error:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Unknown error\"}", &lserror);
	goto cleanup;
invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Invalid format for alarm time.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	if (!retVal && LSErrorIsSet(&lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	return true;
}
bool
_LSPrivateDoMallocTrim(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    struct json_object *ret_obj = NULL;
    struct json_object *true_obj = NULL;
    struct json_object *malloc_trim_obj = NULL;

    ret_obj = json_object_new_object();
    if (JSON_ERROR(ret_obj)) goto error;
       
    true_obj = json_object_new_boolean(true);
    if (JSON_ERROR(true_obj)) goto error;
 

    /* returnValue: true,
     * malloc_trim: int
     */

    typedef int (*malloc_trim_t)(size_t);
    static malloc_trim_t malloc_trim_p = NULL;

    if (malloc_trim_p == NULL) {
        malloc_trim_p = (malloc_trim_t)dlsym(RTLD_DEFAULT, "malloc_trim");
        if (malloc_trim_p == NULL)
            malloc_trim_p = (malloc_trim_t)-1;
    }
    
    int result;
    if (malloc_trim_p != (malloc_trim_t)-1) {
        result = malloc_trim_p(0);
    } else {
        result = -1;
    }

    malloc_trim_obj = json_object_new_int(result);
    if (JSON_ERROR(malloc_trim_obj)) goto error;
        
    json_object_object_add(ret_obj, "returnValue", true_obj);
    json_object_object_add(ret_obj, "malloc_trim", malloc_trim_obj);

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending malloc trim result failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    json_object_put(ret_obj);
    
    return true;

error:
    
    if (!JSON_ERROR(ret_obj)) json_object_put(ret_obj);
    if (!JSON_ERROR(true_obj)) json_object_put(true_obj);
    if (!JSON_ERROR(malloc_trim_obj)) json_object_put(malloc_trim_obj);
    
    return true;
}
bool
_LSPrivateInrospection(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    GHashTableIter iter_category, iter_element;
    gpointer name_category, table_category, name_element, callback;
    struct LSCategoryTable *pTable = NULL;

    struct json_object *ret_obj = NULL;
    struct json_object *category_obj = NULL;
    struct json_object *element_obj = NULL;

    ret_obj = json_object_new_object();

    g_hash_table_iter_init(&iter_category, sh->tableHandlers);
    while (g_hash_table_iter_next(&iter_category, &name_category, &table_category))
    {
        // skip hidden method
        if (strcmp("/com/palm/luna/private", name_category) == 0)
            continue;

        pTable = (struct LSCategoryTable *)table_category;
        category_obj = json_object_new_object();

        // methods
        g_hash_table_iter_init(&iter_element, pTable->methods);
        while (g_hash_table_iter_next(&iter_element, &name_element, &callback))
        {
            element_obj = json_object_new_string("METHOD");
            json_object_object_add(category_obj, name_element, element_obj);
        }

        // signals
        g_hash_table_iter_init(&iter_element, pTable->signals);
        while (g_hash_table_iter_next(&iter_element, &name_element, &callback))
        {
            element_obj = json_object_new_string("SIGNAL");
            json_object_object_add(category_obj, name_element, element_obj);
        }

        json_object_object_add(ret_obj, name_category, category_obj);
    }

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending introspection data failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
        goto error;
    }

    json_object_put(ret_obj);

    return true;

error:

    if (!JSON_ERROR(ret_obj)) json_object_put(ret_obj);
    if (!JSON_ERROR(category_obj)) json_object_put(category_obj);
    if (!JSON_ERROR(element_obj)) json_object_put(element_obj);

    return false;
}
Beispiel #28
0
/**
* @brief Sends a "/alarm" message to the service associated with this alarm.
*
* {"alarmId":1,"fired":true,"key":"appkey"}
*
* @param  alarm
*/
static void
fire_alarm(_Alarm *alarm)
{
	bool retVal;
	char buf_alarm[STD_ASCTIME_BUF_SIZE];

	struct tm tm_alarm;
	time_t rtctime = 0;

	gmtime_r(&alarm->expiry, &tm_alarm);
	asctime_r(&tm_alarm, buf_alarm);

	nyx_system_query_rtc_time(GetNyxSystemDevice(), &rtctime);

	SLEEPDLOG_DEBUG("fire_alarm() : Alarm (%s %s %s) fired at %s (rtc %ld)",
	                alarm->serviceName,
	                alarm->applicationName, alarm->key, buf_alarm, rtctime);

	GString *payload = g_string_sized_new(255);
	g_string_append_printf(payload, "{\"alarmId\":%d,\"fired\":true", alarm->id);

	if (alarm->key)
	{
		g_string_append_printf(payload, ",\"key\":\"%s\"", alarm->key);
	}

	if (alarm->applicationName && strcmp(alarm->applicationName, "") != 0)
	{
		g_string_append_printf(payload, ",\"applicationName\":\"%s\"",
		                       alarm->applicationName);
	}

	g_string_append_printf(payload, "}");

	LSError lserror;
	LSErrorInit(&lserror);

	if (alarm->serviceName && strcmp(alarm->serviceName, "") != 0)
	{
		char *uri = g_strdup_printf("luna://%s/alarm", alarm->serviceName);
		retVal = LSCall(GetLunaServiceHandle(), uri, payload->str,
		                NULL, NULL, NULL, &lserror);

		if (!retVal)
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);
		}

		g_free(uri);
	}

	if (alarm->message)
	{
		retVal = LSMessageReply(GetLunaServiceHandle(), alarm->message,
		                        payload->str, &lserror);

		if (!retVal)
		{
			LSErrorPrint(&lserror, stderr);
			LSErrorFree(&lserror);
		}
	}

	g_string_free(payload, TRUE);
}
bool
_LSPrivateGetMallinfo(LSHandle* sh, LSMessage *message, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);

    struct json_object *ret_obj = NULL;
    struct json_object *true_obj = NULL;
    struct json_object *mallinfo_obj = NULL;
    struct json_object *allocator_name_obj = NULL;
    struct json_object *slot_a_obj = NULL;
    struct json_object *slot_d_obj = NULL;
    struct json_object *slot_e_obj = NULL;
    struct json_object *slot_f_obj = NULL;
    struct json_object *slot_h_obj = NULL;
    struct json_object *slot_i_obj = NULL;
    struct json_object *slot_j_obj = NULL;

    const char *sender = LSMessageGetSenderServiceName(message);

    if (!sender || strcmp(sender, MONITOR_NAME) != 0)
    {
        g_critical("WARNING: mallinfo debug method not called by monitor;"
                   " ignoring (service name: %s, unique_name: %s)",
                   sender, LSMessageGetSender(message));
        return true;
    }

    ret_obj = json_object_new_object();
    if (JSON_ERROR(ret_obj)) goto error;
       
    true_obj = json_object_new_boolean(true);
    if (JSON_ERROR(true_obj)) goto error;
 
    mallinfo_obj = json_object_new_object();
    if (JSON_ERROR(mallinfo_obj)) goto error;

    /* returnValue: true,
     * mallinfo: {key: int,...}
     */

    typedef struct mallinfo (*mallinfo_t)();
    static mallinfo_t mallinfo_p = NULL;

    if (mallinfo_p == NULL) {
        mallinfo_p = (mallinfo_t)dlsym(RTLD_DEFAULT, "mallinfo");
        if (mallinfo_p == NULL)
            mallinfo_p = (mallinfo_t)-1;
    }
    struct mallinfo mi;
    if (mallinfo_p != (mallinfo_t)-1) {
        mi = mallinfo_p();
    } else {
        memset(&mi, '\0', sizeof(mi));
    }
    
    allocator_name_obj = json_object_new_string("ptmalloc");
    if (JSON_ERROR(allocator_name_obj)) goto error;

    slot_a_obj = json_object_new_int(mi.arena);
    if (JSON_ERROR(slot_a_obj)) goto error;

    slot_d_obj = json_object_new_int(mi.hblks);
    if (JSON_ERROR(slot_d_obj)) goto error;

    slot_e_obj = json_object_new_int(mi.hblkhd);
    if (JSON_ERROR(slot_e_obj)) goto error;

    slot_f_obj = json_object_new_int(mi.usmblks);
    if (JSON_ERROR(slot_f_obj)) goto error;

    slot_h_obj = json_object_new_int(mi.uordblks);
    if (JSON_ERROR(slot_h_obj)) goto error;

    slot_i_obj = json_object_new_int(mi.fordblks);
    if (JSON_ERROR(slot_i_obj)) goto error;
    
    slot_j_obj = json_object_new_int(mi.keepcost);
    if (JSON_ERROR(slot_j_obj)) goto error;

    json_object_object_add(mallinfo_obj, "allocator", allocator_name_obj);
    json_object_object_add(mallinfo_obj, "sbrk_bytes", slot_a_obj);
    json_object_object_add(mallinfo_obj, "mmap_count", slot_d_obj);
    json_object_object_add(mallinfo_obj, "mmap_bytes", slot_e_obj);
    json_object_object_add(mallinfo_obj, "max_malloc_bytes", slot_f_obj);
    json_object_object_add(mallinfo_obj, "malloc_bytes", slot_h_obj);
    json_object_object_add(mallinfo_obj, "slack_bytes", slot_i_obj);
    json_object_object_add(mallinfo_obj, "trimmable_slack_bytes", slot_j_obj);
        
    json_object_object_add(ret_obj, "returnValue", true_obj);
    json_object_object_add(ret_obj, "mallinfo", mallinfo_obj);

    bool reply_ret = LSMessageReply(sh, message, json_object_to_json_string(ret_obj), &lserror);
    if (!reply_ret)
    {
        g_critical("%s: sending malloc info failed", __FUNCTION__);
        LSErrorPrint(&lserror, stderr);
        LSErrorFree(&lserror);
    }

    json_object_put(ret_obj);
    
    return true;

error:
    
    if (!JSON_ERROR(ret_obj)) json_object_put(ret_obj);
    if (!JSON_ERROR(true_obj)) json_object_put(true_obj);
    if (!JSON_ERROR(mallinfo_obj)) json_object_put(mallinfo_obj);
    
    if (!JSON_ERROR(allocator_name_obj)) json_object_put(allocator_name_obj);
    if (!JSON_ERROR(slot_a_obj)) json_object_put(slot_a_obj);
    if (!JSON_ERROR(slot_d_obj)) json_object_put(slot_d_obj);
    if (!JSON_ERROR(slot_e_obj)) json_object_put(slot_e_obj);
    if (!JSON_ERROR(slot_f_obj)) json_object_put(slot_f_obj);
    if (!JSON_ERROR(slot_h_obj)) json_object_put(slot_h_obj);
    if (!JSON_ERROR(slot_i_obj)) json_object_put(slot_i_obj);
    if (!JSON_ERROR(slot_j_obj)) json_object_put(slot_j_obj);
    
    return true;
}
Beispiel #30
0
/**
* @brief  Set alarm to fire in a fixed time in the future.
*
* luna://com.palm.sleep/time/alarmAdd
*
* Set alarm to expire in T+5hrs. Response will be sent
* as a call to "luna://com.palm.X/alarm".
*
* {"key":"calendarAlarm", "serviceName":"com.palm.X",
*  "relative_time":"05:00:00"}
*
* Subscribing indicates that you want the alarm message as a response to
* the current call.
*
* {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X",
*  "relative_time":"05:00:00"}
*
* Alarm is sucessfully registered.
* {"alarmId":1}
*
* Alarm failed to be registered:
*
* {"returnValue":false, ...}
* {"returnValue":false,"serivceName":"com.palm.sleep",
*  "errorText":"com.palm.sleep is not running"}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmAdd(LSHandle *sh, LSMessage *message, void *ctx)
{
	time_t alarm_time = 0;
	int rel_hour, rel_min, rel_sec;

	const char *key, *serviceName, *applicationName, *rel_time;
	bool subscribe;

	struct json_object *object;

	int alarm_id;
	bool retVal = false;

	LSError lserror;
	LSErrorInit(&lserror);
	time_t rtctime = 0;

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("%s", LSMessageGetPayload(message));

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));

	applicationName = LSMessageGetApplicationID(message);

	key = json_object_get_string(json_object_object_get(object, "key"));

	rel_time = json_object_get_string(
	               json_object_object_get(object, "relative_time"));

	if (!rel_time)
	{
		goto invalid_format;
	}

	if (!ConvertJsonTime(rel_time, &rel_hour, &rel_min, &rel_sec) ||
	        (rel_hour < 0 || rel_hour > 24 || rel_min < 0 || rel_min > 59 || rel_sec < 0 ||
	         rel_sec > 59))
	{
		goto invalid_format;
	}

	nyx_system_query_rtc_time(GetNyxSystemDevice(), &rtctime);

	SLEEPDLOG_DEBUG("alarmAdd(): (%s %s %s) in %s (rtc %ld)", serviceName,
	                applicationName, key, rel_time, rtctime);
	struct json_object *subscribe_json =
	    json_object_object_get(object, "subscribe");

	subscribe = json_object_get_boolean(subscribe_json);


	alarm_time = reference_time();
	alarm_time += rel_sec;
	alarm_time += rel_min * 60;
	alarm_time += rel_hour * 60 * 60;

	retVal = alarm_queue_new(key, false, alarm_time,
	                         serviceName, applicationName, subscribe, message, &alarm_id);

	if (!retVal)
	{
		goto error;
	}

	/*****************
	 * Use new timeout API
	 */
	{
		char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id);
		_AlarmTimeout timeout;
		_timeout_create(&timeout, "com.palm.sleep", timeout_key,
		                "luna://com.palm.sleep/time/internalAlarmFired",
		                "{}",
		                false /*public bus*/,
		                true /*wakeup*/,
		                "" /*activity_id*/,
		                0 /*activity_duration_ms*/,
		                false /*calendar*/,
		                alarm_time);

		retVal = _timeout_set(&timeout);

		g_free(timeout_key);

		if (!retVal)
		{
			goto error;
		}
	}
	/*****************/

	/* Send alarm id of sucessful alarm add. */
	GString *reply = g_string_sized_new(512);
	g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id);

	if (subscribe_json)
	{
		g_string_append_printf(reply, ",\"subscribed\":%s",
		                       subscribe ? "true" : "false");
	}

	g_string_append_printf(reply, "}");

	retVal = LSMessageReply(sh, message, reply->str, &lserror);

	g_string_free(reply, TRUE);
	goto cleanup;
error:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Unknown error\"}", &lserror);
	goto cleanup;
invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Invalid format for alarm time.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	if (!retVal && LSErrorIsSet(&lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	return true;
}