bool getFilecacheType_method(LSHandle* lshandle, LSMessage *message, void *ctx) { LSError lserror; LSErrorInit(&lserror); if (access_denied(message)) return true; char filename[MAXLINLEN]; // Extract the id argument from the message json_t *object = json_parse_document(LSMessageGetPayload(message)); json_t *type = json_find_first_label(object, "type"); if (!type || (type->child->type != JSON_STRING) || (strspn(type->child->text, ALLOWED_CHARS) != strlen(type->child->text))) { if (!LSMessageRespond(message, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing type\"}", &lserror)) goto error; return true; } sprintf(filename, "/etc/palm/filecache_types/%s", type->child->text); return read_file(message, filename, true); error: LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); end: return false; }
static INT1 *proc_rest_msg(const INT1 *method, const INT1 *url, const INT1 *upload_data) { json_t *root = NULL; INT4 parse_type = 0; INT1 *reply = NULL; if (upload_data) { parse_type = json_parse_document(&root, upload_data); if (parse_type != JSON_OK) { return json_to_reply(NULL, EC_RESTFUL_INVALID_REQ); } } if (strncmp(method, "GET", 3) == 0) { reply = proc_restful_request(HTTP_GET, url, root); } else if (strncmp(method, "POST", 4) == 0) { reply = proc_restful_request(HTTP_POST, url, root); } else if (strncmp(method, "PUT", 3) == 0) { reply = proc_restful_request(HTTP_PUT, url, root); } else if (strncmp(method, "DELETE", 6) == 0) { reply = proc_restful_request(HTTP_DELETE, url, root); } return reply; }
int treeTest1(void) { int err; printf("%s", "====== Tree Test 1 Starts =======\n"); setlocale (LC_ALL, ""); //char *document = "{\"entry\":{\"name\":\"Andew\",\"phone\":\"555 123 456\"}}"; int fd = open("./param_list.json", O_RDONLY); if (-1 == fd) { printf("open file failed\n"); return 1; } struct stat fs; if (fstat(fd, &fs)) { printf("failed to get file stat\n"); close(fd); return 1; } size_t fileLen = (size_t)fs.st_size; char *document = malloc(fileLen); bzero(document, fileLen); size_t count = read(fd, document, fileLen); if (count != fileLen) { printf("failed to read file\n"); free(document); close(fd); return 1; } json_t *root = NULL; //json_t *root = json_new_object(); if (NULL == root) { printf("%s\n", "new json object failed"); } printf("Parsing the document...\n"); err = json_parse_document(&root, document); if (err != JSON_OK) { printf("%s, err=%d\n", "parse error", err); goto cleanup; } printf("Printing the document tree...\n"); json_tree_to_string(root, &document); printf("%s\n", document); // clean up cleanup: json_free_value(&root); free(document); close(fd); printf("%s", "====== Tree Test 1 Ends =======\n"); return EXIT_SUCCESS; }
static int set_online_status_back(LwqqHttpRequest* req) { int err = LWQQ_EC_OK; int ret; char* response; char* value; json_t * json = NULL; LwqqClient* lc = req->lc; if(!lwqq_client_valid(lc)){ err = LWQQ_EC_ERROR; goto done; } if (req->http_code != 200) { err = LWQQ_EC_HTTP_ERROR; goto done; } /** * Here, we got a json object like this: * {"retcode":0,"result":{"uin":1421032531,"cip":2013211875,"index":1060,"port":43415,"status":"online","vfwebqq":"e7ce7913336ad0d28de9cdb9b46a57e4a6127161e35b87d09486001870226ec1fca4c2ba31c025c7","psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e32303200006b2900001544016e0400533cb3546d0000000a4046674d4652585136496d00000028e7ce7913336ad0d28de9cdb9b46a57e4a6127161e35b87d09486001870226ec1fca4c2ba31c025c7","user_state":0,"f":0}} * */ response = req->response; lwqq_verbose(3,"%s\n",response); ret = json_parse_document(&json, response); if (ret != JSON_OK) { err = LWQQ_EC_ERROR; goto done; } if (!(value = json_parse_simple_value(json, "retcode"))) { err = LWQQ_EC_ERROR; goto done; } /** * Do we need parse "seskey? from kernelhcy's code, we need it, * but from the response we got like above, we dont need * */ lwqq__override(lc->seskey,lwqq__json_get_value(json,"seskey")); lwqq__override(lc->cip,lwqq__json_get_value(json,"cip")); lwqq__override(lc->myself->uin,lwqq__json_get_value(json,"uin")); lwqq__override(lc->index,lwqq__json_get_value(json,"index")); lwqq__override(lc->port,lwqq__json_get_value(json,"port")); lwqq__override(lc->vfwebqq,lwqq__json_get_value(json,"vfwebqq")); lwqq__override(lc->psessionid,lwqq__json_get_value(json,"psessionid")); lc->stat = lwqq_status_from_str( json_parse_simple_value(json, "status")); err = LWQQ_EC_OK; done: if (json) json_free_value(&json); lwqq_http_request_free(req); return err; }
string Benchmark::init() throw(std::runtime_error) { raw_buffer inputBuffer = input(); string inputStr(inputBuffer.m_str, inputBuffer.m_len); json_t *parsed = json_parse_document(inputStr.c_str()); if (!parsed) throw runtime_error("Failed to parse json input"); json_free_value(&parsed); return inputStr; }
// // Return a polite response. // Called directly from webOS, and returns directly to webOS. // bool set_debug_log_method(LSHandle* lshandle, LSMessage *message, void *ctx) { log("set_debug_log_method"); LSError lserror; LSErrorInit(&lserror); // Extract the id argument from the message json_t *object = json_parse_document(LSMessageGetPayload(message)); json_t *enableDebugLogging = json_find_first_label(object, "enableDebugLogging"); if(enableDebugLogging) { if(enableDebugLogging->child->type == JSON_TRUE) { log("enableDebugLogging: JSON_TRUE"); g_debugLoggingEnabled = true; } else if(enableDebugLogging->child->type == JSON_FALSE) { log("enableDebugLogging: JSON_FALSE"); g_debugLoggingEnabled = false; remove(LOG_FILE); } else { log("enableDebugLogging: %d", enableDebugLogging->child->type); } } else { if (!LSMessageReply(lshandle, message, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing parameters\"}", &lserror)) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); return false; } } // Local buffer to store the reply char reply[MAXLINLEN]; sprintf(reply, "{\"returnValue\": true, \"debugLoggingEnabled\": %s}", g_debugLoggingEnabled ? "true" : "false"); log(reply); if (!LSMessageReply(lshandle, message, reply, &lserror)) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); return false; } return true; }
json_t* YtkUtils::stringToJson(const std::string &str) { int size = str.size(); char* json = new char[size+1]; strcpy( json, str.c_str() ); json_t *root = 0; if( JSON_OK != json_parse_document(&root, json) ) { root = 0; } return root; }
static void test_remove_items (void) { char* json = "[{\"first\" : 1, \"second\" : 2}]"; json_t* root = NULL; json_t* item; assert (JSON_OK == json_parse_document (&root, json)); json_free_value (&root); assert (JSON_OK == json_parse_document (&root, json)); assert (root->child); item = json_find_first_label (root->child, "first"); json_free_value (&item); json_free_value (&root); assert (JSON_OK == json_parse_document (&root, json)); assert (root->child); item = json_find_first_label (root->child, "second"); json_free_value (&item); json_free_value (&root); printf ("Made It"); }
double Benchmark::execute(size_t numIterations) throw(std::runtime_error) { Timer start, end; json_t *parsed; string inputStr = init(); start.reset(); while (numIterations--) { parsed = json_parse_document(inputStr.c_str()); json_free_value(&parsed); } end.reset(); return end - start; }
size_t Benchmark::execute(double runtime) throw(std::runtime_error) { string inputStr = init(); Timer end; double start = Timer::now(); size_t numIterations = 0; json_t *parsed; for (; end - start < runtime; end.reset()) { parsed = json_parse_document(inputStr.c_str()); json_free_value(&parsed); numIterations++; } return numIterations; }
void BatDown::testJson() { char *fn = "script/2.json"; QFile testFile(fn); if(!testFile.open(QIODevice::ReadOnly | QIODevice::Text) ) return; QByteArray ba = testFile.readAll(); char* json = ba.data(); json_t* root = NULL; json_t* item; assert (JSON_OK == json_parse_document (&root, json)); assert (root->child); item = json_find_first_label (root, "title"); QString ss = QString::fromLocal8Bit(item->child->text); yDEBUG(ss.toLocal8Bit().data()); json_free_value (&item); json_free_value (&root); }
static json_t *ReadArchiveJSON(const char *archive, const char *filename) { json_t *root = NULL; debug(D_VERBOSE, "Loading archive json %s %s\n", archive, filename); char path[CDOGS_PATH_MAX]; sprintf(path, "%s/%s", archive, filename); long len; char *buf = ReadFileIntoBuf(path, "rb", &len); if (buf == NULL) goto bail; const enum json_error e = json_parse_document(&root, buf); if (e != JSON_OK) { LOG(LM_MAP, LL_ERROR, "Invalid syntax in JSON file (%s) error(%d)", filename, (int)e); root = NULL; goto bail; } bail: CFREE(buf); return root; }
// // Encrypt text // bool encrypt_method(LSHandle* lshandle, LSMessage *message, void *ctx) { LSError lserror; LSErrorInit(&lserror); // Local buffer to store the update command char command[MAXLINLEN]; char *document; // Extract the userdata argument from the message json_t *object = json_parse_document(LSMessageGetPayload(message)); json_t *userdata = json_find_first_label(object, "userdata"); if (!userdata || (userdata->child->type != JSON_OBJECT)) { if (!LSMessageRespond(message, "{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing userdata\"}", &lserror)) goto error; return true; } if (json_tree_to_string(userdata->child, &document) != JSON_OK) { if (!LSMessageRespond(message, "{\"errorText\": \"Unable to parse userdata\", \"returnValue\": false, \"errorCode\": -1 }", &lserror)) goto error; return true; } // Store the command, so it can be used in the error report if necessary sprintf(command, "echo '%s' | openssl rsautl -encrypt -certin -inkey /media/cryptofs/apps/usr/palm/applications/com.apptuckerbox.register/certs/com.apptuckerbox.crt | openssl enc -e -a 2>&1", document); return simple_command(message, command); error: LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); end: return false; }
/** * WebQQ logout function * * @param client Lwqq Client * @param err Error code */ void lwqq_logout(LwqqClient *client, LwqqErrorCode *err) { char url[512]; LwqqHttpRequest *req = NULL; int ret; json_t *json = NULL; char *value; struct timeval tv; char *cookies; long int re; if (!client) { lwqq_log(LOG_ERROR, "Invalid pointer\n"); return ; } /* Get the milliseconds of now */ if (gettimeofday(&tv, NULL)) { if (err) *err = LWQQ_EC_ERROR; return ; } re = tv.tv_usec / 1000; re += tv.tv_sec; snprintf(url, sizeof(url), "%s/channel/logout2?clientid=%s&psessionid=%s&t=%ld", "http://d.web2.qq.com", client->clientid, client->psessionid, re); /* Create a GET request */ req = lwqq_http_create_default_request(url, err); if (!req) { goto done; } /* Set header needed by server */ req->set_header(req, "Referer", "http://ptlogin2.qq.com/proxy.html?v=20101025002"); /* Set http cookie */ cookies = lwqq_get_cookies(client); if (cookies) { req->set_header(req, "Cookie", cookies); s_free(cookies); } ret = req->do_request(req, 0, NULL); if (ret) { lwqq_log(LOG_ERROR, "Send logout request failed\n"); if (err) *err = LWQQ_EC_NETWORK_ERROR; goto done; } if (req->http_code != 200) { if (err) *err = LWQQ_EC_HTTP_ERROR; goto done; } ret = json_parse_document(&json, req->response); if (ret != JSON_OK) { if (err) *err = LWQQ_EC_ERROR; goto done; } /* Check whether logout correctly */ value = json_parse_simple_value(json, "retcode"); if (!value || strcmp(value, "0")) { if (err) *err = LWQQ_EC_ERROR; goto done; } value = json_parse_simple_value(json, "result"); if (!value || strcmp(value, "ok")) { if (err) *err = LWQQ_EC_ERROR; goto done; } /* Ok, seems like all thing is ok */ if (err) *err = LWQQ_EC_OK; done: if (json) json_free_value(&json); lwqq_http_request_free(req); }
/** * Set online status, this is the last step of login * * @param err * @param lc */ static void set_online_status(LwqqClient *lc, char *status, LwqqErrorCode *err) { char msg[1024] ={0}; char *buf; LwqqHttpRequest *req = NULL; char *response = NULL; char *cookies; int ret; json_t *json = NULL; char *value; if (!status || !err) { goto done ; } lc->clientid = generate_clientid(); if (!lc->clientid) { lwqq_log(LOG_ERROR, "Generate clientid error\n"); *err = LWQQ_EC_ERROR; goto done ; } snprintf(msg, sizeof(msg), "{\"status\":\"%s\",\"ptwebqq\":\"%s\"," "\"passwd_sig\":""\"\",\"clientid\":\"%s\"" ", \"psessionid\":null}" ,status, lc->cookies->ptwebqq ,lc->clientid); buf = url_encode(msg); snprintf(msg, sizeof(msg), "r=%s", buf); s_free(buf); /* Create a POST request */ req = lwqq_http_create_default_request(LWQQ_URL_SET_STATUS, err); if (!req) { goto done; } /* Set header needed by server */ req->set_header(req, "Cookie2", "$Version=1"); req->set_header(req, "Referer", "http://d.web2.qq.com/proxy.html?v=20101025002"); req->set_header(req, "Content-type", "application/x-www-form-urlencoded"); /* Set http cookie */ cookies = lwqq_get_cookies(lc); if (cookies) { req->set_header(req, "Cookie", cookies); s_free(cookies); } ret = req->do_request(req, 1, msg); if (ret) { *err = LWQQ_EC_NETWORK_ERROR; goto done; } if (req->http_code != 200) { *err = LWQQ_EC_HTTP_ERROR; goto done; } /** * Here, we got a json object like this: * {"retcode":0,"result":{"uin":1421032531,"cip":2013211875,"index":1060,"port":43415,"status":"online","vfwebqq":"e7ce7913336ad0d28de9cdb9b46a57e4a6127161e35b87d09486001870226ec1fca4c2ba31c025c7","psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e32303200006b2900001544016e0400533cb3546d0000000a4046674d4652585136496d00000028e7ce7913336ad0d28de9cdb9b46a57e4a6127161e35b87d09486001870226ec1fca4c2ba31c025c7","user_state":0,"f":0}} * */ response = req->response; ret = json_parse_document(&json, response); if (ret != JSON_OK) { *err = LWQQ_EC_ERROR; goto done; } if (!(value = json_parse_simple_value(json, "retcode"))) { *err = LWQQ_EC_ERROR; goto done; } /** * Do we need parse "seskey? from kernelhcy's code, we need it, * but from the response we got like above, we dont need * */ if ((value = json_parse_simple_value(json, "seskey"))) { lc->seskey = s_strdup(value); } if ((value = json_parse_simple_value(json, "cip"))) { lc->cip = s_strdup(value); } if ((value = json_parse_simple_value(json, "index"))) { lc->index = s_strdup(value); } if ((value = json_parse_simple_value(json, "port"))) { lc->port = s_strdup(value); } if ((value = json_parse_simple_value(json, "status"))) { /* This really need? */ lc->status = s_strdup(value); } if ((value = json_parse_simple_value(json, "vfwebqq"))) { lc->vfwebqq = s_strdup(value); } if ((value = json_parse_simple_value(json, "psessionid"))) { lc->psessionid = s_strdup(value); } *err = LWQQ_EC_OK; done: if (json) json_free_value(&json); lwqq_http_request_free(req); }
static gint do_send_buddy_msg(QQInfo *info, QQSendMsg *msg, GError **err) { GString *uin = msg -> to_uin; gint ret_code = 0; gint res = 0; gchar params[3000]; g_debug("Send msg to %s!(%s, %d)", uin -> str, __FILE__, __LINE__); Request *req = request_new(); Response *rps = NULL; request_set_method(req, "POST"); request_set_version(req, "HTTP/1.1"); request_set_uri(req, MSGFRIPATH); request_set_default_headers(req); request_add_header(req, "Host", MSGHOST); request_add_header(req, "Cookie", info -> cookie -> str); request_add_header(req, "Origin", "http://d.web2.qq.com"); request_add_header(req, "Content-Type", "application/x-www-form-urlencoded"); request_add_header(req, "Referer" , "http://"MSGHOST"/proxy.html?v=20110331002&callback=2"); GString *content; content = qq_sendmsg_contents_tostring(msg); g_snprintf(params, 3000, "r={\"to\":%s,\"face\":%s," "%s,\"msg_id\":%s," "\"clientid\":\"%s\",\"psessionid\":\"%s\"}" , uin -> str, msg -> face -> str , content -> str , msg -> msg_id -> str , info -> clientid -> str , info -> psessionid -> str); g_string_free(content, TRUE); gchar *euri = g_uri_escape_string(params, "=", FALSE); request_append_msg(req, euri, strlen(euri)); g_free(euri); g_snprintf(params, 3000, "%u", (unsigned int)strlen(req -> msg -> str)); request_add_header(req, "Content-Length", params); Connection *con = connect_to_host(MSGHOST, 80); if(con == NULL){ g_warning("Can NOT connect to server!(%s, %d)" , __FILE__, __LINE__); request_del(req); return -1; } send_request(con, req); res = rcv_response(con, &rps); close_con(con); connection_free(con); if (-1 == res || !rps) { g_warning("Null point access (%s, %d)\n", __FILE__, __LINE__); ret_code = -1; goto error; } const gchar *retstatus = rps -> status -> str; json_t *json = NULL; if(g_strstr_len(retstatus, -1, "200") == NULL){ /* * Maybe some error occured. */ g_warning("Resoponse status is NOT 200, but %s (%s, %d)" , retstatus, __FILE__, __LINE__); ret_code = -1; goto error; } switch(json_parse_document(&json, rps -> msg -> str)) { case JSON_OK: break; default: g_warning("json_parser_document: syntax error. (%s, %d)" , __FILE__, __LINE__); } json_t *val = json_find_first_label_all(json, "result"); if(val != NULL){ val = val -> child; if(g_strstr_len(val -> text, -1, "ok") == NULL){ g_warning("Server return error. %s (%s, %d)" , val -> text, __FILE__, __LINE__); } }else{ g_warning("Server return: (%s, %d)%s", __FILE__, __LINE__ , rps -> msg -> str); } json_free_value(&json); error: request_del(req); response_del(rps); return ret_code; }
Config gConfig; int gPicManager; FEATURE(json_format_string, "String format") SCENARIO("Quote handling") GIVEN("a JSON structure containing escaped quotes") json_t *root = json_new_object(); AddStringPair(root, "Foo", "bar \"baz\""); AddStringPair(root, "Spam", "I like \"spam\" and \"eggs\""); WHEN("I format the structure into a string") char *text; json_tree_to_string(root, &text); char *ftext = json_format_string(text); THEN("the result should be valid JSON") json_t *parsed = NULL; SHOULD_INT_EQUAL( (int)json_parse_document(&parsed, ftext), (int)JSON_OK); AND("contain the same strings") SHOULD_BE_TRUE(strstr(ftext, "I like \\\"spam\\\" and \\\"eggs\\\"") != NULL); CFREE(text); CFREE(ftext); json_free_value(&root); json_free_value(&parsed); SCENARIO_END FEATURE_END CBEHAVE_RUN("JSON features are:", TEST_FEATURE(json_format_string))
bool stop_method(LSHandle* lshandle, LSMessage *message, void *ctx) { bool returnVal = true; char line[MAXLINELEN]; // %%% MAGIC NUMBERS ALERT %%% char name[128]; char status[128]; LSError lserror; LSErrorInit(&lserror); char *jsonResponse = 0; int len = 0; json_t *object = json_parse_document(LSMessageGetPayload(message)); json_t *id = json_find_first_label(object, "id"); if (strspn(id->child->text, ALLOWED_CHARS) != strlen(id->child->text)) { LSMessageReply(lshandle, message, "{\"returnValue\":false,\"errorCode\":-1,\"errorText\":\"Invalid id\"}", &lserror); LSErrorFree(&lserror); return true; } // %%% MAGIC NUMBERS ALERT %%% char command[128]; char format[128]; // %%% IGNORING RETURN ALERT %%% sprintf((char *)&command, "/sbin/initctl stop %s 2>&1", id->child->text); json_t *response = json_new_object(); FILE *fp = popen(command, "r"); if (fp) { while ( fgets( line, sizeof line, fp)) { if (sscanf(line, "(%*d/%*d) Job not changed: %127s\n", (char *)&name) == 1) { // %%% IGNORING RETURN ALERT %%% json_insert_pair_into_object(response, "status", json_new_string("Job not changed")); } else if (sscanf(line, "(%*d/%*d) %s %127c\n", (char *)&name, (char *)&status) == 2) { // %%% HACK ALERT %%% *strchr(status,'\n') = 0; // %%% IGNORING RETURN ALERT %%% json_insert_pair_into_object(response, "status", json_new_string(status)); } } if (!pclose(fp)) { // %%% IGNORING RETURN ALERT %%% json_insert_pair_into_object(response, "returnValue", json_new_true()); } else { // %%% IGNORING RETURN ALERT %%% json_insert_pair_into_object(response, "returnValue", json_new_false()); } 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; }
// // 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; }
/** * WebQQ logout function * * @param client Lwqq Client * @param err Error code */ LWQQ_EXPORT void lwqq_logout(LwqqClient *client, LwqqErrorCode *err) { LwqqClient* lc = client; char url[512]; LwqqHttpRequest *req = NULL; int ret; json_t *json = NULL; char *value; struct timeval tv; long int re; if (!client) { lwqq_log(LOG_ERROR, "Invalid pointer\n"); return ; } /* Get the milliseconds of now */ if (gettimeofday(&tv, NULL)) { if (err) *err = LWQQ_EC_ERROR; return ; } re = tv.tv_usec / 1000; re += tv.tv_sec; snprintf(url, sizeof(url), "%s/channel/logout2" "?clientid=%s&psessionid=%s&t=%ld", WEBQQ_D_HOST, client->clientid, client->psessionid, re); /* Create a GET request */ req = lwqq_http_create_default_request(client,url, err); if (!req) { goto done; } /* Set header needed by server */ req->set_header(req, "Referer", WEBQQ_LOGIN_REF_URL); lwqq_http_set_option(req, LWQQ_HTTP_ALL_TIMEOUT,5L); req->retry = 0; ret = req->do_request(req, 0, NULL); if (ret) { lwqq_log(LOG_ERROR, "Send logout request failed\n"); if (err) *err = LWQQ_EC_NETWORK_ERROR; goto done; } if (req->http_code != 200) { if (err) *err = LWQQ_EC_HTTP_ERROR; goto done; } ret = json_parse_document(&json, req->response); if (ret != JSON_OK) { if (err) *err = LWQQ_EC_ERROR; goto done; } /* Check whether logout correctly */ value = json_parse_simple_value(json, "retcode"); if (!value || strcmp(value, "0")) { if (err) *err = LWQQ_EC_ERROR; goto done; } value = json_parse_simple_value(json, "result"); if (!value || strcmp(value, "ok")) { if (err) *err = LWQQ_EC_ERROR; goto done; } /* Ok, seems like all thing is ok */ if (err) *err = LWQQ_EC_OK; done: if (json) json_free_value(&json); lwqq_http_request_free(req); client->stat = LWQQ_STATUS_LOGOUT; }
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; }
static json_object_t mjson_bench_parse(void *context, const char *text, size_t length) { json_t *json = NULL; json_parse_document(&json, text); return (json_object_t) json; }
static gint do_logout(QQInfo *info, GError **err) { gint ret_code = 0; gint res = 0; g_debug("Logout... (%s, %d)", __FILE__, __LINE__); if(info -> psessionid == NULL || info -> psessionid -> len <= 0){ g_warning("Need psessionid !!(%s, %d)", __FILE__, __LINE__); return -1; } gchar params[300]; Request *req = request_new(); Response *rps = NULL; request_set_method(req, "GET"); request_set_version(req, "HTTP/1.1"); g_sprintf(params, LOGOUTPATH"?clientid=%s&psessionid=%s&t=%ld" , info -> clientid -> str , info -> psessionid -> str, get_now_millisecond()); request_set_uri(req, params); request_set_default_headers(req); request_add_header(req, "Host", LOGOUTHOST); request_add_header(req, "Cookie", info -> cookie -> str); request_add_header(req, "Referer", REFERER); Connection *con = connect_to_host(LOGOUTHOST, 80); if(con == NULL){ g_warning("Can NOT connect to server!(%s, %d)" , __FILE__, __LINE__); request_del(req); return -1; } send_request(con, req); res = rcv_response(con, &rps); close_con(con); connection_free(con); if (-1 == res || !rps) { g_warning("Null point access (%s, %d)\n", __FILE__, __LINE__); ret_code = -1; goto error; } const gchar *retstatus = rps -> status -> str; if(g_strstr_len(retstatus, -1, "200") == NULL){ /* * Maybe some error occured. */ g_warning("Resoponse status is NOT 200, but %s (%s, %d)" , retstatus, __FILE__, __LINE__); ret_code = -1; goto error; } json_t *json = NULL; switch(json_parse_document(&json, rps -> msg -> str)) { case JSON_OK: break; default: g_warning("json_parser_document: syntax error. (%s, %d)" , __FILE__, __LINE__); ret_code = -1; goto error; } json_t *retcode, *result; retcode = json_find_first_label_all(json, "retcode"); result = json_find_first_label_all(json, "result"); if(retcode != NULL && result != NULL){ if(g_strstr_len(result -> child -> text, -1, "ok") != NULL){ g_debug("Logout ok!(%s, %d)", __FILE__, __LINE__); ret_code = 0; } }else{ g_debug("(%s, %d)%s", __FILE__, __LINE__, rps -> msg -> str); } json_free_value(&json); error: request_del(req); response_del(rps); return ret_code; }
/* * Get the psessionid. * * This function is the last step of loginning */ static int get_psessionid(QQInfo *info) { int ret = NO_ERR; gint res = 0; if(info -> ptwebqq == NULL || info -> ptwebqq -> len <= 0){ g_warning("Need ptwebqq!!(%s, %d)", __FILE__, __LINE__); return PARAMETER_ERR; } Request *req = request_new(); Response *rps = NULL; request_set_method(req, "POST"); request_set_version(req, "HTTP/1.1"); request_set_uri(req, PSIDPATH); request_set_default_headers(req); request_add_header(req, "Host", PSIDHOST); request_add_header(req, "Cookie2", "$Version=1"); request_add_header(req, "Referer" , "http://d.web2.qq.com/proxy.html?v=20101025002"); GString *clientid = generate_clientid(); info -> clientid = clientid; g_debug("clientid: %s", clientid -> str); gchar* msg = g_malloc(500); g_snprintf(msg, 500, "{\"status\":\"%s\",\"ptwebqq\":\"%s\"," "\"passwd_sig\":""\"\",\"clientid\":\"%s\"" ", \"psessionid\":null}" , info -> me -> status -> str, info -> ptwebqq -> str , clientid -> str); gchar *escape = g_uri_escape_string(msg, NULL, FALSE); g_snprintf(msg, 500, "r=%s", escape); g_free(escape); request_append_msg(req, msg, strlen(msg)); gchar cl[10]; g_sprintf(cl, "%u", (unsigned int)strlen(msg)); request_add_header(req, "Content-Length", cl); request_add_header(req, "Content-Type" , "application/x-www-form-urlencoded"); g_free(msg); gchar *cookie = g_malloc(2000); gint idx = 0; if(info -> ptvfsession != NULL){ idx += g_snprintf(cookie + idx, 2000 - idx, "ptvfsession=%s; " , info -> ptvfsession -> str); } idx += g_snprintf(cookie + idx, 2000 - idx, "%s" , info -> cookie -> str); request_add_header(req, "Cookie", cookie); g_free(cookie); Connection *con = connect_to_host(PSIDHOST, 80); if(con == NULL){ g_warning("Can NOT connect to server!(%s, %d)" , __FILE__, __LINE__); request_del(req); return NETWORK_ERR; } send_request(con, req); res = rcv_response(con, &rps); if (-1 == res || !rps) { g_warning("Null point access (%s, %d)\n", __FILE__, __LINE__); ret = -1; goto error; } const gchar *retstatus = rps -> status -> str; if(g_strstr_len(retstatus, -1, "200") == NULL){ g_warning("Server status %s (%s, %d)", retstatus , __FILE__, __LINE__); ret = NETWORK_ERR; goto error; } json_t *json = NULL; switch(json_parse_document(&json, rps -> msg -> str)) { case JSON_OK: break; default: g_warning("json_parser_document: syntax error. (%s, %d)" , __FILE__, __LINE__); ret = NETWORK_ERR; goto error; } json_t *val; val = json_find_first_label_all(json, "retcode"); if(val -> child -> text[0] != '0'){ g_warning("Server return code %s(%s, %d)", val -> child -> text , __FILE__, __LINE__); ret = NETWORK_ERR; goto error; } val = json_find_first_label_all(json, "seskey"); if(val != NULL){ g_debug("seskey: %s (%s, %d)", val -> child -> text , __FILE__, __LINE__); info -> seskey = g_string_new(val -> child -> text); } val = json_find_first_label_all(json, "cip"); if(val != NULL){ info -> cip = g_string_new(val -> child -> text); } val = json_find_first_label_all(json, "index"); if(val != NULL){ info -> index = g_string_new(val -> child -> text); } val = json_find_first_label_all(json, "port"); if(val != NULL){ info -> port = g_string_new(val -> child -> text); } val = json_find_first_label_all(json, "status"); { g_debug("status: %s (%s, %d)", val -> child -> text , __FILE__, __LINE__); } val = json_find_first_label_all(json, "vfwebqq"); if(val != NULL){ g_debug("vfwebqq: %s (%s, %d)", val -> child -> text , __FILE__, __LINE__); info -> vfwebqq = g_string_new(val -> child -> text); } val = json_find_first_label_all(json, "psessionid"); if(val != NULL){ g_debug("psessionid: %s (%s, %d)", val -> child -> text , __FILE__, __LINE__); info -> psessionid = g_string_new(val -> child -> text); }else{ g_debug("Can not find pesssionid!(%s, %d): %s" , __FILE__, __LINE__, rps -> msg -> str); } error: json_free_value(&json); close_con(con); connection_free(con); request_del(req); response_del(rps); return ret; }
// // 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, ¶mstring); 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; }
// // 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; }
void DealRtpcRsp(char *rbuf,int rlen,const char* lIp, int lPort) { json_t *js_root = NULL; json_t *js_label = NULL; int js_ret = -1; char cmd[4] = ""; unsigned int sn = 0; int result = 0; char cookie[65] = ""; int callId = 0; int ret = 0; //update if (strncmp(lIp, RTPCIP, 16) != 0 || lPort != RTPCPORT) { printf("receive msg from invalid rtpc %s:%d", lIp, lPort); return; } //json format decode json_strip_white_spaces(rbuf); if(JSON_OK != (js_ret = json_parse_document(&js_root,rbuf))) { printf("rtpc_call_udp_deal:json_parse_document err(%d).",js_ret); return; } do { //cmd if(NULL == (js_label = json_find_first_label(js_root,"cmd"))) { printf("js cannot find <%s> label.","cmd"); break; } cmd[0] = js_label->child->text[0]; cmd[1] = '\0'; //sn if(NULL == (js_label = json_find_first_label(js_root,"sn"))) { printf("js cannot find <%s> label.","sn"); break; } sn = atoi(js_label->child->text); //cookie if(NULL == (js_label = json_find_first_label(js_root,"cookie"))) { printf("js cannot find <%s> label.","cookie"); break; } strncpy(cookie,js_label->child->text,sizeof(cookie)); //decode callId from cookie if(-1 == (callId = GetCallIdFromCookie(cookie))) { printf("get callId err,cookie:%s!!!",cookie); break; } //result if(NULL == (js_label = json_find_first_label(js_root,"result"))) { printf("js cannot find <%s> label.","result"); break; } result = atoi(js_label->child->text); printf("cmd:%s,sn:%u,cookie:%s,result:%d\n",cmd,sn,cookie,result); if(cmd[0] == 'O') { ret = DealRtpcCmdORsp(js_root, callId); if( 0 != ret ) { printf("allocate rtpc result=%d!",result); } } else if(cmd[0] == 'D') { if(result != 0) printf("release rtpc result=%d!",result); else DealRtpcCmdDRsp(js_root, callId); } else { printf("unknown cmd=%c!",cmd[0]); } }while(0); json_free_value(&js_root); }
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, "object"); if (!id || (id->child->type != JSON_OBJECT)) { if (!LSMessageRespond(message, "{\"returnValue\": false, \"errorCode\": -1, " "\"errorText\": \"Invalid or missing object parameter\"}", &lserror)) goto error; return true; } char *contents = NULL; if (json_tree_to_string(id->child, &contents) != JSON_OK) { sprintf(buffer, "{\"errorText\": \"Unable to parse object\", \"returnValue\": false, \"errorCode\": -1 }"); if (!LSMessageRespond(message, buffer, &lserror)) goto error; return true; } 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; }