Exemplo n.º 1
0
bool put_file_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  char buffer[MAXBUFLEN];

  json_t *object = json_parse_document(LSMessageGetPayload(message));
  json_t *id;

  // Extract the url argument from the message
  id = json_find_first_label(object, "filename");
  if (!id || (id->child->type != JSON_STRING) ||
      (strlen(id->child->text) >= MAXLINLEN) ||
      (strlen(id->child->text) < 8) ||
      strncmp(id->child->text, "file://", 7)) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, "
			"\"errorText\": \"Invalid or missing filename parameter\"}",
			&lserror)) goto error;
    return true;
  }
  char filename[MAXLINLEN];
  strcpy(filename, id->child->text+7);

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

  char contents[MAXLINLEN];
  strncpy(contents, id->child->text,MAXLINLEN);

  FILE *fp = fopen(filename, "w");
  if (!fp) {
    sprintf(buffer,
	    "{\"errorText\": \"Unable to open %s\", \"returnValue\": false, \"errorCode\": -1 }",
	    filename);
    if (!LSMessageRespond(message, buffer, &lserror)) goto error;
    return true;
  }

  if (fputs(contents, fp) == EOF) {
    (void)fclose(fp);
    (void)unlink(filename);
    sprintf(buffer,
	    "{\"errorText\": \"Unable to write to %s\", \"returnValue\": false, \"errorCode\": -1 }",
	    filename);
    if (!LSMessageRespond(message, buffer, &lserror)) goto error;
    return true;
  }
  
  if (fclose(fp)) {
    sprintf(buffer,
	    "{\"errorText\": \"Unable to close %s\", \"returnValue\": false, \"errorCode\": -1 }",
	    filename);
    if (!LSMessageRespond(message, buffer, &lserror)) goto error;
    return true;
  }

  if (!LSMessageRespond(message, "{\"returnValue\": true}", &lserror)) goto error;
  return true;

 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemplo n.º 2
0
//
// Get the listing of a directory, and return it's contents.
//
bool get_dir_listing_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

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

  struct dirent *ep;

  // Local buffer to hold each line of output from ls
  char line[MAXLINLEN];

  // Is this the first line of output?
  bool first = true;

  // Was there an error in accessing any of the files?
  bool error = false;

  json_t *object = json_parse_document(LSMessageGetPayload(message));
  json_t *id = json_find_first_label(object, "directory");

  if (!id || (id->child->type != JSON_STRING) || (strspn(id->child->text, ALLOWED_CHARS"/") != strlen(id->child->text))) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing directory\"}",
			&lserror)) goto error;
  }

  // Start execution of the command to list the directory contents
  DIR *dp = opendir(id->child->text);

  // If the command cannot be started
  if (!dp) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Unable to open directory\"}",
			&lserror)) goto error;

    // The error report has been sent, so return to webOS.
    return true;
  }

  // Initialise the output message.
  strcpy(buffer, "{");

  // Loop through the list of directory entries.
  while (ep = readdir(dp)) {

    // Start or continue the JSON array
    if (first) {
      strcat(buffer, "\"contents\": [");
      first = false;
    }
    else {
      strcat(buffer, ", ");
    }

    strcat(buffer, "{\"name\":\"");
    strcat(buffer, json_escape_str(ep->d_name, esc_buffer));
    strcat(buffer, "\", ");

    strcat(buffer, "\"type\":\"");
    if (ep->d_type == DT_DIR) {
      strcat(buffer, "directory");
    }
    else if (ep->d_type == DT_REG) {
      strcat(buffer, "file");
    }
    else if (ep->d_type == DT_LNK) {
      strcat(buffer, "symlink");
    }
    else {
      strcat(buffer, "other");
    }
    strcat(buffer, "\"}");
  }

  // Terminate the JSON array
  if (!first) {
    strcat(buffer, "], ");
  }

  // Check the close status of the process, and return the combined error status
  if (closedir(dp) || error) {
    strcat(buffer, "\"returnValue\": false}");
  }
  else {
    strcat(buffer, "\"returnValue\": true}");
  }

  // Return the results to webOS.
  if (!LSMessageRespond(message, buffer, &lserror)) goto error;

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemplo n.º 3
0
bool get_file_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  char run_command_buffer[MAXBUFLEN];
  char command[MAXLINLEN];

  json_t *object = json_parse_document(LSMessageGetPayload(message));
  json_t *id;

  // Extract the filename argument from the message
  id = json_find_first_label(object, "filename");
  if (!id || (id->child->type != JSON_STRING) ||
      (strlen(id->child->text) >= MAXNAMLEN) ||
      (strspn(id->child->text, ALLOWED_CHARS) != strlen(id->child->text))) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, "
			"\"errorText\": \"Invalid or missing filename parameter\", "
			"\"stage\": \"failed\"}",
			&lserror)) goto error;
    return true;
  }
  char filename[MAXNAMLEN];
  sprintf(filename, "/media/internal/.temp/%s", id->child->text);

  // Extract the url argument from the message
  id = json_find_first_label(object, "url");               
  if (!id || (id->child->type != JSON_STRING) ||
      (strlen(id->child->text) >= MAXLINLEN)) {
    if (!LSMessageRespond(message,
			"{\"returnValue\": false, \"errorCode\": -1, "
			"\"errorText\": \"Invalid or missing url parameter\", "
			"\"stage\": \"failed\"}",
			&lserror)) goto error;
    return true;
  }
  char url[MAXLINLEN];
  strcpy(url, id->child->text);

  if (!strncmp(url, "file://", 7)) {
    strcpy(filename, url+7);
  }
  else {

    /* Download the package */

    snprintf(command, MAXLINLEN,
	     "/usr/bin/curl --create-dirs --insecure --location --fail --show-error --output %s %s 2>&1", filename, url);

    strcpy(run_command_buffer, "{\"stdOut\": [");
    if (run_command(command, true, run_command_buffer)) {
      strcat(run_command_buffer, "], \"returnValue\": true, \"stage\": \"download\"}");
      if (!LSMessageRespond(message, run_command_buffer, &lserror)) goto error;
    }
    else {
      strcat(run_command_buffer, "]");
      if (!report_command_failure(message, command, run_command_buffer+11, "\"stage\": \"failed\"")) goto end;
      return true;
    }
  }

  return read_file(message, filename, true);

 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemplo n.º 4
0
struct audio_service* audio_service_create()
{
	struct audio_service *service;
	LSError error;
	pa_mainloop_api *mainloop_api;
	char name[100];

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

	LSErrorInit(&error);

	if (!LSRegisterPubPriv("org.webosports.audio", &service->handle, false, &error)) {
		g_warning("Failed to register the luna service: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

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

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

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

	service->pa_mainloop = pa_glib_mainloop_new(g_main_context_default());
	mainloop_api = pa_glib_mainloop_get_api(service->pa_mainloop);

	snprintf(name, 100, "AudioServiceContext:%i", getpid());
	service->context = pa_context_new(mainloop_api, name);
	service->context_initialized = false;
	pa_context_set_state_callback(service->context, context_state_cb, service);

	if (pa_context_connect(service->context, NULL, 0, NULL) < 0) {
		g_warning("Failed to connect to PulseAudio");
		pa_context_unref(service->context);
		pa_glib_mainloop_free(service->pa_mainloop);
		goto error;
	}

	sample_list = g_slist_alloc();

	return service;

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

	g_free(service);

	return NULL;
}
Exemplo n.º 5
0
//
// Impersonate a call to the requested service and return the output to webOS.
//
bool impersonate_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  bool retVal;
  LSError lserror;
  LSErrorInit(&lserror);
  LSMessageRef(message);

  if (access_denied(message)) return true;

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

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

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

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

  char uri[MAXLINLEN];
  sprintf(uri, "palm://%s/%s", service->child->text, method->child->text);

  char *paramstring = NULL;
  json_tree_to_string (params->child, &paramstring);
  if (!LSCallFromApplication(priv_serviceHandle, uri, paramstring, id->child->text,
			     impersonate_handler, message, NULL, &lserror)) goto error;

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemplo n.º 6
0
/*!
\page com_palm_systemservice_timezone
\n
\section com_palm_systemservice_timezone_get_time_zone_rules getTimeZoneRules

\e Public.

com.palm.systemservice/timezone/getTimeZoneRules

\subsection com_palm_systemservice_timezone_get_time_zone_rules_syntax Syntax:
\code
[
    {
        "tz": string
        "years": [int array]
    }
]
\endcode

\param tz The timezone for which to get information. Required.
\param years Array of years for which to get information. If not specified, information for the current year is returned.

\subsection com_palm_systemservice_timezone_get_time_zone_rules_returns Returns:
\code
{
    "returnValue": true,
    "results": [
        {
            "tz": string,
            "year": int,
            "hasDstChange": false,
            "utcOffset": int,
            "dstOffset": int,
            "dstStart": int,
            "dstEnd": int
        }
    ]
    "errorText": string
}
\endcode

\param returnValue Indicates if the call was succesful.
\param results Object array for the results, see fields below.
\param tz The timezone.
\param year The year.
\param hasDstChange True if daylight saving time is in use in this timezone.
\param utcOffset Time difference from UTC time in seconds.
\param dstOffset Time difference from UTC time in seconds during daylight saving time. -1 if daylight saving time is not used.
\param dstStart The time when daylight saving time starts during the \c year, presented in Unix time. -1 if daylight saving time is not used.
\param dstEnd The time when daylight saving time ends during the \c year, presented in Unix time. -1 if daylight saving time is not used.
\param errorText Description of the error if call was not succesful.

\subsection com_palm_systemservice_timezone_get_time_zone_rules_examples Examples:
\code
luna-send -n 1 -f luna://com.palm.systemservice/timezone/getTimeZoneRules '[ {"tz": "Europe/Helsinki", "years": [2012, 2010]} ]'
\endcode
\code
luna-send -n 1 -f luna://com.palm.systemservice/timezone/getTimeZoneRules '[ {"tz": "Europe/Moscow"} ]'
\endcode

Example responses for succesful calls:
\code
{
    "returnValue": true,
    "results": [
        {
            "tz": "Europe\/Helsinki",
            "year": 2012,
            "hasDstChange": true,
            "utcOffset": 7200,
            "dstOffset": 10800,
            "dstStart": 1332637200,
            "dstEnd": 1351386000
        },
        {
            "tz": "Europe\/Helsinki",
            "year": 2010,
            "hasDstChange": true,
            "utcOffset": 7200,
            "dstOffset": 10800,
            "dstStart": 1269738000,
            "dstEnd": 1288486800
        }
    ]
}
\endcode

\code
{
    "returnValue": true,
    "results": [
        {
            "tz": "Europe\/Moscow",
            "year": 2012,
            "hasDstChange": false,
            "utcOffset": 14400,
            "dstOffset": -1,
            "dstStart": -1,
            "dstEnd": -1
        }
    ]
}
\endcode

Example response for a failed call:
\code
{
    "returnValue": false,
    "errorText": "Missing tz entry"
}
\endcode
*/
bool TimeZoneService::cbGetTimeZoneRules(LSHandle* lsHandle, LSMessage *message,
										 void *user_data)
{
	std::string reply;
	bool ret;
	LSError lsError;
	json_object* root = 0;
	TimeZoneEntryList entries;

	LSErrorInit(&lsError);
	
	const char* payload = LSMessageGetPayload(message);
	if (!payload) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"No payload specifed for message\"}";
		goto Done;
	}

	root = json_tokener_parse(payload);
	if (!root || is_error(root)) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"Cannot parse json payload\"}";
		goto Done;
	}

	if (!json_object_is_type(root, json_type_array)) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"json root needs to be an array\"}";
		goto Done;
	}

	for (int i = 0; i < json_object_array_length(root); i++) {
		json_object* obj = json_object_array_get_idx(root, i);
		json_object* l = 0;

		TimeZoneEntry tzEntry;
		
		// Mandatory (tz)
		l = json_object_object_get(obj, "tz");
		if (!l) {
			reply = "{\"returnValue\": false,"
					" \"errorText\": \"Missing tz entry\"}";
			goto Done;
		}

		if (!json_object_is_type(l, json_type_string)) {
			reply = "{\"returnValue\": false,"
					" \"errorText\": \"tz entry is not string\"}";
			goto Done;
		}

		tzEntry.tz = json_object_get_string(l);

		// Optional (years)
		l = json_object_object_get(obj, "years");
		if (l) {

			if (!json_object_is_type(l, json_type_array)) {
				reply = "{\"returnValue\": false,"
						" \"errorText\": \"years entry is not array\"}";
				goto Done;
			}

			for (int j = 0; j < json_object_array_length(l); j++) {
				json_object* o = json_object_array_get_idx(l, j);

				if (!json_object_is_type(o, json_type_int)) {
					reply = "{\"returnValue\": false,"
							" \"errorText\": \"entry in years array is not integer\"}";
					goto Done;
				}

				tzEntry.years.push_back(json_object_get_int(o));
			}
		}

		if (tzEntry.years.empty()) {
			time_t utcTime = time(NULL);
			struct tm* localTime = localtime(&utcTime);
			tzEntry.years.push_back(localTime->tm_year + 1900);
		}

		entries.push_back(tzEntry);
	}	
	
	reply = TimeZoneService::instance()->getTimeZoneRules(entries);
	
Done:

	ret = LSMessageReply(lsHandle, message, reply.c_str(), &lsError);
	if (!ret)
		LSErrorFree(&lsError);

	if (root && !is_error(root))
		json_object_put(root);

	return true;
}
Exemplo n.º 7
0
int
main(int argc, char **argv)
{
    bool retVal;

    gboolean debug = FALSE;
    gboolean fake_battery = FALSE;
    gboolean visual_leds_suspend = FALSE;
    gboolean verbose = FALSE;
    gboolean err_on_crit = FALSE;
    gboolean fasthalt = FALSE;
    gint maxtemp = 0;
    gint temprate = 0;


    GOptionEntry entries[] = {
        {"debug", 'd', 0, G_OPTION_ARG_NONE, &debug, "turn debug logging on", NULL},
        {"use-fake-battery", 'b', 0, G_OPTION_ARG_NONE, &fake_battery, "Use fake battery", NULL},
        {"visual-leds-suspend", 'l', 0, G_OPTION_ARG_NONE, &visual_leds_suspend, "Use LEDs to show wake/suspend state", NULL},
        {"verbose-syslog", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Use Verbose syslog output", NULL},
        {"error-on-critical", 'e', 0, G_OPTION_ARG_NONE, &err_on_crit, "Crash on critical error", NULL},
        {"maxtemp", 'M', 0, G_OPTION_ARG_INT, &maxtemp, "Set maximum temperature before shutdown (default 60)", NULL},
        {"temprate", 'T', 0, G_OPTION_ARG_INT, &temprate, "Expected maxiumum temperature slew rate (default 12)", NULL},
        {"fasthalt", 'F', 0, G_OPTION_ARG_NONE, &fasthalt, "On overtemp, shut down quickly not cleanly", NULL},
        { NULL }
    };

    GError *error = NULL;
    GOptionContext *ctx;
    ctx = g_option_context_new(" - power daemon");
    g_option_context_add_main_entries(ctx, entries, NULL);
    if (!g_option_context_parse(ctx, &argc, &argv, &error)) {
        g_critical("option parsing failed: %s", error->message);
        exit(1);
    }

    // FIXME integrate this into TheOneInit()
    LOGInit();
    LOGSetHandler(LOGSyslog);

    if (debug) {
        powerd_debug = true;

        LOGSetLevel(G_LOG_LEVEL_DEBUG);
        LOGSetHandler(LOGGlibLog);
    }
   
    signal(SIGTERM, term_handler);
    signal(SIGINT, term_handler);

    if (!g_thread_supported ()) g_thread_init (NULL);

    mainloop = g_main_loop_new(NULL, FALSE);

    /**
     *  initialize the lunaservice and we want it before all the init
     *  stuff happening.
     */
    LSError lserror;
    LSErrorInit(&lserror);

    retVal = LSRegisterPalmService("com.palm.power", &psh, &lserror);
    if (!retVal)
    {
        goto ls_error;
    }

    retVal = LSGmainAttachPalmService(psh, mainloop, &lserror);
    if (!retVal)
    {
        goto ls_error;
    }

    private_sh = LSPalmServiceGetPrivateConnection(psh);

    /**
     * Calls the init functions of all the modules in priority order.
     */
    TheOneInit();

    g_main_loop_run(mainloop);

end:
    g_main_loop_unref(mainloop);

    // save time before quitting...
    timesaver_save();

    return 0;
ls_error:
    g_critical("Fatal - Could not initialize powerd.  Is LunaService Down?. %s",
        lserror.message);
    LSErrorFree(&lserror);
    goto end;
}
/** 
 *******************************************************************************
 * @brief Allocate a new client.
 * 
 * @param  transport        IN  transport 
 * @param  fd               IN  fd 
 * @param  service_name     IN  client service name 
 * @param  unique_name      IN  client unique name 
 * @param  outgoing         IN  outgoing queue (NULL means allocate) 
 * @param  initiator        IN  true if this is the end of the connection that initiated the connection
 * 
 * @retval client on success
 * @retval NULL on failure
 *******************************************************************************
 */
_LSTransportClient*
_LSTransportClientNew(_LSTransport* transport, int fd, const char *service_name, const char *unique_name, _LSTransportOutgoing *outgoing, bool initiator)
{
    _LSTransportClient *new_client = g_slice_new0(_LSTransportClient);

    if (!new_client)
    {
        g_debug("OOM when attempting to add new incoming connection");
        return NULL;
    }

    //new_client->sh = sh;
    new_client->service_name = g_strdup(service_name);
    new_client->unique_name = g_strdup(unique_name);
    new_client->transport = transport;
    new_client->state = _LSTransportClientStateInvalid;
    new_client->is_sysmgr_app_proxy = false;
    new_client->is_dynamic = false;
    new_client->initiator = initiator;

    _LSTransportChannelInit(transport, &new_client->channel, fd, transport->source_priority);

    new_client->cred = _LSTransportCredNew();
    if (!new_client->cred)
    {
        goto error;
    }

    /* Get pid, gid, and uid of client if we're local. It won't work for obvious
     * reasons if it's a TCP/IP connection */
    if (_LSTransportGetTransportType(transport) == _LSTransportTypeLocal)
    {
        LSError lserror;
        LSErrorInit(&lserror);

        if (!_LSTransportGetCredentials(fd, new_client->cred, &lserror))
        {
            LSErrorPrint(&lserror, stderr);
            LSErrorFree(&lserror);
        }
    }

    if (outgoing)
    {
        new_client->outgoing = outgoing;
    }
    else
    {
        new_client->outgoing = _LSTransportOutgoingNew();
        if (!new_client->outgoing)
        {
            goto error;
        }
    }

    new_client->incoming = _LSTransportIncomingNew();
    if (!new_client->incoming)
    {
        goto error;
    }

    return new_client;

error:

    if (new_client->service_name) g_free(new_client->service_name);
    if (new_client->unique_name) g_free(new_client->unique_name);

    if (new_client->outgoing && !outgoing)
    {
        _LSTransportOutgoingFree(new_client->outgoing);
    }
    if (new_client->incoming)
    {
        _LSTransportIncomingFree(new_client->incoming);
    }
    if (new_client)
    {
        g_slice_free(_LSTransportClient, new_client);
    }

    return NULL;
}
Exemplo n.º 9
0
void luna_service_start() {
  LSError lserror;
  LSErrorInit(&lserror);

  g_main_loop_run(loop);
}
Exemplo n.º 10
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(LOG_DEBUG, "%s: %s", __FUNCTION__, 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;
}
Exemplo n.º 11
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(LOG_INFO, "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);
}
Exemplo n.º 12
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;
}
Exemplo n.º 13
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;

    time_t alarm_time = 0;

    LSError lserror;
    LSErrorInit(&lserror);

    object = json_tokener_parse(LSMessageGetPayload(message));
    if ( is_error(object) )
    {
        goto malformed_json;
    }

    SLEEPDLOG(LOG_DEBUG, "%s: %s", __FUNCTION__, 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 (sscanf(cal_time, "%02d:%02d:%02d", &hour, &min, &sec) != 3)
    {
        goto invalid_format;
    }
    if (sscanf(cal_date, "%02d-%02d-%04d", &month, &day, &year) != 3)
    {
        goto invalid_format;
    }

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

    SLEEPDLOG(LOG_INFO, "%s: (%s %s %s) at %s %s", __FUNCTION__,
              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;
}
Exemplo n.º 14
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(LOG_DEBUG, "%s: %s", __FUNCTION__, 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 (sscanf(rel_time, "%02d:%02d:%02d", &rel_hour, &rel_min, &rel_sec) != 3)
    {
        goto invalid_format;
    }

    nyx_system_query_rtc_time(GetNyxSystemDevice(),&rtctime);

    SLEEPDLOG(LOG_INFO, "%s: (%s %s %s) in %s (rtc %ld)", __FUNCTION__,
              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 = rtc_wall_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;
}
Exemplo n.º 15
0
int
main(int argc, char **argv)
{
    bool retVal;

    // FIXME integrate this into TheOneInit()
    LOGInit();
    LOGSetHandler(LOGSyslog);

    signal(SIGTERM, term_handler);
    signal(SIGINT, term_handler);

    if (!g_thread_supported ()) g_thread_init (NULL);

    mainloop = g_main_loop_new(NULL, FALSE);

    /**
     *  initialize the lunaservice and we want it before all the init
     *  stuff happening.
     */
    LSError lserror;
    LSErrorInit(&lserror);

    retVal = LSRegisterPalmService("com.palm.sleep", &psh, &lserror);
    if (!retVal)
    {
        goto ls_error;
    }

    retVal = LSGmainAttachPalmService(psh, mainloop, &lserror);
    if (!retVal)
    {
        goto ls_error;
    }

    private_sh = LSPalmServiceGetPrivateConnection(psh);

    retVal = LSCall(private_sh,"luna://com.palm.lunabus/signal/addmatch","{\"category\":\"/com/palm/power\","
              "\"method\":\"USBDockStatus\"}", ChargerStatus, NULL, NULL, &lserror);
    if (!retVal) {
		SLEEPDLOG(LOG_CRIT,"Error in registering for luna-signal \"chargerStatus\"");
		goto ls_error;
	}

 	int ret = nyx_device_open(NYX_DEVICE_SYSTEM, "Main", &nyxSystem);
 	if(ret != NYX_ERROR_NONE)
 	{
 		SLEEPDLOG(LOG_CRIT,"Sleepd: Unable to open the nyx device system");
 		abort();
 	}


    TheOneInit();

 	LSCall(private_sh,"luna://com.palm.power/com/palm/power/chargerStatusQuery","{}",ChargerStatus,NULL,NULL,&lserror);

    SLEEPDLOG(LOG_INFO,"Sleepd daemon started\n");

    g_main_loop_run(mainloop);

end:
    g_main_loop_unref(mainloop);

     return 0;
ls_error:
	SLEEPDLOG(LOG_CRIT,"Fatal - Could not initialize sleepd.  Is LunaService Down?. %s",
        lserror.message);
    LSErrorFree(&lserror);
    goto end;
}
Exemplo n.º 16
0
/*!
\page com_palm_device_info_service
\n
\section device_info_query query

\e Private. Available only at the private bus.

com.palm.systemservice/deviceInfo/query

\subsection device_info_query_syntax Syntax:
\code
{
    "parameters": [string array]
}
\endcode

\param parameters List of requested parameters. If not specified, all available parameters wiil be returned. 

\subsection os_info_query_return Returns:
\code
{
    "returnValue": boolean,
    "errorCode": string
    "board_type": string
    "bt_addr": string
    "device_name": string
    "hardware_id": string
    "hardware_revision": string
    "installer": string
    "keyboard_type": string
    "modem_present": string
    "nduid": string
    "product_id": string
    "radio_type": string
    "ram_size": string
    "serial_number": string
    "storage_free": string
    "storage_size": string
    "wifi_addr": string
    "last_reset_type": string
    "battery_challange": string
    "battery_response": string
}
\endcode

\param returnValue Indicates if the call was succesful.
\param errorCode Description of the error if call was not succesful.
\param board_type Board type
\param bt_addr Bluetooth address
\param device_name Device name
\param hardware_id Hardware ID
\param hardware_revision Hardware revision
\param installer Installer
\param keyboard_type Keyboard type
\param modem_present Modem availability
\param nduid NDUID
\param product_id Product ID
\param radio_type Radio type
\param ram_size RAM size
\param serial_number Serial number
\param storage_free Free storage size
\param storage_size Storage size
\param wifi_addr WiFi MAC address
\param last_reset_type Reason code for last reboot (may come from /proc/cmdline)
\param battery_challange Battery challenge
\param battery_response Battery response

All listed parameters can have `not supported` value, if not supported by the device.

\subsection device_info_qeury_examples Examples:
\code
luna-send -n 1 -f luna://com.palm.systemservice/deviceInfo/query '{"parameters":["device_name", "storage_size"]}'
\endcode

Example response for a succesful call:
\code
{
    "device_name": "qemux86",
    "storage_size": "32 GB",
    "returnValue": true
}
\endcode

Example response for a failed call:
\code
{
    "errorCode": "Cannot parse json payload"
    "returnValue": false,
}
\endcode
*/
bool DeviceInfoService::cbGetDeviceInformation(LSHandle* lsHandle, LSMessage *message, void *user_data)
{
	std::string reply;
	std::string parameter;

	const char *nyx_result = NULL;
	bool is_parameters_verified = false; // Becomes `true` if we've formed parameter ourself.
	LSError lsError;

	json_object *payload = NULL;
	json_object *payloadParameterList = NULL;
	json_object *jsonResult = json_object_new_object();

	LSErrorInit(&lsError);

	nyx_error_t error = NYX_ERROR_GENERIC;
	nyx_device_handle_t device = NULL;

	const char *payload_data = LSMessageGetPayload(message);
	if (!payload_data) {
	    reply = "{\"returnValue\": false, "
			" \"errorText\": \"No payload specifed for message\"}";
		goto Done;
	}

	payload = json_tokener_parse(payload_data);
	if (!payload || is_error(payload) || !json_object_is_type(payload, json_type_object)) {
		reply = "{\"returnValue\": false, "
		        " \"errorText\": \"Cannot parse/validate json payload\"}";
		goto Done;
	}

	if (json_object_object_get_ex(payload, "parameters", &payloadParameterList))
	{
		if (!payloadParameterList || !json_object_is_type(payloadParameterList, json_type_array)) {
			reply = "{\"returnValue\": false, "
				" \"errorText\": \"`parameters` needs to be an array\"}";
			goto Done;
		}
	}
	else
	{
		// No parameters. Fill array with all available parameters from the s_commandMap.
		is_parameters_verified = true;
		payloadParameterList = json_object_new_array();
		for (command_map_t::iterator it = s_commandMap.begin(); it != s_commandMap.end(); ++it)
		{
			json_object_array_add(payloadParameterList, json_object_new_string(it->first.c_str()));
		}
	}

	error = nyx_init();
	if (NYX_ERROR_NONE != error)
	{
		qCritical() << "Failed to inititalize nyx library: " << error;
		reply = "{\"returnValue\": false, "
			" \"errorText\": \"Can not initialize nyx\"}";
		goto Done;
	}

	error = nyx_device_open(NYX_DEVICE_DEVICE_INFO, "Main", &device);
	if ((NYX_ERROR_NONE != error) || (NULL == device))
	{
		qCritical() << "Failed to open `Main` nyx device: " << error;
		reply = "{\"returnValue\": false, "
			" \"errorText\": \"Internal error. Can't open nyx device\"}";
		goto Done;
	}

	for (int i = 0; i < json_object_array_length(payloadParameterList); i++)
	{
		parameter = json_object_get_string(json_object_array_get_idx(payloadParameterList, i));
		command_map_t::iterator query = s_commandMap.find(parameter);

		if (!is_parameters_verified && query == s_commandMap.end())
		{
			reply = "{\"returnValue\": false, "
				" \"errorText\": \"Invalid parameter: " + parameter + "\"}";
			goto Done;
		}

	    // Some device don't have all available parameters. We will just ignore them.
		error = nyx_device_info_query(device, query->second, &nyx_result);
		if (NYX_ERROR_NONE == error)
		{
			json_object_object_add(jsonResult, parameter.c_str(), json_object_new_string(nyx_result));
		}
		else
		{
			json_object_object_add(jsonResult, parameter.c_str(), json_object_new_string("not supported"));
		}
	}

	json_object_object_add(jsonResult, "returnValue", json_object_new_boolean(true));
	reply = json_object_to_json_string(jsonResult);

Done:
	bool ret = LSMessageReply(lsHandle, message, reply.c_str(), &lsError);
	if (!ret)
		LSErrorFree(&lsError);

	if (NULL != device)
		nyx_device_close(device);
	nyx_deinit();

	if (payload && !is_error(payload))
		json_object_put(payload);
	if (payloadParameterList && !is_error(payloadParameterList))
		json_object_put(payloadParameterList);
	if (jsonResult && !is_error(jsonResult))
		json_object_put(jsonResult);

	return true;
}
Exemplo n.º 17
0
int main(int argc, char ** argv)
{
    setenv("QT_PLUGIN_PATH","/usr/plugins",1);
    setenv("QT_QPA_PLATFORM", "minimal",1);
    QApplication app(argc, argv);

	parseCommandlineOptions(argc, argv);
	setLoglevel(Settings::settings()->m_logLevel.c_str());

	g_log_set_default_handler(logFilter, NULL);
	g_warning("Started");

	SystemRestore::createSpecialDirectories();
	
	// Initialize the Preferences database
	(void) PrefsDb::instance();
	///and system restore (refresh settings while I'm at it...)
	SystemRestore::instance()->refreshDefaultSettings();
	
	//run startup restore before anything else starts
	SystemRestore::startupConsistencyCheck();
	
	Mainloop * mainLoopObj = new Mainloop();
	g_gmainLoop = mainLoopObj->getMainLoopPtr();
	
	//GMainLoop* mainLoop =  g_main_loop_new(NULL, FALSE);	
	
	LSPalmService* serviceHandle = NULL;
	LSError lsError;
	bool result;

	LSErrorInit(&lsError);

	// Register the service
	result = LSRegisterPalmService("com.palm.systemservice", &serviceHandle, &lsError);
	if (!result) {
		g_warning("Failed to register service: com.palm.sysservice");
		return -1;
	}

//	LSHandle * serviceHandlePublic = LSPalmServiceGetPublicConnection(serviceHandle);
	LSHandle * serviceHandlePrivate = LSPalmServiceGetPrivateConnection(serviceHandle);
		
	result = LSGmainAttachPalmService(serviceHandle, g_gmainLoop, &lsError);
	if (!result) {
		g_warning("Failed to attach service handle to main loop");
		return -1;
	}

	//turn novacom on if requested
	if (Settings::settings()->m_turnNovacomOnAtStartup)
	{
		turnNovacomOn(serviceHandlePrivate);
	}

	if ((result = LSCall(serviceHandlePrivate,"palm://com.palm.bus/signal/registerServerStatus",
			"{\"serviceName\":\"com.palm.image2\", \"subscribe\":true}",
			cbComPalmImage2Status,NULL,NULL, &lsError)) == false)
	{
		//non-fatal
		LSErrorFree(&lsError);
		LSErrorInit(&lsError);
	}

	// register for storage daemon signals
	result = LSCall(serviceHandlePrivate,
			"palm://com.palm.lunabus/signal/addmatch",
			"{\"category\":\"/storaged\", \"method\":\"MSMAvail\"}",
			SystemRestore::msmAvailCallback, NULL, SystemRestore::instance()->getLSStorageToken(), &lsError);
	if (!result)
		return -1;

	result = LSCall(serviceHandlePrivate,
			"palm://com.palm.lunabus/signal/addmatch",
			"{\"category\":\"/storaged\", \"method\":\"MSMProgress\"}",
			SystemRestore::msmProgressCallback, NULL, SystemRestore::instance()->getLSStorageToken(), &lsError);
	if (!result)
		return -1;

	result = LSCall(serviceHandlePrivate,
			"palm://com.palm.lunabus/signal/addmatch",
			"{\"category\":\"/storaged\", \"method\":\"MSMEntry\"}",
			SystemRestore::msmEntryCallback, NULL, SystemRestore::instance()->getLSStorageToken(), &lsError);
	if (!result)
		return -1;

	result = LSCall(serviceHandlePrivate,
			"palm://com.palm.lunabus/signal/addmatch",
			"{\"category\":\"/storaged\", \"method\":\"MSMFscking\"}",
			SystemRestore::msmFsckingCallback, NULL, SystemRestore::instance()->getLSStorageToken(), &lsError);
	if (!result)
		return -1;

	result = LSCall(serviceHandlePrivate,
			"palm://com.palm.lunabus/signal/addmatch",
			"{\"category\":\"/storaged\", \"method\":\"PartitionAvail\"}",
			SystemRestore::msmPartitionAvailCallback, NULL, SystemRestore::instance()->getLSStorageToken(), &lsError);
	if (!result)
		return -1;

	// Initialize the Prefs Factory
	PrefsFactory::instance()->setServiceHandle(serviceHandle);
	BackupManager::instance()->setServiceHandle(serviceHandle);

	//init the image service
	ImageServices * imgSvc = ImageServices::instance(mainLoopObj);
	if (!imgSvc) {
		g_warning("Image service failed init!");
	}

	//init the timezone service;
	TimeZoneService* tzSvc = TimeZoneService::instance();
	tzSvc->setServiceHandle(serviceHandle);
	
	// Run the main loop
	g_main_loop_run(g_gmainLoop);
	
	return 0;
}
Exemplo n.º 18
0
 ls_error ()
     : error_()
     , owner_(true)
 {
     LSErrorInit(&error_);
 }
Exemplo n.º 19
0
// http://msdn.microsoft.com/en-us/library/ms725481.aspx
bool TimeZoneService::cbGetTimeZoneFromEasData(LSHandle* lsHandle, LSMessage *message,
											   void *user_data)
{
	std::string reply;
	bool ret;
	LSError lsError;
	json_object* root = 0;
	json_object* label = 0;

	int easBias;
	EasSystemTime easStandardDate;
	int easStandardBias;
	EasSystemTime easDaylightDate;
	int easDaylightBias;

	LSErrorInit(&lsError);

	easBias = 0;
	easStandardDate.valid = false;
	easStandardBias = 0;
	easDaylightDate.valid = false;
	easDaylightBias = 0;

    // {"bias": integer, standardDate:{"year": integer, "month": integer, "dayOfWeek": integer, "day": integer, "hour": integer, "minute": integer, "second": integer}, "standardBias": integer, "daylightDate":{"year": integer, "month": integer, "dayOfWeek": integer, "day": integer, "hour": integer, "minute": integer, "second": integer}, "daylightBias": integer}
    VALIDATE_SCHEMA_AND_RETURN(lsHandle,
                               message,
                               SCHEMA_5(REQUIRED(bias, integer), NAKED_OBJECT_OPTIONAL_7(standardDate, year, integer, month, integer, dayOfWeek, integer, day, integer, hour, integer, minute, integer, second, integer), OPTIONAL(standardBias, integer), NAKED_OBJECT_OPTIONAL_7(daylightDate, year, integer, month, integer, dayOfWeek, integer, day, integer, hour, integer, minute, integer, second, integer),OPTIONAL(daylightBias, integer)));
	
	const char* payload = LSMessageGetPayload(message);
	if (!payload) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"No payload specifed for message\"}";
		goto Done;
	}

	root = json_tokener_parse(payload);
	if (!root || is_error(root)) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"Cannot parse json payload\"}";
		goto Done;
	}

	// bias. mandatory (everything else is optional)
	label = json_object_object_get(root, "bias");
	if (!label || !json_object_is_type(label, json_type_int)) {
		reply = "{\"returnValue\": false, "
				" \"errorText\": \"bias value missing\"}";
		goto Done;
	}
	easBias = json_object_get_int(label);

	// standard date
	label = json_object_object_get(root, "standardDate");
	if (label && json_object_is_type(label, json_type_object))
		readEasDate(label, easStandardDate);

	// standard bias
	label = json_object_object_get(root, "standardBias");
	if (label && json_object_is_type(label, json_type_int))
		easStandardBias = json_object_get_int(label);

	// daylight date
	label = json_object_object_get(root, "daylightDate");
	if (label && json_object_is_type(label, json_type_object))
		readEasDate(label, easDaylightDate);

	// daylight bias
	label = json_object_object_get(root, "daylightBias");
	if (label && json_object_is_type(label, json_type_int))
		easDaylightBias = json_object_get_int(label);

	// Both standard and daylight bias need to specified together,
	// otherwise both are invalid
	if (!easDaylightDate.valid)
		easStandardDate.valid = false;

	if (!easStandardDate.valid)
		easDaylightDate.valid = false;

	{
		// Get all timezones matching the current offset
		PrefsHandler* handler = PrefsFactory::instance()->getPrefsHandler("timeZone");
		TimePrefsHandler* tzHandler = static_cast<TimePrefsHandler*>(handler);
		TimeZoneService* tzService = TimeZoneService::instance();

		std::list<std::string> timeZones = tzHandler->getTimeZonesForOffset(-easBias);

		if (timeZones.empty()) {

			reply = "{\"returnValue\": false, "
					" \"errorText\": \"Failed to find any timezones with specified bias value\"}";
			goto Done;
		}

		if (!easStandardDate.valid) {
			// No additional data available for refinement. Just use the
			// first timezone entry in the list
			json_object* obj = json_object_new_object();
			json_object_object_add(obj, "returnValue", json_object_new_boolean(true));
			json_object_object_add(obj, "timeZone", json_object_new_string(timeZones.begin()->c_str()));
			reply = json_object_to_json_string(obj);
			json_object_put(obj);

			goto Done;
		}
		else {

			time_t utcTime = time(NULL);
			struct tm* localTime = localtime(&utcTime);
			int currentYear = localTime->tm_year + 1900;

			updateEasDateDayOfMonth(easStandardDate, currentYear);
			updateEasDateDayOfMonth(easDaylightDate, currentYear);
				
			
			for (std::list<std::string>::const_iterator it = timeZones.begin();
				 it != timeZones.end(); ++it) {
				TimeZoneEntry tzEntry;
				tzEntry.tz = (*it);
				tzEntry.years.push_back(currentYear);

				TimeZoneResultList tzResultList = tzService->getTimeZoneRuleOne(tzEntry);
				if (tzResultList.empty())
					continue;

				const TimeZoneResult& tzResult = tzResultList.front();
	
				printf("For timezone: %s\n", tzEntry.tz.c_str());
				printf("year: %d, utcOffset: %lld, dstOffset: %lld, dstStart: %lld, dstEnd: %lld\n",
					   tzResult.year, tzResult.utcOffset, tzResult.dstOffset,
					   tzResult.dstStart, tzResult.dstEnd);

				// Set this timezone as the current timezone, so that we can calculate when the
				// DST transitions occurs in seconds for the specified eas data
				setenv("TZ", tzEntry.tz.c_str(), 1);

				struct tm tzBrokenTime;
				tzBrokenTime.tm_sec = easStandardDate.second;
				tzBrokenTime.tm_min = easStandardDate.minute;
				tzBrokenTime.tm_hour = easStandardDate.hour;
				tzBrokenTime.tm_mday = easStandardDate.day;
				tzBrokenTime.tm_mon = easStandardDate.month - 1;
				tzBrokenTime.tm_year = currentYear - 1900;
				tzBrokenTime.tm_wday = 0;
				tzBrokenTime.tm_yday = 0;
				tzBrokenTime.tm_isdst = 1;

				time_t easStandardDateSeconds = ::mktime(&tzBrokenTime);

				tzBrokenTime.tm_sec = easDaylightDate.second;
				tzBrokenTime.tm_min = easDaylightDate.minute;
				tzBrokenTime.tm_hour = easDaylightDate.hour;
				tzBrokenTime.tm_mday = easDaylightDate.day;
				tzBrokenTime.tm_mon = easDaylightDate.month - 1;
				tzBrokenTime.tm_year = currentYear - 1900;
				tzBrokenTime.tm_wday = 0;
				tzBrokenTime.tm_yday = 0;
				tzBrokenTime.tm_isdst = 0;

				time_t easDaylightDateSeconds = ::mktime(&tzBrokenTime);

				printf("eas dstStart: %ld, dstEnd: %ld\n", easDaylightDateSeconds, easStandardDateSeconds);
				
				if (easStandardDateSeconds == tzResult.dstEnd &&
					easDaylightDateSeconds == tzResult.dstStart) {
					// We have a winner
					json_object* obj = json_object_new_object();
					json_object_object_add(obj, "returnValue", json_object_new_boolean(true));
					json_object_object_add(obj, "timeZone", json_object_new_string(tzEntry.tz.c_str()));
					reply = json_object_to_json_string(obj);
					json_object_put(obj);
					goto Done;
				}
			}

			reply = "{\"returnValue\": false, "
					" \"errorText\": \"Failed to find any timezones with specified parametes\"}";
		}
	}

Done:

	ret = LSMessageReply(lsHandle, message, reply.c_str(), &lsError);
	if (!ret)
		LSErrorFree(&lsError);

	if (root && !is_error(root))
		json_object_put(root);

	return true;	
}
Exemplo n.º 20
0
static bool read_file(LSMessage *message, char *filename, bool subscribed) {
  LSError lserror;
  LSErrorInit(&lserror);

  char file_buffer[CHUNKSIZE+CHUNKSIZE+1];
  char file_esc_buffer[MAXBUFLEN];

  FILE * file = fopen(filename, "r");
  if (!file) {
    sprintf(file_buffer,
	    "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Cannot open %s\"}",
	    filename);
    
    if (!LSMessageRespond(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 (!LSMessageRespond(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 (!LSMessageRespond(message, file_buffer, &lserror)) goto error;

  }

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

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

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

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

  }

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
Exemplo n.º 21
0
//
// Run a shell command, and return the output in-line in a buffer for returning to webOS.
// The global run_command_buffer must be initialised before calling this function.
// The return value says whether the command executed successfully or not.
//
static bool run_command(char *command, bool escape, char *buffer) {
  LSError lserror;
  LSErrorInit(&lserror);

  char esc_buffer[MAXBUFLEN];

  // Local buffers to store the current and previous lines.
  char line[MAXLINLEN];

  // fprintf(stderr, "Running command %s\n", command);

  // buffer is assumed to be initialised, ready for strcat to append.

  // Is this the first line of output?
  bool first = true;

  bool array = false;

  // Start execution of the command, and read the output.
  FILE *fp = popen(command, "r");

  // Return immediately if we cannot even start the command.
  if (!fp) {
    return false;
  }

  // Loop through the output lines
  while (fgets(line, sizeof line, fp)) {

    // Chomp the newline
    char *nl = strchr(line,'\n'); if (nl) *nl = 0;

    // Add formatting breaks between lines
    if (first) {
      if (buffer[strlen(buffer)-1] == '[') {
	array = true;
      }
      first = false;
    }
    else {
      if (array) {
	strcat(buffer, ", ");
      }
      else {
	strcat(buffer, "<br>");
      }
    }
    
    // Append the unfiltered output to the buffer.
    if (escape) {
      if (array) {
	strcat(buffer, "\"");
      }
      strcat(buffer, json_escape_str(line, esc_buffer));
      if (array) {
	strcat(buffer, "\"");
      }
    }
    else {
      strcat(buffer, line);
    }
  }
  
  // Check the close status of the process
  if (pclose(fp)) {
    return false;
  }

  return true;
 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  // %%% We need a way to distinguish command failures from LSMessage failures %%%
  // %%% This may need to be true if we just want to ignore LSMessage failures %%%
  return false;
}
Exemplo n.º 22
0
 Error() { LSErrorInit(&_error); }