// set Processor and Environment states from XML or JSON in binary. // state is in JSON format. XML can be read for backwards compatibility.. // void MLPluginProcessor::setPatchAndEnvStatesFromBinary (const void* data, int sizeInBytes) { // first try getting XML from binary- this will fail if blob is not in XML format XmlElementPtr xmlState(getXmlFromBinary (data, sizeInBytes)); if (xmlState) { bool setViewAttributes = true; setStateFromXML(*xmlState, setViewAttributes); } else { // TODO uncompress here std::string stateStr (static_cast<const char *>(data), sizeInBytes); // trim starting whitespace const char * pStart = stateStr.data(); const char * pTrimmedStart = pStart; while(isspace(*pTrimmedStart) && (pTrimmedStart - pStart < sizeInBytes)) { pTrimmedStart++; } // assume JSON bool OK = true; cJSON* root = cJSON_Parse(pTrimmedStart); if(root) { cJSON* patchState = cJSON_GetObjectItem(root, "patch"); if(patchState) { mpPatchState->setStateFromJSON(patchState); } else { OK = false; } cJSON* environmentState = cJSON_GetObjectItem(root, "environment"); if(environmentState) { mpEnvironmentState->setStateFromJSON(environmentState); } else { OK = false; } cJSON_Delete(root); } if(!OK) { // TODO notify user in release debug() << "MLPluginProcessor::setPatchAndEnvStatesFromBinary: couldn't load JSON!\n"; } } // push state for access by "Revert To saved" mpPatchState->clearStateStack(); mpPatchState->pushStateToStack(); }
int callback(middleware_t *middleware, http_method_t http_method, const char *url, const char *request, char *response) { if (strcmp(url, "/api/directors") == 0) { if (http_method == http_method_get) { cJSON *json = cJSON_CreateArray(); const director_t *directorArray; size_t numberOfDirectors; directors_get_all(middleware->directors, &directorArray, &numberOfDirectors); for (size_t i = 0; i < numberOfDirectors; ++i) { const director_t *director = directorArray + i; cJSON *jsonDir = cJSON_CreateObject(); cJSON_AddNumberToObject(jsonDir, "id", director->id); cJSON_AddStringToObject(jsonDir, "name", director->name); cJSON_AddStringToObject(jsonDir, "surname", director->surname); cJSON_AddNumberToObject(jsonDir, "salary", director->salary); cJSON_AddNumberToObject(jsonDir, "rating", director->rating); char birthdateStr[128]; sprintf(birthdateStr, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday); cJSON_AddStringToObject(jsonDir, "birthdate", birthdateStr); cJSON *jsonStartup = cJSON_CreateObject(); cJSON_AddStringToObject(jsonStartup, "name", director->startup.name); cJSON_AddStringToObject(jsonStartup, "country", director->startup.country); cJSON_AddItemToObject(jsonDir, "startup", jsonStartup); cJSON_AddItemToArray(json, jsonDir); } strcpy(response, cJSON_Print(json)); cJSON_Delete(json); return 1; } else if (http_method == http_method_post) { cJSON *json = cJSON_Parse(request); if (json) { cJSON *jsonName = cJSON_GetObjectItem(json, "name"); cJSON *jsonSurname = cJSON_GetObjectItem(json, "surname"); cJSON *jsonSalary = cJSON_GetObjectItem(json, "salary"); cJSON *jsonRating = cJSON_GetObjectItem(json, "rating"); cJSON *jsonBirthdate = cJSON_GetObjectItem(json, "birthdate"); cJSON *jsonStartup = cJSON_GetObjectItem(json, "startup"); if (jsonName && jsonSurname && jsonSalary && jsonRating && jsonBirthdate && jsonStartup) { cJSON *jsonStartupName = cJSON_GetObjectItem(jsonStartup, "name"); cJSON *jsonStartupCountry = cJSON_GetObjectItem(jsonStartup, "country"); if (jsonStartupName && jsonStartupCountry) { director_t director; strcpy(director.name, jsonName->valuestring); strcpy(director.surname, jsonSurname->valuestring); director.salary = jsonSalary->valueint; director.rating = jsonRating->valuedouble; memset(&director.birthdate, 0, sizeof(struct tm)); sscanf(jsonBirthdate->valuestring, "%i-%i-%i", &director.birthdate.tm_year, &director.birthdate.tm_mon, &director.birthdate.tm_mday); director.birthdate.tm_year -= 1900; director.birthdate.tm_mon -= 1; strcpy(director.startup.name, jsonStartupName->valuestring); strcpy(director.startup.country, jsonStartupCountry->valuestring); directors_insert(middleware->directors, &director); cJSON_Delete(json); strcpy(response, "OK"); return 1; } } } cJSON_Delete(json); } } else if (strncmp(url, "/api/directors/", strlen("/api/directors/")) == 0) { size_t directorId = atoi(strstr(strstr(url + 1, "/") + 1, "/") + 1); if (http_method == http_method_get) { const director_t *director = directors_get(middleware->directors, directorId); if (director) { cJSON *json = cJSON_CreateObject(); cJSON_AddNumberToObject(json, "id", director->id); cJSON_AddStringToObject(json, "name", director->name); cJSON_AddStringToObject(json, "surname", director->surname); cJSON_AddNumberToObject(json, "salary", director->salary); cJSON_AddNumberToObject(json, "rating", director->rating); char birthdateStr[128]; sprintf(birthdateStr, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday); cJSON_AddStringToObject(json, "birthdate", birthdateStr); cJSON *jsonStartup = cJSON_CreateObject(); cJSON_AddStringToObject(jsonStartup, "name", director->startup.name); cJSON_AddStringToObject(jsonStartup, "country", director->startup.country); cJSON_AddItemToObject(json, "startup", jsonStartup); strcpy(response, cJSON_Print(json)); cJSON_Delete(json); return 1; } } else if (http_method == http_method_delete) { if (directors_remove(middleware->directors, directorId)) { strcpy(response, "OK"); return 1; } } } else if (strcmp(url, "/") == 0) { response[0] = 0; stradd(response, "<html><body><h1>Hello!</h1><br>"); stradd(response, "<h2>Navigate to <a href=\"/directors\">directors list</a></h2><br>"); stradd(response, "<h2>Navigate to <a href=\"/api/directors\">api</a></h2><br>"); stradd(response, "<body><html>"); return 1; } else if (strcmp(url, "/directors") == 0) { if (http_method == http_method_get) { response[0] = 0; stradd(response, "<html><body><h1>Directors</h1><br><ul>"); const director_t *directorArray; size_t numberOfDirectors; directors_get_all(middleware->directors, &directorArray, &numberOfDirectors); for (size_t i = 0; i < numberOfDirectors; ++i) { const director_t *director = directorArray + i; stradd(response, "<li>"); char hrefBuffer[32]; sprintf(hrefBuffer, "<a href=\"/directors/%u\">", director->id); stradd(response, hrefBuffer); stradd(response, director->name); stradd(response, " "); stradd(response, director->surname); stradd(response, "</a>"); stradd(response, "</li>"); } stradd(response, "</ul>"); stradd(response, "<h2>Navigate to <a href=\"/new-director\">new director creation page</a></h2>"); stradd(response, "</body></html>"); return 1; } else if (http_method == http_method_post) { url_params_t *url_params = url_params_parse(request); const char *name = url_params_get(url_params, "name"); if((strlen(name)) == 0) return 0; const char *surname = url_params_get(url_params, "surname"); if((strlen(surname)) == 0) return 0; const char *salary = url_params_get(url_params, "salary"); if((strlen(salary)) == 0) return 0; const char *rating = url_params_get(url_params, "rating"); if((strlen(rating)) == 0) return 0; const char *birthdate = url_params_get(url_params, "birthdate"); if((strlen(birthdate)) == 0) return 0; const char *startupName = url_params_get(url_params, "startup_name"); if((strlen(startupName)) == 0) return 0; const char *startupCountry = url_params_get(url_params, "startup_country"); if((strlen(startupCountry)) == 0) return 0; director_t director; strcpy(director.name, name); strcpy(director.surname, surname); director.salary = atoi(salary); director.rating = atof(rating); memset(&director.birthdate, 0, sizeof(struct tm)); sscanf(birthdate, "%i-%i-%i", &director.birthdate.tm_year, &director.birthdate.tm_mon, &director.birthdate.tm_mday); director.birthdate.tm_year -= 1900; director.birthdate.tm_mon -= 1; strcpy(director.startup.name, startupName); strcpy(director.startup.country, startupCountry); directors_insert(middleware->directors, &director); strcpy(response, "<html><body><h2>Successfully added</h2><br><h1><a href=\"/directors\">Go back</a></h2><br><h2><a href=\"/new-director\">Add new</a></h2></body></html>"); return 1; } } else if (strncmp(url, "/directors/", strlen("/directors/")) == 0) { size_t directorId = atoi(strstr(url + 1, "/") + 1); if (http_method == http_method_get) { const director_t *director = directors_get(middleware->directors, directorId); if (director) { response[0] = 0; stradd(response, "<html><body><h1>Director: "); stradd(response, director->name); stradd(response, " "); stradd(response, director->surname); stradd(response, "</h1><br><ul>"); char buffer[32]; stradd(response, "<li>"); stradd(response, "Salary: "); sprintf(buffer, "%u", director->salary); stradd(response, buffer); stradd(response, "</li>"); stradd(response, "<li>"); stradd(response, "Rating: "); sprintf(buffer, "%f", director->rating); stradd(response, buffer); stradd(response, "</li>"); stradd(response, "<li>"); stradd(response, "Birthdate: "); sprintf(buffer, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday); stradd(response, buffer); stradd(response, "</li>"); stradd(response, "<li>Startup: <ul><li>"); stradd(response, "Name: "); stradd(response, director->startup.name); stradd(response, "</li><li>"); stradd(response, "Country: "); stradd(response, director->startup.country); stradd(response, "</li></ul></li></ul>"); stradd(response, "<form method=\"post\" action=\""); stradd(response, url); stradd(response, "\"><button type=\"submit\"><h1>Delete</h1></button>"); stradd(response, "</body></html>"); return 1; } } else if (http_method == http_method_post) { if (directors_remove(middleware->directors, directorId)) { strcpy(response, "<html><body><h2>Successfully deleted</h2><br><h1><a href=\"/directors\">Go back</a></h2></body></html>"); return 1; } } } else if (strcmp(url, "/new-director") == 0) { response[0] = 0; stradd(response, "<html><body><h1>Add new director</h1><br>"); stradd(response, "<form method=\"post\" action=\"/directors\">"); stradd(response, "Name: <input type=\"text\" name=\"name\"><br><br>"); stradd(response, "Surname: <input type=\"text\" name=\"surname\"><br><br>"); stradd(response, "Salary: <input type=\"text\" name=\"salary\"><br><br>"); stradd(response, "Rating: <input type=\"text\" name=\"rating\"><br><br>"); stradd(response, "Birthdate: <input type=\"text\" name=\"birthdate\"><br><br>"); stradd(response, "Startup name: <input type=\"text\" name=\"startup_name\"><br><br>"); stradd(response, "Startup country: <input type=\"text\" name=\"startup_country\"><br><br>"); stradd(response, "<button type=\"Submit\">Submit</button>"); stradd(response, "</form></body></html>"); return 1; } return 0; }
/** * The entity handler determines how to process a POST request. * Per the REST paradigm, POST can also be used to update representation of existing * resource or create a new resource. * For pstat, it updates only tm and om. */ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest) { OCEntityHandlerResult ehRet = OC_EH_ERROR; cJSON *postJson = NULL; if (ehRequest->resource) { postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData); VERIFY_NON_NULL(TAG, postJson, INFO); cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME); VERIFY_NON_NULL(TAG, jsonPstat, INFO); cJSON *commitHashJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME); uint16_t commitHash = 0; if (commitHashJson) { commitHash = commitHashJson->valueint; } cJSON *tmJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME); if (tmJson && gPstat) { gPstat->tm = (OicSecDpm_t)tmJson->valueint; if(0 == tmJson->valueint && gPstat->commitHash == commitHash) { gPstat->isOp = true; gPstat->cm = NORMAL; OC_LOG (INFO, TAG, PCF("CommitHash is valid and isOp is TRUE")); } else { OC_LOG (INFO, TAG, PCF("CommitHash is not valid")); } } cJSON *omJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME); if (omJson && gPstat) { /* * Check if the operation mode is in the supported provisioning services * operation mode list. */ for(size_t i=0; i< gPstat->smLen; i++) { if(gPstat->sm[i] == omJson->valueint) { gPstat->om = (OicSecDpom_t)omJson->valueint; break; } } } // Convert pstat data into JSON for update to persistent storage char *jsonStr = BinToPstatJSON(gPstat); if (jsonStr) { cJSON *jsonPstat = cJSON_Parse(jsonStr); OICFree(jsonStr); if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat)) { ehRet = OC_EH_OK; } } } exit: //Send payload to request originator if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL)) { OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandlePstatPostRequest")); } cJSON_Delete(postJson); return ehRet; }
static void* task_worker( void* pArg ) { UTV_RESULT result; cJSON* task; cJSON* taskId; cJSON* output; UTV_BYTE* sessionId; sessionId = UtvMalloc( SESSION_ID_SIZE ); UtvLiveSupportGetSessionId( sessionId, SESSION_ID_SIZE ); while ( UtvLiveSupportIsSessionActive() ) { result = UtvInternetDeviceWebServiceLiveSupportGetNextTask( sessionId, GET_NEXT_TASK_TIMEOUT_SECONDS, (void**)&task ); if ( UTV_OK == result ) { if ( task ) { taskId = cJSON_GetObjectItem( task, "TASK_ID" ); /* * If the taskId is -1 then the session has been terminated. */ if ( -1 == taskId->valueint ) { /* * This is an early exit so make sure we free up the task object. */ cJSON_Delete( task ); break; } UtvLiveSupportSetSessionState( UTV_LIVE_SUPPORT_SESSION_STATE_RUNNING ); output = process_task( task ); UtvInternetDeviceWebServiceLiveSupportCompleteTask( sessionId, taskId->valueint, output ); cJSON_Delete( task ); } } else { UtvMessage( UTV_LEVEL_ERROR, "%s: Error occured getting next task, terminating task worker \"%s\"", __FUNCTION__, UtvGetMessageString( result ) ); break; } } UtvFree( sessionId ); s_taskWorkerThread = 0; /* * If the session is terminated by the Agent instead of the NetReady Services then the * session ID is already zero and there is no need to print anything or set the session * ID to zero. */ if ( UtvLiveSupportIsSessionActive() ) { /* * If the result from the get next task request is UTV_OK it means the session was * terminated from the NetReady Services and not internally initiated so pass FALSE to * the session shutdown processing. * * If the result from the get next task request is NOT UTV_OK it means an error occurred * within this processing and that the shutdown is being initiated internally so pass * TRUE to the session shutdown processing. */ UtvLiveSupportSessionShutdown( ( result != UTV_OK ) ); } UTV_THREAD_EXIT; }
indigo_error_t ind_cxn_cfg_stage(cJSON *config) { indigo_error_t err; int i; err = ind_cfg_parse_loglevel(config, "logging.connection", OFCONNECTIONMANAGER_CONFIG_LOG_BITS_DEFAULT, &staged_config.log_flags); if (err != INDIGO_ERROR_NONE) { return err; } /* Not supporting setting log options yet */ err = ind_cfg_lookup_int(config, "keepalive_period_ms", &staged_config.keepalive_period_ms); if (err == INDIGO_ERROR_NONE) { if (staged_config.keepalive_period_ms <= 0) { AIM_LOG_ERROR("'keepalive_period_ms' must be greater than 0"); return INDIGO_ERROR_PARAM; } } else if (err == INDIGO_ERROR_PARAM) { AIM_LOG_ERROR("Config: Could not parse 'keepalive_period_ms'"); return err; } else if (err == INDIGO_ERROR_NOT_FOUND) { AIM_LOG_ERROR("Config: Missing required key 'keepalive_period_ms'"); return err; } err = parse_controllers(config); if (err != INDIGO_ERROR_NONE) { return err; } for (i = 0; i < staged_config.num_controllers; i++) { /* @FIXME local? listen? priority? */ staged_config.controllers[i].config.periodic_echo_ms = staged_config.keepalive_period_ms; staged_config.controllers[i].config.reset_echo_count = 3; /* @FIXME */ } /* verify TLS parameters */ /* * for now, we should be able to accept: * - TLS config with switch cert and key specified, * cipher_list and CA cert optional * - if cipher_list is specified, it should be valid * - if CA cert is specified, it should be consistent with switch cert * - TLS config with parameters specified, but * CA cert, switch cert and switch priv key files not present */ { cJSON *node = cJSON_GetObjectItem(config, "tls"); if (node) { if (node->type != cJSON_Object) { AIM_LOG_ERROR("Config: expected tls to be an object"); return INDIGO_ERROR_PARAM; } err = parse_tls_config(node); if (err != INDIGO_ERROR_NONE) { AIM_LOG_ERROR("Config: error parsing TLS config: %s", indigo_strerror(err)); return err; } } else { AIM_LOG_VERBOSE("Config: TLS config not found, continuing"); } } staged_config.valid = true; return INDIGO_ERROR_NONE; }
int msg_tcp_handler(int sockfd,struct online_list *clientlist) { int ret; char buf[ TCP_BUFFER_SIZE ]; memset( buf, '\0', TCP_BUFFER_SIZE ); ret = recv( sockfd, buf, TCP_BUFFER_SIZE, 0 ); if( ret < 0 ) { if( ( errno != EAGAIN ) && ( errno != EWOULDBLOCK ) ) { close( sockfd ); return -1; } } else if( ret == 0 ) { close( sockfd ); return -1; } cJSON *msg = cJSON_Parse(buf); /* debug */ char *out = cJSON_Print(msg); printf("recv buf: %s\n",out); free(out); if(!msg) { return -1; /* debug("parse json",__LINE__); */ } char msgtype[64] = ""; strcpy(msgtype,cJSON_GetObjectItem(msg,"MsgType")->valuestring); if(strcmp(MSG_QUERY_RES,msgtype) == 0) { /* search resource */ printf("MsgType: MSG_QUERY_RES\n"); cJSON *child = NULL; child = cJSON_GetObjectItem(msg,"QueryKey"); if(child == NULL) { /* not found child */ cJSON_Delete(msg); return 0; } if(strlen(cJSON_GetObjectItem(msg,"QueryKey")->valuestring) <= 1) { /* key is shorter */ cJSON_Delete(msg); return 0; } struct queryres query; strcpy(query.key, cJSON_GetObjectItem(msg,"QueryKey")->valuestring); /* debug */ printf("QueryKey: %s\n",query.key); /* query database */ struct resource_type res[10]; int len = 10; char *text = NULL; get_res_list(query,res,&len); text = res_list_to_json(res,len); /* debug */ printf("send: %s\n",text); /* response query msg */ send(sockfd,text,strlen(text)+1, 0); free(text); } else if (strcmp(MSG_GET_PUSH,msgtype) == 0) { /* get push */ /* debug */ printf("MsgType: MSG_GET_PUSH\n"); /* get want number */ int numwanted = cJSON_GetObjectItem(msg,"NumWanted")->valueint; /* default push method */ struct resource_type share_res[10]; int len = numwanted; get_push_list(share_res,&len); /* get push list */ char *text = NULL; text = res_list_to_json(share_res,len); /* convert res list to json */ /* debug */ printf("send: %s\n",text); /* response query msg */ send(sockfd,text,strlen(text)+1, 0); free(text); } else if (strcmp(MSG_SHARE_RES,msgtype) == 0) { /* share resource */ printf("MsgType: MSG_SHARE_RES\n"); struct resource_share share_res; json_to_resource_share(buf,&share_res); /* convert json to resource share */ add_share_resource(&share_res); /* add share resource into db */ /* debug */ printf("Resource: Name:%s, Tag:%s, Size:%s, MD5:%s, Owner:%s, PieceCount:%d\n", share_res.name,share_res.tag,share_res.size,share_res.md5, share_res.mac,share_res.piececount); } else if (strcmp(MSG_DOWNLOAD_RES,msgtype) == 0) { /* download resource */ /* debug */ printf("MsgType: MSG_DOWNLOAD_RES\n"); struct download_req msgreq; struct peer_info peers[20]; int len = 1; json_to_download_req(buf,&msgreq); /*convert json to download_req */ /* debug */ printf("download_req: ip:%s, md5:%s, numwant:%d, event:%s\n",msgreq.clientip,msgreq.md5,msgreq.numwant,msgreq.event); loadbalance_on_server(clist,&msgreq,peers,&len); /* algorithm loadbalance on server */ char *text = NULL; text = peer_info_to_json(peers,len); /* convert peer_info to json */ /* debug */ printf("Downloaded: %s\n",text); send(sockfd,text,strlen(text)+1, 0); } else if(strcmp(MSG_QUIT,msgtype) == 0) { /* quit */ printf("MsgType: MSG_QUIT\n"); char *clientip; clientip = cJSON_GetObjectItem(msg,"ClientIP")->valuestring; printf("quit ip: %s\n",clientip); del_from_online_list(clist,clientip); print_clist(clist); } free(msg); return 0; }
int CWorldOther::SdkServerVerify(T_VECTOR_OBJECT* p, CPluto& u) { #if 0 //注释掉老代码 if (p->size() != 4) { return -1; } string& url = VOBJECT_GET_SSTR((*p)[0]); int32_t nFd = VOBJECT_GET_I32((*p)[1]); string& strAccount = VOBJECT_GET_SSTR((*p)[2]); string& strPlatId = VOBJECT_GET_SSTR((*p)[3]); CMailBox* pmb = u.GetMailbox(); if (NULL == pmb) { return -1; } CPluto* duplicate = new CPluto(u.GetBuff(), u.GetMaxLen()); duplicate->SetMailbox(pmb); int ret = threadpool_add_job(g_threadpool, ThreadJob_SdkServerVerify, (void*)(duplicate)); if (ret != 0) { //直接返回服务器繁忙,请稍后再试 //printf("服务器繁忙,请稍后再试!\n"); //std::cout << "服务器繁忙,请稍后再试!" << endl; LogWarning("CWorldOther::SdkServerVerify", "threadpool list is full."); CPluto* u2 = new CPluto; u2->Encode(MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK); (*u2)<< int32_t(-2) << nFd << strAccount << strPlatId << EndPluto; g_pluto_sendlist.PushPluto(u2); //不适合多线程发送 //pmb->RpcCall(GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, -2, nFd, strAccount, strPlatId); } return 0; #endif if (p->size() != 4) { return -1; } string& url = VOBJECT_GET_SSTR((*p)[0]); int32_t nFd = VOBJECT_GET_I32((*p)[1]); string& strAccount = VOBJECT_GET_SSTR((*p)[2]); string& strPlatId = VOBJECT_GET_SSTR((*p)[3]); CMailBox* pmb = u.GetMailbox(); pluto_msgid_t msg_id = u.GetMsgId();; string resp = ""; int ret = GetUrl_new(url.c_str(), resp); if (ret != CURLE_OK) { LogWarning("CWorldOther::SdkServerVerify", "%s ret = %d", strAccount.c_str(), ret); //todo:faild. SyncRpcCall(g_pluto_sendlist, SERVER_LOGINAPP, MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, ret, nFd, strAccount, strPlatId); return 0; } Trim(resp); cJSON* json = cJSON_Parse(resp.c_str()); cJSON* childJs = cJSON_GetObjectItem(json, "code"); int rst = cJSON_GetObjectItem(json, "code")->valueint; if (rst == 1) { //succeed. if (strAccount.c_str() != cJSON_GetObjectItem(json, "msg")->valuestring) { ret = 0; } else { LogWarning("CWorldOther::SdkServerVerify", "strAccount[%s] msg[%s]", strAccount.c_str(), cJSON_GetObjectItem(json, "msg")->valuestring); ret = 1; //pmb->RpcCall(GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, int32_t(1), nFd, strAccount, strPlatId); } } else { //failed. LogWarning("CWorldOther::SdkServerVerify", "strAccount[%s] rst[%d]", strAccount.c_str(), rst); ret = -1; //pmb->RpcCall(GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, -1, nFd, strAccount, strPlatId); } SyncRpcCall(g_pluto_sendlist, SERVER_LOGINAPP, MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, ret, nFd, strAccount, strPlatId); return 0; }
void cJSONExt_GetBool(cJSON* object, const char* name, bool* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = obj->valueint > 0 ? true : false; }
void cJSONExt_GetChar(cJSON* object, const char* name, char* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = (char)obj->valueint; }
int Switch_Control::ParseMessage(char* strMesg,int iLen,int accept_fd) { cJSON *pcmd = NULL; char cJsonBuff[1024 * 2]={0}; int iRecvLen = 0; char Req_buf[1024]={0}; char Replay_buf[1024]={0}; memcpy(Req_buf,strMesg,iLen); char *Rcv_buf=strMesg; Pubc::replace(Rcv_buf,"XXEE",""); cJSON* pRoot = cJSON_Parse(Rcv_buf); if (pRoot) { pcmd = cJSON_GetObjectItem(pRoot, "cmd"); if (pcmd) { //判断请求类型 if (strcmp(pcmd->valuestring, "add_ads_stream") == 0) { printf("--Add_stream request \n"); fflush(stdout); //通过 cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid"); char strsessionid[128] ={0}; if(psessionid) memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1); cJSON* pToken = cJSON_GetObjectItem(pRoot, "input_url"); char input_url[256] ={0}; if(pToken) memcpy(input_url,pToken->valuestring,strlen(pToken->valuestring)+1); char output_url[256] ={0}; cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "output_url"); if(pStreamID) memcpy(output_url,pStreamID->valuestring,strlen(pStreamID->valuestring)+1); cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno"); char strSerialNo[128] ={0}; if(pSerialNo) memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1); memset(Replay_buf,0,sizeof(Replay_buf)); ManagerFactory::instance()->AddOneSwitch(Req_buf,Replay_buf,strsessionid,input_url); // write(Replay_buf,strlen(Replay_buf)); //报文回复 Stream ptmpRequest; ptmpRequest.m_clientSocket = accept_fd; //ptmpRequest.Send_Jsoon_str(); ptmpRequest.Send_str(Replay_buf); LOG_INFO_FORMAT("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); struct timeval tv1; long long time1; gettimeofday(&tv1, NULL); time1 = tv1.tv_sec*1000 + tv1.tv_usec / 1000; printf("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); printf("******* Rcv time =%ld *****\n",time1); } else if(strcmp(pcmd->valuestring, "del_ads_stream") == 0) { printf("--Del_stream request \n"); fflush(stdout); //通过 cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid"); char strsessionid[128] ={0}; if(psessionid) memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1); cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno"); char strSerialNo[128] ={0}; if(pSerialNo) memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1); memset(Replay_buf,0,sizeof(Replay_buf)); ManagerFactory::instance()->DeleteOneSwitch(Req_buf,Replay_buf,strsessionid); //write(Replay_buf,strlen(Replay_buf)); Stream ptmpRequest; ptmpRequest.m_clientSocket = accept_fd; //ptmpRequest.Send_Jsoon_str(); ptmpRequest.Send_str(Replay_buf); LOG_INFO_FORMAT("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); struct timeval tv1; long long time1; gettimeofday(&tv1, NULL); time1 = tv1.tv_sec*1000 + tv1.tv_usec / 1000; printf("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); printf("******* Rcv time =%ld *****\n",time1); } else if(strcmp(pcmd->valuestring, "reset_device") == 0) { printf("--Reset_stream request \n"); fflush(stdout); //通过 cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno"); char strSerialNo[128] ={0}; if(pSerialNo) memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1); ManagerFactory::instance()->DeleteAllWsitch(Req_buf,Replay_buf,NULL); // write(Replay_buf,strlen(Replay_buf)); Stream ptmpRequest; ptmpRequest.m_clientSocket = accept_fd; //ptmpRequest.Send_Jsoon_str(); ptmpRequest.Send_str(Replay_buf); LOG_INFO_FORMAT("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); struct timeval tv1; long long time1; gettimeofday(&tv1, NULL); time1 = tv1.tv_sec*1000 + tv1.tv_usec / 1000; printf("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); printf("******* Rcv time =%ld *****\n",time1); } else if (strcmp(pcmd->valuestring, "change_stream") == 0) { printf("--Change_stream request \n"); fflush(stdout); } else if (strcmp(pcmd->valuestring, "req_ads_stream") == 0) { printf("--req_ads_stream request \n"); fflush(stdout); cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid"); char strsessionid[128] ={0}; int iSeessionID = 0; if(psessionid) { memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1); //iSeessionID = atoi(strsessionid); } cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno"); char strSerialNo[128] ={0}; if(pSerialNo) memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1); memset(Replay_buf,0,sizeof(Replay_buf)); ManagerFactory::instance()->ReqOneSwitchForPort(Req_buf,Replay_buf,strsessionid); //write(Replay_buf,strlen(Replay_buf)); Stream ptmpRequest; ptmpRequest.m_clientSocket = accept_fd; //ptmpRequest.Send_Jsoon_str(); ptmpRequest.Send_str(Replay_buf); LOG_INFO_FORMAT("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); struct timeval tv1; long long time1; gettimeofday(&tv1, NULL); time1 = tv1.tv_sec*1000 + tv1.tv_usec / 1000; printf("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); printf("******* Rcv time =%ld *****\n",time1); } else if(strcmp(pcmd->valuestring, "check_session") == 0) { printf("--check_session \n"); //通过 cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid"); char strsessionid[128] ={0}; int iSeessionID = 0; if(psessionid) { memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1); //iSeessionID = atoi(strsessionid); } cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno"); char strSerialNo[128] ={0}; if(pSerialNo) memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1); memset(Replay_buf,0,sizeof(Replay_buf)); ManagerFactory::instance()->CheckOneSwitch(Req_buf,Replay_buf,strsessionid); // write(Replay_buf,strlen(Replay_buf)); Stream ptmpRequest; ptmpRequest.m_clientSocket = accept_fd; //ptmpRequest.Send_Jsoon_str(); ptmpRequest.Send_str(Replay_buf); LOG_INFO_FORMAT("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); struct timeval tv1; long long time1; gettimeofday(&tv1, NULL); time1 = tv1.tv_sec*1000 + tv1.tv_usec / 1000; printf("INFO - [SWM]: tcp send %d bytes :[%s] \n",strlen(Replay_buf),Replay_buf); printf("******* Rcv time =%ld *****\n",time1); } } } }
int Switch_Control::SendResetMessage(const char* phostIp,int iPort) { struct sockaddr_in s_addr; int sockid; socklen_t addr_len; sockid=socket(AF_INET,SOCK_STREAM,0); s_addr.sin_family = AF_INET ; s_addr.sin_addr.s_addr = inet_addr(phostIp) ; s_addr.sin_port=htons((unsigned short)iPort); /* if (-1 == fcntl(sockid, F_SETFL, O_NONBLOCK)) { printf("fcntl socket error!\n"); fflush(stdout); return -1; } */ unsigned long ul = 1; ioctl(sockid, FIONBIO, &ul); //设置为非阻塞模式 struct timeval timeout={3,1000*500}; //1秒 int len = sizeof(timeout); setsockopt(sockid,SOL_SOCKET,SO_SNDTIMEO, &timeout,len); setsockopt(sockid,SOL_SOCKET,SO_RCVTIMEO,&timeout,len); fd_set set; printf("---begin connect \n"); //重复连接3次,防止中断等原因导致的异常 for(int i=0;i<3;i++) { bool ret = false; int iret = -1; iret = connect(sockid,(struct sockaddr *)&s_addr,(int)(sizeof(s_addr))); if(iret == -1) { struct timeval tm; tm.tv_sec = 0; tm.tv_usec = 1000*500; FD_ZERO(&set); FD_SET(sockid, &set); int error=-1; if( select(sockid+1, NULL, &set, NULL, &tm) > 0) { getsockopt(sockid, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len); if(error == 0) { ret = true; printf("---error no \n"); //::close(sockid); //break; } else ret = false; } else ret = false; } else if(iret==0) { break; } if(i==2) { //cout<<"connect Error "<<p_host<<":"<<p_Port<<endl; //perror("::connect"); ::close(sockid); return -1; } printf("---sleeep\n"); usleep(1000); //cout<<"connect again: "<<p_host<<":"<<p_Port<<endl; } int optval = 1; ul = 0; ioctl(sockid, FIONBIO, &ul); //设置为阻塞模式 printf("---connect success \n"); char alivetick[1024]={0}; int iData=0; char strdata[32]={0}; sprintf(strdata,"%d",iData); //发送心跳 Stream ptmpRequest; ptmpRequest.m_clientSocket = sockid; //cJSON *pRet_root; ptmpRequest.pRet_root = cJSON_CreateObject(); ptmpRequest.Requst_Json_str(2,"cmd","reset_device"); ptmpRequest.Requst_Json_str(2,"returnCode","0"); ptmpRequest.Requst_Json_str(2,"serialno","11111111"); ptmpRequest.Send_Jsoon_str(); memset(alivetick,0,sizeof(alivetick)); int length = 0; int i_rc = 0, i_count = 0; int iRecvLen = 0; do { i_rc = recv(sockid, alivetick + i_count, 2000 - i_count, 0); if (i_rc <= 0)break;//异常关闭 i_count += i_rc; } while (strstr(alivetick, "XXEE") == NULL); iRecvLen = i_count; if (iRecvLen <= 0){ ::close(sockid); return -1; } printf("recv:%s \n",alivetick); cJSON *pcmd = NULL; //解析报文数据 replace(alivetick, "XXEE", ""); cJSON* pRoot = cJSON_Parse(alivetick); if (pRoot) { pcmd = cJSON_GetObjectItem(pRoot, "cmd"); if (pcmd) { //判断请求类型 if(strcmp(pcmd->valuestring, "reset_device") == 0) { ::close(sockid); return 0; } } } ::close(sockid); return -1; }
int Switch_Control::ConnectToSever(const char* phostIp,int iPort,int *pCurrent_num,int *pMax_num) { struct sockaddr_in s_addr; int sockid; socklen_t addr_len; sockid=socket(AF_INET,SOCK_STREAM,0); s_addr.sin_family = AF_INET ; s_addr.sin_addr.s_addr = inet_addr(phostIp) ; s_addr.sin_port=htons((unsigned short)iPort); fcntl(sockid,F_SETFD, FD_CLOEXEC); /* if (-1 == fcntl(sockid, F_SETFL, O_NONBLOCK)) { printf("fcntl socket error!\n"); fflush(stdout); return -1; } */ unsigned long ul = 1; ioctl(sockid, FIONBIO, &ul); //设置为非阻塞模式 struct timeval timeout={10,1000*500}; //1秒 int len = sizeof(timeout); setsockopt(sockid,SOL_SOCKET,SO_SNDTIMEO, &timeout,len); setsockopt(sockid,SOL_SOCKET,SO_RCVTIMEO,&timeout,len); fd_set set; printf("---begin connect \n"); //重复连接3次,防止中断等原因导致的异常 for(int i=0;i<3;i++) { bool ret = false; int iret = -1; iret = connect(sockid,(struct sockaddr *)&s_addr,(int)(sizeof(s_addr))); if(iret == -1) { struct timeval tm; tm.tv_sec = 5; tm.tv_usec = 1000*500; FD_ZERO(&set); FD_SET(sockid, &set); int error=-1; if( select(sockid+1, NULL, &set, NULL, &tm) > 0) { getsockopt(sockid, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len); if(error == 0) { ret = true; printf("---error no \n"); //break; } else ret = false; } else ret = false; } else if(iret==0) { break; } if(i==2) { //cout<<"connect Error "<<p_host<<":"<<p_Port<<endl; //perror("::connect"); printf("--connect error \n"); LOG_ERROR("ERROR - [SWM]: connect error \n"); ::close(sockid); return -1; } // printf("---sleep \n"); usleep(1000); //cout<<"connect again: "<<p_host<<":"<<p_Port<<endl; } ul = 0; ioctl(sockid, FIONBIO, &ul); //设置为阻塞模式 printf("---connect success \n"); int optval = 1; // setsockopt(sockid,SOL_SOCKET,SO_KEEPALIVE,(char *)(&optval),sizeof(optval)); char alivetick[1024]={0}; int iData=0; char strdata[32]={0}; sprintf(strdata,"%d",iData); //发送心跳 Stream ptmpRequest; ptmpRequest.m_clientSocket = sockid; //cJSON *pRet_root; ptmpRequest.pRet_root = cJSON_CreateObject(); ptmpRequest.Requst_Json_str(2,"cmd","alivetick"); ptmpRequest.Requst_Json_str(2,"dataid",strdata); ptmpRequest.Send_Jsoon_str(); //LOG_INFO("INFO - [SWM]: send alive \n"); memset(alivetick,0,sizeof(alivetick)); int length = 0; int i_rc = 0, i_count = 0; int iRecvLen = 0; do { i_rc = recv(sockid, alivetick + i_count, 2000 - i_count, 0); if (i_rc <= 0)break;//异常关闭 i_count += i_rc; } while (strstr(alivetick, "XXEE") == NULL); iRecvLen = i_count; if (iRecvLen <= 0) { ::close(sockid); LOG_ERROR("ERROR - [SWM]: Recv error \n"); return -1; } alivetick[iRecvLen]='\0'; LOG_INFO_FORMAT("INFO - [SWM]: tcp recved %d bytes :[%s] \n",iRecvLen,alivetick); printf("recv:%s \n",alivetick); fflush(stdout); cJSON *pcmd = NULL; //解析报文数据 replace(alivetick, "XXEE", ""); cJSON* pRoot = cJSON_Parse(alivetick); if (pRoot) { pcmd = cJSON_GetObjectItem(pRoot, "cmd"); if (pcmd) { //判断请求类型 if (strcmp(pcmd->valuestring, "alivetick") == 0) { //通过 printf("--alive tick repay \n"); cJSON* pDataid = cJSON_GetObjectItem(pRoot, "dataid"); char strDataid[128] ={0}; if(pDataid) memcpy(strDataid,pDataid->valuestring,strlen(pDataid->valuestring)+1); int iRecvData = atoi(strDataid); cJSON* pcurrent = cJSON_GetObjectItem(pRoot, "current_num"); char strcurrent[128] ={0}; if(pcurrent) memcpy(strcurrent,pcurrent->valuestring,strlen(pcurrent->valuestring)+1); int icurrentnum = atoi(strcurrent); cJSON* pmaxnum = cJSON_GetObjectItem(pRoot, "max_num"); char strmax[128] ={0}; if(pmaxnum) memcpy(strmax,pmaxnum->valuestring,strlen(pmaxnum->valuestring)+1); int imaxtnum = atoi(strmax); *pCurrent_num = icurrentnum; *pMax_num = imaxtnum; if(iRecvData == (iData +1)) { //正常心跳 ::close(sockid); //printf("---- alive keep \n"); return 0; } } } } ::close(sockid); return -1; }
int svrapp::client_req(param_list * pl){ ipaddr &peeraddr = pl->n->get_peeraddr(); log_out(log_debug, "client_req::%s..%s\n", peeraddr.ip, pl->content); cnt_info * cif = (cnt_info*)pl->n->get_context(); if (!cif){ cif = new cnt_info(cnt_type); cif->parse_token(NULL) ; pl->n->set_context(cif); m_cntmap[cif->get_numkey()] = pl->n; } cJSON * jsdev = cJSON_GetObjectItem(pl->jsdata, "device_id"); if(!jsdev || jsdev->type != cJSON_Number){ log_out(log_error, "client_req::invalid device(%s)\n", pl->content); post_ack(pl->n, pl->ack_cmd, pl->serial, ERROR_PARAM, "device_id invalid"); return -1; } uint platform = get_platform_code_delete_item(pl->jsdata); char devkey[strkey_len] = {0}; create_devkey(platform, jsdev->valueuint64, devkey); std::map<strkey_t, app_connection*>::iterator it = m_devmap.find(devkey); if(it == m_devmap.end()){ log_out(log_error, "client_req::device(%s) off line\n", devkey); post_ack(pl->n, pl->ack_cmd, pl->serial, ERROR_DEV_OFFLINE, "device is offline"); return -1; } //***********save cmd**************** //here fixed int channel = 0; cJSON * jschn = cJSON_GetObjectItem(pl->jsdata, "channel"); if(jschn && jschn->type == cJSON_Number){ channel = jschn->valueint; } char chnkey[strkey_len] = {0}; create_chnkey(devkey, channel, chnkey); int index = hash_key(jsdev->valueuint64, max_group_count); std::map<strkey_t, cmd_s> & temp = m_cmds_map[index]; std::map<strkey_t, cmd_s>::iterator it1 = temp.find(chnkey); if(it1 == temp.end()){ cmd_s cs; memset(&cs, 0, sizeof(cs)); it1 = temp.insert(std::make_pair(chnkey, cs)).first; } cmd_s &cs = it1->second; cs.last_cmd_time = (uint)time(NULL); strncpy(cs.last_cmd, pl->cmd, sizeof(cs.last_cmd) -1 ); //***********save cmd**************** //create_serial char new_serial[128] = {0}; create_serial(cif->get_numkey(), pl->serial, new_serial, sizeof(new_serial)); //create devkey cJSON_DeleteItemFromParent(pl->jsdata, jsdev); cJSON_AddStringToObject(pl->jsdata, "devkey", devkey); char * out = cJSON_PrintUnformatted(pl->jsdata); app_connection * dn = it->second; post_req(dn, pl->cmd, out, new_serial); free(out); return 0; }
/** * JsonÎļþ½âÎö * * \param text * * \return */ void* RenRenAPI_JsonParse_BlogGetComments(char *text) { int i = 0; cJSON *jsonall; cJSON *json; cJSON *pTemp0; tResponseBlogGetComments* Response = new tResponseBlogGetComments; memset(Response, 0 , sizeof(tResponseBlogGetComments)); jsonall = cJSON_Parse(text); Response->nArraySize = cJSON_GetArraySize(jsonall); if(Response->nArraySize>0) { Response->Array = (tResponseBlogGetCommentsItem*) malloc(sizeof( tResponseBlogGetCommentsItem) * Response->nArraySize ); memset(Response->Array, 0 , sizeof(tResponseBlogGetCommentsItem) * Response->nArraySize); for(i = 0; i<Response->nArraySize; i++) { json = cJSON_GetArrayItem(jsonall, i); pTemp0 = cJSON_GetObjectItem(json, "id"); if(pTemp0) { Response->Array[i].id = pTemp0->valueint; } pTemp0 = cJSON_GetObjectItem(json, "uid"); if(pTemp0) { Response->Array[i].uid = pTemp0->valueint; } pTemp0 = cJSON_GetObjectItem(json, "name"); if(pTemp0) { STRCPY_Ex(Response->Array[i].name, pTemp0->valuestring); } pTemp0 = cJSON_GetObjectItem(json, "headurl"); if(pTemp0) { STRCPY_Ex(Response->Array[i].headurl, pTemp0->valuestring); } pTemp0 = cJSON_GetObjectItem(json, "time"); if(pTemp0) { STRCPY_Ex(Response->Array[i].time, pTemp0->valuestring); } pTemp0 = cJSON_GetObjectItem(json, "content"); if(pTemp0) { STRCPY_Ex(Response->Array[i].content, pTemp0->valuestring); } pTemp0 = cJSON_GetObjectItem(json, "is_whisper"); if(pTemp0) { STRCPY_Ex(Response->Array[i].is_whisper, pTemp0->valuestring); } } } cJSON_Delete(jsonall); return Response; }
char *pNXT_jsonhandler(cJSON **argjsonp,char *argstr,char *verifiedsender) { struct NXThandler_info *mp = Global_mp; long len; struct coin_info *cp; int32_t valid,firsttime = 1; cJSON *secretobj = 0,*json; char NXTACCTSECRET[1024],sender[64],*origparmstxt,*parmstxt=0,encoded[NXT_TOKEN_LEN+1],*retstr = 0; again: sender[0] = 0; if ( verifiedsender != 0 && verifiedsender[0] != 0 ) safecopy(sender,verifiedsender,sizeof(sender)); valid = -1; //printf("pNXT_jsonhandler argjson.%p\n",*argjsonp); if ( *argjsonp != 0 ) { secretobj = cJSON_GetObjectItem(*argjsonp,"secret"); copy_cJSON(NXTACCTSECRET,secretobj); if ( NXTACCTSECRET[0] == 0 && (cp= get_coin_info("BTCD")) != 0 ) { safecopy(NXTACCTSECRET,cp->NXTACCTSECRET,sizeof(NXTACCTSECRET)); cJSON_ReplaceItemInObject(*argjsonp,"secret",cJSON_CreateString(NXTACCTSECRET)); //printf("got cp.%p for BTCD (%s) (%s)\n",cp,cp->NXTACCTSECRET,cJSON_Print(*argjsonp)); } parmstxt = cJSON_Print(*argjsonp); len = strlen(parmstxt); stripwhite_ns(parmstxt,len); //printf("parmstxt.(%s)\n",parmstxt); } if ( *argjsonp == 0 ) { json = cJSON_CreateObject(); cJSON_AddItemToObject(json,"error",cJSON_CreateString("cant parse")); cJSON_AddItemToObject(json,"argstr",cJSON_CreateString(argstr)); retstr = cJSON_Print(json); free_json(json); return(retstr); } else { origparmstxt = parmstxt; parmstxt = verify_tokenized_json(sender,&valid,argjsonp,parmstxt); } retstr = pNXT_json_commands(mp,Global_pNXT,*argjsonp,sender,valid,argstr); //printf("back from pNXT_json_commands\n"); if ( firsttime != 0 && retstr == 0 && *argjsonp != 0 && parmstxt == 0 ) { cJSON *reqobj; uint64_t nxt64bits; char _tokbuf[4096],NXTaddr[64],buf[1024];//,*str; firsttime = 0; reqobj = cJSON_GetObjectItem(*argjsonp,"requestType"); copy_cJSON(buf,reqobj); if ( cJSON_GetObjectItem(*argjsonp,"requestType") != 0 ) cJSON_ReplaceItemInObject(*argjsonp,"time",cJSON_CreateNumber(time(NULL))); else cJSON_AddItemToObject(*argjsonp,"time",cJSON_CreateNumber(time(NULL))); nxt64bits = issue_getAccountId(0,NXTACCTSECRET); expand_nxt64bits(NXTaddr,nxt64bits); cJSON_ReplaceItemInObject(*argjsonp,"NXT",cJSON_CreateString(NXTaddr)); printf("replace NXT.(%s)\n",NXTaddr); //#ifndef __linux__ if ( strcmp(buf,"teleport") != 0 && strcmp(buf,"tradebot") != 0 && strcmp(buf,"makeoffer") != 0 && strcmp(buf,"select") != 0 && strcmp(buf,"checkmessages") != 0 && Global_pNXT->privacyServer != 0 ) { parmstxt = remove_secret(argjsonp,parmstxt); issue_generateToken(mp->curl_handle2,encoded,parmstxt,NXTACCTSECRET); encoded[NXT_TOKEN_LEN] = 0; sprintf(_tokbuf,"[%s,{\"token\":\"%s\"}]",parmstxt,encoded); retstr = sendmessage(NXTaddr,NXTACCTSECRET,_tokbuf,(int32_t)strlen(_tokbuf)+1,Global_pNXT->privacyServer_NXTaddr,_tokbuf); } else //#endif { issue_generateToken(mp->curl_handle2,encoded,origparmstxt,NXTACCTSECRET); encoded[NXT_TOKEN_LEN] = 0; sprintf(_tokbuf,"[%s,{\"token\":\"%s\"}]",origparmstxt,encoded); if ( *argjsonp != 0 ) free_json(*argjsonp); *argjsonp = cJSON_Parse(_tokbuf); if ( origparmstxt != 0 ) free(origparmstxt), origparmstxt = 0; goto again; } } //printf("free parmstxt.%p, argjson.%p\n",parmstxt,*argjsonp); if ( parmstxt != 0 ) free(parmstxt); return(retstr); }
void cJSONExt_GetUnsignedInt(cJSON* object, const char* name, unsigned int* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = (unsigned int)obj->valuedouble; }
void *Trends_StateEngine(void* dummy) { TRENDS_Message_t msg; TRENDS_Message_t *ptempmsg; CCurl m_Curl;//CCurl = new CCurl(); while(1) { Sync_Sem_Wait(TrendMessageList->SyncMessageSem); Sync_Mutex_Lock(TrendMessageList->SyncMessageMux); ptempmsg = (TRENDS_Message_t *)qlist_get(TrendMessageList); memcpy(&msg,ptempmsg,sizeof(TRENDS_Message_t)); qlist_out(TrendMessageList); Sync_Mutex_UnLock(TrendMessageList->SyncMessageMux); switch(msg.m_msgtype) { case TRENDS_INPUT_MSG: if(msg.m_keyvalue == TRENDS_KEY_UP) { char * m_buf = NULL; int m_len = 0; int ret; if(!m_Curl.LoadUrl(M_UrlStr,M_UrlStr)) { FILE *fp = fopen("./kaka","rb"); if(!fp) { fprintf(stdout,"fopen read fail \n"); } fseek (fp , 0 , SEEK_END); long lSize = ftell (fp); rewind (fp); m_buf = (char*) malloc (sizeof(char)*lSize); if(m_buf == NULL) fprintf(stdout,"malloc fail \n"); ret = fread (m_buf,1,lSize,fp); if(ret != lSize) fprintf(stdout,"fread may ErrorHappened \n"); fclose(fp); printf("I READ IT FROM KAKA\n"); } else m_Curl.GetBuffer(m_buf,m_len); cJSON * m_jroot = cJSON_Parse(m_buf); if(!m_jroot) printf("cJSON_Parse Error\n"); cJSON * m_yiSub = cJSON_GetObjectItem(m_jroot, "yi18"); int yisize = cJSON_GetArraySize(m_yiSub); printf("%d\n", yisize); for(int icnt = 0; icnt < yisize; icnt++) { cJSON * pyiSubSub = cJSON_GetArrayItem(m_yiSub, icnt); if(pyiSubSub == NULL) continue; YiSubItem newysItem; cJSON * pyiSubSubItem = cJSON_GetObjectItem(pyiSubSub, "title"); newysItem.title = pyiSubSubItem->valuestring; printf("%03d.%s\n",icnt,newysItem.title); } //cJSON * cJSON_GetArrayItem(cJSON * array,int item); //printf("%s\n", cJSON_Print(m_jroot)) cJSON_Delete(m_jroot); if(m_buf) free(m_buf); fflush(stdout); } break; case TRENDS_MODULE_MSG: case TRENDS_STATE_CHANGE: break; default: break; } memset(&msg,0,sizeof(TRENDS_Message_t)); } }
void cJSONExt_GetInt(cJSON* object, const char* name, int* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = obj->valueint; }
void Map::ReadJsonFile(char * filename) { m_filename=filename; cJSON *root; char * jsonContent; s3eFile* fileHandler; fileHandler=s3eFileOpen(filename, "rb"); if (fileHandler != NULL) { // Allocate buffer to be filled with the files contents int32 fileSize = s3eFileGetSize(fileHandler); jsonContent = (char*)s3eMallocBase(fileSize+1); // Read data from file if (s3eFileRead(&jsonContent[0], fileSize+1, 1, fileHandler) != 1) { // An kError has occurred, retrieve information for display std::cout<<s3eFileGetErrorString()<<std::endl; } else { // Data reading has been successful jsonContent[fileSize] = '\0'; } } else { // Something went wrong during opening of the file retrieve error for display std::cout<<s3eFileGetErrorString()<<std::endl; } if (fileHandler) s3eFileClose(fileHandler); root = cJSON_Parse(jsonContent); s3eFileFlush(fileHandler); _height=cJSON_GetObjectItem(root,"height")->valueint; cJSON *layers = cJSON_GetObjectItem(root,"layers"); _tileHeight=cJSON_GetObjectItem(root,"tileheight")->valueint; _tileWidth=cJSON_GetObjectItem(root,"tilewidth")->valueint; _width=cJSON_GetObjectItem(root,"width")->valueint; _layer_base->Init(cJSON_GetArrayItem(layers,0)); _layer_middle->Init(cJSON_GetArrayItem(layers,1)); _layer_maze->Init(cJSON_GetArrayItem(layers,2)); cJSON *tilesets = cJSON_GetObjectItem(root,"tilesets"); _tileset_map->Init(cJSON_GetArrayItem(tilesets,0)); _tileset_maze->Init(cJSON_GetArrayItem(tilesets,1)); cJSON * properties=cJSON_GetObjectItem(root,"properties"); int propSize=cJSON_GetArraySize(properties); for(int i=propSize-1;i!=-1;i--) { cJSON * prop=cJSON_GetArrayItem(properties,i); char* propString=prop->valuestring; char* name=prop->string; char* chars_array = strtok(propString, ","); if(CharCMP(name,"Block",sizeof("Block"))) { while(chars_array) { _EventBlock.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } else if(CharCMP(name,"BG",sizeof("BG"))) { _BGImage=Iw2DCreateImageResource(propString); } else if(CharCMP(name,"Door",sizeof("Door"))) { while(chars_array) { m_doors.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } else if(CharCMP(name,"EndPoint",sizeof("EndPoint"))) { _EndPos[0]=atoi(chars_array); chars_array = strtok(NULL, ","); _EndPos[1]=atoi(chars_array); } else if(CharCMP(name,"StartPoint",sizeof("StartPoint"))) { _StartPos[0]=atoi(chars_array); chars_array = strtok(NULL, ","); _StartPos[1]=atoi(chars_array); } else if(CharCMP(name,"emaze",sizeof("emaze"))) { while(chars_array) { mapEndIndex.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } else if(CharCMP(name,"etmaze",sizeof("etmaze"))) { while(chars_array) { mazeEndIndex.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } else if(CharCMP(name,"smaze",sizeof("smaze"))) { while(chars_array) { mapStartIndex.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } else if(CharCMP(name,"stmaze",sizeof("stmaze"))) { while(chars_array) { mazeStartIndex.append(atoi(chars_array)); chars_array = strtok(NULL, ","); } } } _total=_height*_width; _size=CIwSVec2(_width*_tileWidth,_height*_tileHeight); }
void cJSONExt_GetFloat(cJSON* object, const char* name, float* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = (float)obj->valuedouble; }
/*************************************************************************** Function: push_to_cloud Description: Input: mt action_str old_str new_str Output: none Return: 0:receive status[1(if modifypassword) or 2(if modifyalias)] positive:receive status[(-9,-10)(if modifypassword) or (-11,-12,-13)(if modifyalias)] negative:other error Others: none ***************************************************************************/ static int push_to_cloud(modifyType mt, const char *action_str, const char *old_str, const char *new_str) { cJSON *send_json, *receive_json, *status_json; char *json_send_out; char send_str[CA_PUSH_TO_CLOUD_LEN], receive_str[CA_PUSH_TO_CLOUD_LEN]; int fd, nwrite, nread, re, nfd; struct sockaddr_in servaddr; // Section1: prepare for push send_json = cJSON_CreateObject(); if (!send_json) { CA_DEBUG("create send_json failed\n"); return -1; } cJSON_AddStringToObject(send_json, "action", action_str); switch (mt) { case modifyPasswordType: cJSON_AddStringToObject(send_json, "old_password", old_str); cJSON_AddStringToObject(send_json, "new_password", new_str); break; case modifyAliasType: cJSON_AddStringToObject(send_json, "old_alias", old_str); cJSON_AddStringToObject(send_json, "new_alias", new_str); break; default: CA_DEBUG("undefined modifyType:%d\n", mt); cJSON_Delete(send_json); return -1; } if ( (json_send_out = cJSON_PrintUnformatted(send_json)) == 0 ) { CA_DEBUG("%d print send_json failed\n", mt); cJSON_Delete(send_json); return -1; } cJSON_Delete(send_json); nwrite = snprintf(send_str, CA_PUSH_TO_CLOUD_LEN, "%s", json_send_out); nwrite += 1; // including the terminated null free(json_send_out); // Section2: send and receive // reWrite the next line //fd = Tcp_connect("192.168.1.121", FEATURE_GDGL_CPROXY_CA_PUSH_PORT_STR); if ( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { CA_DEBUG("%d socket error\n", mt); return -2; } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(FEATURE_GDGL_CPROXY_CA_PUSH_PORT); //if ( (re = inet_pton(AF_INET, "192.168.1.238", &servaddr.sin_addr)) <= 0) { if ( (re = inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr)) <= 0) { CA_DEBUG("%d inet_pton error:%d\n", mt, re); close(fd); return -2; } if ( connect(fd, (SA *) &servaddr, sizeof(servaddr)) < 0 ) { CA_DEBUG("%d connect error\n", mt); close(fd); return -2; } if ( writen(fd, send_str, nwrite) != nwrite ) { CA_DEBUG("%d write error\n", mt); close(fd); return -2; } if ( (nfd = readable_timeo(fd, PUSH_TO_CLOUD_TIMEOUT)) < 0) { CA_DEBUG("%d readable_timeo error\n", mt); close(fd); return -2; } else if (nfd == 0) { //timeout, close connection CA_DEBUG("%d readable_timeo timeout\n", mt); close(fd); return -2; } while (1) { if ( (nread = read(fd, receive_str, CA_PUSH_TO_CLOUD_LEN - 1)) < 0) { if (errno == EINTR) continue; else { CA_DEBUG("%d read error\n", mt); close(fd); return -2; } } else if (nread == 0) { CA_DEBUG("%d closed by other end\n", mt); close(fd); return -2; } else break; } close(fd); receive_str[nread] = 0; // add the terminated null CA_DEBUG("%d receive:\n%s\n", mt, receive_str); // Section3: parse result receive_json = cJSON_Parse(receive_str); if (!receive_json) { CA_DEBUG("%d receive_json parse Error before:%s\n", mt, cJSON_GetErrorPtr()); return -3; } status_json = cJSON_GetObjectItem(receive_json, "status"); if (!status_json) { cJSON_Delete(receive_json); CA_DEBUG("%d receive no status\n", mt); return -3; } if (status_json->type != cJSON_Number) { CA_DEBUG("%d receive status but not a number\n", mt); cJSON_Delete(receive_json); return -3; } switch (status_json->valueint) { case PUSH_TO_CLOUD_RESPONSE_JSON_PARSE_FAILED: CA_DEBUG("%d receive [json parse failed]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_REQ_HANDLER_INVALID: CA_DEBUG("%d receive [request handler invalid]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_INVALID_ACTION: CA_DEBUG("%d receive [invalid action]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_UNKNOWN_ACTION: CA_DEBUG("%d receive [unknown action]\n", mt); cJSON_Delete(receive_json); return -3; default: break; } if (mt == modifyPasswordType) { switch (status_json->valueint) { case PUSH_TO_CLOUD_RESPONSE_PASSWD_SUCCESS: cJSON_Delete(receive_json); return 0; case PUSH_TO_CLOUD_RESPONSE_INVALID_OLD_PASSWD: CA_DEBUG("%d receive [invalid old_password]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_INVALID_NEW_PASSWD: CA_DEBUG("%d receive [invalid new_password]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_OLD_PASSWD_ERR: CA_DEBUG("%d receive [old password not correct]\n", mt); cJSON_Delete(receive_json); return clientAdminPushToCloudOldPasswdErr; case PUSH_TO_CLOUD_RESPONSE_PASSWD_SAME: CA_DEBUG("%d receive [same passwords]\n", mt); cJSON_Delete(receive_json); return clientAdminPushToCloudPasswdSame; default: CA_DEBUG("%d receive unsupported status:[%d]\n", mt, status_json->valueint); cJSON_Delete(receive_json); return -3; } } else if (mt == modifyAliasType) { switch (status_json->valueint) { case PUSH_TO_CLOUD_RESPONSE_ALIAS_SUCCESS: cJSON_Delete(receive_json); return 0; case PUSH_TO_CLOUD_RESPONSE_INVALID_OLD_ALIAS: CA_DEBUG("%d receive [invalid old_alias]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_INVALID_NEW_ALIAS: CA_DEBUG("%d receive [invalid new_alias]\n", mt); cJSON_Delete(receive_json); return -3; case PUSH_TO_CLOUD_RESPONSE_OLD_ALIAS_NOT_EXIST: CA_DEBUG("%d receive [old alias not exist]\n", mt); cJSON_Delete(receive_json); return clientAdminPushToCloudOldAliasNotExist; case PUSH_TO_CLOUD_RESPONSE_NEW_ALIAS_EXIST: CA_DEBUG("%d receive [new alias already exist]\n", mt); cJSON_Delete(receive_json); return clientAdminPushToCloudNewAliasExist; case PUSH_TO_CLOUD_RESPONSE_ALIAS_SAME: CA_DEBUG("%d receive [same aliases]\n", mt); cJSON_Delete(receive_json); return clientAdminPushToCloudAliasSame; default: CA_DEBUG("%d receive unsupported status:[%d]\n", mt, status_json->valueint); cJSON_Delete(receive_json); return -3; } } else { CA_DEBUG("undefined modifyType:%d\n", mt); cJSON_Delete(receive_json); return -3; } }
void cJSONExt_GetDouble(cJSON* object, const char* name, double* variable) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) *variable = obj->valuedouble; }
static cJSON* process_task( cJSON* input ) { struct TaskCommandHandler* handler; UTV_RESULT result; UTV_BOOL failedRequest = UTV_FALSE; int idx; cJSON* requests; cJSON* request; cJSON* command; cJSON* inputs; cJSON* commandName; UTV_UINT32 commandNameLength; cJSON* output; cJSON* responses; cJSON* response; cJSON* outputs; responses = cJSON_CreateArray(); requests = cJSON_GetObjectItem( input, "REQUESTS" ); for ( idx = 0; idx < cJSON_GetArraySize( requests ); idx++ ) { request = cJSON_GetArrayItem( requests, idx ); command = cJSON_DetachItemFromObject( request, "COMMAND" ); inputs = cJSON_GetObjectItem( request, "INPUTS" ); commandName = cJSON_GetObjectItem( command, "NAME" ); commandNameLength = UtvStrlen( (UTV_BYTE*) commandName->valuestring ); response = cJSON_CreateObject(); outputs = cJSON_CreateArray(); cJSON_AddItemToObject( response, "COMMAND", command ); if ( !failedRequest ) { handler = s_handler_list; while ( handler != NULL ) { if ( commandNameLength == UtvStrlen( handler->command_name ) ) { if ( !UtvMemcmp( commandName->valuestring, handler->command_name, commandNameLength ) ) { result = handler->command_handler( inputs, outputs ); break; } } handler = handler->next; } if ( NULL == handler ) { UtvMessage( UTV_LEVEL_WARN, "%s: Unknown command \"%s\"", __FUNCTION__, commandName->valuestring ); result = UTV_LIVE_SUPPORT_COMMAND_UNKNOWN; } failedRequest = ( result != UTV_OK ); } else { UtvMessage( UTV_LEVEL_WARN, "%s: Command \"%s\" not processed", __FUNCTION__, commandName->valuestring ); result = UTV_LIVE_SUPPORT_COMMAND_NOT_PROCESSED; } cJSON_AddNumberToObject( response, "RESULT", result ); cJSON_AddItemToObject( response, "OUTPUTS", outputs ); cJSON_AddItemToArray( responses, response ); } output = cJSON_CreateObject(); cJSON_AddItemToObject( output, "RESPONSES", responses ); return ( output ); }
void cJSONExt_GetString(cJSON* object, const char* name, char* variable, int buffersize) { cJSON* obj = cJSON_GetObjectItem( object, name ); if( obj ) strcpy_s( variable, buffersize, obj->valuestring ); }
void CLogin::OnBnClickedOk2() { // TODO: 在此添加控件通知处理程序代码 USES_CONVERSION; CString user, passwd; m_user.GetWindowText(user); m_passwd.GetWindowText(passwd); MD5tool MD5tool; passwd = MD5tool.PutMD5(passwd); cJSON *rootback, *data; rootback = cJSON_CreateObject(); cJSON_AddStringToObject(rootback, "Type", "21"); cJSON_AddItemToObject(rootback, "Data", data = cJSON_CreateObject()); cJSON_AddStringToObject(data, "user", T2A(user)); cJSON_AddStringToObject(data, "passwd", T2A(passwd)); char* back = cJSON_Print(rootback); cJSON_Delete(rootback); //cJSON_Delete(data); WORD wVersion = MAKEWORD(2, 2); WSADATA wsadata; if ((::WSAStartup(wVersion, &wsadata)) == SOCKET_ERROR) { return; } if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2) { WSACleanup(); return; } SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); int port = 12126; SOCKADDR_IN addSock; inet_pton(AF_INET, theApp.Getip(), &addSock.sin_addr.S_un.S_addr); addSock.sin_family = AF_INET; addSock.sin_port = htons(port); int Ret = connect(sockSrv, (SOCKADDR*)&addSock, sizeof(SOCKADDR)); if (Ret != 0) { WSACleanup(); return; } CString Socketdata; Socketdata.Format(_T("%s"), CStringW(back)); theApp.SocketSend(sockSrv, Socketdata); //send(sockSrv, back, strlen(back) + 1, 0); free(back); /*char revData[100000]; int ret = recv(sockSrv, revData, 100000, 0);*/ CString Sockrec = theApp.SocketRecv(sockSrv); if (Sockrec == CString()) return; /* if (ret == 0) { // 此处连接WM_PAINT显示,待实现 //MessageBox((HWND)pM, _T("错误 7. 请检查网络连接!"), _T("程序异常"), MB_OK); return; } if (ret == SOCKET_ERROR) return; revData[ret] = '\0';*/ cJSON * root; root = cJSON_Parse(T2A(Sockrec)); if (NULL == root) { //错误处理 return; } //size = cJSON_GetArraySize(root); cJSON * pSub = cJSON_GetObjectItem(root, "Type"); char* type = pSub->valuestring; CString Type, Data; Type.Format(_T("%s"), CStringW(type)); pSub = cJSON_GetObjectItem(root, "Data"); type = pSub->valuestring; Data.Format(_T("%s"), CStringW(type)); cJSON_Delete(root); if (Type.CompareNoCase(_T("21")) == 0) { if (Data.CompareNoCase(_T("OK")) != 0) { closesocket(sockSrv); WSACleanup(); m_user.SetWindowText(_T("")); m_passwd.SetWindowText(_T("")); AfxMessageBox(_T("用户名或密码错误!")); return; } } else { closesocket(sockSrv); WSACleanup(); m_user.SetWindowText(_T("")); m_passwd.SetWindowText(_T("")); AfxMessageBox(_T("用户名或密码错误!")); return; } theApp.User = user; closesocket(sockSrv); WSACleanup(); CDialogEx::OnOK(); }
void* ThreadJob_SdkServerVerify(void* arg) { CPluto& u = *((CPluto*)arg); pluto_msgid_t msg_id = u.GetMsgId();; mogo::T_VECTOR_OBJECT* p = NULL; CMailBox* pmb = u.GetMailbox(); if(!pmb) { //如果没有mb,是从本进程发来的包 delete &u; return (void*)-1; } uint8_t authz = pmb->GetAuthz(); if(authz != MAILBOX_CLIENT_TRUSTED) { LogWarning("ThreadJob_SdkServerVerify", "invalid rpcall error.unknown msgid:%d\n", msg_id); delete &u; return (void*)-1; } p = g_worldOther.GetRpcUtil().Decode(u); if(p == NULL) { LogWarning("ThreadJob_SdkServerVerify", "rpc Decode error.unknown msgid:%d\n", msg_id); delete &u; return (void*)-2; } if(u.GetDecodeErrIdx() > 0) { ClearTListObject(p); //PrintHexPluto(u); LogWarning("ThreadJob_SdkServerVerify", "rpc Decode error.msgid:%d;pluto err idx=%d\n", msg_id, u.GetDecodeErrIdx()); delete &u; return (void*)-3; } if (p->size() != 4) { delete &u; return (void*)-4; } string& url = VOBJECT_GET_SSTR((*p)[0]); int32_t nFd = VOBJECT_GET_I32((*p)[1]); string& strAccount = VOBJECT_GET_SSTR((*p)[2]); string& strPlatId = VOBJECT_GET_SSTR((*p)[3]); //CMailBox* pmb = u.GetMailbox(); string resp = ""; int ret = GetUrl(url.c_str(), resp); if (ret != CURLE_OK) { LogWarning("CWorldOther::SdkServerVerify", "%s ret = %d", strAccount.c_str(), ret); //todo:faild. pmb->RpcCall(g_worldOther.GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, ret, nFd, strAccount, strPlatId); delete &u; return 0; } Trim(resp); cJSON* json = cJSON_Parse(resp.c_str()); cJSON* childJs = cJSON_GetObjectItem(json, "code"); int rst = cJSON_GetObjectItem(json, "code")->valueint; if (rst == 1) { //succeed. if (strAccount.c_str() != cJSON_GetObjectItem(json, "msg")->valuestring) { ret = 0; } else { LogWarning("CWorldOther::SdkServerVerify", "strAccount[%s] msg[%s]", strAccount.c_str(), cJSON_GetObjectItem(json, "msg")->valuestring); ret = 1; //pmb->RpcCall(GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, int32_t(1), nFd, strAccount, strPlatId); } } else { //failed. LogWarning("CWorldOther::SdkServerVerify", "strAccount[%s] rst[%d]", strAccount.c_str(), rst); ret = -1; //pmb->RpcCall(GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, -1, nFd, strAccount, strPlatId); } pmb->RpcCall(g_worldOther.GetRpcUtil(), MSGID_LOGINAPP_LOGIN_VERIFY_CALLBACK, ret, nFd, strAccount, strPlatId); delete &u; return (void*)0; }
OicSecPstat_t * JSONToPstatBin(const char * jsonStr) { if(NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecPstat_t *pstat = NULL; cJSON *jsonPstat = NULL; cJSON *jsonObj = NULL; unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {}; uint32_t outLen = 0; B64Result b64Ret = B64_OK; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, INFO); jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME); VERIFY_NON_NULL(TAG, jsonPstat, INFO); pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t)); VERIFY_NON_NULL(TAG, pstat, INFO); jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR); pstat->isOp = jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR); memcpy(pstat->deviceID.id, base64Buff, outLen); jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->commitHash = jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->cm = (OicSecDpm_t)jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->om = (OicSecDpom_t)jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); if (cJSON_Array == jsonObj->type) { pstat->smLen = cJSON_GetArraySize(jsonObj); int idxx = 0; VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR); pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t)); VERIFY_NON_NULL(TAG, pstat->sm, ERROR); do { cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx); VERIFY_NON_NULL(TAG, jsonSm, ERROR); pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint; }while ( ++idxx < pstat->smLen); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { OC_LOG (ERROR, TAG, PCF("JSONToPstatBin failed")); DeletePstatBinData(pstat); pstat = NULL; } return pstat; }
char *pNXT_json_commands(struct NXThandler_info *mp,struct pNXT_info *gp,cJSON *argjson,char *sender,int32_t valid,char *origargstr) { static char *teleport[] = { (char *)teleport_func, "teleport", "V", "NXT", "secret", "amount", "dest", "coin", "minage", "M", "N", 0 }; static char *telepod[] = { (char *)telepod_func, "telepod", "V", "NXT", "secret", "crc", "i", "h", "c", "v", "a", "t", "o", "p", "k", "L", "s", "M", "N", "D", 0 }; static char *transporter[] = { (char *)transporter_func, "transporter", "V", "NXT", "secret", "coin", "height", "minage", "value", "totalcrc", "telepods", "M", "N", "sharenrs", "pubaddr", 0 }; static char *transporterstatus[] = { (char *)transporterstatus_func, "transporter_status", "V", "NXT", "secret", "status", "coin", "totalcrc", "value", "num", "minage", "height", "crcs", "sharei", "M", "N", "sharenrs", "ind", "pubaddr", 0 }; static char *tradebot[] = { (char *)tradebot_func, "tradebot", "V", "NXT", "secret", "code", 0 }; static char *respondtx[] = { (char *)respondtx_func, "respondtx", "V", "NXT", "signedtx", 0 }; static char *processutx[] = { (char *)processutx_func, "processutx", "V", "NXT", "secret", "utx", "sig", "full", 0 }; static char *publishaddrs[] = { (char *)publishaddrs_func, "publishaddrs", "V", "NXT", "secret", "pubNXT", "pubkey", "BTCD", "BTC", "pNXT", 0 }; static char *getpubkey[] = { (char *)getpubkey_func, "getpubkey", "V", "NXT", "addr", "secret", 0 }; static char *sellp[] = { (char *)sellpNXT_func, "sellpNXT", "V", "NXT", "amount", "secret", 0 }; static char *buyp[] = { (char *)buypNXT_func, "buypNXT", "V", "NXT", "amount", "secret", 0 }; static char *sendmsg[] = { (char *)sendmsg_func, "sendmessage", "V", "NXT", "dest", "secret", "msg", 0 }; static char *checkmsg[] = { (char *)checkmsg_func, "checkmessages", "V", "NXT", "sender", "secret", 0 }; static char *send[] = { (char *)sendpNXT_func, "send", "V", "NXT", "amount", "secret", "dest", "level","paymentid", 0 }; static char *select[] = { (char *)selectserver_func, "select", "V", "NXT", "ipaddr", "port", "secret", 0 }; static char *orderbook[] = { (char *)orderbook_func, "orderbook", "V", "NXT", "obookid", "polarity", "allfields", "secret", 0 }; static char *getorderbooks[] = { (char *)getorderbooks_func, "getorderbooks", "V", "NXT", "secret", 0 }; static char *placebid[] = { (char *)placebid_func, "placebid", "V", "NXT", "obookid", "polarity", "volume", "price", "assetA", "assetB", "secret", 0 }; static char *placeask[] = { (char *)placeask_func, "placeask", "V", "NXT", "obookid", "polarity", "volume", "price", "assetA", "assetB", "secret", 0 }; static char *makeoffer[] = { (char *)makeoffer_func, "makeoffer", "V", "NXT", "secret", "other", "assetA", "qtyA", "assetB", "qtyB", "type", 0 }; static char **commands[] = { getpubkey, transporterstatus, telepod, transporter, tradebot, respondtx, processutx, publishaddrs, checkmsg, placebid, placeask, makeoffer, sendmsg, orderbook, getorderbooks, sellp, buyp, send, teleport, select }; int32_t i,j; cJSON *obj,*nxtobj,*objs[64]; char NXTaddr[64],command[4096],**cmdinfo,*retstr; memset(objs,0,sizeof(objs)); command[0] = 0; memset(NXTaddr,0,sizeof(NXTaddr)); if ( argjson != 0 ) { obj = cJSON_GetObjectItem(argjson,"requestType"); nxtobj = cJSON_GetObjectItem(argjson,"NXT"); copy_cJSON(NXTaddr,nxtobj); copy_cJSON(command,obj); //printf("(%s) command.(%s) NXT.(%s)\n",cJSON_Print(argjson),command,NXTaddr); } printf("%llu pNXT_json_commands sender.(%s) valid.%d | size.%d | command.(%s) orig.(%s)\n",(long long)Global_pNXT->privacyServer,sender,valid,(int32_t)(sizeof(commands)/sizeof(*commands)),command,origargstr); for (i=0; i<(int32_t)(sizeof(commands)/sizeof(*commands)); i++) { cmdinfo = commands[i]; //printf("needvalid.(%c) sender.(%s) valid.%d %d of %d: cmd.(%s) vs command.(%s)\n",cmdinfo[2][0],sender,valid,i,(int32_t)(sizeof(commands)/sizeof(*commands)),cmdinfo[1],command); if ( strcmp(cmdinfo[1],command) == 0 ) { if ( cmdinfo[2][0] != 0 ) { if ( NXTaddr[0] == 0 ) strcpy(NXTaddr,sender); if ( sender[0] == 0 || valid != 1 || (strcmp(NXTaddr,sender) != 0 && strcmp(sender,Global_pNXT->privacyServer_NXTaddr) != 0) ) { printf("verification valid.%d missing for %s sender.(%s) vs NXT.(%s)\n",valid,cmdinfo[1],sender,NXTaddr); return(0); } } for (j=3; cmdinfo[j]!=0&&j<3+(int32_t)(sizeof(objs)/sizeof(*objs)); j++) objs[j-3] = cJSON_GetObjectItem(argjson,cmdinfo[j]); retstr = (*(json_handler)cmdinfo[0])(sender,valid,objs,j-3,origargstr); if ( 0 && retstr != 0 ) printf("json_handler returns.(%s)\n",retstr); return(retstr); } } return(0); }
int entry_group_weibo( struct ev_loop *loop, char *data, size_t size ) { int ok = API_OK; char *body = NULL; cJSON *obj = NULL; cJSON *temp= NULL; struct cnt_pool *redis_pool = NULL; struct cnt_pool *static_pool = NULL; struct cnt_pool *weidb_pool = NULL; void *redis_priority = NULL; void *redis_receive = NULL; void *redis_weibo = NULL; void *redis_senderInfo = NULL; void *redis_expire = NULL; struct async_ctx *task = NULL; /*从配置文件中,得到IP,和port*/ int i = get_redis_link_index(); char *host = g_weibo_cfg_file.weibo_store[i].host; short port = g_weibo_cfg_file.weibo_store[i].port; /*一次性取出程序执行所有连接数,如果连接数不够,将数据打印到LOG日志里,程序返回,打印错误码, 这样做是为了防止当连接数到达连接池顶峰时,一直取不到连接,代码一直夯在哪里*/ // redis_priority = redis_pool_gain(loop, &redis_pool,host,port); redis_priority = pool_api_gain(loop, &redis_pool,host,port); if (NULL==redis_priority) { x_printf(W, "%s\n",data); ok = REDIS_POOL_GAIN_FAILED; return ok; } // redis_weibo = redis_pool_gain(loop, &redis_pool,host,port); redis_weibo = pool_api_gain(loop, &redis_pool,host,port); if (NULL==redis_weibo) { x_printf(W, "%s\n",data); ok = REDIS_POOL_GAIN_FAILED; return ok; } // redis_senderInfo = redis_pool_gain(loop, &redis_pool,host,port); redis_senderInfo = pool_api_gain(loop, &redis_pool,host,port); if (NULL==redis_senderInfo) { x_printf(W, "%s\n",data); ok = REDIS_POOL_GAIN_FAILED; return ok; } // redis_expire = redis_pool_gain(loop, &redis_pool,host,port); redis_expire = pool_api_gain(loop, &redis_pool,host,port); if (NULL==redis_expire) { x_printf(W, "%s\n",data); ok = REDIS_POOL_GAIN_FAILED; return ok; } i = get_redis_static_link_index(); host = g_weibo_cfg_file.weibo_static[i].host; port = g_weibo_cfg_file.weibo_static[i].port; // redis_receive = redis_pool_gain(loop, &static_pool,host,port); redis_receive = pool_api_gain(loop, &static_pool,host,port); if (NULL==redis_receive) { x_printf(W, "%s\n",data); ok = REDIS_POOL_GAIN_FAILED; return ok; } i = get_weidb_link_index(); host = g_weibo_cfg_file.weidb[i].host; port = g_weibo_cfg_file.weidb[i].port; task = (struct async_ctx *)pool_api_gain(loop, &weidb_pool, host, port); if (NULL==task) { x_printf(W, "%s\n",data); ok = HTTP_POOL_GAIN_FAILED; return ok; } Weibo *wb = calloc(1, sizeof(Weibo));//开空间并初始化 if(!wb){ ok = API_NO_MEMORY; goto ERROR_PUBLIC; } wb->loop = loop; /******判断传入进来的参数******/ if (NULL == data || 0 == size) { ok = API_NO_DATA; goto ERROR_PUBLIC; }else{ if (size > MAX_LEN_STRING){ ok = API_DATA_TOO_LONG; goto ERROR_PUBLIC; } } /*data cjson parse*/ obj = cJSON_Parse (data); if (NULL == obj) { ok = API_INVALID_JSON; goto ERROR_PUBLIC; } wb->cjson = obj; /*check groupID*/ temp = cJSON_GetObjectItem(obj, "groupID"); if (NULL==temp){ ok = API_INVALID_GROUPID; goto ERROR_PUBLIC; } wb->groupID = temp->valuestring; if (!wb->groupID){ ok = API_INVALID_GROUPID; goto ERROR_PUBLIC; } /*check other*/ ok = parse_parments (wb, obj); if (ok != API_OK){ goto ERROR_PUBLIC; } wb->loop = loop; wb->pool = redis_pool; wb->redisPriority = redis_priority; /*receiver:priority */ ok = weibo_set_receive(wb,loop,redis_receive,static_pool); if (ok != API_OK){ goto ERROR_PUBLIC; } /*bizid:weibo and bizid:senderInfo*/ ok = weibo_send_info(wb,loop,redis_weibo,redis_senderInfo,redis_expire,redis_pool); if (ok != API_OK){ goto ERROR_PUBLIC; } /*cJSON form turn into string form*/ body = cJSON_Print(obj); if (!body){ ok = JSON_OP_FAIL; goto ERROR_PUBLIC; } /*data transmitting*/ ok=weibo_data_transmit(body,"weidb_group",loop,weidb_pool,task,host,port); if (ok != API_OK){ goto ERROR_PUBLIC; } free(body); /*cant't free json,free it in callback*/ obj = NULL; return ok; ERROR_PUBLIC: if (obj){ cJSON_Delete(obj); } if(body){ free(body); } return ok; }
OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr, const bool isIncResName) { if (NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecDoxm_t *doxm = NULL; cJSON *jsonDoxm = NULL; cJSON *jsonObj = NULL; size_t jsonObjLen = 0; unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {}; uint32_t outLen = 0; B64Result b64Ret = B64_OK; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); if(isIncResName) { jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME); VERIFY_NON_NULL(TAG, jsonDoxm, ERROR); } else { jsonDoxm = jsonRoot; } doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t)); VERIFY_NON_NULL(TAG, doxm, ERROR); //Oxm -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME); if (jsonObj && cJSON_Array == jsonObj->type) { doxm->oxmLen = cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR); doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t)); VERIFY_NON_NULL(TAG, doxm->oxm, ERROR); for (size_t i = 0; i < doxm->oxmLen ; i++) { cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxm, ERROR); doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint; } } //OxmSel -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint; } else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->oxmSel = gDoxm->oxmSel; } //sct -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->sct = (OicSecCredType_t)jsonObj->valueint; } else // PUT/POST JSON may not have sct so set it to the gDoxm->sct { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->sct = gDoxm->sct; } //Owned -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->owned = jsonObj->valueint; } else // PUT/POST JSON may not have owned so set it to the gDomx->owned { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->owned = gDoxm->owned; } //DeviceId -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); if(cJSON_String == jsonObj->type) { //Check for empty string, in case DeviceId field has not been set yet if (jsonObj->valuestring[0]) { outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)), ERROR); memcpy(doxm->deviceID.id, base64Buff, outLen); } } } else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id { VERIFY_NON_NULL(TAG, gDoxm, ERROR); memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id)); } //Owner -- will be empty when device status is unowned. jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEV_OWNER_NAME); if(true == doxm->owned) { VERIFY_NON_NULL(TAG, jsonObj, ERROR); } if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR); outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR); memcpy(doxm->owner.id, base64Buff, outLen); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteDoxmBinData(doxm); doxm = NULL; } return doxm; }