void ScreenOverlayManager::SaveLayouts()
{
#if MYFW_WINDOWS && MYFW_USING_WX
    cJSON* layouts = cJSON_CreateObject();

    for( int i=0; i<ScreenOverlay_NumScreens; i++ )
    {
        if( m_LayoutJSONStrings[i][LayoutType_Wide] != 0 ||
            m_LayoutJSONStrings[i][LayoutType_Tall] != 0 ||
            m_LayoutJSONStrings[i][LayoutType_Square] != 0 )
        {
            cJSON* screenlayout = cJSON_CreateObject();
            cJSON_AddItemToObject( layouts, ScreenOverlayNames[i], screenlayout );

            if( m_LayoutJSONStrings[i][LayoutType_Wide] )
                cJSON_AddStringToObject( screenlayout, "Wide", m_LayoutJSONStrings[i][LayoutType_Wide] );
            if( m_LayoutJSONStrings[i][LayoutType_Tall] )
                cJSON_AddStringToObject( screenlayout, "Tall", m_LayoutJSONStrings[i][LayoutType_Tall] );
            if( m_LayoutJSONStrings[i][LayoutType_Square] )
                cJSON_AddStringToObject( screenlayout, "Square", m_LayoutJSONStrings[i][LayoutType_Square] );
        }
    }

    char* layoutstring = cJSON_Print( layouts );
    cJSON_Delete( layouts );

    char filename[MAX_PATH];
    sprintf_s( filename, MAX_PATH, "Data/Layouts/allscreens.layout" );
    FILE* file;
    fopen_s( &file, filename, "wb" );
    fprintf( file, layoutstring );
    fclose( file );

    free( layoutstring );
#endif
}
Example #2
0
bool Stream::Send_Jsoon_str()
{


	char cJsonBuff[1024 * 2];
	char * m_tmp;
	m_tmp = cJSON_Print(pRet_root);
	memset(cJsonBuff, 0, sizeof(cJsonBuff));
	sprintf(cJsonBuff, "%sXXEE", m_tmp);
	free(m_tmp);
	printf("-----%s \n",cJsonBuff);
	fflush(stdout);
	cJSON_Delete(pRet_root);
	pRet_root = NULL;

	
	if(m_clientSocket != -1)
	{
		send(m_clientSocket, cJsonBuff, strlen(cJsonBuff), 0);
		printf("---send len=%d\n",strlen(cJsonBuff));
		printf("---send over\n");
		fflush(stdout);
	}
}
Example #3
0
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;
}
int ixcgi_reqstb_streaming(char *handle, char *type, int16_t port, int16_t ttl, int fe_id, int ch_id, char *path, char *in, size_t in_size)
{
    cJSON   *root;
    char    *out;
    size_t  n_recv;
    int     timeout = 12000;

    if ((root = cJSON_CreateObject()) == NULL)
        return -1;

    cJSON_AddItemToObject(root, HTTPD_OPCODE, cJSON_CreateString(HTTPD_STREAMING));
    cJSON_AddItemToObject(root, HTTPD_STREAMING_MY_IP, cJSON_CreateString(getenv("REMOTE_ADDR")));

    if (handle[0]) {
        cJSON_AddItemToObject(root, HTTPD_STREAMING_STOP, cJSON_CreateString(handle));
        timeout = 2000;
    } else {
        cJSON_AddItemToObject(root, HTTPD_STREAMING_TYPE, cJSON_CreateString(type));
        cJSON_AddItemToObject(root, HTTPD_STREAMING_PORT, cJSON_CreateNumber(port));
        cJSON_AddItemToObject(root, HTTPD_STREAMING_TTL, cJSON_CreateNumber(ttl));

        if ((fe_id >= 0) && (ch_id > 0)) {
            cJSON_AddItemToObject(root, HTTPD_STREAMING_FE_ID, cJSON_CreateNumber(fe_id));
            cJSON_AddItemToObject(root, HTTPD_STREAMING_CH_ID, cJSON_CreateNumber(ch_id));
        } else {
            cJSON_AddItemToObject(root, HTTPD_STREAMING_PATH, cJSON_CreateString(path));
        }
    }

    n_recv = send_recv_stbd(out = cJSON_Print(root), in, in_size, timeout);

    cJSON_Delete(root);
    free(out);

    return (n_recv == 0) ? -1 : 0 ;
}
Example #5
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;
}
Example #6
0
int32_t process_NXT_event(struct NXThandler_info *mp,int32_t histmode,char *txid,int64_t type,int64_t subtype,struct NXT_AMhdr *AMhdr,char *sender,char *receiver,char *assetid,int64_t assetoshis,char *comment,cJSON *json)
{
    int32_t i,count,highest_priority;
    NXT_handler NXT_handler = 0;
    void *handlerdata = 0;
    struct NXT_protocol *p;
    struct NXT_protocol_parms PARMS;
    count = 0;
    highest_priority = -1;
    memset(&PARMS,0,sizeof(PARMS));
    if ( Num_NXThandlers == 0 )
        printf("WARNING: process_NXT_event Num_NXThandlers.%d\n",Num_NXThandlers);
    for (i=0; i<Num_NXThandlers; i++)
    {
        if ( (p= NXThandlers[i]) != 0 )
        {
            if ( AMhdr != 0 || ((p->type < 0 || p->type == type) && (p->subtype < 0 || p->subtype == subtype)) )
            {
                if ( AMhdr != 0 )
                {
                    if ( p->AMsigfilter != 0 && p->AMsigfilter != AMhdr->sig )
                        continue;
                }
                else if ( p->assetlist != 0 && assetid != 0 && listcmp(p->assetlist,assetid) != 0 )
                    continue;
                if ( strcmp(sender,GENESISACCT) == 0 || strcmp(receiver,GENESISACCT) == 0 || //is_gateway_addr(sender) != 0 ||
                     (AMhdr == 0 || p->whitelist == 0 || listcmp(p->whitelist,sender) == 0) ||
                     (AMhdr != 0 && cmp_nxt64bits(sender,AMhdr->nxt64bits) == 0) )
                {
                    if ( p->priority > highest_priority )
                    {
                        count = 1;
                        highest_priority = p->priority;
                        NXT_handler = p->NXT_handler;
                        handlerdata = p->handlerdata;
                        PARMS.argjson = json; PARMS.txid = txid; PARMS.sender = sender; PARMS.receiver = receiver;
                        PARMS.type = (int32_t)type; PARMS.subtype = (int32_t)subtype; PARMS.priority = highest_priority; PARMS.histflag = histmode;
                        if ( AMhdr != 0 )
                        {
                            PARMS.mode = NXTPROTOCOL_AMTXID;
                            PARMS.AMptr = AMhdr;
                        }
                        else
                        {
                            PARMS.mode = NXTPROTOCOL_TYPEMATCH;
                            PARMS.assetid = assetid;
                            PARMS.assetoshis = assetoshis;
                            PARMS.comment = comment;
                        }
                        //printf("call NXT_handler\n");
                        (*NXT_handler)(mp,&PARMS,handlerdata);
                   }
                    else if ( p->priority == highest_priority )
                        count++;
                }
                //printf("end iter\n");
            }
        }
    }
    if ( count > 1 )
        printf("WARNING: (%s) claimed %d times, priority.%d\n",cJSON_Print(json),count,highest_priority);  // this is bad, also leaks mem!
    if ( 0 && highest_priority >= 0 && NXT_handler != 0 )
    {
        //printf("count.%d handler.%p NXThandler_info_handler.%p AMhdr.%p\n",count,NXT_handler,multigateway_handler,AMhdr);
        PARMS.argjson = json; PARMS.txid = txid; PARMS.sender = sender; PARMS.receiver = receiver;
        PARMS.type = (int32_t)type; PARMS.subtype = (int32_t)subtype; PARMS.priority = highest_priority; PARMS.histflag = histmode;
        if ( AMhdr != 0 )
        {
            PARMS.mode = NXTPROTOCOL_AMTXID;
            PARMS.AMptr = AMhdr;
        }
        else
        {
            PARMS.mode = NXTPROTOCOL_TYPEMATCH;
            PARMS.assetid = assetid;
            PARMS.assetoshis = assetoshis;
            PARMS.comment = comment;
        }
        (*NXT_handler)(mp,&PARMS,handlerdata);///histmode,txid,AMhdr,sender,receiver,assetid,assetoshis,comment,json);
    }
    return(count != 0);
}
Example #7
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);
			}
		}
	}
}
Example #8
0
/**
 * @brief Convert the JSON object to a string.
 * @return A JSON string representation of the object.
 */
std::string JsonObject::toString() {
	char *data = cJSON_Print(m_node);
	std::string ret(data);
	free(data);
	return ret;
} // toString
char *InstantDEX_parser(char *forwarder,char *sender,int32_t valid,char *origargstr,cJSON *origargjson)
{
    static char *allorderbooks[] = { (char *)allorderbooks_func, "allorderbooks", "", 0 };
    static char *orderbook[] = { (char *)orderbook_func, "orderbook", "", "baseid", "relid", "allfields", "oldest", "maxdepth", "base", "rel", "gui", "showall", "exchange", 0 };
    static char *lottostats[] = { (char *)lottostats_func, "lottostats", "", "timestamp", 0 };
    static char *cancelquote[] = { (char *)cancelquote_func, "cancelquote", "", "quoteid", 0 };
    static char *openorders[] = { (char *)openorders_func, "openorders", "", 0 };
    static char *placebid[] = { (char *)placebid_func, "placebid", "", "baseid", "relid", "volume", "price", "timestamp", "baseamount", "relamount", "gui", "automatch", "minperc", "duration", "exchange", "offerNXT", 0 };
    static char *placeask[] = { (char *)placeask_func, "placeask", "", "baseid", "relid", "volume", "price", "timestamp", "baseamount", "relamount", ",gui", "automatch", "minperc", "duration", "exchange", "offerNXT", 0 };
    static char *bid[] = { (char *)bid_func, "bid", "", "baseid", "relid", "volume", "price", "timestamp", "baseamount", "relamount", "gui", "automatch", "minperc", "duration", "exchange", "offerNXT", 0 };
    static char *ask[] = { (char *)ask_func, "ask", "", "baseid", "relid", "volume", "price", "timestamp", "baseamount", "relamount", "gui", "automatch", "minperc", "duration", "exchange", "offerNXT", 0 };
    static char *makeoffer3[] = { (char *)makeoffer3_func, "makeoffer3", "", "baseid", "relid", "quoteid", "perc", "deprecated", "baseiQ", "reliQ", "askoffer", "price", "volume", "exchange", "baseamount", "relamount", "offerNXT", "minperc", "jumpasset", 0 };
    static char *respondtx[] = { (char *)respondtx_func, "respondtx", "", "cmd", "assetid", "quantityQNT", "priceNQT", "triggerhash", "quoteid", "sig", "data", "minperc", "offerNXT", "otherassetid", "otherqty", 0 };
    static char *jumptrades[] = { (char *)jumptrades_func, "jumptrades", "", 0 };
    static char *tradehistory[] = { (char *)tradehistory_func, "tradehistory", "", "timestamp", 0 };
    static char **commands[] = { allorderbooks, lottostats, cancelquote, respondtx, jumptrades, tradehistory, openorders, makeoffer3, placebid, bid, placeask, ask, orderbook };
    int32_t i,j,localaccess = 0;
    cJSON *argjson,*obj,*nxtobj,*secretobj,*objs[64];
    char NXTaddr[MAX_JSON_FIELD],NXTACCTSECRET[MAX_JSON_FIELD],command[MAX_JSON_FIELD],offerNXT[MAX_JSON_FIELD],**cmdinfo,*argstr,*retstr=0;
    memset(objs,0,sizeof(objs));
    command[0] = 0;
    valid = 1;
    memset(NXTaddr,0,sizeof(NXTaddr));
    if ( is_cJSON_Array(origargjson) != 0 )
    {
        argjson = cJSON_GetArrayItem(origargjson,0);
        argstr = cJSON_Print(argjson), _stripwhite(argstr,' ');
    } else argjson = origargjson, argstr = origargstr;
    NXTACCTSECRET[0] = 0;
    if ( argjson != 0 )
    {
        if ( (obj= cJSON_GetObjectItem(argjson,"requestType")) == 0 )
            obj = cJSON_GetObjectItem(argjson,"method");
        nxtobj = cJSON_GetObjectItem(argjson,"NXT");
        secretobj = cJSON_GetObjectItem(argjson,"secret");
        copy_cJSON(NXTaddr,nxtobj);
        copy_cJSON(offerNXT,cJSON_GetObjectItem(argjson,"offerNXT"));
        if ( NXTaddr[0] == 0 && offerNXT[0] == 0 )
        {
            strcpy(NXTaddr,SUPERNET.NXTADDR);
            strcpy(offerNXT,SUPERNET.NXTADDR);
            strcpy(sender,SUPERNET.NXTADDR);
            ensure_jsonitem(argjson,"NXT",NXTaddr);
            ensure_jsonitem(argjson,"offerNXT",offerNXT);
        }
        else if ( offerNXT[0] == 0 && strcmp(NXTaddr,SUPERNET.NXTADDR) == 0 )
        {
            strcpy(offerNXT,SUPERNET.NXTADDR);
            strcpy(sender,SUPERNET.NXTADDR);
            ensure_jsonitem(argjson,"offerNXT",offerNXT);
        }
        else strcpy(sender,offerNXT);
        if ( strcmp(offerNXT,SUPERNET.NXTADDR) == 0 )
            localaccess = 1;
        if ( localaccess != 0 && strcmp(NXTaddr,SUPERNET.NXTADDR) != 0 )
        {
            strcpy(NXTaddr,SUPERNET.NXTADDR);
            ensure_jsonitem(argjson,"NXT",NXTaddr);
            //printf("subsititute NXT.%s\n",NXTaddr);
        }
//printf("localaccess.%d myaddr.(%s) NXT.(%s) offerNXT.(%s)\n",localaccess,SUPERNET.NXTADDR,NXTaddr,offerNXT);
        copy_cJSON(command,obj);
        copy_cJSON(NXTACCTSECRET,secretobj);
        if ( NXTACCTSECRET[0] == 0 )
        {
            if ( localaccess != 0 || strcmp(command,"findnode") != 0 )
            {
                safecopy(NXTACCTSECRET,SUPERNET.NXTACCTSECRET,sizeof(NXTACCTSECRET));
                strcpy(NXTaddr,SUPERNET.NXTADDR);
             }
        }
//printf("(%s) argstr.(%s) command.(%s) NXT.(%s) valid.%d\n",cJSON_Print(argjson),argstr,command,NXTaddr,valid);
        //fprintf(stderr,"SuperNET_json_commands sender.(%s) valid.%d | size.%d | command.(%s) orig.(%s)\n",sender,valid,(int32_t)(sizeof(commands)/sizeof(*commands)),command,origargstr);
        for (i=0; i<(int32_t)(sizeof(commands)/sizeof(*commands)); i++)
        {
            cmdinfo = commands[i];
            if ( strcmp(cmdinfo[1],command) == 0 )
            {
                //printf("needvalid.(%c) valid.%d %d of %d: cmd.(%s) vs command.(%s)\n",cmdinfo[2][0],valid,i,(int32_t)(sizeof(commands)/sizeof(*commands)),cmdinfo[1],command);
                if ( cmdinfo[2][0] != 0 && valid <= 0 )
                    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])(localaccess,valid,sender,objs,j-3,argstr);
                break;
            }
        }
    } else printf("not JSON to parse?\n");
    if ( argstr != origargstr )
        free(argstr);
    return(retstr);
}
Example #10
0
void *ChangeLightRepresentation (void *param)
{
    (void)param;
    OCStackResult result = OC_STACK_ERROR;

    uint8_t j = 0;
    uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
    OCObservationId obsNotify[numNotifies];

    while (!gQuitFlag)
    {
        sleep(10);
        Light.power += 5;
        if (gLightUnderObservation)
        {
            OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
            if (gObserveNotifyType == 1)
            {
                // Notify list of observers. Alternate observers on the list will be notified.
                j = 0;
                for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2))
                {
                    if (interestedObservers[i].valid == true)
                    {
                        obsNotify[j] = interestedObservers[i].observationId;
                        j++;
                    }
                }

                cJSON *json = cJSON_CreateObject();
                cJSON *format;
                cJSON_AddStringToObject(json,"href",gResourceUri);
                cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
                cJSON_AddStringToObject(format, "state", (char *) (Light.state ? "on":"off"));
                cJSON_AddNumberToObject(format, "power", Light.power);
                char * obsResp = cJSON_Print(json);
                cJSON_Delete(json);
                result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
                        (unsigned char *)obsResp, OC_NA_QOS);
                free(obsResp);
            }
            else if (gObserveNotifyType == 0)
            {
                // Notifying all observers
                result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
                if (OC_STACK_NO_OBSERVERS == result)
                {
                    OC_LOG (INFO, TAG,
                            "=======> No more observers exist, stop sending observations");
                    gLightUnderObservation = 0;
                }
            }
            else
            {
                OC_LOG (ERROR, TAG, "Incorrect notification type selected");
            }
        }
#ifdef WITH_PRESENCE
        if(stopPresenceCount > 0)
        {
            OC_LOG_V(INFO, TAG, "================ presence count %d", stopPresenceCount);
        }
        if(!stopPresenceCount--)
        {
            OC_LOG(INFO, TAG, "================ stopping presence");
            OCStopPresence();
        }
#endif
    }
    return NULL;
}
Example #11
0
struct coin777 *coin777_create(char *coinstr,cJSON *argjson)
{
    char *serverport,*path=0,*conf=0; struct destbuf tmp;
    struct coin777 *coin = calloc(1,sizeof(*coin));
    safecopy(coin->name,coinstr,sizeof(coin->name));
    if ( argjson == 0 )
    {
        coin->minconfirms = (strcmp("BTC",coinstr) == 0) ? 3 : 10;
        coin->estblocktime = (strcmp("BTC",coinstr) == 0) ? 600 : 120;
    }
    else
    {
        coin->minoutput = get_API_nxt64bits(cJSON_GetObjectItem(argjson,"minoutput"));
        coin->minconfirms = get_API_int(cJSON_GetObjectItem(argjson,"minconfirms"),(strcmp("BTC",coinstr) == 0) ? 3 : 10);
        coin->estblocktime = get_API_int(cJSON_GetObjectItem(argjson,"estblocktime"),(strcmp("BTC",coinstr) == 0) ? 600 : 120);
        coin->jsonstr = cJSON_Print(argjson);
        coin->argjson = cJSON_Duplicate(argjson,1);
        if ( (serverport= cJSON_str(cJSON_GetObjectItem(argjson,"rpc"))) != 0 )
            safecopy(coin->serverport,serverport,sizeof(coin->serverport));
        path = cJSON_str(cJSON_GetObjectItem(argjson,"path"));
        conf = cJSON_str(cJSON_GetObjectItem(argjson,"conf"));

        copy_cJSON(&tmp,cJSON_GetObjectItem(argjson,"assetid")), safecopy(coin->mgw.assetidstr,tmp.buf,sizeof(coin->mgw.assetidstr));
        coin->mgw.assetidbits = calc_nxt64bits(coin->mgw.assetidstr);
        copy_cJSON(&tmp,cJSON_GetObjectItem(argjson,"issuer")), safecopy(coin->mgw.issuer,tmp.buf,sizeof(coin->mgw.issuer));;
        coin->mgw.issuerbits = conv_acctstr(coin->mgw.issuer);
        printf(">>>>>>>>>>>> a issuer.%s %llu assetid.%llu minoutput.%llu\n",coin->mgw.issuer,(long long)coin->mgw.issuerbits,(long long)coin->mgw.assetidbits,(long long)coin->minoutput);
        //uint32_t set_assetname(uint64_t *multp,char *name,uint64_t assetbits);
        _set_assetname(&coin->mgw.ap_mult,coin->mgw.assetname,0,coin->mgw.assetidbits);
        printf("assetname.(%s) mult.%llu\n",coin->mgw.assetname,coin->mgw.ap_mult);
        strcpy(coin->mgw.coinstr,coinstr);
        if ( (coin->mgw.special= cJSON_GetObjectItem(argjson,"special")) == 0 )
            coin->mgw.special = cJSON_GetObjectItem(COINS.argjson,"special");
        if ( coin->mgw.special != 0 )
            coin->mgw.special = NXT_convjson(coin->mgw.special);
        printf("CONVERTED.(%s)\n",cJSON_Print(coin->mgw.special));
        coin->mgw.limbo = cJSON_GetObjectItem(argjson,"limbo");
        coin->mgw.dust = get_API_nxt64bits(cJSON_GetObjectItem(argjson,"dust"));
        coin->mgw.txfee = get_API_nxt64bits(cJSON_GetObjectItem(argjson,"txfee_satoshis"));
        if ( coin->mgw.txfee == 0 )
            coin->mgw.txfee = (uint64_t)(SATOSHIDEN * get_API_float(cJSON_GetObjectItem(argjson,"txfee")));
        if ( coin->mgw.txfee == 0 )
            coin->mgw.txfee = 10000;
        coin->mgw.NXTfee_equiv = get_API_nxt64bits(cJSON_GetObjectItem(argjson,"NXTfee_equiv_satoshis"));
        if ( coin->mgw.NXTfee_equiv == 0 )
            coin->mgw.NXTfee_equiv = (uint64_t)(SATOSHIDEN * get_API_float(cJSON_GetObjectItem(argjson,"NXTfee_equiv")));
        copy_cJSON(&tmp,cJSON_GetObjectItem(argjson,"opreturnmarker")), safecopy(coin->mgw.opreturnmarker,tmp.buf,sizeof(coin->mgw.opreturnmarker));
        printf("OPRETURN.(%s)\n",coin->mgw.opreturnmarker);
        copy_cJSON(&tmp,cJSON_GetObjectItem(argjson,"marker2")), safecopy(coin->mgw.marker2,tmp.buf,sizeof(coin->mgw.marker2));
        coin->mgw.redeemheight = get_API_int(cJSON_GetObjectItem(argjson,"redeemheight"),430000);
        coin->mgw.use_addmultisig = get_API_int(cJSON_GetObjectItem(argjson,"useaddmultisig"),(strcmp("BTC",coinstr) != 0));
        coin->mgw.do_opreturn = get_API_int(cJSON_GetObjectItem(argjson,"do_opreturn"),(strcmp("BTC",coinstr) == 0));
        coin->mgw.oldtx_format = get_API_int(cJSON_GetObjectItem(argjson,"oldtx_format"),(strcmp("BTC",coinstr) == 0));
        coin->mgw.firstunspentind = get_API_int(cJSON_GetObjectItem(argjson,"firstunspent"),(strcmp("BTCD",coinstr) == 0) ? 2500000 : 0);
        if ( (coin->mgw.NXTconvrate = get_API_float(cJSON_GetObjectItem(argjson,"NXTconvrate"))) == 0 )
        {
            if ( coin->mgw.NXTfee_equiv != 0 && coin->mgw.txfee != 0 )
                coin->mgw.NXTconvrate = ((double)coin->mgw.NXTfee_equiv / coin->mgw.txfee);
        }
        copy_cJSON(&tmp,cJSON_GetObjectItem(argjson,"marker")), safecopy(coin->mgw.marker,tmp.buf,sizeof(coin->mgw.marker));
        printf("OPRETURN.(%s)\n",coin->mgw.opreturnmarker);
    }
    printf("coin777_create %s: (%s) %llu mult.%llu NXTconvrate %.8f minconfirms.%d issuer.(%s) %llu opreturn.%d oldformat.%d\n",coin->mgw.coinstr,coin->mgw.assetidstr,(long long)coin->mgw.assetidbits,(long long)coin->mgw.ap_mult,coin->mgw.NXTconvrate,coin->minconfirms,coin->mgw.issuer,(long long)coin->mgw.issuerbits,coin->mgw.do_opreturn,coin->mgw.oldtx_format);
    extract_userpass(coin->serverport,coin->userpass,coinstr,SUPERNET.userhome,path,conf);
    printf("COIN.%s serverport.(%s) userpass.(%s)\n",coin->name,coin->serverport,coin->userpass);
    COINS.LIST = realloc(COINS.LIST,(COINS.num+1) * sizeof(*coin));
    COINS.LIST[COINS.num] = coin, COINS.num++;
    //ensure_packedptrs(coin);
    return(coin);
}
Example #12
0
void http_server_start(http_server_t *http_server) {
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(1);
    }

    SOCKET s;
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket : %d" , WSAGetLastError());
        exit(1);
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(8888);

    if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    listen(s, 3);

    int c = sizeof(struct sockaddr_in);
    SOCKET newSocket;
    struct sockaddr_in client;
    while ((newSocket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET) {
        char message[500000];
        char request[500000];
        int recvSize = recv(newSocket, request, sizeof(request), 0);
        request[recvSize] = '\0';

        http_server_request_method_t http_server_request_method;
        char url[128];
        char requestMessage[500000];
        parseHttpRequest(request, &http_server_request_method, url, requestMessage);
        printf("%s\n", url);

        if (strcmp(url, "/directors") == 0) {
            cJSON *json = cJSON_CreateArray();

            for (size_t i = 0; i < directors_size(http_server->directors); ++i) {
                director_t *director = directors_get(http_server->directors, i);

                cJSON *jsonDir = cJSON_CreateObject();
                cJSON_AddStringToObject(jsonDir, "name", director->name);
                cJSON_AddStringToObject(jsonDir, "surname", director->surname);
                char birthdateStr[128];
                sprintf(birthdateStr, "%i-%i-%i", director->birth_date.tm_year, director->birth_date.tm_mday, director->birth_date.tm_mon);
                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_AddNumberToObject(jsonDir, "salary", director->salary);
                cJSON_AddNumberToObject(jsonDir, "rating", director->rating);

                cJSON_AddItemToArray(json, jsonDir);
            }

            char *jsonStr = cJSON_Print(json);

            makeHttpResponse(jsonStr, message);
            cJSON_Delete(json);
            send(newSocket, message, strlen(message), 0);
        } else if (strncmp(url, "/directors/", strlen("/directors/")) == 0) {
            size_t directorIndex = atoi(strstr(url + 1, "/") + 1);
            director_t *director = directors_get(http_server->directors, directorIndex);

            if (http_server_request_method == http_server_request_method_delete) {
                directors_remove(http_server->directors, directorIndex);

                makeHttpResponse("", message);
                send(newSocket, message, strlen(message), 0);
            } else if (http_server_request_method == http_server_request_method_post) {
                cJSON *json = cJSON_Parse(requestMessage);

                cJSON *subItem = json->child;
                while (subItem) {
                    if ((subItem->type == cJSON_String) && (strcmp(subItem->string, "name") == 0))
                        director_update(director, subItem->valuestring, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
                    if ((subItem->type == cJSON_String) && (strcmp(subItem->string, "surname") == 0))
                        director_update(director, NULL, subItem->valuestring, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
                    if ((subItem->type == cJSON_String) && (strcmp(subItem->string, "birthdate") == 0)) {
                        int year;
                        int day;
                        int month;
                        sscanf(subItem->valuestring, "%i-%i-%i", &year, &day, &month);
                        director_update(director, NULL, NULL, &year, &day, &month, NULL, NULL, NULL, NULL);
                    }
                    if ((subItem->type == cJSON_Object) && (strcmp(subItem->string, "startup") == 0)) {
                        cJSON *subJtem = subItem->child;
                        while (subJtem) {
                            if ((subJtem->type == cJSON_String) && (strcmp(subJtem->string, "name") == 0))
                                director_update(director, NULL, NULL, NULL, NULL, NULL, subJtem->valuestring, NULL, NULL, NULL);
                            if ((subJtem->type == cJSON_String) && (strcmp(subJtem->string, "country") == 0))
                                director_update(director, NULL, NULL, NULL, NULL, NULL, NULL, subJtem->valuestring, NULL, NULL);

                            subJtem = subJtem->next;
                        }
                    }
                    if ((subItem->type == cJSON_Number) && (strcmp(subItem->string, "salary") == 0)) {
                        director_update(director, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &subItem->valueint, NULL);
                    }
                    if ((subItem->type == cJSON_Number) && (strcmp(subItem->string, "rating") == 0)) {
                        director_update(director, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &subItem->valuedouble);
                    }

                    subItem = subItem->next;
                }

                makeHttpResponse("", message);
                send(newSocket, message, strlen(message), 0);
            } else {
                cJSON *json = cJSON_CreateObject();
                cJSON_AddStringToObject(json, "name", director->name);
                cJSON_AddStringToObject(json, "surname", director->surname);
                char birthdateStr[128];
                sprintf(birthdateStr, "%i-%i-%i", director->birth_date.tm_year, director->birth_date.tm_mday, director->birth_date.tm_mon);
                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);
                cJSON_AddNumberToObject(json, "salary", director->salary);
                cJSON_AddNumberToObject(json, "rating", director->rating);

                char *jsonStr = cJSON_Print(json);

                makeHttpResponse(jsonStr, message);
                cJSON_Delete(json);
                send(newSocket, message, strlen(message), 0);
            }
        } else {
            const char *message = "HTTP/1.1 404\r\nContent-length: 0\r\n\r\n";
            send(newSocket, message, strlen(message), 0);
        }

        closesocket(newSocket);
    }

    if (newSocket == INVALID_SOCKET) {
        printf("accept failed with error code : %d" , WSAGetLastError());
        exit(1);
    }

    closesocket(s);
    WSACleanup();
}
int write_bb_black_respond(char* fileName,char *rev)
{
    long len;
    char sw[15];

    char uid[60];
    char ip_s[20];
    char port_s[10];
    char port_l[10];
    char* pContent;
    //First read the old config
    FILE* fp = fopen(fileName, "rb+");
    if(fp==NULL)
    {
        DEBUG_printf("open error\n");
        exit(1);
    }
    fseek(fp,0,SEEK_END);
    len=ftell(fp);
    if(0 == len)
    {
        return 0;
    }
    fseek(fp,0,SEEK_SET);
    pContent = (char*) malloc(sizeof(char)*len+100);
    fread(pContent,1,len,fp);
    fclose(fp);
    cJSON *jsonroot = cJSON_Parse(pContent); //json
    strcpy(sw,cJSON_GetObjectItem(jsonroot,"api-switch")->valuestring);
    strcpy(uid,cJSON_GetObjectItem(jsonroot,"api-uid")->valuestring);

    strcpy(ip_s,cJSON_GetObjectItem(jsonroot,"ip_server")->valuestring);
    strcpy(port_s,cJSON_GetObjectItem(jsonroot,"port_server")->valuestring);
    strcpy(port_l,cJSON_GetObjectItem(jsonroot,"port_local")->valuestring);
    cJSON_Delete(jsonroot);
    //Write configuration, update
    fp = fopen(fileName, "w+");
    if(fp==NULL)
    {
        DEBUG_printf("open error\n");
    }
    cJSON *root;
    char *out;
    root=cJSON_CreateObject();
    cJSON_AddStringToObject(root, "api-switch" , sw);
    cJSON_AddStringToObject(root, "api-uid", uid);
    cJSON_AddStringToObject(root, "auth", rev);
    cJSON_AddStringToObject(root, "ip_server" ,ip_s);
    cJSON_AddStringToObject(root, "port_server", port_s);
    cJSON_AddStringToObject(root, "port_local", port_l);
    out=cJSON_Print(root);
    fprintf(fp,"%s",out);
    fclose(fp);

    cJSON_Delete(root);
    free(out);
    out = NULL;
    root = NULL;
    free(pContent);
    return 1;
}
Example #14
0
static int _load_config()
{
	cJSON *config = NULL;
	cJSON *data = NULL;
	cJSON *elm = NULL;
	cJSON *startTime = NULL;
	cJSON *command = NULL;
	int cnt = 0;
	int index = 0;
	int hour,min,second;
	int ret = OK;
	
	if (NULL != task)
	{
		free(task);
		task = NULL;
	}

	config = _get_JSON_from_file(CONFIG_FILE_PATH);
	if (NULL == config)
	{
		LOG_ERR("get config errer");
		ret = ERROR;
		goto leave;
	}

	/* attendtion free */
	PRINTF("data = %s", cJSON_Print(config));	
	data = cJSON_GetObjectItem(config, "data");
	cnt = cJSON_GetArraySize(data);

	task = (TASK_ENTRY *)malloc(sizeof(TASK_ENTRY)*cnt);
	if (NULL == task)
	{
		LOG_ERR("malloc error!");
		ret = ERROR;
		goto leave;
	}
	
	for(index = 0; index < cnt; index++)
	{
		elm = cJSON_GetArrayItem(data, index);
		startTime = cJSON_GetObjectItem(elm, "startTime");
		if( startTime != NULL && startTime->type == cJSON_String )
		{
			sscanf(startTime->valuestring, "%d:%d:%d", &hour, &min, &second);
			task[index].startTime = hour * 60 * 60 + min * 60 + second;
		}
		
		command = cJSON_GetObjectItem(elm, "command");
		if( command != NULL && command->type == cJSON_String )
		{
			if(strlen(command->valuestring) < MAX_COMMAND_LENGTH)
			{
				strcpy(task[index].command, command->valuestring);
			}
			else
			{
				LOG_ERR("command %s size %d error!", command->valuestring, strlen(command->valuestring));
				_log_to_file(ERROR_LOG_FILE_PATH, "command %s size %d error!",	command->valuestring, strlen(command->valuestring));
			}
		}
	}

	_quick_sort(0, cnt - 1, task);
	task_index = 0;
	task_MAX = cnt;
	
#ifdef LOG_DEBUG
	for(index = 0; index < cnt; index++)
	{
		PRINTF("%02d:%02d:%02d	%s", task[index].startTime/3600, (task[index].startTime % 3600)/60, task[index].startTime%60, task[index].command);
	}
#endif

leave:
	if(config)
		cJSON_Delete(config);
	
	return ret;
}
Example #15
0
char *jprint(cJSON *json,int32_t freeflag) { char *str; if ( json == 0 ) return(clonestr("{}")); str = cJSON_Print(json), _stripwhite(str,' '); if ( freeflag != 0 ) free_json(json); return(str); }
Example #16
0
/** Considers user-defined configuration. Loads and parses user-defined configuration
* '.config.json' present in user's home directory for 'plugin interface' and
* 'plugins' configuration properties and concats with iotkit-comm configuration properties.
*/
void concatUserDefinedConfigurations() {
    char *home, config_file[1024];

    home = getenv("HOME");
    if (home == NULL || strlen(home) == 0) {
        struct passwd *pw = getpwuid(getuid());
        home = pw->pw_dir;
    }

    strcpy(config_file, home);
    if (*(home + (strlen(home) - 1)) != '/') {
        strcat(config_file, "/");
    }

    strcat(config_file, USER_CONFIG_FILENAME);

    char *out;
    cJSON *json = NULL, *jitem;
    FILE *fp = fopen(config_file, "rb");

    if (fp == NULL) {
        fprintf(stderr,"Warning: Optional user config file not found. Continuing...\n");
    } else {
        fseek(fp, 0, SEEK_END);
        long size = ftell(fp);
        rewind(fp);

        // read the file
        char *buffer = (char *)malloc(size+1);
        if (buffer != NULL) {
            fread(buffer, 1, size, fp);
            // parse the file
            json = cJSON_Parse(buffer);
        }
        if (json == NULL || !json) {
            fprintf(stderr,"Error before: [%s]\n",cJSON_GetErrorPtr());
        } else {
            #if DEBUG
                out = cJSON_Print(json, 2);
                fprintf(stderr,"%s\n", out);
                free(out);
            #endif

            if (!isJsonObject(json)) {
                handleParseConfigError();
            }

            jitem = cJSON_GetObjectItem(json, "pluginInterfaceDirPaths");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            int pathSize = strlen(g_configData.pluginInterfaceDir) + strlen(jitem->valuestring) + 2;
            char *pluginInterfaceDirPaths = (char *)malloc(sizeof(char) * pathSize);
            if (pluginInterfaceDirPaths != NULL) {
                strcpy(pluginInterfaceDirPaths, g_configData.pluginInterfaceDir);
                strcat(pluginInterfaceDirPaths, ":");
                strcat(pluginInterfaceDirPaths, jitem->valuestring);
                g_configData.pluginInterfaceDir = pluginInterfaceDirPaths;
            }
            #if DEBUG
                printf("pluginInterfaceDir = %s\n", g_configData.pluginInterfaceDir);
            #endif

            jitem = cJSON_GetObjectItem(json, "pluginDirPaths");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            pathSize = strlen(g_configData.pluginDir) + strlen(jitem->valuestring) + 2;
            char *pluginDirPaths = (char *)malloc(sizeof(char) * pathSize);
            if (pluginDirPaths != NULL) {
                strcpy(pluginDirPaths, g_configData.pluginDir);
                strcat(pluginDirPaths, ":");
                strcat(pluginDirPaths, jitem->valuestring);
                g_configData.pluginDir = pluginDirPaths;
            }
            #if DEBUG
                printf("pluginDir = %s\n", g_configData.pluginDir);
            #endif

endParseConfig:
            cJSON_Delete(json);
        }

        free(buffer);
        fclose(fp); // close the file pointer
    }
}
Example #17
0
OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize)
{
    OCEntityHandlerResult ehResult = OC_EH_OK;
    char *respPLPost_light = NULL;
    cJSON *json;
    cJSON *format;

    /*
     * 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.
     * In the sample below, if the POST is for /a/light then a new instance of the Light
     * resource is created with default representation (if representation is included in
     * POST payload it can be used as initial values) as long as the instance is
     * lesser than max new instance count. Once max instance count is reached, POST on
     * /a/light updated the representation of /a/light (just like PUT)
     */

    if (ehRequest->resource == Light.handle)
    {
        if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
        {
            // Create new Light instance
            char newLightUri[URI_MAXSIZE];
            snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance);

            json = cJSON_CreateObject();
            cJSON_AddStringToObject(json,"href",gResourceUri);
            cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
            cJSON_AddStringToObject(format, "createduri", (char *) newLightUri);

            if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance]))
            {
                OC_LOG (INFO, TAG, "Created new Light instance\n");
                gLightInstance[gCurrLightInstance].state = 0;
                gLightInstance[gCurrLightInstance].power = 0;
                gCurrLightInstance++;
                respPLPost_light = cJSON_Print(json);
                strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH);
                ehResult = OC_EH_RESOURCE_CREATED;
            }

            cJSON_Delete(json);
        }
        else
        {
            // Update repesentation of /a/light
            Light.state = true;
            Light.power = 11;
            respPLPost_light = constructJsonResponse(ehRequest);
        }
    }
    else
    {
        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
        {
            if (ehRequest->resource == gLightInstance[i].handle)
            {
                gLightInstance[i].state = true;
                gLightInstance[i].power = 22;
                if (i == 0)
                {
                    respPLPost_light = constructJsonResponse(ehRequest);
                    break;
                }
                else if (i == 1)
                {
                    respPLPost_light = constructJsonResponse(ehRequest);
                }
            }
        }
    }

    if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light)))
    {
        strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light));
    }
    else
    {
        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
                maxPayloadSize);
        ehResult = OC_EH_ERROR;
    }

    free(respPLPost_light);
    return ehResult;
}
Example #18
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 *jsonstr,cJSON *json,int32_t initflag,char *tokenstr)
{
    char *resultstr,*methodstr,zerobuf[1],*coinstr,*str = 0; cJSON *array,*item; int32_t i,n,j = 0; struct coin777 *coin; struct destbuf tmp;
    retbuf[0] = 0;
    if ( initflag > 0 )
    {
        if ( json != 0 )
        {
            COINS.argjson = cJSON_Duplicate(json,1);
            COINS.slicei = get_API_int(cJSON_GetObjectItem(json,"slice"),0);
            if ( (array= cJSON_GetObjectItem(json,"coins")) != 0 && (n= cJSON_GetArraySize(array)) > 0 )
            {
                for (i=j=0; i<n; i++)
                {
                    item = cJSON_GetArrayItem(array,i);
                    coinstr = cJSON_str(cJSON_GetObjectItem(item,"name"));
                    if ( coinstr != 0 && coinstr[0] != 0 && (coin= coin777_find(coinstr,0)) == 0 )
                    {
                        printf("CALL coin777_create.(%s) (%s)\n",coinstr,cJSON_Print(item));
                        coin777_create(coinstr,item);
                    }
                }
            }
        } else strcpy(retbuf,"{\"result\":\"no JSON for init\"}");
        COINS.readyflag = 1;
        plugin->allowremote = 1;
        //plugin->sleepmillis = 1;
    }
    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"));
        coinstr = cJSON_str(cJSON_GetObjectItem(json,"coin"));
        if ( methodstr == 0 || methodstr[0] == 0 )
        {
            printf("(%s) has not method\n",jsonstr);
            return(0);
        }
        //printf("COINS.(%s) for (%s) (%s)\n",methodstr,coinstr!=0?coinstr:"",jsonstr);
        if ( resultstr != 0 && strcmp(resultstr,"registered") == 0 )
        {
            plugin->registered = 1;
            strcpy(retbuf,"{\"result\":\"activated\"}");
        }
        else
        {
            zerobuf[0] = 0;
            str = 0;
            //printf("INSIDE COINS.(%s) methods.%ld\n",jsonstr,sizeof(coins_methods)/sizeof(*coins_methods));
            copy_cJSON(&tmp,cJSON_GetObjectItem(json,"NXT")), safecopy(sender,tmp.buf,32);
            if ( coinstr == 0 )
                coinstr = zerobuf;
            else coin = coin777_find(coinstr,1);
#ifdef INSIDE_MGW
            if ( strcmp(methodstr,"acctpubkeys") == 0 )
            {
                if ( SUPERNET.gatewayid >= 0 )
                {
                    if ( coinstr[0] == 0 )
                        strcpy(retbuf,"{\"result\":\"need to specify coin\"}");
                    else if ( (coin= coin777_find(coinstr,1)) != 0 )
                    {
                        int32_t MGW_publish_acctpubkeys(char *coinstr,char *str);
                        char *get_msig_pubkeys(char *coinstr,char *serverport,char *userpass);
                        if ( (str= get_msig_pubkeys(coin->name,coin->serverport,coin->userpass)) != 0 )
                        {
                            MGW_publish_acctpubkeys(coin->name,str);
                            strcpy(retbuf,"{\"result\":\"published and processed acctpubkeys\"}");
                            free(str), str= 0;
                        } else sprintf(retbuf,"{\"error\":\"no get_msig_pubkeys result\",\"method\":\"%s\"}",methodstr);
                    } else sprintf(retbuf,"{\"error\":\"no coin777\",\"method\":\"%s\"}",methodstr);
                } else sprintf(retbuf,"{\"error\":\"gateway only method\",\"method\":\"%s\"}",methodstr);
            }
            else if ( strcmp(methodstr,"gotmsigaddr") == 0 )
            {
                if ( SUPERNET.gatewayid < 0 )
                    printf("GOTMSIG.(%s)\n",jsonstr);
            }
            else
#endif
                sprintf(retbuf,"{\"error\":\"unsupported method\",\"method\":\"%s\"}",methodstr);
        }
    }
    //printf("<<<<<<<<<<<< INSIDE PLUGIN.(%s) initflag.%d process %s slice.%d\n",SUPERNET.myNXTaddr,initflag,plugin->name,COINS.slicei);
    return(plugin_copyretstr(retbuf,maxlen,str));
}
Example #19
0
void data_sel()
{
	int rc=0;
	char *out;
	char sql[250]={0};
	const char *box_id=NULL,*city_id=NULL,*city_name=NULL,*site_id=NULL,*site_name=NULL,*area_id=NULL,*area_name=NULL,*guide_id=NULL,*guide_name=NULL,*type=NULL,*tel=NULL,*gps=NULL,*province_id=NULL,*province_name=NULL;
	sqlite3 *db;
	sqlite3_stmt *ppstmt=NULL;
	cJSON *root;

	rc = sqlite3_open("/ailvgo/www/database/box.db",&db);
	if((rc != SQLITE_OK)&&(MODEL==1))
	{
		printf("open database error_sel!\n");
	}
//	printf("mobile:%s\n",ptr1);
//	printf("time:%s\n",ptr2);
	memset(sql,0,sizeof(sql));
	sprintf(sql,"select box_id,city_id,city_name,site_id,site_name,area_id,area_name,guide_id,guide_name, type,province_id,province_name,tel,gps from box_info");
	rc=sqlite3_prepare(db,sql,-1,&ppstmt,0);
	if((rc != SQLITE_OK)&&(MODEL==1))
	{
		fprintf(stderr,"SQL error:%s \n",sqlite3_errmsg(db));
	}
	rc=sqlite3_step(ppstmt);
	if(rc==SQLITE_ROW)
	{
		root=cJSON_CreateObject();
		while(rc == SQLITE_ROW)
		{
			box_id=sqlite3_column_text(ppstmt,0);
			city_id=sqlite3_column_text(ppstmt,1);
			city_name=sqlite3_column_text(ppstmt,2);
			site_id=sqlite3_column_text(ppstmt,3);
		//	printf("site_id:%s\n",site_id);
			site_name=sqlite3_column_text(ppstmt,4);
			area_id=sqlite3_column_text(ppstmt,5);
			area_name=sqlite3_column_text(ppstmt,6);
			guide_id=sqlite3_column_text(ppstmt,7);
			guide_name=sqlite3_column_text(ppstmt,8);
			type=sqlite3_column_text(ppstmt,9);
			province_id=sqlite3_column_text(ppstmt,10);
			province_name=sqlite3_column_text(ppstmt,11);
			tel=sqlite3_column_text(ppstmt,12);
			gps=sqlite3_column_text(ppstmt,13);

			cJSON_AddStringToObject(root,"type",  type);  	
			cJSON_AddStringToObject(root,"box_id",  box_id);  	
			cJSON_AddStringToObject(root,"province_id",  province_id);  	
			cJSON_AddStringToObject(root,"province_name",province_name); 	
			cJSON_AddStringToObject(root,"city_id", city_id);  	
			cJSON_AddStringToObject(root,"city_name",city_name);
			if(NULL != site_id)			  
			{
				cJSON_AddStringToObject(root,"gps",gps);
				cJSON_AddStringToObject(root,"tel",tel);
				cJSON_AddStringToObject(root,"site_id",site_id);
				cJSON_AddStringToObject(root,"site_name",site_name);
				cJSON_AddStringToObject(root,"area_id",area_id);
				cJSON_AddStringToObject(root,"area_name",area_name);
				if(NULL != guide_id)
				{
					cJSON_AddStringToObject(root,"guide_id",guide_id);
					cJSON_AddStringToObject(root,"guide_name",guide_name);
				}
			}
			rc = sqlite3_step(ppstmt);
		}
		out =cJSON_Print(root);
		printf("%s\n",out);
//		printf("1");
		cJSON_Delete(root);
		free(out);
	}
	else
	{
		printf("");
	}

	sqlite3_finalize(ppstmt);
	sqlite3_close(db);

}
Example #20
0
//test begin----------------------------
void testJson(char* buf,int n){
   int i,j;
   printf(">>testJson() ~000>>buf size:%d >>buf is:%s \n",n,buf);
   printf(">>testJson() ~000>>buf size:%d  \n",n);
   if(n<=0)
     return;
   char bufNew[n];
   for(i=0;i<n;i++){
     bufNew[i] = buf[i];
   } 
/*    //test begin lilei
   char ** str;
   char a[2] ="ab";
   int len;
   len = base64DecodeStringRemoveEndZero(a,str);
   printf(">>testJson() 111.2.1 a is:%s\n",a);
   printf(">>testJson() 111.2>>decode str is:%s >>len:%d \n",*str,len);
   return;
   //test end  */
   char packageName[SMALL_TEXT_BUFFER_SIZE];
   char className[SMALL_TEXT_BUFFER_SIZE];
   char title[SMALL_TEXT_BUFFER_SIZE];
   char byteMap[BYTEMAP_BUFFER_SIZE];
   char * jsonStr;
    
   cJSON *fmt = NULL,*JSONroot = NULL,*mJSONroot;
   JSONroot = cJSON_Parse(bufNew);
   int num = cJSON_GetArraySize(JSONroot);//check arrays 
   printf(">>testJson() 222>>json root size is:%d \n",num);
   
   fmt = cJSON_GetObjectItem(JSONroot,KEY_MESSAGE_TYPE);
   int msgType = fmt->valueint;
   printf(">>testJson() 33>>msgType is:%d \n",msgType);
    
   
   if(isInArray(msgType,jsonContainPackage,sizeof(jsonContainPackage)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_PACKAGE_NAME);
     bzero(packageName,SMALL_TEXT_BUFFER_SIZE);     //clear packageName
     snprintf(packageName,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>>packageName is:%s \n",packageName);
   }
   
   if(isInArray(msgType,jsonContainClass,sizeof(jsonContainClass)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_CLASS_NAME);
     bzero(className,SMALL_TEXT_BUFFER_SIZE);         //clear className
     snprintf(className,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>className is:%s>>className len is:%ld \n",className,strlen(className));
   }
   if(isInArray(msgType,jsonContainTitle,sizeof(jsonContainTitle)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_CLASS_TITLE);
     bzero(title,SMALL_TEXT_BUFFER_SIZE);             //clear title
     snprintf(title,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     int length  = strlen(title);
     int lenDec = -1;
     char * convert = base64_decode(title,length,&lenDec);
     int lenBase64 = strlen(convert);
     printf(">>testJson() 33>>base64 decode title is:%s >>title is:%s \n",convert,title); 
     int i;
     printf(">>testJson() 33>>base64 decode title length is:%d >>origin title length is:%d \n",lenBase64,length);
     for(i = 0;i<lenBase64;i++){
       printf(">>testJson() 33>titile convert[%d]:%d \n",i,convert[i]);
     }
   }
   
   if(isInArray(msgType,jsonContainBytemap,sizeof(jsonContainBytemap)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_BYTEMAP);
     bzero(byteMap,BYTEMAP_BUFFER_SIZE);               //clear byteMap
     snprintf(byteMap,BYTEMAP_BUFFER_SIZE,"%s",fmt->valuestring);
     //printf(">>testJson() 33>byteMap is:%s \n",byteMap);
     printf(">>testJson() 33>byteMap length is:%ld \n",strlen(byteMap));
     writePngFileBase64(byteMap,strlen(byteMap),className,strlen(className));//save image
     printf(">>testJson() 33>byteMap of %s save end>>time is:%ld \n",className,getNowMills());
   }
   if(isInArray(msgType,jsonContainAllAppInfo,sizeof(jsonContainAllAppInfo)/sizeof(short))){
     fmt = cJSON_GetObjectItem(JSONroot,KEY_ALL_APPS); //this fmt is array [...]
     //char allAppInfo[LONG_TEXT_BUFFER_SIZE];
     int arraySize = cJSON_GetArraySize(fmt);
     //snprintf(allAppInfo,LONG_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
     printf(">>testJson() 33>all app size is:%d \n",arraySize);
     cJSON * jsonApp = fmt->child;
     int appNum = 0;
     while(jsonApp != NULL){
       int count = cJSON_GetArraySize(jsonApp);

       fmt = cJSON_GetObjectItem(jsonApp,KEY_PACKAGE_NAME); //this fmt is object
       bzero(packageName,SMALL_TEXT_BUFFER_SIZE);           //clear packageName
       snprintf(packageName,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
       
       fmt = cJSON_GetObjectItem(jsonApp,KEY_CLASS_NAME);       
       bzero(className,SMALL_TEXT_BUFFER_SIZE);             //clear className
       snprintf(className,SMALL_TEXT_BUFFER_SIZE,"%s",fmt->valuestring);
       jsonApp = jsonApp->next;
       //printf(">>testJson() 33>>packageName:%s >>className:%s \n",packageName,className);
       //get one app
       appNum++;
       if(appNum >= 0){
         printf(">>testJson() 33>>packageName:%s >>className:%s \n",packageName,className);
         mJSONroot = cJSON_CreateObject();  //for send to android
         cJSON_AddItemToObject(mJSONroot,KEY_MESSAGE_TYPE,cJSON_CreateNumber(MESSAGE_LINUX_GETONEAPP));
         cJSON_AddItemToObject(mJSONroot,KEY_PACKAGE_NAME,cJSON_CreateString(packageName));
         cJSON_AddItemToObject(mJSONroot,KEY_CLASS_NAME,cJSON_CreateString(className)); 
         jsonStr = cJSON_Print(mJSONroot);
         cJSON_Delete(mJSONroot);
         printf(">>testJson() 33>>appNum == %d~~~~~~~~~~~~~~should send\n",appNum);
         sendMsgToAndroid(jsonStr); //if get all app should not do below
       }
     }
    // cJSON_Delete(JSONroot);
    // return;   //if get all app should not do below
   }
   //perse action
   mJSONroot = cJSON_CreateObject();  //for send to android
   switch(msgType){
     case MESSAGE_ANDROID_READY:
        cJSON_AddItemToObject(mJSONroot,KEY_MESSAGE_TYPE,cJSON_CreateNumber(MESSAGE_LINUX_GETALL));
        jsonStr = cJSON_Print(mJSONroot);  
        //printf(">>testJson() 444>>should send message is:%s >>length is:%ld \n",jsonStr,strlen(jsonStr));      
        sendMsgToAndroid(jsonStr);    
	break;
     
     default:
     ;   
   }
   //cJSON_Delete(fmt);
   cJSON_Delete(JSONroot);
   cJSON_Delete(mJSONroot);
}
Example #21
0
BOARD conectar(char *name,BOARD *Board)
{

    BITBOARD BitBoard;
    int tamanho;
    char cor;
    char retorno[10000];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        Board=NULL;
        return *Board;
    }

    printf("Initialised.");

    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d" , WSAGetLastError());
    }

    printf("Socket created.\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    while(cor!= 'b' && cor!='p')
    {
        printf("\nEscolha a cor para jogar( b- brancas 50100 , p- pretas 50200 )\n");
        cor=getchar();
        cor=tolower(cor);
        if(cor=='b')
            server.sin_port = htons( 50100 );
        if(cor=='p')
            server.sin_port = htons( 50200 );
    }


    //Connect to remote server
    if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("connect error");
        Board=NULL;
        return *Board;
    }
    puts("Connected");
    cJSON *entrada,*saida;
    entrada=cJSON_CreateObject();
    cJSON_AddItemToObject(entrada, "name", cJSON_CreateString("Bobot"));
    name=cJSON_PrintUnformatted(entrada);
    puts(name);

    if( send(s , name , strlen(name) , 0) < 0)
    {
        puts("Send failed");
        Board=NULL;
        return *Board;
    }
    puts("Data Send\n");
    if((tamanho = recv(s , retorno , 10000 , 0)) == SOCKET_ERROR)
    {
        puts("recv failed");
        Board=NULL;
        return *Board;
    }
    int i;
    retorno[tamanho]='\0';
    puts("Reply received\n");
    saida=cJSON_Parse(retorno);
    name=cJSON_Print(saida);
    puts(name);
    Board->whiteInfractions=cJSON_GetObjectItem(saida,"white_infractions")->valueint;
    Board->blackInfractions=cJSON_GetObjectItem(saida,"black_infractions")->valueint;
    Board->fiftymoves=cJSON_GetObjectItem(saida,"50moves")->valueint;
    Board->enpassant[0]=cJSON_GetObjectItem(saida,"enpassant")->valueint;
    Board->enpassant[1]=cJSON_GetObjectItem(saida,"enpassant")->next->valueint;
    Board->draw=cJSON_GetObjectItem(saida,"draw")->valueint;
    Board->badmove=cJSON_GetObjectItem(saida,"bad_move")->valueint;
    Board->winner= cJSON_GetObjectItem(saida,"winner")->valueint;
    for(i=0;i<BOARD_SIZE;i++)
        Board->board[i]=cJSON_GetObjectItem(saida,"board")->valuestring[i];
    Board->whoMoves=cJSON_GetObjectItem(saida,"who_moves")->valueint;
    int whoMoves=Board->whoMoves;
    printf("%d\n",whoMoves);
    BitBoard=BoardParser(whoMoves,Board->board);
    return *Board;
}
Example #22
0
static void connection_cb(struct ev_loop *loop, ev_io *w, int revents) {
	struct jrpc_connection *conn;
	struct jrpc_server *server = (struct jrpc_server *) w->data;
	size_t bytes_read = 0;
	//get our 'subclassed' event watcher
	conn = (struct jrpc_connection *) w;
	int fd = conn->fd;
	if (conn->pos == (conn->buffer_size - 1)) {
		char * new_buffer = realloc(conn->buffer, conn->buffer_size *= 2);
		if (new_buffer == NULL) {
			perror("Memory error");
			return close_connection(loop, w);
		}
		conn->buffer = new_buffer;
		memset(conn->buffer + conn->pos, 0, conn->buffer_size - conn->pos);
	}
	// can not fill the entire buffer, string must be NULL terminated
	int max_read_size = conn->buffer_size - conn->pos - 1;
	if ((bytes_read = read(fd, conn->buffer + conn->pos, max_read_size))
			== -1) {
		perror("read");
		return close_connection(loop, w);
	}
	if (!bytes_read) {
		// client closed the sending half of the connection
		if (server->debug_level)
			printf("Client closed connection.\n");
		return close_connection(loop, w);
	} else {
		cJSON *root;
		char *end_ptr = NULL;
		conn->pos += bytes_read;

		if ((root = cJSON_Parse_Stream(conn->buffer, &end_ptr)) != NULL) {
			if (server->debug_level > 1) {
				char * str_result = cJSON_Print(root);
				printf("Valid JSON Received:\n%s\n", str_result);
				free(str_result);
			}

			if (root->type == cJSON_Object) {
				eval_request(server, conn, root);
			}
			//shift processed request, discarding it
			memmove(conn->buffer, end_ptr, strlen(end_ptr) + 2);

			conn->pos = strlen(end_ptr);
			memset(conn->buffer + conn->pos, 0,
					conn->buffer_size - conn->pos - 1);

			cJSON_Delete(root);
		} else {
			// did we parse the all buffer? If so, just wait for more.
			// else there was an error before the buffer's end
			if (end_ptr != (conn->buffer + conn->pos)) {
				if (server->debug_level) {
					printf("INVALID JSON Received:\n---\n%s\n---\n",
							conn->buffer);
				}
				send_error(conn, JRPC_PARSE_ERROR,
						strdup(
								"Parse error. Invalid JSON was received by the server."),
						NULL);
				return close_connection(loop, w);
			}
		}
	}

}
Example #23
0
void StatQuery_Prepare( stat_query_t *query )
{
	if( !query->req && query->url )
	{
		// GET request, finish the url and create the object
		query->req = wswcurl_create( query->url );
	}
	// only allow json for POST requests
	else if( query->has_json )
	{
		const char *json_text;
		size_t jsonSize, b64Size;
		unsigned long compSize;
		void *compData, *b64Data;
		int z_result;

		if( query->url )
		{
			Com_Printf( "StatQuery: Tried to add JSON field to GET request\n" );
			return;
		}

		json_text = cJSON_Print( query->json_out );
		jsonSize = strlen( json_text );

		// compress
		compSize = (jsonSize * 1.1) + 12;
		compData = SQALLOC( compSize );
		if( compData == NULL )
		{
			Com_Printf("StatQuery: Failed to allocate space for compressed JSON\n");
			return;
		}
		z_result = compress( compData, &compSize, (unsigned char*)json_text, jsonSize );
		if( z_result != Z_OK )
		{
			Com_Printf("StatQuery: Failed to compress JSON\n");
			SQFREE( compData );
			return;
		}

		// base64
		b64Data = base64_encode( compData, compSize, &b64Size );
		if( b64Data == NULL )
		{
			Com_Printf("StatQuery: Failed to base64_encode JSON\n");
			SQFREE( compData );
			return;
		}

		// Com_Printf("Match report size: %u, compressed: %u, base64'd: %u\n", reportSize, compSize, b64Size );

		// we dont need this anymore
		SQFREE( compData );
		compData = NULL;

		// set the json field to POST request
		wswcurl_formadd_raw( query->req, "data", b64Data, b64Size );

		SQFREE( b64Data );
	}
}
Example #24
0
/* Create a bunch of objects as demonstration. */
static int print_preallocated(cJSON *root)
{
    /* declarations */
    char *out = NULL;
    char *buf = NULL;
    char *buf_fail = NULL;
    int len = 0;
    int len_fail = 0;

    /* formatted print */
    out = cJSON_Print(root);

    /* create buffer to succeed */
    /* the extra 64 bytes are in case a floating point value is printed */
    len = strlen(out) + 64;
    buf = (char*)malloc(len);
    if (buf == NULL)
    {
        printf("Failed to allocate memory.\n");
        exit(1);
    }

    /* create buffer to fail */
    len_fail = strlen(out);
    buf_fail = (char*)malloc(len_fail);
    if (buf_fail == NULL)
    {
        printf("Failed to allocate memory.\n");
        exit(1);
    }

    /* Print to buffer */
    if (!cJSON_PrintPreallocated(root, buf, len, 1)) {
        printf("cJSON_PrintPreallocated failed!\n");
        if (strcmp(out, buf) != 0) {
            printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n");
            printf("cJSON_Print result:\n%s\n", out);
            printf("cJSON_PrintPreallocated result:\n%s\n", buf);
        }
        free(out);
        free(buf_fail);
        free(buf);
        return -1;
    }

    /* success */
    printf("%s\n", buf);

    /* force it to fail */
    if (cJSON_PrintPreallocated(root, buf_fail, len_fail, 1)) {
        printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n");
        printf("cJSON_Print result:\n%s\n", out);
        printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail);
        free(out);
        free(buf_fail);
        free(buf);
        return -1;
    }

    free(out);
    free(buf_fail);
    free(buf);
    return 0;
}
Example #25
0
/* Create a bunch of objects as demonstration. */
void create_objects()
{
    cJSON *root, *fmt, *img, *thm, *fld; char *out; int i;	/* declare a few. */
                                                            /* Our "days of the week" array: */
    const char *strings[7] = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
    /* Our matrix: */
    int numbers[3][3] = { { 0,-1,0 },{ 1,0,0 },{ 0,0,1 } };
    /* Our "gallery" item: */
    int ids[4] = { 116,943,234,38793 };
    /* Our array of "records": */
    struct record fields[2] = {
        { "zip",37.7668,-1.223959e+2,"","SAN FRANCISCO","CA","94107","US" },
        { "zip",37.371991,-1.22026e+2,"","SUNNYVALE","CA","94085","US" } };

    /* Here we construct some JSON standards, from the JSON site. */

    /* Our "Video" datatype: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
    cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
    cJSON_AddStringToObject(fmt, "type", "rect");
    cJSON_AddNumberToObject(fmt, "width", 1920);
    cJSON_AddNumberToObject(fmt, "height", 1080);
    cJSON_AddFalseToObject(fmt, "interlace");
    cJSON_AddNumberToObject(fmt, "frame rate", 24);

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);	/* Print to text, Delete the cJSON, print it, release the string. */

                                                                                        /* Our "days of the week" array: */
    root = cJSON_CreateStringArray(strings, 7);

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

    /* Our matrix: */
    root = cJSON_CreateArray();
    for (i = 0; i<3; i++) cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));

    /*	cJSON_ReplaceItemInArray(root,1,cJSON_CreateString("Replacement")); */

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);


    /* Our "gallery" item: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());
    cJSON_AddNumberToObject(img, "Width", 800);
    cJSON_AddNumberToObject(img, "Height", 600);
    cJSON_AddStringToObject(img, "Title", "View from 15th Floor");
    cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());
    cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
    cJSON_AddNumberToObject(thm, "Height", 125);
    cJSON_AddStringToObject(thm, "Width", "100");
    cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

    /* Our array of "records": */

    root = cJSON_CreateArray();
    for (i = 0; i<2; i++)
    {
        cJSON_AddItemToArray(root, fld = cJSON_CreateObject());
        cJSON_AddStringToObject(fld, "precision", fields[i].precision);
        cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);
        cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);
        cJSON_AddStringToObject(fld, "Address", fields[i].address);
        cJSON_AddStringToObject(fld, "City", fields[i].city);
        cJSON_AddStringToObject(fld, "State", fields[i].state);
        cJSON_AddStringToObject(fld, "Zip", fields[i].zip);
        cJSON_AddStringToObject(fld, "Country", fields[i].country);
    }

    /*	cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root,1),"City",cJSON_CreateIntArray(ids,4)); */

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

}
Example #26
0
int main()
{
	char AccessKey[256]={0};
	char ScreteKey[256]={0};
	char Space[64]={0};
	char Path[256]={0};

	time_t deadline;

	ReadUploadInfo("./Information.ini", AccessKey, ScreteKey, Space, Path);
	std::vector<FileInfo> fi;
	ScanAllFile(Path,fi);

	Qiniu_Client client;
	QINIU_ACCESS_KEY=(const char *)AccessKey;
	QINIU_SECRET_KEY=(const char *)ScreteKey;

	Qiniu_Servend_Init(-1);
	Qiniu_Client_InitMacAuth(&client, 1024, NULL);

	printf("\n\nStart Uploading...\n");
	for(std::vector<FileInfo>::const_iterator it = fi.begin(); it < fi.end(); ++it)
	{

		char hash[29]="";
		memcpy(hash,it->Hash,28);
		bool ft=repeatcheck(&client, Space, it->FileLocalInfo,hash);
		if (ft) continue;

		char *output;
		char encodedPutPolicy[256]={0};
		time_t deadline;
		time(&deadline);
		deadline=deadline+7200;

		unsigned char hmac_sha1code[256]={0};
		unsigned int hmac_sha1code_length;
		char encodesign[512]={0};

		char scope[256]="";

		cJSON *fmt;
		fmt=cJSON_CreateObject();
		sprintf_s(scope,256,"%s:%s",Space,it->FileLocalInfo);
		cJSON_AddStringToObject(fmt,"scope",scope);
		cJSON_AddNumberToObject(fmt,"deadline",deadline);

		output=cJSON_Print(fmt);
		printf("%s\n",output);

		//Get Code 3£ºencodedPutPolicy
		size_t destlength=urlsafe_b64_encode(output,strlen(output),encodedPutPolicy,256);

		printf("encodedPutPolicy=%s\n",encodedPutPolicy);
		//Get Code 2£ºencodesign
		unsigned char *sign = HMAC(EVP_sha1(),ScreteKey,strlen(ScreteKey), 
									(const unsigned char *)encodedPutPolicy,destlength,
									(unsigned char *) hmac_sha1code,
									&hmac_sha1code_length);

		destlength=urlsafe_b64_encode(hmac_sha1code,strlen((const char *)hmac_sha1code),encodesign,256);

		char UpLoadToken[1024];
		sprintf_s(UpLoadToken,"%s:%s:%s",AccessKey,encodesign,encodedPutPolicy);
		
		char *LocalHashCode=upload(&client, UpLoadToken, it->FileLocalInfo, it->FileGlobalInfo);
		//if (LocalHashCode == NULL)
		//{
		//	int uploadflag=resumable_upload(&client, UpLoadToken, 
		//					it->FileLocalInfo, it->FileGlobalInfo,Space);
		//}
		free(output);

	}
	printf("\n\nStop Uploading...\n");
	Qiniu_Client_Cleanup(&client);
	Qiniu_Servend_Cleanup();
}
Example #27
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));
}
Example #28
0
/** Parses iotkit-comm configuration file
 * @param[in] config_file path to the configuration file
 */
bool parseConfigFile(char *config_file) {
    char *out;
    cJSON *json = NULL, *jitem, *child, *subjson;
    bool status = true;
    FILE *fp = fopen(config_file, "rb");

    if (fp == NULL) {
        fprintf(stderr,"Error can't open file %s\n", config_file);
        status = false;
    } else {
        fseek(fp, 0, SEEK_END);
        long size = ftell(fp);
        rewind(fp);

        // read the file
        char *buffer = (char *)malloc(size+1);
        if (buffer != NULL) {
            fread(buffer, 1, size, fp);
            // parse the file
            json = cJSON_Parse(buffer);
        }
        if (json == NULL || !json) {
            fprintf(stderr,"Error before: [%s]\n",cJSON_GetErrorPtr());
            status = false;
        } else {
            #if DEBUG
                out = cJSON_Print(json, 2);
                fprintf(stderr,"%s\n", out);
                free(out);
            #endif

            if (!isJsonObject(json)) {
                handleParseConfigError();
            }

            jitem = cJSON_GetObjectItem(json, "pluginInterfaceDir");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            g_configData.pluginInterfaceDir = strdup(jitem->valuestring);
            #if DEBUG
                printf("pluginInterfaceDir = %s\n", g_configData.pluginInterfaceDir);
            #endif

            jitem = cJSON_GetObjectItem(json, "pluginDir");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            g_configData.pluginDir = strdup(jitem->valuestring);
            #if DEBUG
                printf("pluginDir = %s\n", g_configData.pluginDir);
            #endif


            jitem = cJSON_GetObjectItem(json, "communication");
            if (!isJsonObject(json)) {
                handleParseConfigError();
            }

            subjson = cJSON_GetObjectItem(jitem, "pluginFileSuffixes");
            if (!isJsonObject(json)) {
                handleParseConfigError();
            }

            jitem = cJSON_GetObjectItem(subjson, "clientFileSuffix");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            g_configData.clientFileSuffix = strdup(jitem->valuestring);
            #if DEBUG
                printf("clientFileSuffix = %s\n", g_configData.clientFileSuffix);
            #endif


            jitem = cJSON_GetObjectItem(subjson, "serverFileSuffix");
            if (!isJsonString(jitem)) {
                handleParseConfigError();
            }

            g_configData.serverFileSuffix = strdup(jitem->valuestring);
            #if DEBUG
                printf("serverFileSuffix = %s\n", g_configData.serverFileSuffix);
            #endif

endParseConfig:
            cJSON_Delete(json);
        }

        free(buffer);
        fclose(fp); // close the file pointer
    }

    concatUserDefinedConfigurations();

    return status;
}
Example #29
0
char *status_json_string(int no_cache, int periodical)
{
	char *out = NULL;
	int pe;
	
	/* if we have a very recent status JSON available, return it instead. */
	if (!no_cache) {
		if ((pe = pthread_mutex_lock(&status_json_mt))) {
			hlog(LOG_ERR, "status_json_string(): could not lock status_json_mt: %s", strerror(pe));
			return NULL;
		}
		if (status_json_cached && (status_json_cache_t == tick || status_json_cache_t == tick - 1)) {
			out = hstrdup(status_json_cached);
			if ((pe = pthread_mutex_unlock(&status_json_mt))) {
				hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
				hfree(out);
				return NULL;
			}
			return out;
		}
		if ((pe = pthread_mutex_unlock(&status_json_mt))) {
			hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
			return NULL;
		}
	}
	
	/* Ok, go and build the JSON tree */
	cJSON *root = cJSON_CreateObject();
	if (http_status_options)
		cJSON_AddStringToObject(root, "status_options", http_status_options);
	status_check_motd(root);
	
	cJSON *server = cJSON_CreateObject();
	cJSON_AddStringToObject(server, "server_id", serverid);
	cJSON_AddStringToObject(server, "admin", myadmin);
	cJSON_AddStringToObject(server, "email", myemail);
	cJSON_AddStringToObject(server, "software", PROGNAME);
	cJSON_AddStringToObject(server, "software_version", version_build);
	cJSON_AddStringToObject(server, "software_build_time", verstr_build_time);
	cJSON_AddStringToObject(server, "software_build_user", verstr_build_user);
	cJSON_AddStringToObject(server, "software_build_features", verstr_features);
	cJSON_AddNumberToObject(server, "uptime", tick - startup_tick);
	cJSON_AddNumberToObject(server, "tick_now", tick);
	cJSON_AddNumberToObject(server, "time_now", now);
	cJSON_AddNumberToObject(server, "time_started", startup_time);
	status_uname(server);
	cJSON_AddItemToObject(root, "server", server);
	
	cJSON *memory = cJSON_CreateObject();
#ifndef _FOR_VALGRIND_
	struct cellstatus_t cellst;
	historydb_cell_stats(&cellst), 
	cJSON_AddNumberToObject(memory, "historydb_cells_used", historydb_cellgauge);
	cJSON_AddNumberToObject(memory, "historydb_cells_free", cellst.freecount);
	cJSON_AddNumberToObject(memory, "historydb_used_bytes", historydb_cellgauge*cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "historydb_allocated_bytes", (long)cellst.blocks * (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "historydb_block_size", (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "historydb_blocks", (long)cellst.blocks);
	cJSON_AddNumberToObject(memory, "historydb_blocks_max", (long)cellst.blocks_max);
	cJSON_AddNumberToObject(memory, "historydb_cell_size", cellst.cellsize);
	cJSON_AddNumberToObject(memory, "historydb_cell_size_aligned", cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "historydb_cell_align", cellst.alignment);
	
	dupecheck_cell_stats(&cellst), 
	cJSON_AddNumberToObject(memory, "dupecheck_cells_used", dupecheck_cellgauge);
	cJSON_AddNumberToObject(memory, "dupecheck_cells_free", cellst.freecount);
	cJSON_AddNumberToObject(memory, "dupecheck_used_bytes", dupecheck_cellgauge*cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "dupecheck_allocated_bytes", (long)cellst.blocks * (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "dupecheck_block_size", (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "dupecheck_blocks", (long)cellst.blocks);
	cJSON_AddNumberToObject(memory, "dupecheck_blocks_max", (long)cellst.blocks_max);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_size", cellst.cellsize);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_size_aligned", cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_align", cellst.alignment);
	
	struct cellstatus_t cellst_filter, cellst_filter_wx, cellst_filter_entrycall;
	filter_cell_stats(&cellst_filter, &cellst_filter_entrycall, &cellst_filter_wx),
	cJSON_AddNumberToObject(memory, "filter_cells_used", filter_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_cells_free", cellst_filter.freecount);
	cJSON_AddNumberToObject(memory, "filter_used_bytes", filter_cellgauge*cellst_filter.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_allocated_bytes", (long)cellst_filter.blocks * (long)cellst_filter.block_size);
	cJSON_AddNumberToObject(memory, "filter_block_size", (long)cellst_filter.block_size);
	cJSON_AddNumberToObject(memory, "filter_blocks", (long)cellst_filter.blocks);
	cJSON_AddNumberToObject(memory, "filter_blocks_max", (long)cellst_filter.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_cell_size", cellst_filter.cellsize);
	cJSON_AddNumberToObject(memory, "filter_cell_size_aligned", cellst_filter.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_cell_align", cellst_filter.alignment);
	
	cJSON_AddNumberToObject(memory, "filter_wx_cells_used", filter_wx_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_wx_cells_free", cellst_filter_wx.freecount);
	cJSON_AddNumberToObject(memory, "filter_wx_used_bytes", filter_wx_cellgauge*cellst_filter_wx.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_wx_allocated_bytes", (long)cellst_filter_wx.blocks * (long)cellst_filter_wx.block_size);
	cJSON_AddNumberToObject(memory, "filter_wx_block_size", (long)cellst_filter_wx.block_size);
	cJSON_AddNumberToObject(memory, "filter_wx_blocks", (long)cellst_filter_wx.blocks);
	cJSON_AddNumberToObject(memory, "filter_wx_blocks_max", (long)cellst_filter_wx.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_size", cellst_filter_wx.cellsize);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_size_aligned", cellst_filter_wx.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_align", cellst_filter_wx.alignment);
	
	cJSON_AddNumberToObject(memory, "filter_entrycall_cells_used", filter_entrycall_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cells_free", cellst_filter_entrycall.freecount);
	cJSON_AddNumberToObject(memory, "filter_entrycall_used_bytes", filter_entrycall_cellgauge*cellst_filter_entrycall.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_entrycall_allocated_bytes", (long)cellst_filter_entrycall.blocks * (long)cellst_filter_entrycall.block_size);
	cJSON_AddNumberToObject(memory, "filter_entrycall_block_size", (long)cellst_filter_entrycall.block_size);
	cJSON_AddNumberToObject(memory, "filter_entrycall_blocks", (long)cellst_filter_entrycall.blocks);
	cJSON_AddNumberToObject(memory, "filter_entrycall_blocks_max", (long)cellst_filter_entrycall.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_size", cellst_filter_entrycall.cellsize);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_size_aligned", cellst_filter_entrycall.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_align", cellst_filter_entrycall.alignment);
	
	struct cellstatus_t cellst_pbuf_small, cellst_pbuf_medium, cellst_pbuf_large;
	incoming_cell_stats(&cellst_pbuf_small, &cellst_pbuf_medium, &cellst_pbuf_large);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_used", cellst_pbuf_small.cellcount - cellst_pbuf_small.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_free", cellst_pbuf_small.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_alloc", cellst_pbuf_small.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_small_used_bytes", (cellst_pbuf_small.cellcount - cellst_pbuf_small.freecount)*cellst_pbuf_small.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_small_allocated_bytes", (long)cellst_pbuf_small.blocks * (long)cellst_pbuf_small.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_small_block_size", (long)cellst_pbuf_small.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_small_blocks", (long)cellst_pbuf_small.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_small_blocks_max", (long)cellst_pbuf_small.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_size", cellst_pbuf_small.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_size_aligned", cellst_pbuf_small.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_align", cellst_pbuf_small.alignment);
	
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_used", cellst_pbuf_medium.cellcount - cellst_pbuf_medium.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_free", cellst_pbuf_medium.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_alloc", cellst_pbuf_medium.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_used_bytes", (cellst_pbuf_medium.cellcount - cellst_pbuf_medium.freecount)*cellst_pbuf_medium.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_medium_allocated_bytes", (long)cellst_pbuf_medium.blocks * (long)cellst_pbuf_medium.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_medium_block_size", (long)cellst_pbuf_medium.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_medium_blocks", (long)cellst_pbuf_medium.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_medium_blocks_max", (long)cellst_pbuf_medium.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_size", cellst_pbuf_medium.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_size_aligned", cellst_pbuf_medium.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_align", cellst_pbuf_medium.alignment);
	
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_used", cellst_pbuf_large.cellcount - cellst_pbuf_large.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_free", cellst_pbuf_large.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_alloc", cellst_pbuf_large.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_large_used_bytes", (cellst_pbuf_large.cellcount - cellst_pbuf_large.freecount)*cellst_pbuf_large.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_large_allocated_bytes", (long)cellst_pbuf_large.blocks * (long)cellst_pbuf_large.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_large_block_size", (long)cellst_pbuf_large.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_large_blocks", (long)cellst_pbuf_large.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_large_blocks_max", (long)cellst_pbuf_large.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_size", cellst_pbuf_large.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_size_aligned", cellst_pbuf_large.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_align", cellst_pbuf_large.alignment);
	
	struct cellstatus_t cellst_client_heard;
	client_heard_cell_stats(&cellst_client_heard);
	cJSON_AddNumberToObject(memory, "client_heard_cells_used", cellst_client_heard.cellcount - cellst_client_heard.freecount);
	cJSON_AddNumberToObject(memory, "client_heard_cells_free", cellst_client_heard.freecount);
	cJSON_AddNumberToObject(memory, "client_heard_cells_alloc", cellst_client_heard.cellcount);
	cJSON_AddNumberToObject(memory, "client_heard_used_bytes", (cellst_client_heard.cellcount - cellst_client_heard.freecount)*cellst_client_heard.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "client_heard_allocated_bytes", (long)cellst_client_heard.blocks * (long)cellst_client_heard.block_size);
	cJSON_AddNumberToObject(memory, "client_heard_block_size", (long)cellst_client_heard.block_size);
	cJSON_AddNumberToObject(memory, "client_heard_blocks", (long)cellst_client_heard.blocks);
	cJSON_AddNumberToObject(memory, "client_heard_blocks_max", (long)cellst_client_heard.blocks_max);
	cJSON_AddNumberToObject(memory, "client_heard_cell_size", cellst_client_heard.cellsize);
	cJSON_AddNumberToObject(memory, "client_heard_cell_size_aligned", cellst_client_heard.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "client_heard_cell_align", cellst_client_heard.alignment);
#endif
	
	cJSON_AddItemToObject(root, "memory", memory);
	
	cJSON *historydb = cJSON_CreateObject();
	cJSON_AddNumberToObject(historydb, "inserts", historydb_inserts);
	cJSON_AddNumberToObject(historydb, "lookups", historydb_lookups);
	cJSON_AddNumberToObject(historydb, "hashmatches", historydb_hashmatches);
	cJSON_AddNumberToObject(historydb, "keymatches", historydb_keymatches);
	cJSON_AddNumberToObject(historydb, "noposcount", historydb_noposcount);
	cJSON_AddNumberToObject(historydb, "cleaned", historydb_cleanup_cleaned);
	cJSON_AddItemToObject(root, "historydb", historydb);
	
	cJSON *dupecheck = cJSON_CreateObject();
	cJSON_AddNumberToObject(dupecheck, "dupes_dropped", dupecheck_dupecount);
	cJSON_AddNumberToObject(dupecheck, "uniques_out", dupecheck_outcount);
	cJSON_AddItemToObject(root, "dupecheck", dupecheck);
	
	cJSON *dupe_vars = cJSON_CreateObject();
	cJSON_AddNumberToObject(dupe_vars, "exact", dupecheck_dupetypes[0]);
	cJSON_AddNumberToObject(dupe_vars, "space_trim", dupecheck_dupetypes[DTYPE_SPACE_TRIM]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_strip", dupecheck_dupetypes[DTYPE_STRIP_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_clear", dupecheck_dupetypes[DTYPE_CLEAR_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_spaced", dupecheck_dupetypes[DTYPE_SPACED_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "low_strip", dupecheck_dupetypes[DTYPE_LOWDATA_STRIP]);
	cJSON_AddNumberToObject(dupe_vars, "low_spaced", dupecheck_dupetypes[DTYPE_LOWDATA_SPACED]);
	cJSON_AddNumberToObject(dupe_vars, "del_strip", dupecheck_dupetypes[DTYPE_DEL_STRIP]);
	cJSON_AddNumberToObject(dupe_vars, "del_spaced", dupecheck_dupetypes[DTYPE_DEL_SPACED]);
	cJSON_AddItemToObject(dupecheck, "variations", dupe_vars);
	
	cJSON *json_totals = cJSON_CreateObject();
	cJSON *json_listeners = cJSON_CreateArray();
	accept_listener_status(json_listeners, json_totals);
	cJSON_AddItemToObject(root, "totals", json_totals);
	cJSON_AddItemToObject(root, "listeners", json_listeners);
	
	cJSON *json_clients = cJSON_CreateArray();
	cJSON *json_uplinks = cJSON_CreateArray();
	cJSON *json_peers = cJSON_CreateArray();
	cJSON *json_workers = cJSON_CreateArray();
	worker_client_list(json_workers, json_clients, json_uplinks, json_peers, json_totals, memory);
	cJSON_AddItemToObject(root, "workers", json_workers);
	cJSON_AddItemToObject(root, "uplinks", json_uplinks);
	cJSON_AddItemToObject(root, "peers", json_peers);
	cJSON_AddItemToObject(root, "clients", json_clients);
	
	/* if this is a periodical per-minute dump, collect historical data */
	if (periodical) {
		cJSON *ct, *cv;
		struct cdata_list_t *cl;
		for (cl = cdata_list; (cl); cl = cl->next) {
			ct = cJSON_GetObjectItem(root, cl->tree);
			if (!ct)
				continue;
				
			cv = cJSON_GetObjectItem(ct, cl->name);
			
			/* cJSON's cv->valueint is just an integer, which will overflow
			 * too quickly. So, let's take the more expensive valuedouble.
			 */
			if (cl->gauge)
				cdata_gauge_sample(cl->cd, (cv) ? cv->valuedouble : -1);
			else
				cdata_counter_sample(cl->cd, (cv) ? cv->valuedouble : -1);
		}
	}
	
	cJSON_AddNumberToObject(json_totals, "tcp_bytes_rx_rate", cdata_get_last_value("totals.tcp_bytes_rx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "tcp_bytes_tx_rate", cdata_get_last_value("totals.tcp_bytes_tx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "udp_bytes_rx_rate", cdata_get_last_value("totals.udp_bytes_rx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "udp_bytes_tx_rate", cdata_get_last_value("totals.udp_bytes_tx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "bytes_rx_rate", (cdata_get_last_value("totals.tcp_bytes_rx") + cdata_get_last_value("totals.udp_bytes_rx")) / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "bytes_tx_rate", (cdata_get_last_value("totals.tcp_bytes_tx") + cdata_get_last_value("totals.udp_bytes_tx")) / CDATA_INTERVAL);
	
	cJSON *json_rx_errs = cJSON_CreateStringArray(inerr_labels, INERR_BUCKETS);
	cJSON_AddItemToObject(root, "rx_errs", json_rx_errs);
	
	cJSON_AddItemToObject(root, "alarms", status_error_json());
	
	/* the tree is built, print it out to a malloc'ed string */
	out = cJSON_Print(root);
	cJSON_Delete(root);
	
	/* cache it */
	if ((pe = pthread_mutex_lock(&status_json_mt))) {
		hlog(LOG_ERR, "status_json_string(): could not lock status_json_mt: %s", strerror(pe));
                                return NULL;
	}
	if (status_json_cached)
		hfree(status_json_cached);
		
	status_json_cached = hstrdup(out);
	status_json_cache_t = tick;
	
	if ((pe = pthread_mutex_unlock(&status_json_mt))) {
		hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
		return NULL;
	}
	
	return out;
}
Example #30
0
/** Parses plugin interfaces. Loads the function names present in the corresponding plugin defined in the service specification JSON
* @param[in] inf_file file path for the plugin interface
* @return returns true upon successful parsing and false otherwise
*/
bool parsePluginInterfaces(char *inf_file) {
    char *out;
    int numentries = 0, i = 0;
    cJSON *json = NULL, *jitem, *child;
    bool status = true;
    FILE *fp = fopen(inf_file, "rb");

    if (fp == NULL) {
        fprintf(stderr,"Error can't open file %s\n", inf_file);
        status = false;
    } else {
        fseek(fp, 0, SEEK_END);
        long size = ftell(fp);
        rewind(fp);

        // read the file
        char *buffer = (char *)malloc(size+1);
        if (buffer != NULL) {
            fread(buffer, 1, size, fp);
            // parse the file
            json = cJSON_Parse(buffer);
        }
        if (json == NULL || !json) {
            fprintf(stderr,"Error before: [%s]\n",cJSON_GetErrorPtr());
            status = false;
        } else {
            #if DEBUG
                out = cJSON_Print(json, 2);
                printf("%s\n", out);
                free(out);
            #endif

            if (!isJsonObject(json)) {
                handleParseInterfacesError();
            }

            jitem = cJSON_GetObjectItem(json, "functions");
            if (!isJsonArray(jitem)) {
                handleParseInterfacesError();
            }

            child = jitem->child;
            /* How many entries in the array? */
            while (child && numentries++ < MAX_PROPERTIES) {
                child = child->next;
            }
            if (!numentries) {
                handleParseInterfacesError();
            }

            g_funcEntries = numentries;
            g_funcSignatures = (char **)malloc(numentries*sizeof(char*));
            if (!g_funcSignatures) {
                handleParseInterfacesError();
            }

            memset(g_funcSignatures,0,numentries*sizeof(char*));
            child = jitem->child;
            while (child) {
                if (!isJsonString(child)) {
                    handleParseInterfacesError();
                }

                g_funcSignatures[i] = strdup(child->valuestring);
                child = child->next;
                #if DEBUG
                    printf("g_funcSignature = %s\n", g_funcSignatures[i]);
                #endif
                i++;
            }

endParseInterfaces:
            cJSON_Delete(json);
        }

        free(buffer);
        fclose(fp); // close the file pointer
    }

    return status;
}