bool receiveWriteRequest(uint8_t* message) {
    cJSON *root = cJSON_Parse((char*)message);
    bool foundMessage = false;
    if(root != NULL) {
        foundMessage = true;
        cJSON* nameObject = cJSON_GetObjectItem(root, "name");
        if(nameObject == NULL) {
            cJSON* idObject = cJSON_GetObjectItem(root, "id");
            if(idObject == NULL) {
                debug("Write request is malformed, "
                        "missing name or id: %s", message);
            } else {
                receiveRawWriteRequest(idObject, root);
            }
        } else {
            receiveTranslatedWriteRequest(nameObject, root);
        }
        cJSON_Delete(root);
    } else {
        debug("No valid JSON in incoming buffer yet -- "
                "if it's valid, may be out of memory");
    }
    return foundMessage;
}
Exemple #2
0
char *SuperNET_JSON(char *JSONstr)
{
    char *retstr = 0;
    struct coin_info *cp = get_coin_info("BTCD");
    cJSON *json;
    if ( Finished_init == 0 )
        return(0);
    if ( Debuglevel > 1 )
        printf("got JSON.(%s)\n",JSONstr);
    if ( cp != 0 && (json= cJSON_Parse(JSONstr)) != 0 )
    {
        if ( 1 && is_BTCD_command(json) != 0 ) // deadlocks as the SuperNET API came from locked BTCD RPC
        {
            //if ( Debuglevel > 1 )
            //    printf("is_BTCD_command\n");
            return(block_on_SuperNET(0,JSONstr));
        }
        else retstr = block_on_SuperNET(1,JSONstr);
        free_json(json);
    } else printf("couldnt parse (%s)\n",JSONstr);
    if ( retstr == 0 )
        retstr = clonestr("{\"result\":null}");
    return(retstr);
}
Exemple #3
0
cJSON *load_json( const char *filename )
{
#ifdef ENABLE_CONFIGURATION
    FILE *f = dir_fopen_warn(get_user_directory(), filename, "rb");
    if (f == NULL)
        return NULL;

    size_t buffer_len = ftell_eof(f);
    char *buffer = malloc(buffer_len + 1);

    fread(buffer, 1, buffer_len, f);
    buffer[buffer_len] = '\0';

    fclose(f);

    cJSON *root = cJSON_Parse(buffer);

    free(buffer);

    return root;
#else
    return NULL;
#endif /*ENABLE_CONFIGURATION*/
}
Exemple #4
0
void parse(direct ** dir)
{
    FILE * file = fopen("director.json", "r");
    char text[10000];
    char line[100];

    while(fgets(line, 100, file) != NULL)
    {
        strcat(text, line);
    }
    fclose(file);

    cJSON * jList = cJSON_Parse(text);
    if (!jList)
    {
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    for (int i = 0; i < cJSON_GetArraySize(jList); i++)
    {
        cJSON * jItem = cJSON_GetArrayItem(jList, i);
        char * name = cJSON_GetObjectItem(jItem, "name")->valuestring;
        char * surname = cJSON_GetObjectItem(jItem, "surname")->valuestring;
        char * birthdate = cJSON_GetObjectItem(jItem, "birthdate")->valuestring;
        char * company = cJSON_GetObjectItem(jItem, "company")->valuestring;
        char * name_com = cJSON_GetObjectItem(jItem, "name_com")->valuestring;
        char * specialization = cJSON_GetObjectItem(jItem, "specialization")->valuestring;
        int year = cJSON_GetObjectItem(jItem, "year")->valueint;
        double rating = cJSON_GetObjectItem(jItem, "rating")->valuedouble;
    

        Director_set(Director[i], name, surname, birthdate, company, name_com, specialization, year, rating);
    }
    cJSON_Delete(jList);
}
Exemple #5
0
/**
 * Function to update persistent storage
 */
static bool UpdatePersistentStorage(OicSecPstat_t * pstat)
{
    bool bRet = false;

    if (pstat)
    {
        // Convert pstat data into JSON for update to persistent storage
        char *jsonStr = BinToPstatJSON(pstat);
        if (jsonStr)
        {
            cJSON *jsonPstat = cJSON_Parse(jsonStr);
            OICFree(jsonStr);

            if (jsonPstat &&
                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat)))
            {
                bRet = true;
            }
            cJSON_Delete(jsonPstat);
        }
    }

    return bRet;
}
Exemple #6
0
static void append_stdfields(char *retbuf,int32_t max,struct plugin_info *plugin,uint64_t tag,int32_t allfields)
{
    char tagstr[512]; cJSON *json; int32_t len;
//printf("APPEND.(%s) (%s)\n",retbuf,plugin->name);
    tagstr[0] = 0;
    len = (int32_t)strlen(retbuf);
    if ( len > 4 && retbuf[len-1] != ']' && (json= cJSON_Parse(retbuf)) != 0 )
    {
        if ( tag != 0 && get_API_nxt64bits(cJSON_GetObjectItem(json,"tag")) == 0 )
            sprintf(tagstr,",\"tag\":\"%llu\"",(long long)tag);
        if ( cJSON_GetObjectItem(json,"serviceNXT") == 0 && plugin->SERVICENXT[0] != 0 )
            sprintf(tagstr+strlen(tagstr),",\"serviceNXT\":\"%s\"",plugin->SERVICENXT);
        if ( cJSON_GetObjectItem(json,"NXT") == 0 )
            sprintf(tagstr+strlen(tagstr),",\"NXT\":\"%s\"",plugin->NXTADDR);
        if ( allfields != 0 )
        {
            //if ( SUPERNET.iamrelay != 0 )
            //    sprintf(retbuf+strlen(retbuf)-1,",\"myipaddr\":\"%s\"}",plugin->ipaddr);
            sprintf(retbuf+strlen(retbuf)-1,",\"allowremote\":%d%s}",plugin->allowremote,tagstr);
            sprintf(retbuf+strlen(retbuf)-1,",\"permanentflag\":%d,\"daemonid\":\"%llu\",\"myid\":\"%llu\",\"plugin\":\"%s\",\"endpoint\":\"%s\",\"millis\":%.2f,\"sent\":%u,\"recv\":%u}",plugin->permanentflag,(long long)plugin->daemonid,(long long)plugin->myid,plugin->name,plugin->bindaddr[0]!=0?plugin->bindaddr:plugin->connectaddr,milliseconds2(),plugin->numsent,plugin->numrecv);
         }
         else sprintf(retbuf+strlen(retbuf)-1,",\"daemonid\":\"%llu\",\"myid\":\"%llu\",\"allowremote\":%d%s}",(long long)plugin->daemonid,(long long)plugin->myid,plugin->allowremote,tagstr);
    }
}
Exemple #7
0
void            SocketService::logipslots(const QString &vmid)
{
    QString   params = "&hostId="+ vmid;
    std::string   hostid = params.toLocal8Bit().data();
    std::string   hostmac = "&boxId=" + boxmac;
    std::string   hoststatus = "&status=" + vmstatus;
    std::string   httpinfo =  httphead + "iChange";
    std::string   checkinfo = userpass + hostid + hostmac + hoststatus; 
    std::string   strmsg = "";

    qDebug()<<"checkinfo:"<<checkinfo.c_str();
    http->Post(httpinfo, checkinfo, strmsg);
    qDebug() << "logip:"<<strmsg.c_str();
    cJSON   *json  = cJSON_Parse(strmsg.data());
    if(json == NULL)
    {
        return;
    }
    cJSON   *json_result = cJSON_GetObjectItem(json,"result");
    if(json_result == NULL)
    {
        emit  signals_httperror("JSON Pare error!");
        return ;
    }
    QString   result = json_result->valuestring;
    if(result.compare("false") == 0)
    {
        cJSON   *json_error = cJSON_GetObjectItem(json,"errorMsg");

        emit  signals_httperror(json_error->valuestring);

    }
    cJSON_Delete(json);


}
size_t parse(char *ptr, size_t size, size_t nmemb, char *data)
{
	if(size*nmemb <= 2)
	{
		return size*nmemb;
	} 

	printf("%s\n", ptr); //DEBUG

	cJSON *root = cJSON_Parse(ptr);
	struct cJSON *current = root->child;

	while(strcmp(current->string, "text") != 0) 
	{
		if(current->next != NULL)
		{
			current = current->next;
		} else {
			break;
			printf("done"); //DEBUG
		}
	}

	if(strstr(current->valuestring, "START") != NULL)
	{
		bcm2835_gpio_write(PIN, HIGH);		

	} else if(strstr(current->valuestring, "OFF") != NULL)
	{
		bcm2835_gpio_write(PIN, LOW);
	}

	printf("Current object: %s\n", cJSON_Print(current)); //DEBUG

	return size*nmemb;
}
Exemple #9
0
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
    char *itemstr = 0; cJSON *item,*obj; double onorders,btcvalue;
    *balancep = 0.;
    if ( exchange->balancejson != 0 && (item= jobj(exchange->balancejson,coinstr)) != 0 )
    {
        itemstr = jprint(item,0);
        *balancep = jdouble(item,"available");
        onorders = jdouble(item,"onOrders");
        btcvalue = jdouble(item,"btcValue");
        if ( (obj= cJSON_Parse(itemstr)) != 0 )
        {
            free(itemstr);
            jaddstr(obj,"base",coinstr);
            jaddnum(obj,"balance",*balancep);
            jaddnum(obj,"onOrders",onorders);
            jaddnum(obj,"btcvalue",btcvalue);
            itemstr = jprint(obj,1);
        }
    }
    if ( itemstr == 0 )
        return(clonestr("{\"error\":\"cant find coin balance\"}"));
    return(itemstr);
}
Exemple #10
0
/**
 * @todo document this function including why code might need to call this.
 * The current suspicion is that it's not being called as much as it should.
 */
static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
{
    bool bRet = false;

    if (NULL != doxm)
    {
        // Convert Doxm data into JSON for update to persistent storage
        char *jsonStr = BinToDoxmJSON(doxm);
        if (jsonStr)
        {
            cJSON *jsonDoxm = cJSON_Parse(jsonStr);
            OICFree(jsonStr);

            if (jsonDoxm &&
                    (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
            {
                bRet = true;
            }
            cJSON_Delete(jsonDoxm);
        }
    }

    return bRet;
}
Exemple #11
0
int platform_load(int type, const char *proto)
{
    assert(proto);

    std::fstream fs(proto, std::ios::in | std::ios::binary);

    if (!fs) {
        LOG_ERROR("json",
                "Can NOT open file %s.", proto);
        return -1;
    }

    std::stringstream iss;

    iss << fs.rdbuf();
    cJSON *json = cJSON_Parse(iss.str().c_str());
    if (json == NULL) {
        LOG_ERROR("json",
                "Can NOT parse json file %s.", proto);
        return -1;
    }
    s_jsons.insert(std::make_pair<int, cJSON*>(type, json));
    return 0;
}
Exemple #12
0
cJSON *SIGNPOST(char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
    static CURL *cHandle;
    char url[1024],req[1024],md5secret[128],tmp[1024],dest[1025],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*sig,*data = 0;
    cJSON *json; uint64_t nonce;
    hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
    json = 0;
    nonce = exchange_nonce(exchange) * 1000 + ((uint64_t)milliseconds() % 1000);
    sprintf(tmp,"%llu%s%s",(long long)nonce,exchange->userid,exchange->apikey);
    calc_md5(md5secret,exchange->apisecret,(int32_t)strlen(exchange->apisecret));
    if ( (sig= hmac_sha256_str(dest,md5secret,(int32_t)strlen(md5secret),tmp)) != 0 )
    {
        sprintf(req,"{\"key\":\"%s\",%s\"nonce\":%llu,\"signature\":\"%s\"}",exchange->apikey,payload,(long long)nonce,sig);
        sprintf(hdr1,"Content-Type:application/json"), sprintf(hdr2,"charset=utf-8"), sprintf(hdr3,"Content-Length:%ld",(long)strlen(req));
        sprintf(url,"https://api.quadrigacx.com/v2/%s",path);
        if ( (data= curl_post(&cHandle,url,0,req,hdr1,hdr2,hdr3,hdr4)) != 0 )
            json = cJSON_Parse(data);
    }
    if ( retstrp != 0 )
        *retstrp = data;
    else if ( data != 0 )
        free(data);
    return(json);
}
Exemple #13
0
	cJSON* do_get_list()
	{
		wchar header[128];
		const wchar_t* arr[1];
		arr[0] = header;

		wchar url[128];
		char buf[128];

		cl::StringUtil::format(buf, 128, "Authorization: %s\r\n", g_token);
		cl::StringUtil::char_to_wchar(header, 128, buf);

		cl::StringUtil::format(buf, 128, "http://%s/v2/instances", g_host);
		cl::StringUtil::char_to_wchar(url, 128, buf);

		char* response;
		int len;
		unsigned long code;
		int ret = urlRequest(url, L"GET", arr, 1, NULL, 0, &code, &response, &len);

		if(ret)
		{
			if(code == 200)
			{
				cJSON* root = cJSON_Parse(response);
				cl_free(response);
				return root;
			}
			else
			{
				cl_free(response);
				return NULL;
			}
		}
		return NULL;
	}
Exemple #14
0
static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName)
{
    char *jsonStr = NULL;
    FILE *fp = NULL;
    FILE *fp1 = NULL;
    uint8_t *aclCbor = NULL;
    uint8_t *pstatCbor = NULL;
    uint8_t *doxmCbor = NULL;
    uint8_t *amaclCbor = NULL;
    uint8_t *svcCbor = NULL;
    uint8_t *credCbor = NULL;
    cJSON *jsonRoot = NULL;
    OCStackResult ret = OC_STACK_ERROR;
    size_t size = GetJSONFileSize(jsonFileName);
    if (0 == size)
    {
        OIC_LOG (ERROR, TAG, "Failed converting to JSON");
        return;
    }

    jsonStr = (char *)OICMalloc(size + 1);
    VERIFY_NON_NULL(TAG, jsonStr, FATAL);

    fp = fopen(jsonFileName, "r");
    if (fp)
    {
        size_t bytesRead = fread(jsonStr, 1, size, fp);
        jsonStr[bytesRead] = '\0';

        OIC_LOG_V(DEBUG, TAG, "Read %zu bytes", bytesRead);
        fclose(fp);
        fp = NULL;
    }
    else
    {
        OIC_LOG (ERROR, TAG, "Unable to open JSON file!!");
        goto exit;
    }

    jsonRoot = cJSON_Parse(jsonStr);

    cJSON *value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
    //printf("ACL json : \n%s\n", cJSON_PrintUnformatted(value));
    size_t aclCborSize = 0;
    if (NULL != value)
    {
        OicSecAcl_t *acl = JSONToAclBin(jsonStr);
        VERIFY_NON_NULL(TAG, acl, FATAL);
        ret = AclToCBORPayload(acl, &aclCbor, &aclCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Acl to Cbor Payload");
            DeleteACLList(acl);
            goto exit;
        }
        printf("ACL Cbor Size: %zd\n", aclCborSize);
        DeleteACLList(acl);
    }

    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
    size_t pstatCborSize = 0;
    if (NULL != value)
    {
        OicSecPstat_t *pstat = JSONToPstatBin(jsonStr);
        VERIFY_NON_NULL(TAG, pstat, FATAL);
        ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload");
            DeletePstatBinData(pstat);
            goto exit;
        }
        printf("PSTAT Cbor Size: %zd\n", pstatCborSize);
        DeletePstatBinData(pstat);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
    size_t doxmCborSize = 0;
    if (NULL != value)
    {
        OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr);
        VERIFY_NON_NULL(TAG, doxm, FATAL);
        ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload");
            DeleteDoxmBinData(doxm);
            goto exit;
        }
        printf("DOXM Cbor Size: %zd\n", doxmCborSize);
        DeleteDoxmBinData(doxm);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
    size_t amaclCborSize = 0;
    if (NULL != value)
    {
        OicSecAmacl_t *amacl = JSONToAmaclBin(jsonStr);
        VERIFY_NON_NULL(TAG, amacl, FATAL);
        ret = AmaclToCBORPayload(amacl, &amaclCbor, &amaclCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Amacl to Cbor Payload");
            DeleteAmaclList(amacl);
            goto exit;
        }
        printf("AMACL Cbor Size: %zd\n", amaclCborSize);
        DeleteAmaclList(amacl);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
    size_t svcCborSize = 0;
    if (NULL != value)
    {
        OicSecSvc_t *svc = JSONToSvcBin(jsonStr);
        VERIFY_NON_NULL(TAG, svc, FATAL);
        ret = SVCToCBORPayload(svc, &svcCbor, &svcCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Svc to Cbor Payload");
            DeleteSVCList(svc);
            goto exit;
        }
        printf("SVC Cbor Size: %zd\n", svcCborSize);
        DeleteSVCList(svc);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
    //printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value));
    size_t credCborSize = 0;
    int secureFlag = 0;
    if (NULL != value)
    {
        OicSecCred_t *cred = JSONToCredBin(jsonStr);
        VERIFY_NON_NULL(TAG, cred, FATAL);
        ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
            DeleteCredList(cred);
            goto exit;
        }
        printf("CRED Cbor Size: %zd\n", credCborSize);
        DeleteCredList(cred);
    }

    CborEncoder encoder;
    size_t cborSize = aclCborSize + pstatCborSize + doxmCborSize + svcCborSize + credCborSize + amaclCborSize;

    printf("Total Cbor Size : %zd\n", cborSize);
    cborSize += 255; // buffer margin for adding map and byte string
    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
    VERIFY_NON_NULL(TAG, outPayload, ERROR);
    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
    CborEncoder map;
    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Main Map.");
    if (aclCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, aclCbor, aclCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
    }

    if (pstatCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, pstatCbor, pstatCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
    }
    if (doxmCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, doxmCbor, doxmCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value.");
    }
    if (amaclCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, amaclCbor, amaclCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Value.");
    }
    if (svcCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, svcCbor, svcCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
    }
    if (credCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, credCbor, credCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
    }

    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Container.");

    size_t s = encoder.ptr - outPayload;
    OIC_LOG_V(DEBUG, TAG, "Payload size %zu", s);

    fp1 = fopen(cborFileName, "w");
    if (fp1)
    {
        size_t bytesWritten = fwrite(outPayload, 1, s, fp1);
        if (bytesWritten == s)
        {
            OIC_LOG_V(DEBUG, TAG, "Written %zu bytes", bytesWritten);
        }
        else
        {
            OIC_LOG_V(ERROR, TAG, "Failed writing %zu bytes", s);
        }
        fclose(fp1);
        fp1 = NULL;
    }
exit:

    cJSON_Delete(jsonRoot);
    OICFree(aclCbor);
    OICFree(doxmCbor);
    OICFree(pstatCbor);
    OICFree(amaclCbor);
    OICFree(svcCbor);
    OICFree(credCbor);
    OICFree(jsonStr);
    return ;
}
Exemple #15
0
OicSecCred_t * JSONToCredBin(const char * jsonStr)
{
    if (NULL == jsonStr)
    {
        OIC_LOG(ERROR, TAG,"JSONToCredBin jsonStr in NULL");
        return NULL;
    }

    OicSecCred_t *headCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
    OCStackResult ret = OC_STACK_ERROR;
    cJSON *jsonRoot = NULL;
    VERIFY_NON_NULL(TAG, headCred, ERROR);

    jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    cJSON *jsonCredMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
    VERIFY_NON_NULL(TAG, jsonCredMap, ERROR);

    // creds
    cJSON *jsonCredArray = NULL;
    jsonCredArray = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_CREDS_NAME);
    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);

    if (cJSON_Array == jsonCredArray->type)
    {
        int numCred = cJSON_GetArraySize(jsonCredArray);
        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
        int idx = 0;
        do
        {
            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
            VERIFY_NON_NULL(TAG, jsonCred, ERROR);

            OicSecCred_t *cred = NULL;
            if(idx == 0)
            {
                cred = headCred;
            }
            else
            {
                cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
                OicSecCred_t *temp = headCred;
                while (temp->next)
                {
                    temp = temp->next;
                }
                temp->next = cred;
            }
            VERIFY_NON_NULL(TAG, cred, ERROR);

            size_t jsonObjLen = 0;
            cJSON *jsonObj = NULL;

            //CredId -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
            if(jsonObj)
            {
                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
                cred->credId = jsonObj->valueint;
            }

            //subject -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECTID_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
            ret = ConvertStrToUuid(jsonObj->valuestring, &cred->subject);
            VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);

            //CredType -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
            cred->credType = (OicSecCredType_t)jsonObj->valueint;
            //PrivateData is mandatory for some of the credential types listed below.
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);

            if (NULL != jsonObj)
            {
                cJSON *jsonPriv = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME);
                VERIFY_NON_NULL(TAG, jsonPriv, ERROR);
                jsonObjLen = strlen(jsonPriv->valuestring);
                cred->privateData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
                VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                memcpy(cred->privateData.data, jsonPriv->valuestring, jsonObjLen);
                cred->privateData.len = jsonObjLen;

                cJSON *jsonEncoding = cJSON_GetObjectItem(jsonObj, OIC_JSON_ENCODING_NAME);
                VERIFY_NON_NULL(TAG, jsonEncoding, ERROR);

                if(strcmp(OIC_SEC_ENCODING_RAW, jsonEncoding->valuestring) == 0)
                {
                    cred->privateData.encoding = OIC_ENCODING_RAW;
                }
                else if(strcmp(OIC_SEC_ENCODING_BASE64, jsonEncoding->valuestring) == 0)
                {
                    cred->privateData.encoding = OIC_ENCODING_BASE64;
                }
                else
                {
                    printf("Unknow encoding type dectected!\n");
                    printf("json2cbor will use \"oic.sec.encoding.raw\" as default encoding type.\n");
                    cred->privateData.encoding = OIC_ENCODING_RAW;
                }
            }
#ifdef __WITH_X509__
            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);

            if (NULL != jsonObj)
            {
                cJSON *jsonPub = cJSON_GetObjectItem(jsonObj, OIC_JSON_DATA_NAME);
                VERIFY_NON_NULL(TAG, jsonPub, ERROR);
                jsonObjLen = strlen(jsonPub->valuestring);
                cred->publicData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
                VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
                memcpy(cred->publicData.data, jsonPub->valuestring, jsonObjLen);
                cred->publicData.len = jsonObjLen;
            }
#endif //  __WITH_X509__
            //Period -- Not Mandatory
            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
            if(jsonObj && cJSON_String == jsonObj->type)
            {
                jsonObjLen = strlen(jsonObj->valuestring) + 1;
                cred->period = (char *)OICMalloc(jsonObjLen);
                VERIFY_NON_NULL(TAG, cred->period, ERROR);
                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
            }
            cred->next = NULL;
        } while( ++idx < numCred);
    }

    // rownerid
    cJSON *jsonCredObj = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_ROWNERID_NAME);
    VERIFY_NON_NULL(TAG, jsonCredObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_String == jsonCredObj->type, ERROR);
    ret = ConvertStrToUuid(jsonCredObj->valuestring, &headCred->rownerID);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
    ret = OC_STACK_OK;

exit:

    if (OC_STACK_OK != ret)
    {
        DeleteCredList(headCred);
        headCred = NULL;
    }
    return headCred;
}
Exemple #16
0
OicSecPstat_t* JSONToPstatBin(const char * jsonStr)
{
    printf("IN JSONToPstatBin\n");
    if(NULL == jsonStr)
    {
        return NULL;
    }

    OCStackResult ret = OC_STACK_ERROR;
    OicSecPstat_t *pstat = NULL;
    cJSON *jsonPstat = NULL;
    cJSON *jsonObj = NULL;

    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);
    ret = ConvertStrToUuid(jsonObj->valuestring, &pstat->deviceID);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);

    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ROWNERID_NAME);
    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
    ret = ConvertStrToUuid(jsonObj->valuestring, &pstat->rownerID);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);

    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_TM_NAME);
    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
    pstat->tm  = (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);
    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
    pstat->smLen = 1;
    pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
    pstat->sm[0] = (OicSecDpom_t)jsonObj->valueint;

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        OIC_LOG(ERROR, TAG, "JSONToPstatBin failed");
    }
    printf("OUT JSONToPstatBin\n");
    return pstat;
}
Exemple #17
0
OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr)
{
    printf("IN JSONToDoxmBin\n");
    if (NULL == jsonStr)
    {
        return NULL;
    }

    OCStackResult ret = OC_STACK_ERROR;
    OicSecDoxm_t *doxm =  NULL;
    cJSON *jsonDoxm = NULL;
    cJSON *jsonObj = NULL;

    size_t jsonObjLen = 0;

    cJSON *jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);

    doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(OicSecDoxm_t));
    VERIFY_NON_NULL(TAG, doxm, ERROR);

    //OxmType -- not Mandatory
    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
    if ((jsonObj) && (cJSON_Array == jsonObj->type))
    {
        doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj);
        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);

        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);

        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
        {
            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);

            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
        }
    }

    //Oxm -- not Mandatory
    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXMS_NAME);
    if (jsonObj && cJSON_Array == jsonObj->type)
    {
        doxm->oxmLen = (size_t)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;
    }

    //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;
    }

    //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;
    }

    //DPC -- Mandatory
    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME);
    if (jsonObj)
    {
        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
        doxm->dpc = jsonObj->valueint;
    }

    //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])
            {
                ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->deviceID);
                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
            }
        }
    }

    //rowner -- Mandatory
    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_ROWNERID_NAME);
    if (true == doxm->owned)
    {
        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    }
    if (jsonObj)
    {
        ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->rownerID);
        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
    }

    //Owner -- will be empty when device status is unowned.
    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVOWNERID_NAME);
    if (true == doxm->owned)
    {
        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    }
    if (jsonObj)
    {
        ret = ConvertStrToUuid(jsonObj->valuestring, &doxm->owner);
                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
    }

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        DeleteDoxmBinData(doxm);
        doxm = NULL;
    }
    printf("OUT JSONToDoxmBin\n");
    return doxm;
}
Exemple #18
0
OicSecAcl_t* JSONToAclBin(const char * jsonStr)
{
    OCStackResult ret = OC_STACK_ERROR;
    OicSecAcl_t * headAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
    cJSON *jsonRoot = NULL;

    VERIFY_NON_NULL(TAG, jsonStr, ERROR);

    jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    cJSON *jsonAclMap = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
    VERIFY_NON_NULL(TAG, jsonAclMap, ERROR);

    cJSON *jsonAclObj = NULL;

    // aclist
    jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ACLIST_NAME);
    VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);

    // aclist-aces
    cJSON *jsonAclArray = NULL;
    jsonAclArray = cJSON_GetObjectItem(jsonAclObj, OIC_JSON_ACES_NAME);
    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);

    if (cJSON_Array == jsonAclArray->type)
    {

        int numAcl = cJSON_GetArraySize(jsonAclArray);
        int idx = 0;

        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
        do
        {
            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);

            OicSecAce_t *ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
            VERIFY_NON_NULL(TAG, ace, ERROR);
            LL_APPEND(headAcl->aces, ace);

            size_t jsonObjLen = 0;
            cJSON *jsonObj = NULL;
            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECTID_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
            if(strcmp(jsonObj->valuestring, WILDCARD_RESOURCE_URI) == 0)
            {
                ace->subjectuuid.id[0] = '*';
            }
            else
            {
                ret = ConvertStrToUuid(jsonObj->valuestring, &ace->subjectuuid);
                VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
            }
            // Resources -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);

            size_t resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
            VERIFY_SUCCESS(TAG, resourcesLen > 0, ERROR);

            for(size_t idxx = 0; idxx < resourcesLen; idxx++)
            {
                OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
                VERIFY_NON_NULL(TAG, rsrc, ERROR);

                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);

                //href
                size_t jsonRsrcObjLen = 0;
                cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
                VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);

                jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
                rsrc->href = (char*)OICMalloc(jsonRsrcObjLen);
                VERIFY_NON_NULL(TAG, (rsrc->href), ERROR);
                OICStrcpy(rsrc->href, jsonRsrcObjLen, jsonRsrcObj->valuestring);

                //rel
                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_REL_NAME);
                if(jsonRsrcObj)
                {
                    jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
                    rsrc->rel = (char*)OICMalloc(jsonRsrcObjLen);
                    VERIFY_NON_NULL(TAG, (rsrc->rel), ERROR);
                    OICStrcpy(rsrc->rel, jsonRsrcObjLen, jsonRsrcObj->valuestring);
                }

                //rt
                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_RT_NAME);
                if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
                {
                    rsrc->typeLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
                    VERIFY_SUCCESS(TAG, (0 < rsrc->typeLen), ERROR);
                    rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
                    VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
                    for(size_t i = 0; i < rsrc->typeLen; i++)
                    {
                        cJSON *jsonRsrcType = cJSON_GetArrayItem(jsonRsrcObj, i);
                        rsrc->types[i] = OICStrdup(jsonRsrcType->valuestring);
                        VERIFY_NON_NULL(TAG, (rsrc->types[i]), ERROR);
                    }
                }

                //if
                jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_IF_NAME);
                if(jsonRsrcObj && cJSON_Array == jsonRsrcObj->type)
                {
                    rsrc->interfaceLen = (size_t)cJSON_GetArraySize(jsonRsrcObj);
                    VERIFY_SUCCESS(TAG, (0 < rsrc->interfaceLen), ERROR);
                    rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
                    VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
                    for(size_t i = 0; i < rsrc->interfaceLen; i++)
                    {
                        cJSON *jsonInterface = cJSON_GetArrayItem(jsonRsrcObj, i);
                        rsrc->interfaces[i] = OICStrdup(jsonInterface->valuestring);
                        VERIFY_NON_NULL(TAG, (rsrc->interfaces[i]), ERROR);
                    }
                }

                LL_APPEND(ace->resources, rsrc);
            }

            // Permissions -- Mandatory
            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
            ace->permission = jsonObj->valueint;

            //Validity -- Not Mandatory
            cJSON *jsonValidityObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_VALIDITY_NAME);
            if(jsonValidityObj)
            {
                VERIFY_SUCCESS(TAG, cJSON_Array == jsonValidityObj->type, ERROR);
                size_t validityLen = cJSON_GetArraySize(jsonValidityObj);
                VERIFY_SUCCESS(TAG, (0 < validityLen), ERROR);

                cJSON *jsonValidity = NULL;
                for(size_t i = 0; i < validityLen; i++)
                {
                    jsonValidity = cJSON_GetArrayItem(jsonValidityObj, i);
                    VERIFY_NON_NULL(TAG, jsonValidity, ERROR);
                    VERIFY_SUCCESS(TAG, (jsonValidity->type == cJSON_Array), ERROR);

                    OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
                    VERIFY_NON_NULL(TAG, validity, ERROR);
                    LL_APPEND(ace->validities, validity);

                    //Period
                    cJSON* jsonPeriod = cJSON_GetArrayItem(jsonValidity, 0);
                    if(jsonPeriod)
                    {
                        VERIFY_SUCCESS(TAG, (cJSON_String == jsonPeriod->type), ERROR);

                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
                        validity->period = (char*)OICMalloc(jsonObjLen);
                        VERIFY_NON_NULL(TAG, validity->period, ERROR);
                        OICStrcpy(validity->period, jsonObjLen, jsonPeriod->valuestring);
                    }

                    //Recurrence
                    cJSON* jsonRecurObj = cJSON_GetArrayItem(jsonValidity, 1);
                    if(jsonRecurObj)
                    {
                        VERIFY_SUCCESS(TAG, (cJSON_Array == jsonRecurObj->type), ERROR);
                        validity->recurrenceLen = cJSON_GetArraySize(jsonRecurObj);
                        VERIFY_SUCCESS(TAG, (0 < validity->recurrenceLen), ERROR);

                        validity->recurrences = (char**)OICCalloc(validity->recurrenceLen, sizeof(char*));
                        VERIFY_NON_NULL(TAG, validity->recurrences, ERROR);

                        cJSON *jsonRecur = NULL;
                        for(size_t i = 0; i < validity->recurrenceLen; i++)
                        {
                            jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
                            VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
                            jsonObjLen = strlen(jsonRecur->valuestring) + 1;
                            validity->recurrences[i] = (char*)OICMalloc(jsonObjLen);
                            VERIFY_NON_NULL(TAG, validity->recurrences[i], ERROR);
                            OICStrcpy(validity->recurrences[i], jsonObjLen, jsonRecur->valuestring);
                        }
                    }
                }
            }
        } while( ++idx < numAcl);
    }


    // rownerid
    jsonAclObj = cJSON_GetObjectItem(jsonAclMap, OIC_JSON_ROWNERID_NAME);
    VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_String == jsonAclObj->type, ERROR);
    ret = ConvertStrToUuid(jsonAclObj->valuestring, &headAcl->rownerID);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        DeleteACLList(headAcl);
        headAcl = NULL;
    }
    return headAcl;
}
Exemple #19
0
int
lcbvb_load_json(lcbvb_CONFIG *cfg, const char *data)
{
    cJSON *cj = NULL, *jnodes = NULL;
    char *tmp = NULL;
    unsigned ii;

    if ((cj = cJSON_Parse(data)) == NULL) {
        SET_ERRSTR(cfg, "Couldn't parse JSON");
        goto GT_ERROR;
    }

    if (!get_jstr(cj, "name", &tmp)) {
        SET_ERRSTR(cfg, "Expected 'name' key");
        goto GT_ERROR;
    }
    cfg->bname = strdup(tmp);

    if (!get_jstr(cj, "nodeLocator", &tmp)) {
        SET_ERRSTR(cfg, "Expected 'nodeLocator' key");
        goto GT_ERROR;
    }

    if (get_jarray(cj, "nodesExt", &jnodes)) {
        cfg->is3x = 1;
    } else if (!get_jarray(cj, "nodes", &jnodes)) {
        SET_ERRSTR(cfg, "expected 'nodesExt' or 'nodes' array");
        goto GT_ERROR;
    }

    if (!strcmp(tmp, "ketama")) {
        cfg->dtype = LCBVB_DIST_KETAMA;
    } else {
        cfg->dtype = LCBVB_DIST_VBUCKET;
    }

    if (get_jstr(cj, "uuid", &tmp)) {
        cfg->buuid = strdup(tmp);
    }

    if (!get_jint(cj, "rev", &cfg->revid)) {
        cfg->revid = -1;
    }

    /** Get the number of nodes. This traverses the list. Yuck */
    cfg->nsrv = cJSON_GetArraySize(jnodes);

    /** Allocate a temporary one on the heap */
    cfg->servers = calloc(cfg->nsrv, sizeof(*cfg->servers));
    for (ii = 0; ii < cfg->nsrv; ii++) {
        int rv;
        cJSON *jsrv = cJSON_GetArrayItem(jnodes, ii);

        if (cfg->is3x) {
            rv = build_server_3x(cfg, cfg->servers + ii, jsrv);
        } else {
            rv = build_server_2x(cfg, cfg->servers + ii, jsrv);
        }

        if (!rv) {
            SET_ERRSTR(cfg, "Failed to build server");
            goto GT_ERROR;
        }
    }

    /* Count the number of _data_ servers in the cluster. Per the spec,
     * these will always appear in order (so that we won't ever have "holes") */
    for (ii = 0; ii < cfg->nsrv; ii++) {
        if (!cfg->servers[ii].svc.data) {
            break;
        }
    }
    cfg->ndatasrv = ii;

    if (cfg->dtype == LCBVB_DIST_VBUCKET) {
        if (!parse_vbucket(cfg, cj)) {
            SET_ERRSTR(cfg, "Failed to parse vBucket map");
            goto GT_ERROR;
        }
    } else {
        /* If there is no $HOST then we can update the ketama config, otherwise
         * we must wait for the hostname to be replaced! */
        if (strstr(data, "$HOST") == NULL) {
            if (!update_ketama(cfg)) {
                SET_ERRSTR(cfg, "Failed to establish ketama continuums");
            }
        }
    }
    cfg->servers = realloc(cfg->servers, sizeof(*cfg->servers) * cfg->nsrv);
    cfg->randbuf = malloc(cfg->nsrv * sizeof(*cfg->randbuf));
    cJSON_Delete(cj);
    return 0;

    GT_ERROR:
    if (cj) {
        cJSON_Delete(cj);
    }
    return -1;
}
Exemple #20
0
cJSON *BALANCES(struct exchange_info *exchange,cJSON *argjson)
{
    return(cJSON_Parse("{\"error\":\"yahoo is readonly data source\"}"));
}
Exemple #21
0
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
    if ( retstrp != 0 )
        *retstrp = clonestr("{\"error\":\"yahoo is readonly data source\"}");
    return(cJSON_Parse("{}"));
}
Exemple #22
0
int32_t PLUGNAME(_process_json)(char *forwarder,char *sender,int32_t valid,struct plugin_info *plugin,uint64_t tag,char *retbuf,int32_t maxlen,char *origjsonstr,cJSON *origjson,int32_t initflag,char *tokenstr)
{
    char *resultstr,*retstr = 0,*methodstr,*jsonstr,*destplugin,*submethod; struct destbuf tagstr,endpoint;
    cJSON *retjson,*json,*tokenobj; uint32_t nonce;
    struct applicant_info apply;
    retbuf[0] = 0;
    if ( tokenstr == 0 )
        tokenstr = "";
    if ( is_cJSON_Array(origjson) != 0 && cJSON_GetArraySize(origjson) == 2 )
        json = cJSON_GetArrayItem(origjson,0), jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' ');
    else json = origjson, jsonstr = origjsonstr;
    if ( Debuglevel > 2 )
        printf("<<<<<<<<<<<< INSIDE relays PLUGIN! process %s [(%s).(%s)]\n",plugin->name,jsonstr,tokenstr);
    if ( initflag > 0 )
    {
        // configure settings
        RELAYS.readyflag = 1;
        plugin->allowremote = 1;
        strcpy(retbuf,"{\"result\":\"initflag > 0\"}");
    }
    else
    {
        if ( plugin_result(retbuf,json,tag) > 0 )
            return((int32_t)strlen(retbuf));
        resultstr = cJSON_str(cJSON_GetObjectItem(json,"result"));
        methodstr = cJSON_str(cJSON_GetObjectItem(json,"method"));
        destplugin = cJSON_str(cJSON_GetObjectItem(json,"destplugin"));
        submethod = cJSON_str(cJSON_GetObjectItem(json,"submethod"));
        if ( methodstr == 0 || methodstr[0] == 0 )
        {
            printf("(%s) has not method\n",jsonstr);
            return(0);
        }
        //fprintf(stderr,"RELAYS methodstr.(%s) (%s)\n",methodstr,jsonstr);
        if ( resultstr != 0 && strcmp(resultstr,"registered") == 0 )
        {
            plugin->registered = 1;
            strcpy(retbuf,"{\"result\":\"activated\"}");
        }
#ifdef INSIDE_MGW
        else if ( strcmp(methodstr,"msigaddr") == 0 )
        {
            char *devMGW_command(char *jsonstr,cJSON *json);
            if ( SUPERNET.gatewayid >= 0 )
                retstr = devMGW_command(jsonstr,json);
        }
#endif
        else
        {
            strcpy(retbuf,"{\"result\":\"relay command under construction\"}");
            if ( strcmp(methodstr,"list") == 0 )
                retstr = relays_jsonstr(jsonstr,json);
            else if ( strcmp(methodstr,"telepathy") == 0 )
            {
                sprintf(retbuf,"%s",jsonstr);
            }
            else if ( strcmp(methodstr,"busdata") == 0 )
            {
                retstr = busdata_sync(&nonce,jsonstr,cJSON_str(cJSON_GetObjectItem(json,"broadcast")),0);
                // {"plugin":"relay","method":"busdata","destplugin":"relay","submethod":"join","broadcast":"join","endpoint":""}
            }
            else if ( strcmp(methodstr,"allservices") == 0 )
            {
                if ( (retjson= serviceprovider_json()) != 0 )
                {
                    retstr = cJSON_Print(retjson), _stripwhite(retstr,' ');
                    free_json(retjson);
                    //printf("got.(%s)\n",retstr);
                } else printf("null serviceprovider_json()\n");
            }
            else if ( strcmp(methodstr,"protocol") == 0 || strcmp(methodstr,"allprotocols") == 0 )
            {
                if ( strcmp(methodstr,"protocol") == 0 && valid > 0 )
                    protocols_register(sender,jstr(json,"protocol"),jstr(json,"endpoint"),jint(json,"disconnect"));
                if ( (retjson= protocols_json(jstr(json,"protocol"))) != 0 )
                {
                    retstr = cJSON_Print(retjson), _stripwhite(retstr,' ');
                    free_json(retjson);
                } else printf("null protocols_json()\n");
            }
            else if ( strcmp(methodstr,"join") == 0 )
            {
                if ( SUPERNET.noncing == 0 )
                {
                    copy_cJSON(&tagstr,cJSON_GetObjectItem(json,"tag"));
                    copy_cJSON(&endpoint,cJSON_GetObjectItem(json,"endpoint"));
                    SUPERNET.noncing = 1;
                    if ( SUPERNET.iamrelay != 0 )
                    {
                        portable_thread_create((void *)calc_nonces,clonestr(endpoint.buf));
                        sprintf(retbuf,"{\"result\":\"noncing\",\"endpoint\":\"%s\"}",endpoint.buf);
                    }
                    //fprintf(stderr,"join or nonce.(%s)\n",retbuf);
                }
            }
            else if ( strcmp(methodstr,"nonce") == 0 )
            {
                struct destbuf endpoint,sender,destpoint,relaypoint,globalpoint,noncestr;
                memset(&apply,0,sizeof(apply));
                copy_cJSON(&destpoint,cJSON_GetObjectItem(json,"destpoint"));
                copy_cJSON(&endpoint,cJSON_GetObjectItem(json,"lbendpoint"));
                copy_cJSON(&relaypoint,cJSON_GetObjectItem(json,"relaypoint"));
                copy_cJSON(&globalpoint,cJSON_GetObjectItem(json,"globalpoint"));
                copy_cJSON(&sender,cJSON_GetObjectItem(json,"NXT"));
                if ( SUPERNET.noncing != 0 && strcmp(SUPERNET.lbendpoint,destpoint.buf) == 0 )
                {
                    if ( endpoint.buf[0] != 0 && tokenstr[0] != 0 && (tokenobj= cJSON_Parse(tokenstr)) != 0 )
                    {
                        strcpy(apply.lbendpoint,endpoint.buf);
                        strcpy(apply.relayendpoint,relaypoint.buf);
                        strcpy(apply.globalendpoint,globalpoint.buf);
                        apply.senderbits = calc_nxt64bits(sender.buf);
                        copy_cJSON(&noncestr,cJSON_GetObjectItem(tokenobj,"nonce"));
                        if ( noncestr.buf[0] != 0 )
                            apply.nonce = (uint32_t)calc_nxt64bits(noncestr.buf);
                        //printf("tokenobj.(%s) -> nonce.%u\n",tokenstr,apply.nonce);
                        free_json(tokenobj);
                        recv_nonces(&apply);
                    }
                }
            }
        }
    }
    return(plugin_copyretstr(retbuf,maxlen,retstr));
}
void App42GameResponse::init()
{
    if(_result != 200)
    {
        Util::app42Trace("App42Game failed result is %d", _result);
        buildErrorMessage();
        return;
    }
    cJSON *ptrBody = cJSON_Parse(_body.c_str());
    cJSON* ptrApp42 = Util::getJSONChild("app42", ptrBody);
    cJSON* ptrResponse = Util::getJSONChild("response", ptrApp42);
    cJSON* ptrGames = Util::getJSONChild("games", ptrResponse);
    cJSON* ptrGame = Util::getJSONChild("game", ptrGames);
    
    cJSON* child = ptrGame;
    if(child->type == cJSON_Array)
    {
        child = child->child;
    }
    while(child != NULL && child->type == cJSON_Object)
    {
        App42Game app42Game;
        app42Game.name = Util::getJSONString("name", child);
        app42Game.description = Util::getJSONString("description", child);
        games.push_back(app42Game);
        child = child->next;
        if(Util::getJSONChild("scores",ptrGame))
        {
			cJSON* ptrScores = Util::getJSONChild("scores",ptrGame);
			cJSON* ptrScore = Util::getJSONChild("score",ptrScores);
			cJSON* child = ptrScore;
			if(child->type == cJSON_Array)
            {
				child = child->child;
			}
			while(child != NULL && child->type == cJSON_Object)
            {
				App42Score app42Score;
                app42Score.setUserName(Util::getJSONString("userName", child));
                app42Score.setRank(Util::getJSONString("rank", child));
                app42Score.setScoreId(Util::getJSONString("scoreId", child));
                app42Score.setScoreValue(Util::getJSONDouble("value", child));
                app42Score.setCreatedOn(Util::getJSONString("createdOn", child));
                
                cJSON *ptrJsonDoc = Util::getJSONChild("jsonDoc", child);
                if (ptrJsonDoc != NULL)
                {
                    vector<JSONDocument> docArray;
                    if (ptrJsonDoc->type == cJSON_Array)
                    {
                        ptrJsonDoc = ptrJsonDoc->child;
                    }
                    while(ptrJsonDoc != NULL && ptrJsonDoc->type == cJSON_Object)
                    {
                        JSONDocument jsonDOC;
                        buildJsonDocument(ptrJsonDoc, &jsonDOC);
                        ptrJsonDoc = ptrJsonDoc->next;
                        docArray.push_back(jsonDOC);
                    }
                    app42Score.setJsonDocList(docArray);
                }
				scores.push_back(app42Score);
				child = child->next;
			}
		}
    }
    cJSON_Delete(ptrBody);
}
Exemple #24
0
static OicSecSvc_t* JSONToSvcBin(const char * jsonStr)
{
    OCStackResult ret = OC_STACK_ERROR;
    OicSecSvc_t * headSvc = NULL;
    OicSecSvc_t * prevSvc = NULL;
    cJSON *jsonRoot = NULL;
    cJSON *jsonSvcArray = NULL;

    VERIFY_NON_NULL(TAG, jsonStr, ERROR);

    jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);

    if (cJSON_Array == jsonSvcArray->type)
    {
        int numSvc = cJSON_GetArraySize(jsonSvcArray);
        int idx = 0;

        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
        do
        {
            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);

            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
            VERIFY_NON_NULL(TAG, svc, ERROR);

            headSvc = (headSvc) ? headSvc : svc;
            if (prevSvc)
            {
                prevSvc->next = svc;
            }

            cJSON *jsonObj = NULL;
            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
            uint32_t outLen = 0;
            B64Result b64Ret = B64_OK;

            // Service Device Identity
            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            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(svc->svcdid.id)), ERROR);
            memcpy(svc->svcdid.id, base64Buff, outLen);

            // Service Type
            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
            svc->svct = (OicSecSvcType_t)jsonObj->valueint;

            // Resource Owners
            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);

            svc->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);

            size_t idxx = 0;
            do
            {
                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
                outLen = 0;
                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
                           sizeof(base64Buff), &outLen);

                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
                                   ERROR);
                memcpy(svc->owners[idxx].id, base64Buff, outLen);
            } while ( ++idxx < svc->ownersLen);

            prevSvc = svc;
        } while( ++idx < numSvc);
    }

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        DeleteSVCList(headSvc);
        headSvc = NULL;
    }
    return headSvc;
}
Exemple #25
0
static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr)
{
    OCStackResult ret = OC_STACK_ERROR;
    OicSecAmacl_t * headAmacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));

    cJSON *jsonRoot = NULL;
    cJSON *jsonAmacl = NULL;

    VERIFY_NON_NULL(TAG, jsonStr, ERROR);

    jsonRoot = cJSON_Parse(jsonStr);
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    jsonAmacl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
    VERIFY_NON_NULL(TAG, jsonAmacl, INFO);

    cJSON *jsonObj = NULL;

    // Resources -- Mandatory
    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
    VERIFY_NON_NULL(TAG, jsonObj, ERROR);

    // Rlist
    cJSON *jsonRlistArray = cJSON_GetObjectItem(jsonObj, OIC_JSON_RLIST_NAME);
    VERIFY_NON_NULL(TAG, jsonRlistArray, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_Array == jsonRlistArray->type, ERROR);

    headAmacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonRlistArray);
    headAmacl->resources = (char**)OICCalloc(headAmacl->resourcesLen, sizeof(char*));
    size_t idxx = 0;
    do
    {
        cJSON *jsonRsrc = cJSON_GetArrayItem(jsonRlistArray, idxx);
        VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);

        cJSON *jsonRsrcObj = cJSON_GetObjectItem(jsonRsrc, OIC_JSON_HREF_NAME);
        VERIFY_NON_NULL(TAG, jsonRsrcObj, ERROR);
        VERIFY_SUCCESS(TAG, cJSON_String == jsonRsrcObj->type, ERROR);

        size_t jsonRsrcObjLen = 0;
        jsonRsrcObjLen = strlen(jsonRsrcObj->valuestring) + 1;
        headAmacl->resources[idxx] = (char*)OICMalloc(jsonRsrcObjLen);
        VERIFY_NON_NULL(TAG, (headAmacl->resources[idxx]), ERROR);
        OICStrcpy(headAmacl->resources[idxx], jsonRsrcObjLen, jsonRsrcObj->valuestring);

    } while ( ++idxx < headAmacl->resourcesLen);

    // Ams -- Mandatory
    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_AMS_NAME);
    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);

    headAmacl->amssLen = (size_t)cJSON_GetArraySize(jsonObj);
    VERIFY_SUCCESS(TAG, headAmacl->amssLen > 0, ERROR);
    headAmacl->amss = (OicUuid_t*)OICCalloc(headAmacl->amssLen, sizeof(OicUuid_t));
    VERIFY_NON_NULL(TAG, headAmacl->amss, ERROR);

    idxx = 0;
    do
    {
        cJSON *jsonAms = cJSON_GetArrayItem(jsonObj, idxx);
        VERIFY_NON_NULL(TAG, jsonAms, ERROR);
        VERIFY_SUCCESS(TAG, cJSON_String == jsonAms->type, ERROR);

        memcpy(headAmacl->amss[idxx].id, (OicUuid_t *)jsonAms->valuestring, strlen(jsonAms->valuestring));

    } while ( ++idxx < headAmacl->amssLen);


    // Rowner -- Mandatory
    jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_ROWNERID_NAME);
    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);

    ret = ConvertStrToUuid(jsonObj->valuestring, &headAmacl->rownerID);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);

    ret = OC_STACK_OK;

exit:
    cJSON_Delete(jsonRoot);
    if (OC_STACK_OK != ret)
    {
        DeleteAmaclList(headAmacl);
        headAmacl = NULL;
    }
    return headAmacl;
}
Exemple #26
0
void thread_ssid_msgio(void)
{
	int ret = pthread_detach(pthread_self());
	Debug("pthread_self():%lu, ret[%d]", pthread_self(), ret);
	char mac[32] = {0};
	char ssid[14] = {"FotileAP_"};
	int retssid = 0;
	while (1) 
	{
		fd_set rset, wset;
		FD_ZERO(&rset);
		//FD_ZERO(&wset);
		int i, maxfd, rcvfd;
		maxfd = set_get_max(&ssid_fdset);
		for(i=0;i<set_get_elem_num(&ssid_fdset);i++)
		{
			FD_SET(set_at(&ssid_fdset, i),&rset);
		}
		//FD_SET(socket_fd,&wset);
		struct timeval tval;
		tval.tv_sec = 0;
		tval.tv_usec = 10000;
		if(select(maxfd+1, &rset, NULL, NULL,&tval) > 0)
		{
			int i;
			for(i=0;i<set_get_elem_num(&ssid_fdset);i++)
			{
				if(FD_ISSET(set_at(&ssid_fdset, i), &rset))
				{
					rcvfd = set_at(&ssid_fdset, i);
					break;
				}
			}
			
			char szRcv[MAX_MESSAGE_LEN] = {0};
			int len = 0;
			int lens =0;
			unsigned char mac_arr[6] = {0};		//not use

			if (retssid == 0){
				retssid = get_eth0_mac(mac, mac_arr, 32);
				ssid[9] = mac[12];
				ssid[10] = mac[13];
				ssid[11] = mac[15];
				ssid[12] = mac[16];
				Debug("first time get ssid!");
			}else{

			}
			int ret = recv(rcvfd, szRcv, MAX_MESSAGE_LEN, 0);
			//Info("ret[%d]%s", ret, szRcv);
			if (ret > 0) 
			{
				cJSON *root1 = cJSON_Parse(szRcv);
				cJSON *root2 = cJSON_CreateObject();
				if(strcmp(cJSON_GetObjectItem(root1,"type")->valuestring,"reqssid") == 0)
				{
					cJSON_AddItemToObject(root2, "type", cJSON_CreateString("reqssid"));
					cJSON_AddNumberToObject(root2, "seq", cJSON_GetObjectItem(root1,"seq")->valueint);
					if(retssid > 0)
					{
						cJSON_AddNumberToObject(root2, "respcode", 0);
						cJSON_AddStringToObject(root2, "respmsg", ssid);
					}
					else
					{
						cJSON_AddNumberToObject(root2, "respcode", -1);
						cJSON_AddStringToObject(root2,"respmsg",  "error:get ssid failed!");
					}
					char *out = cJSON_Print(root2);
					//Info("out[%s]", out);
					lens = strlen(out);
					send(rcvfd, out , lens ,0);
					//Info("%s",rendered);
					cJSON_Delete(root1);
					cJSON_Delete(root2);
					free(out);
				}else{
					Warn("param error!");
				}
			} 
			else
			{
				//Warn("[fd:%d]rcv error! close socket", rcvfd);
				set_erase(rcvfd, &ssid_fdset);
				close(rcvfd);
			}
		}
	}
}
Exemple #27
0
void ICACHE_FLASH_ATTR
mjyun_receive(const char * event_name, const char * event_data)
{
	/* {"m":"set", "d":{"r":18,"g":100,"b":7,"w":0,"s":1000}} */
	INFO("RECEIVED: key:value [%s]:[%s]\r\n", event_name, event_data);

	if (0 == os_strcmp(event_name, "set")) {
		cJSON * pD = cJSON_Parse(event_data);
		if ((NULL != pD) && (cJSON_Object == pD->type)) {
			cJSON * pR = cJSON_GetObjectItem(pD, "r");
			cJSON * pG = cJSON_GetObjectItem(pD, "g");
			cJSON * pB = cJSON_GetObjectItem(pD, "b");
			cJSON * pW = cJSON_GetObjectItem(pD, "w");
			cJSON * pS = cJSON_GetObjectItem(pD, "s");

			mcu_status_t mst;
			mst.r = sys_status.mcu_status.r;
			mst.g = sys_status.mcu_status.g;
			mst.b = sys_status.mcu_status.b;
			mst.w = sys_status.mcu_status.w;
			mst.s = sys_status.mcu_status.s;

			if ((NULL != pR) && (cJSON_Number == pR->type)) {
				if (mst.r != pR->valueint) {
					mst.r = pR->valueint;
				}
			}
			if ((NULL != pG) && (cJSON_Number == pG->type)) {
				if (mst.g != pG->valueint) {
					mst.g = pG->valueint;
				}
			}
			if ((NULL != pB) && (cJSON_Number == pB->type)) {
				if (mst.b != pB->valueint) {
					mst.b = pB->valueint;
				}
			}
			if ((NULL != pW) && (cJSON_Number == pW->type)) {
				if (mst.w != pW->valueint) {
					mst.w = pW->valueint;
				}
			}
			if ((NULL != pS) && (cJSON_Number == pS->type)) {
				if (mst.s != pS->valueint) {
					mst.s = pS->valueint;
				}
			}

			app_apply_settings(&mst);
			app_check_mcu_save(&mst);

			// notify the other users
			app_push_status(&mst);
		} else {
			INFO("%s: Error when parse JSON\r\n", __func__);
		}
		cJSON_Delete(pD);
	}

	if (0 == os_strcmp(event_name, "get")) {
		INFO("RX Get status Request!\r\n");
		app_push_status(NULL);
	}

	if(os_strncmp(event_data, "ota", 3) == 0) {
		INFO("OTA: upgrade the firmware!\r\n");
		mjyun_mini_ota_start("ota/dev/bulb/files");
	}
}
Exemple #28
0
// Called on a reconnect
void G_ReadClientSessionData( gclient_t *client ) {
	clientSession_t *sess = &client->sess;
	cJSON *root = NULL, *object = NULL;
	char fileName[MAX_QPATH] = {};
	char *buffer = NULL;
	fileHandle_t f = NULL_FILE;
	unsigned int len = 0;
	const char *tmp = NULL;
	char jsonError[MAX_STRING_CHARS] = {};

	Com_sprintf( fileName, sizeof(fileName), "session/client%02i.json", client - level.clients );
	len = trap->FS_Open( fileName, &f, FS_READ );

	// no file
	if ( !f || !len || len == -1 ) {
		trap->FS_Close( f );
		return;
	}

	buffer = (char *)malloc( len + 1 );
	if ( !buffer ) {
		return;
	}

	trap->FS_Read( buffer, len, f );
	trap->FS_Close( f );
	buffer[len] = '\0';

	// read buffer
	root = cJSON_Parse( buffer, jsonError, sizeof(jsonError) );
	free( buffer );

	if ( !root ) {
		Com_Printf( "G_ReadSessionData(%02i): could not parse session data\n", client - level.clients );
		return;
	}

	if ( (object = cJSON_GetObjectItem( root, "sessionTeam" )) ) {
		sess->sessionTeam = (team_t)cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "spectatorNum" )) ) {
		sess->spectatorNum = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "spectatorState" )) ) {
		sess->spectatorState = (spectatorState_t)cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "spectatorClient" )) ) {
		sess->spectatorClient = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "wins" )) ) {
		sess->wins = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "losses" )) ) {
		sess->losses = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "setForce" )) ) {
		sess->setForce = (qboolean)cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "saberLevel" )) ) {
		sess->saberLevel = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "selectedFP" )) ) {
		sess->selectedFP = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "updateUITime" )) ) {
		sess->updateUITime = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "duelTeam" )) ) {
		sess->duelTeam = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "siegeDesiredTeam" )) ) {
		sess->siegeDesiredTeam = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "saberType" )) ) {
		if ( (tmp = cJSON_ToString( object )) ) {
			Q_strncpyz( sess->saberType, tmp, sizeof(sess->saberType) );
		}
	}
	if ( (object = cJSON_GetObjectItem( root, "saber2Type" )) ) {
		if ( (tmp = cJSON_ToString( object )) ) {
			Q_strncpyz( sess->saber2Type, tmp, sizeof(sess->saber2Type) );
		}
	}
	if ( (object = cJSON_GetObjectItem( root, "IP" )) ) {
		if ( (tmp = cJSON_ToString( object )) ) {
			Q_strncpyz( sess->IP, tmp, sizeof(sess->IP) );
		}
	}
	if ( (object = cJSON_GetObjectItem( root, "connTime" )) ) {
		sess->connTime = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "noq3fill" )) ) {
		sess->noq3fill = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "validated" )) ) {
		sess->validated = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "adminRank" )) ) {
		sess->adminRank = cJSON_ToInteger( object );
	}
	if ( (object = cJSON_GetObjectItem( root, "canUseCheats" )) ) {
		sess->canUseCheats = !!cJSON_ToInteger( object );
	}

	client->ps.fd.saberAnimLevel = client->sess.saberLevel;
	client->ps.fd.saberDrawAnimLevel = client->sess.saberLevel;
	client->ps.fd.forcePowerSelected = client->sess.selectedFP;

	cJSON_Delete( root );
	root = NULL;
}
Exemple #29
0
int main(int args,char *argv[]){
    const int smallOutputNumber=-1;
    int i,j;
    cJSON *root;
    int num_chromosome;
    int req_type=1;
    char buffer[30];
    char req_gene[20]={0};
    cJSON *msg;
    char req_kind[50]="E.coli K12-DH10B";

    pi=0;
    ini=0;
    req_restrict.rfc10=0;
    req_restrict.rfc12=0;
    req_restrict.rfc12a=0;
    req_restrict.rfc21=0;
    req_restrict.rfc23=0;
    req_restrict.rfc25=0;

    char *req_str=argv_default;
    if(args==2) req_str=argv[1];

    cJSON *request=cJSON_Parse(req_str);
    if(check_req(request)){
        onError("illegal args");
        return 0;
    }

    i=1;
    j=1;

    cJSON *cJSON_temp;
    cJSON_temp=cJSON_GetObjectItem(request,"type");
    if(cJSON_temp) req_type=cJSON_temp->valueint;
    char req_pam[PAM_LEN+1];
    int req_pam_len;
    strcpy(req_pam,cJSON_GetObjectItem(request,"pam")->valuestring);
    req_pam_len=(int)strlen(req_pam);
    char req_specie[30];
    struct return_struct rs;
    int ptts_num;
    int len[NUM_CHROMOSOME];
    strcpy(req_specie,cJSON_GetObjectItem(request,"specie")->valuestring);
    if(strcmp(req_specie,"SARS")==0){
        rs=info_readin(PTT_SARS,ptts,str,wai,NULL);
    }else if(strcmp(req_specie,"E.coli")==0){
        cJSON_temp=cJSON_GetObjectItem(request,"kind");
        if(cJSON_temp) strcpy(req_kind,cJSON_temp->valuestring);
        rs=info_readin(PTT_ECOLI,ptts,str,wai,req_kind);
    }else if(strcmp(req_specie,"Saccharomycetes")==0){
        rs=info_readin(PTT_SACCHAROMYCETES,ptts,str,wai,NULL);
    }else{
        onError("no specie");
        return 0;
    }
    ptts_num=rs.ptts_num;
    num_chromosome=rs.num_chromosome;
    for(i=1;i<=num_chromosome;i++) len[i]=rs.len[i];

    double req_r1=0.65;
    cJSON_temp=cJSON_GetObjectItem(request,"gene");
    if(cJSON_temp){
        req_r1=cJSON_GetObjectItem(request,"r1")->valuedouble;
    }

    cJSON_temp=cJSON_GetObjectItem(request,"gene");
    int req_id,req_gene_start,req_gene_end;
    if(cJSON_temp){
        strcpy(req_gene,cJSON_temp->valuestring);
        for(int i=0;i<ptts_num;i++){
            if(strcmp(req_gene,ptts[i].gene)==0){
                req_id=ptts[i].chromosome;
                req_gene_start=ptts[i].s;
                req_gene_end=ptts[i].t;
                break;
            }
        }
    }else{
        char req_location[20];
        strcpy(req_location,cJSON_GetObjectItem(request,"location")->valuestring);
        sscanf(req_location,"%d:%d..%d",&req_id,&req_gene_start,&req_gene_end);
    }

    char req_rfc[10];
    strcpy(req_rfc,cJSON_GetObjectItem(request,"rfc")->valuestring);
    req_restrict.rfc10=req_rfc[0]-48;
    req_restrict.rfc12=req_rfc[1]-48;
    req_restrict.rfc12a=req_rfc[2]-48;
    req_restrict.rfc21=req_rfc[3]-48;
    req_restrict.rfc23=req_rfc[4]-48;
    req_restrict.rfc25=req_rfc[5]-48;

    generate_filename(buffer,req_specie,req_kind,req_pam,req_type);
    dc_init(buffer);
    /*
    This part above is for read in JSON-style request.
    The result stored in req_specie, req_pam, req_gene_start, req_gene_end, rfc and so on.
    At the same time, it reads in ptt file for specie,
    and also open files.
    */

    for(int id=1;id<=num_chromosome;id++){
        for(i=LEN;i<len[id]-req_pam_len;i++){       // All possible gRNAs, +direction
            if(check_pam(str[id]+i,req_pam)){
                psb_site[pi].index=i;
                psb_site[pi].strand='+';
                psb_site[pi].chromosome=id;
                for(j=0;j<req_pam_len;j++) psb_site[pi].pam[j]=(str[id]+i)[j];
                psb_site[pi].pam[j]=0;
                for(j=0;j<LEN;j++) psb_site[pi].nt[j]=(str[id]+i-LEN)[j];
                psb_site[pi].nt[j]=0;
                pi++;
            }
        }
        char req_pam_rev[PAM_LEN];
        int last=-1;
        dna_rev(req_pam_rev,req_pam,req_pam_len);
        for(i=0;i<len[id]-LEN-req_pam_len;i++){     // All possible gRNAs, -direction
            if(check_pam(str[id]+i,req_pam_rev)){
                psb_site[pi].index=i+req_pam_len-1;
                psb_site[pi].strand='-';
                psb_site[pi].chromosome=id;
                if(req_pam_len!=last){
                    last=req_pam_len;
                }
                for(j=0;j<req_pam_len;j++) psb_site[pi].pam[j]=dna_rev_char((str[id]+i)[req_pam_len-1-j]);
                psb_site[pi].pam[j]=0;
                for(j=0;j<LEN;j++) psb_site[pi].nt[j]=dna_rev_char((str[id]+i+req_pam_len)[LEN-j-1]);
                psb_site[pi].nt[j]=0;
                pi++;
            }
        }
    }

    for(i=0;i<pi;i++){
        fflush(stdout);
        if(psb_site[i].chromosome!=req_id) continue;
        if(psb_site[i].strand=='+'){
            if(psb_site[i].index<req_gene_start || psb_site[i].index+req_pam_len-1>req_gene_end) continue;
            for(j=psb_site[i].index-LEN;j<psb_site[i].index+req_pam_len-1;j++){
                if(wai[req_id][j]!=1) break;
            }
            if(j<psb_site[i].index+req_pam_len-1) j=0;
            else j=1;
        }else{
            if(psb_site[i].index-req_pam_len+1<req_gene_start || psb_site[i].index>req_gene_end) continue;
            for(j=psb_site[i].index-req_pam_len+1;j<psb_site[i].index+LEN;j++){
                if(wai[req_id][j]!=1) break;
            }
            if(j<psb_site[i].index+LEN) j=0;
            else j=1;
        }
        if(j){
            score(i,&ini,req_type,req_r1);
        }
    }

    dc_save();

    sort(in_site,in_site+ini,cmp_in_site);  // Sort & Output

    root=cJSON_CreateObject();
    cJSON_AddNumberToObject(root,"status",0);

    msg=cJSON_CreateObject();
    cJSON_AddStringToObject(msg,"specie",req_specie);
    cJSON_AddStringToObject(msg,"kind",req_kind);
    cJSON_AddStringToObject(msg,"gene",req_gene);
    sprintf(buffer,"%d:%d..%d",req_id,req_gene_start,req_gene_end);
    cJSON_AddStringToObject(msg,"location",buffer);
    cJSON_AddItemToObject(root,"message",msg);

    vector<cJSON*> list;
    list.clear();
    for(i=0;i<ini && i!=smallOutputNumber;i++){
        cJSON *ans=cJSON_CreateObject();
        sprintf(buffer,"#%d",i+1);
        cJSON_AddStringToObject(ans,"key",buffer);
        sprintf(buffer,"%s%s",in_site[i].nt,in_site[i].pam);
        cJSON_AddStringToObject(ans,"grna",buffer);
        sprintf(buffer,"%d:%d",in_site[i].chromosome,in_site[i].index);
        cJSON_AddStringToObject(ans,"position",buffer);
        char xs[2];
        xs[0]=in_site[i].strand;
        xs[1]=0;
        cJSON_AddStringToObject(ans,"strand",xs);
        cJSON_AddNumberToObject(ans,"total_score",(int)in_site[i].score);
        cJSON_AddNumberToObject(ans,"Sspe",(int)(req_r1*in_site[i].Sspe_nor));
        cJSON_AddNumberToObject(ans,"Seff",(int)((1.0-req_r1)*in_site[i].Seff_nor));
        cJSON_AddNumberToObject(ans,"count",in_site[i].count);
        cJSON_AddItemToObject(ans,"offtarget",in_site[i].otj);

        list.push_back(ans);
    }

    cJSON_AddItemToObject(root,"result",Create_array_of_anything(&(list[0]),list.size()));

    printf("%s\n",NomoreSpace(argv[0]=cJSON_Print(root)));

    free(argv[0]);
    return 0;
}
int remote_control()
{
	ghttp_request *req;
	char *http_body = NULL;
	req = ghttp_request_new();
	sqlite3 *db = NULL;
        int rc = 0;
        sqlite3_stmt *ppstmt = NULL;
        char sql_cmd[100] ={0};
        const char *box_id;
        char box_id_tmp[10] = {0};
        const char *wan_state;
        char *errorMsg = NULL;
	char request_url[200] = {0};

	printf("****************************************\n");
        printf("remote_control : start\n");
        printf("****************************************\n");

        rc = sqlite3_open(box_db, &db);
        if(rc == SQLITE_ERROR)
        {
                printf("cannot open box.db!\n");
                return 0;
        }

        strcpy(sql_cmd, "select box_id from box_info");
        sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0);
        rc = sqlite3_step(ppstmt);
	if(rc == SQLITE_ROW)
        {
                box_id = sqlite3_column_text(ppstmt, 0);
                strcpy(box_id_tmp, box_id);
                printf("box_id : %s\n", box_id_tmp);
        }
	
        sqlite3_finalize(ppstmt);
        sqlite3_close(db);

	printf("send http request...\n");
        sprintf(request_url, "http://www.ailvgobox.com/box_manage/remote_control.php?box_id=%s", box_id_tmp);
        printf("request_url  : %s\n", request_url);
	http_body = send_http_request(req, request_url);
	fprintf(stderr, "http_body : %s\n", http_body);

	cJSON *node;
	
        if(http_body)
        {
        	printf("HTTP success!\n");

                if(strcmp(http_body, "null") == 0)
                     printf("http_body : null, no remote_control!\n");
                else
                {
                     node = cJSON_Parse(http_body);
                     ParseJSON(node, box_id_tmp);
                }
        }
	else
        {
                printf("HTTP failure!\n");
        }

        if(http_body)
               free(http_body);

        ghttp_request_destroy(req);
        free(request_url);
        printf("remote_control : complete!\n");
        return 1;
}