Beispiel #1
0
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count)	{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Beispiel #2
0
void server_masters(socket_t * client, http_request_t * req, db_t * db)
{
    char buffer[10240] = "";

    if (strcmp(req->method, "GET") == 0)
    {
        list_t * masters = list_new();

        char * countK = (char *)http_request_getArg(req, "countK");
        char * countP = (char *)http_request_getArg(req, "countP");

        if(countK != NULL && countP != NULL)
        {
            db_filtration(db, masters, atoi(countK), atoi(countP));
        }
        else
        {
            db_parse(db, masters);
        }

        cJSON * jPageText = cJSON_CreateArray();

        for(int i = 0; i < list_size(masters); i++)
        {
            master_t * sm = list_get(masters, i);

            cJSON * jText = cJSON_CreateObject();
            cJSON_AddItemToObject(jText, "Name", cJSON_CreateString(master_getName(sm)));
            cJSON_AddItemToObject(jText, "Surname", cJSON_CreateString(master_getSurname(sm)));
            cJSON_AddItemToObject(jText, "CountK", cJSON_CreateNumber(master_getCountK(sm)));
            cJSON_AddItemToObject(jText, "CountP", cJSON_CreateNumber(master_getCountP(sm)));
            cJSON_AddItemToArray(jPageText, jText);
        }

        char * pageText = cJSON_Print(jPageText);

        list_free(masters);

        char * textJSON = textToJSON(pageText);
        strcat(buffer, textJSON);
        free(textJSON);
    }
    else if (strcmp(req->method, "POST") == 0)
    {
        char * name = (char *)http_request_getArg(req, "name");
        char * surname = (char *)http_request_getArg(req, "surname");
        char * countK = (char *)http_request_getArg(req, "countK");
        char * countP = (char *)http_request_getArg(req, "countP");

        if(verification(name, surname, countK, countP) == 1)
        {
            db_insertData(db, name, surname, atoi(countK), atoi(countP));

            cJSON * jText = cJSON_CreateObject();
            cJSON_AddItemToObject(jText, "Name", cJSON_CreateString(name));
            cJSON_AddItemToObject(jText, "Surname", cJSON_CreateString(surname));
            cJSON_AddItemToObject(jText, "CountK", cJSON_CreateNumber(atoi(countK)));
            cJSON_AddItemToObject(jText, "CountP", cJSON_CreateNumber(atoi(countP)));
            char * pageText = cJSON_Print(jText);

            char * textJSON = textToJSON(pageText);
            strcat(buffer, textJSON);
            free(textJSON);
        }
        else
        {
            cJSON * jText = cJSON_CreateObject();
            cJSON_AddItemToObject(jText, "Error", cJSON_CreateString("Wrong input"));
            char * pageText = cJSON_Print(jText);

            char * textJSON = textToJSON(pageText);
            strcat(buffer, textJSON);
            free(textJSON);
        }
    }

    socket_write_string(client, buffer);
    socket_close(client);
}
void conference_event_mod_channel_handler(const char *event_channel, cJSON *json, const char *key, switch_event_channel_id_t id)
{
	cJSON *data, *addobj = NULL;
	const char *action = NULL;
	char *value = NULL;
	cJSON *jid = 0;
	char *conference_name = strdup(event_channel + 15);
	char cid[32] = "";
	char *p;
	switch_stream_handle_t stream = { 0 };
	char *exec = NULL;
	cJSON *msg, *jdata, *jvalue;
	char *argv[10] = {0};
	int argc = 0;

	if (conference_name && (p = strchr(conference_name, '@'))) {
		*p = '\0';
	}

	if ((data = cJSON_GetObjectItem(json, "data"))) {
		action = cJSON_GetObjectCstr(data, "command");
		if ((jid = cJSON_GetObjectItem(data, "id"))) {
			if (jid->valueint) {
				switch_snprintf(cid, sizeof(cid), "%d", jid->valueint);
			} else if (!zstr(jid->valuestring)) {
				switch_snprintf(cid, sizeof(cid), "%s", jid->valuestring);
			}
		}

		if ((jvalue = cJSON_GetObjectItem(data, "value"))) {

			if (jvalue->type == cJSON_Array) {
				int i;
				argc = cJSON_GetArraySize(jvalue);
				if (argc > 10) argc = 10;

				for (i = 0; i < argc; i++) {
					cJSON *str = cJSON_GetArrayItem(jvalue, i);
					if (str->type == cJSON_String) {
						argv[i] = str->valuestring;
					}
				}
			} else if (jvalue->type == cJSON_String) {
				value = jvalue->valuestring;
				argv[argc++] = value;
			}
		}
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "conf %s CMD %s [%s] %s\n", conference_name, key, action, cid);

	if (zstr(action)) {
		goto end;
	}

	SWITCH_STANDARD_STREAM(stream);

	if (!strcasecmp(action, "kick")) {
		exec = switch_mprintf("%s %s %s", conference_name, action, cid);
	} else if (!strcasecmp(action, "mute") ||
		!strcasecmp(action, "unmute") ||
		!strcasecmp(action, "tmute") ||
		!strcasecmp(action, "vmute") ||
		!strcasecmp(action, "unvmute") ||
		!strcasecmp(action, "tvmute")) {
		if (argv[0]) {
		  exec = switch_mprintf("%s %s %s %s", conference_name, action, cid, argv[0]);
		} else {
		  exec = switch_mprintf("%s %s %s", conference_name, action, cid);
		}
	} else if (!strcasecmp(action, "volume_in") ||
			   !strcasecmp(action, "volume_out") ||
			   !strcasecmp(action, "vid-res-id") ||
			   !strcasecmp(action, "vid-floor") ||
			   !strcasecmp(action, "vid-layer") ||
			   !strcasecmp(action, "vid-canvas") ||
			   !strcasecmp(action, "vid-watching-canvas") ||
			   !strcasecmp(action, "vid-banner")) {
		exec = switch_mprintf("%s %s %s %s", conference_name, action, cid, argv[0]);
	} else if (!strcasecmp(action, "play") || !strcasecmp(action, "stop")) {
		exec = switch_mprintf("%s %s %s", conference_name, action, argv[0]);
	} else if (!strcasecmp(action, "recording") || !strcasecmp(action, "vid-layout") || !strcasecmp(action, "vid-write-png")) {

		if (!argv[1]) {
			argv[1] = "all";
		}

		exec = switch_mprintf("%s %s %s %s", conference_name, action, argv[0], argv[1]);

	} else if (!strcasecmp(action, "transfer")) {
		conference_member_t *member;
		conference_obj_t *conference;

		if (cid[0] == '\0') {
			stream.write_function(&stream, "-ERR Call transfer requires id");
			goto end;
		}

		exec = switch_mprintf("%s %s %s", argv[0], switch_str_nil(argv[1]), switch_str_nil(argv[2]));
		stream.write_function(&stream, "+OK Call transferred to %s", argv[0]);

		if ((conference = conference_find(conference_name, NULL))) {
			if ((member = conference_member_get(conference, atoi(cid)))) {
				switch_ivr_session_transfer(member->session, argv[0], argv[1], argv[2]);
				switch_thread_rwlock_unlock(member->rwlock);
			}
			switch_thread_rwlock_unlock(conference->rwlock);
		}
		goto end;
	} else if (!strcasecmp(action, "list-videoLayouts")) {
		switch_hash_index_t *hi;
		void *val;
		const void *vvar;
		cJSON *array = cJSON_CreateArray();
		conference_obj_t *conference = NULL;
		if ((conference = conference_find(conference_name, NULL))) {
			switch_mutex_lock(conference_globals.setup_mutex);
			if (conference->layout_hash) {
				for (hi = switch_core_hash_first(conference->layout_hash); hi; hi = switch_core_hash_next(&hi)) {
					switch_core_hash_this(hi, &vvar, NULL, &val);
					cJSON_AddItemToArray(array, cJSON_CreateString((char *)vvar));
				}
			}

			if (conference->layout_group_hash) {
				for (hi = switch_core_hash_first(conference->layout_group_hash); hi; hi = switch_core_hash_next(&hi)) {
					char *name;
					switch_core_hash_this(hi, &vvar, NULL, &val);
					name = switch_mprintf("group:%s", (char *)vvar);
					cJSON_AddItemToArray(array, cJSON_CreateString(name));
					free(name);
				}
			}

			switch_mutex_unlock(conference_globals.setup_mutex);
			switch_thread_rwlock_unlock(conference->rwlock);
		}
		addobj = array;
	}

	if (exec) {
		conference_api_main_real(exec, NULL, &stream);
	}

 end:

	msg = cJSON_CreateObject();
	jdata = json_add_child_obj(msg, "data", NULL);

	cJSON_AddItemToObject(msg, "eventChannel", cJSON_CreateString(event_channel));
	cJSON_AddItemToObject(jdata, "action", cJSON_CreateString("response"));

	if (addobj) {
		cJSON_AddItemToObject(jdata, "conf-command", cJSON_CreateString(action));
		cJSON_AddItemToObject(jdata, "response", cJSON_CreateString("OK"));
		cJSON_AddItemToObject(jdata, "responseData", addobj);
	} else if (exec) {
		cJSON_AddItemToObject(jdata, "conf-command", cJSON_CreateString(exec));
		cJSON_AddItemToObject(jdata, "response", cJSON_CreateString((char *)stream.data));
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ALERT,"RES [%s][%s]\n", exec, (char *)stream.data);
	} else {
		cJSON_AddItemToObject(jdata, "error", cJSON_CreateString("Invalid Command"));
	}

	switch_event_channel_broadcast(event_channel, &msg, __FILE__, conference_globals.event_channel_id);


	switch_safe_free(stream.data);
	switch_safe_free(exec);

	switch_safe_free(conference_name);

}
Beispiel #4
0
cJSON* CHPRepPayloadToJson(OCRepPayload* repData)
{
    cJSON *outJson = cJSON_CreateObject();
    if (outJson == NULL)
    {
        return NULL;
    }

    OCRepPayloadValue* val = repData->values;
    while (val)
    {
        switch (val->type)
        {
            case OCREP_PROP_NULL:
                break;
            case OCREP_PROP_INT:
                OIC_LOG_V(DEBUG, TAG, "%s(int):%d", val->name, (int)val->i);
                cJSON_AddNumberToObject(outJson,val->name,(int)val->i);
                break;
            case OCREP_PROP_DOUBLE:
                OIC_LOG_V(DEBUG, TAG, "%s(double):%f", val->name, val->d);
                cJSON_AddNumberToObject(outJson,val->name,val->d);
                break;
            case OCREP_PROP_BOOL:
                OIC_LOG_V(DEBUG, TAG, "%s(bool):%s", val->name, val->b ? "true" : "false");
                cJSON_AddBoolToObject(outJson,val->name,val->b);
                break;
            case OCREP_PROP_STRING:
                OIC_LOG_V(DEBUG, TAG, "%s(string):%s", val->name, val->str);
                cJSON_AddStringToObject(outJson,val->name,val->str);
                break;
            case OCREP_PROP_OBJECT:
            {
                cJSON *objJson = CHPRepPayloadToJson(val->obj);
                if (objJson != NULL)
                {
                    cJSON_AddItemToObject(outJson,val->name,objJson);
                }
                break;
            }
            case OCREP_PROP_ARRAY:
            {
                unsigned int i = 0;
                int arraySize = (int)val->arr.dimensions[0];
                switch (val->arr.type)
                {
                    case OCREP_PROP_INT:
                        OIC_LOG_V(DEBUG, TAG, "%s(int array)", val->name);
                        if (arraySize > 0)
                        {
                            int castVal[val->arr.dimensions[0]];
                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
                            {
                                castVal[i] = (int)val->arr.iArray[i];
                            }
                            cJSON *array = cJSON_CreateIntArray(castVal,arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_DOUBLE:
                        OIC_LOG_V(DEBUG, TAG, "%s(double array)", val->name);
                        if (arraySize > 0)
                        {
                            cJSON *array = cJSON_CreateDoubleArray(val->arr.dArray,arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_STRING:
                        OIC_LOG_V(DEBUG, TAG, "%s(string array)", val->name);
                        if (arraySize > 0)
                        {
                            cJSON *array = cJSON_CreateStringArray((const char**)val->arr.strArray,
                                                                   arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_OBJECT:
                        if (arraySize > 0)
                        {
                            cJSON *arrayJson = cJSON_CreateArray();
                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
                            {
                                cJSON *objJson = CHPRepPayloadToJson(val->arr.objArray[i]);
                                if (objJson != NULL && arrayJson != NULL)
                                {
                                    cJSON_AddItemToArray(arrayJson, objJson);
                                }
                            }
                            if (arrayJson != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,arrayJson);
                            }
                        }
                        break;
                    case OCREP_PROP_BOOL:
                        //TODO : Not support - cJSON_CreateBoolArray
                        break;
                    default:
                        OIC_LOG_V(ERROR, TAG, "Unknown/unsupported array type: %s", val->name);
                        break;
                }
                break;
            }
            default:
                OIC_LOG_V(ERROR, TAG, "Unknown type: %s", val->name);
                break;
        }
        val = val->next;
    }

    if( repData->values != NULL)
    {
        return outJson;
    }
    else
    {
        cJSON_Delete(outJson);
        return NULL;
    }
}
int main(int argc, char **argv)
{
    const char *dir = DEFAULTDIR;
    const char *group = GROUPGLOBAL;
    const char *user = USER;
    const char *agent_id = NULL;

    gid_t gid;
    uid_t uid;
    int c = 0, info_agent = 0, update_rootcheck = 0,
        list_agents = 0, show_last = 0,
        resolved_only = 0;
    int active_only = 0, csv_output = 0, json_output = 0;

    char shost[512];
    cJSON *json_root = NULL;

    /* Set the name */
    OS_SetName(ARGV0);

    /* User arguments */
    if (argc < 2) {
        helpmsg();
    }

    while ((c = getopt(argc, argv, "VhqrDdLlcsju:i:")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 'h':
                helpmsg();
                break;
            case 'D':
                nowDebug();
                break;
            case 'l':
                list_agents++;
                break;
            case 's':
                csv_output = 1;
                break;
            case 'j':
                json_output = 1;
                break;
            case 'c':
                active_only++;
                break;
            case 'r':
                resolved_only = 1;
                break;
            case 'q':
                resolved_only = 2;
                break;
            case 'L':
                show_last = 1;
                break;
            case 'i':
                info_agent++;
                if (!optarg) {
                    merror("%s: -u needs an argument", ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                break;
            case 'u':
                if (!optarg) {
                    merror("%s: -u needs an argument", ARGV0);
                    helpmsg();
                }
                agent_id = optarg;
                update_rootcheck = 1;
                break;
            default:
                helpmsg();
                break;
        }

    }

    if (json_output)
        json_root = cJSON_CreateObject();

    /* Get the group name */
    gid = Privsep_GetGroup(group);
    uid = Privsep_GetUser(user);
    if (uid == (uid_t) - 1 || gid == (gid_t) - 1) {
        ErrorExit(USER_ERROR, ARGV0, user, group);
    }

    /* Set the group */
    if (Privsep_SetGroup(gid) < 0) {
        ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno));
    }

    /* Chroot to the default directory */
    if (Privsep_Chroot(dir) < 0) {
        ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno));
    }

    /* Inside chroot now */
    nowChroot();

    /* Set the user */
    if (Privsep_SetUser(uid) < 0) {
        ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno));
    }

    /* Get server hostname */
    memset(shost, '\0', 512);
    if (gethostname(shost, 512 - 1) != 0) {
        strncpy(shost, "localhost", 32);
        return (0);
    }

    /* List available agents */
    if (list_agents) {
        if (!csv_output) {
            printf("\nOSSEC HIDS %s. List of available agents:",
                   ARGV0);
            printf("\n   ID: 000, Name: %s (server), IP: 127.0.0.1, "
                   "Active/Local\n", shost);
        } else {
            printf("000,%s (server),127.0.0.1,Active/Local,\n", shost);
        }
        print_agents(1, active_only, csv_output, 0);
        printf("\n");
        exit(0);
    }

    /* Update rootcheck database */
    if (update_rootcheck) {
        char json_buffer[1024];

        /* Clean all agents (and server) db */
        if (strcmp(agent_id, "all") == 0) {
            DIR *sys_dir;
            struct dirent *entry;

            sys_dir = opendir(ROOTCHECK_DIR);
            if (!sys_dir) {
                if (json_output) {
                    cJSON_AddNumberToObject(json_root, "error", 11);
                    snprintf(json_buffer, 1023, "%s: Unable to open: '%s'", ARGV0, ROOTCHECK_DIR);
                    cJSON_AddStringToObject(json_root, "message", json_buffer);
                    printf("%s", cJSON_PrintUnformatted(json_root));
                    exit(1);
                } else
                    ErrorExit("%s: Unable to open: '%s'", ARGV0, ROOTCHECK_DIR);
            }

            while ((entry = readdir(sys_dir)) != NULL) {
                FILE *fp;
                char full_path[OS_MAXSTR + 1];

                /* Do not even attempt to delete . and .. :) */
                if ((strcmp(entry->d_name, ".") == 0) ||
                        (strcmp(entry->d_name, "..") == 0)) {
                    continue;
                }

                snprintf(full_path, OS_MAXSTR, "%s/%s", ROOTCHECK_DIR,
                         entry->d_name);

                fp = fopen(full_path, "w");
                if (fp) {
                    fclose(fp);
                }
                if (entry->d_name[0] == '.') {
                    unlink(full_path);
                }
            }

            closedir(sys_dir);

            if (json_output) {
                cJSON_AddNumberToObject(json_root, "error", 0);
                cJSON_AddStringToObject(json_root, "data", "Policy and auditing database updated");
                printf("%s", cJSON_PrintUnformatted(json_root));
            } else
                printf("\n** Policy and auditing database updated.\n\n");

            exit(0);
        }

        else if ((strcmp(agent_id, "000") == 0) ||
                 (strcmp(agent_id, "local") == 0)) {
            char final_dir[1024];
            FILE *fp;
            snprintf(final_dir, 1020, "/%s/rootcheck", ROOTCHECK_DIR);

            fp = fopen(final_dir, "w");
            if (fp) {
                fclose(fp);
            }
            unlink(final_dir);

            if (json_output) {
                cJSON_AddNumberToObject(json_root, "error", 0);
                cJSON_AddStringToObject(json_root, "data", "Policy and auditing database updated");
                printf("%s", cJSON_PrintUnformatted(json_root));
            } else
                printf("\n** Policy and auditing database updated.\n\n");

            exit(0);
        }

        /* Database from remote agents */
        else {
            int i;
            keystore keys;

            OS_ReadKeys(&keys);

            i = OS_IsAllowedID(&keys, agent_id);
            if (i < 0) {
                if (json_output) {
                    cJSON_AddNumberToObject(json_root, "error", 12);
                    snprintf(json_buffer, 1023, "Invalid agent id '%s'.", agent_id);
                    cJSON_AddStringToObject(json_root, "message", json_buffer);
                    printf("%s", cJSON_PrintUnformatted(json_root));
                    exit(1);
                } else {
                    printf("\n** Invalid agent id '%s'.\n", agent_id);
                    helpmsg();
                }
            }

            /* Delete syscheck */
            delete_rootcheck(keys.keyentries[i]->name,
                             keys.keyentries[i]->ip->ip, 0);

            if (json_output) {
                 cJSON_AddNumberToObject(json_root, "error", 0);
                 cJSON_AddStringToObject(json_root, "data", "Policy and auditing database updated");
                 printf("%s", cJSON_PrintUnformatted(json_root));
            } else
                printf("\n** Policy and auditing database updated.\n\n");

            exit(0);
        }
    }

    /* Print information from an agent */
    if (info_agent) {
        int i;
        char final_ip[128 + 1];
        char final_mask[128 + 1];
        keystore keys;
        cJSON *json_events = NULL;

        if (json_output)
            json_events = cJSON_CreateArray();

        if ((strcmp(agent_id, "000") == 0) ||
                (strcmp(agent_id, "local") == 0)) {
            if (!(csv_output || json_output))
                printf("\nPolicy and auditing events for local system '%s - %s':\n",
                       shost, "127.0.0.1");

            print_rootcheck(NULL, NULL, NULL, resolved_only, csv_output,
                            json_events, show_last);

            if (json_output) {
                cJSON_AddNumberToObject(json_root, "error", 0);
                cJSON_AddItemToObject(json_root, "data", json_events);
                printf("%s", cJSON_PrintUnformatted(json_root));
            }
        } else {
            OS_ReadKeys(&keys);

            i = OS_IsAllowedID(&keys, agent_id);
            if (i < 0) {
                if (json_output) {
                    char json_buffer[1024];
                    snprintf(json_buffer, 1023, "Invalid agent id '%s'", agent_id);
                    cJSON_AddNumberToObject(json_root, "error", 13);
                    cJSON_AddStringToObject(json_root, "message", json_buffer);
                    printf("%s", cJSON_PrintUnformatted(json_root));
                    exit(1);
                } else {
                    printf("\n** Invalid agent id '%s'.\n", agent_id);
                    helpmsg();
                }
            }

            final_ip[128] = '\0';
            final_mask[128] = '\0';
            getNetmask(keys.keyentries[i]->ip->netmask,
                       final_mask, 128);
            snprintf(final_ip, 128, "%s%s", keys.keyentries[i]->ip->ip,
                     final_mask);

            if (!csv_output)
                printf("\nPolicy and auditing events for agent "
                       "'%s (%s) - %s':\n",
                       keys.keyentries[i]->name, keys.keyentries[i]->id,
                       final_ip);

            print_rootcheck(keys.keyentries[i]->name,
                            keys.keyentries[i]->ip->ip, NULL,
                            resolved_only, csv_output, json_events, show_last);

            if (json_output) {
                cJSON_AddNumberToObject(json_root, "error", 0);
                cJSON_AddItemToObject(json_root, "data", json_events);
                printf("%s", cJSON_PrintUnformatted(json_root));
            }
        }

        exit(0);
    }

    if (json_output) {
        cJSON_AddNumberToObject(json_root, "error", 10);
        cJSON_AddStringToObject(json_root, "message", "Invalid argument combination");
        printf("%s", cJSON_PrintUnformatted(json_root));
        exit(1);
    } else {
        printf("\n** Invalid argument combination.\n");
        helpmsg();
    }

    return (0);
}
Beispiel #6
0
char * BinToDoxmJSON(const OicSecDoxm_t * doxm, const bool isIncResName)
{
    if (NULL == doxm)
    {
        return NULL;
    }

    char *jsonStr = NULL;
    cJSON *jsonDoxm = NULL;
    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
    uint32_t outLen = 0;
    B64Result b64Ret = B64_OK;

    cJSON *jsonRoot = cJSON_CreateObject();
    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);

    if(isIncResName)
    {
        jsonDoxm = cJSON_CreateObject();
        VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
        cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
    }
    else
    {
        jsonDoxm = jsonRoot;
    }

    //Oxm -- Not Mandatory
    if(doxm->oxmLen > 0)
    {
        cJSON *jsonOxmArray = cJSON_CreateArray();
        VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
        for (size_t i = 0; i < doxm->oxmLen; i++)
        {
            cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
        }
    }

    //OxmSel -- Mandatory
    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);

    //sct -- Mandatory
    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, (int)doxm->sct);

    //Owned -- Mandatory
    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);

    //TODO: Need more clarification on deviceIDFormat field type.
#if 0
    //DeviceIdFormat -- Mandatory
    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
#endif

    //DeviceId -- Mandatory
    outLen = 0;
    b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
                    sizeof(base64Buff), &outLen);
    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);

    //Owner -- Mandatory
    outLen = 0;
    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
                    sizeof(base64Buff), &outLen);
    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEV_OWNER_NAME, base64Buff);

    outLen = 0;
    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
                    sizeof(base64Buff), &outLen);
    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);

    //Rowner -- Mandatory
    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);

    jsonStr = cJSON_PrintUnformatted(jsonRoot);

exit:
    if (jsonRoot)
    {
        cJSON_Delete(jsonRoot);
    }
    return jsonStr;
}
Beispiel #7
0
static int create_conman_config(char **config)
{
  cJSON *root = NULL, *connections = NULL, *connection = NULL,
      *links = NULL, *link = NULL;

  root = cJSON_CreateObject();
  if (!root)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      return ERROR;
    }

  connections = cJSON_CreateArray();
  if (!connections)
    {
      exapp_dbg("cJSON_CreateArray failed\n");
      goto errout_free;
    }

  connection = cJSON_CreateObject();
  if (!connection)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      goto errout_free;
    }

  links = cJSON_CreateArray();
  if (!links)
    {
      exapp_dbg("cJSON_CreateArray failed\n");
      goto errout_free;
    }

  link = cJSON_CreateObject();
  if (!link)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      goto errout_free;
    }

#ifdef CONFIG_SDK_EXAMPLE_APP_CONNECTION_MODEM
  cJSON_AddNumberToObject(link, "connectionId", 0);
  cJSON_AddStringToObject(link, "pinCode", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_PIN);
  cJSON_AddStringToObject(link, "accessPointName", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_NAME);
  cJSON_AddStringToObject(link, "userName", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_USER);
  cJSON_AddStringToObject(link, "password", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_PASSWD);

  cJSON_AddItemToArray(links, link);
  cJSON_AddItemToObject(connection, "cellularConnections", links);
#elif defined CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI
  cJSON_AddNumberToObject(link, "connectionId", 0);
  cJSON_AddStringToObject(link, "ssid", CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI_SSID);
  cJSON_AddStringToObject(link, "password", CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI_PSK);
  cJSON_AddStringToObject(link, "encryption", "wpa2");

  cJSON_AddItemToArray(links, link);
  cJSON_AddItemToObject(connection, "wifiConnections", links);
#else
# error "Connectivity misconfigured"
#endif

  cJSON_AddItemToArray(connections, connection);
  cJSON_AddItemToObject(root, "connections", connections);

  *config = cJSON_PrintUnformatted(root);

  cJSON_Delete(root); /* Deletes the whole tree */

  return OK;

errout_free:

  cJSON_Delete(root);
  cJSON_Delete(connections);
  cJSON_Delete(connection);
  cJSON_Delete(links);
  cJSON_Delete(link);

  return ERROR;
}
Beispiel #8
0
int callback(middleware_t *middleware, http_method_t http_method, const char *url, const char *request, char *response) {
    if (strcmp(url, "/api/directors") == 0) {
        if (http_method == http_method_get) {
            cJSON *json = cJSON_CreateArray();

            const director_t *directorArray;
            size_t numberOfDirectors;
            directors_get_all(middleware->directors, &directorArray, &numberOfDirectors);
            for (size_t i = 0; i < numberOfDirectors; ++i) {
                const director_t *director = directorArray + i;

                cJSON *jsonDir = cJSON_CreateObject();
                cJSON_AddNumberToObject(jsonDir, "id", director->id);
                cJSON_AddStringToObject(jsonDir, "name", director->name);
                cJSON_AddStringToObject(jsonDir, "surname", director->surname);
                cJSON_AddNumberToObject(jsonDir, "salary", director->salary);
                cJSON_AddNumberToObject(jsonDir, "rating", director->rating);
                char birthdateStr[128];
                sprintf(birthdateStr, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday);
                cJSON_AddStringToObject(jsonDir, "birthdate", birthdateStr);
                cJSON *jsonStartup = cJSON_CreateObject();
                cJSON_AddStringToObject(jsonStartup, "name", director->startup.name);
                cJSON_AddStringToObject(jsonStartup, "country", director->startup.country);
                cJSON_AddItemToObject(jsonDir, "startup", jsonStartup);

                cJSON_AddItemToArray(json, jsonDir);
            }

            strcpy(response, cJSON_Print(json));
            cJSON_Delete(json);

            return 1;
        } else if (http_method == http_method_post) {
            cJSON *json = cJSON_Parse(request);

            if (json) {
                cJSON *jsonName = cJSON_GetObjectItem(json, "name");
                cJSON *jsonSurname = cJSON_GetObjectItem(json, "surname");
                cJSON *jsonSalary = cJSON_GetObjectItem(json, "salary");
                cJSON *jsonRating = cJSON_GetObjectItem(json, "rating");
                cJSON *jsonBirthdate = cJSON_GetObjectItem(json, "birthdate");
                cJSON *jsonStartup = cJSON_GetObjectItem(json, "startup");
                if (jsonName && jsonSurname && jsonSalary && jsonRating && jsonBirthdate && jsonStartup) {
                    cJSON *jsonStartupName = cJSON_GetObjectItem(jsonStartup, "name");
                    cJSON *jsonStartupCountry = cJSON_GetObjectItem(jsonStartup, "country");
                    if (jsonStartupName && jsonStartupCountry) {
                        director_t director;
                        strcpy(director.name, jsonName->valuestring);
                        strcpy(director.surname, jsonSurname->valuestring);
                        director.salary = jsonSalary->valueint;
                        director.rating = jsonRating->valuedouble;
                        memset(&director.birthdate, 0, sizeof(struct tm));
                        sscanf(jsonBirthdate->valuestring, "%i-%i-%i", &director.birthdate.tm_year, &director.birthdate.tm_mon, &director.birthdate.tm_mday);
                        director.birthdate.tm_year -= 1900;
                        director.birthdate.tm_mon -= 1;
                        strcpy(director.startup.name, jsonStartupName->valuestring);
                        strcpy(director.startup.country, jsonStartupCountry->valuestring);

                        directors_insert(middleware->directors, &director);
                        cJSON_Delete(json);

                        strcpy(response, "OK");

                        return 1;
                    }
                }
            }

            cJSON_Delete(json);
        }
    } else if (strncmp(url, "/api/directors/", strlen("/api/directors/")) == 0) {
        size_t directorId = atoi(strstr(strstr(url + 1, "/") + 1, "/") + 1);

        if (http_method == http_method_get) {
            const director_t *director = directors_get(middleware->directors, directorId);
            if (director) {
                cJSON *json = cJSON_CreateObject();

                cJSON_AddNumberToObject(json, "id", director->id);
                cJSON_AddStringToObject(json, "name", director->name);
                cJSON_AddStringToObject(json, "surname", director->surname);
                cJSON_AddNumberToObject(json, "salary", director->salary);
                cJSON_AddNumberToObject(json, "rating", director->rating);
                char birthdateStr[128];
                sprintf(birthdateStr, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday);
                cJSON_AddStringToObject(json, "birthdate", birthdateStr);
                cJSON *jsonStartup = cJSON_CreateObject();
                cJSON_AddStringToObject(jsonStartup, "name", director->startup.name);
                cJSON_AddStringToObject(jsonStartup, "country", director->startup.country);
                cJSON_AddItemToObject(json, "startup", jsonStartup);

                strcpy(response, cJSON_Print(json));
                cJSON_Delete(json);

                return 1;
            }
        } else if (http_method == http_method_delete) {
            if (directors_remove(middleware->directors, directorId)) {
                strcpy(response, "OK");
                return 1;
            }
        }
    } else if (strcmp(url, "/") == 0) {
        response[0] = 0;
        stradd(response, "<html><body><h1>Hello!</h1><br>");
        stradd(response, "<h2>Navigate to <a href=\"/directors\">directors list</a></h2><br>");
        stradd(response, "<h2>Navigate to <a href=\"/api/directors\">api</a></h2><br>");
        stradd(response, "<body><html>");
        return 1;
    } else if (strcmp(url, "/directors") == 0) {
        if (http_method == http_method_get) {
            response[0] = 0;
            stradd(response, "<html><body><h1>Directors</h1><br><ul>");

            const director_t *directorArray;
            size_t numberOfDirectors;
            directors_get_all(middleware->directors, &directorArray, &numberOfDirectors);
            for (size_t i = 0; i < numberOfDirectors; ++i) {
                const director_t *director = directorArray + i;

                stradd(response, "<li>");
                char hrefBuffer[32];
                sprintf(hrefBuffer, "<a href=\"/directors/%u\">", director->id);
                stradd(response, hrefBuffer);
                stradd(response, director->name);
                stradd(response, " ");
                stradd(response, director->surname);
                stradd(response, "</a>");
                stradd(response, "</li>");
            }

            stradd(response, "</ul>");
            stradd(response, "<h2>Navigate to <a href=\"/new-director\">new director creation page</a></h2>");
            stradd(response, "</body></html>");

            return 1;
        } else if (http_method == http_method_post) {
            url_params_t *url_params = url_params_parse(request);

            const char *name = url_params_get(url_params, "name");
            if((strlen(name)) == 0)
                return 0;
            const char *surname = url_params_get(url_params, "surname");
            if((strlen(surname)) == 0)
                return 0;
            const char *salary = url_params_get(url_params, "salary");
            if((strlen(salary)) == 0)
                return 0;
            const char *rating = url_params_get(url_params, "rating");
            if((strlen(rating)) == 0)
                return 0;
            const char *birthdate = url_params_get(url_params, "birthdate");
            if((strlen(birthdate)) == 0)
                return 0;
            const char *startupName = url_params_get(url_params, "startup_name");
            if((strlen(startupName)) == 0)
                return 0;
            const char *startupCountry = url_params_get(url_params, "startup_country");
            if((strlen(startupCountry)) == 0)
                return 0;

            director_t director;
            strcpy(director.name, name);
            strcpy(director.surname, surname);
            director.salary = atoi(salary);
            director.rating = atof(rating);
            memset(&director.birthdate, 0, sizeof(struct tm));
            sscanf(birthdate, "%i-%i-%i", &director.birthdate.tm_year, &director.birthdate.tm_mon, &director.birthdate.tm_mday);
            director.birthdate.tm_year -= 1900;
            director.birthdate.tm_mon -= 1;
            strcpy(director.startup.name, startupName);
            strcpy(director.startup.country, startupCountry);

            directors_insert(middleware->directors, &director);

            strcpy(response, "<html><body><h2>Successfully added</h2><br><h1><a href=\"/directors\">Go back</a></h2><br><h2><a href=\"/new-director\">Add new</a></h2></body></html>");

            return 1;
        }
    } else if (strncmp(url, "/directors/", strlen("/directors/")) == 0) {
        size_t directorId = atoi(strstr(url + 1, "/") + 1);

        if (http_method == http_method_get) {
            const director_t *director = directors_get(middleware->directors, directorId);
            if (director) {
                response[0] = 0;

                stradd(response, "<html><body><h1>Director: ");
                stradd(response, director->name);
                stradd(response, " ");
                stradd(response, director->surname);
                stradd(response, "</h1><br><ul>");

                char buffer[32];

                stradd(response, "<li>");
                stradd(response, "Salary: ");
                sprintf(buffer, "%u", director->salary);
                stradd(response, buffer);
                stradd(response, "</li>");

                stradd(response, "<li>");
                stradd(response, "Rating: ");
                sprintf(buffer, "%f", director->rating);
                stradd(response, buffer);
                stradd(response, "</li>");

                stradd(response, "<li>");
                stradd(response, "Birthdate: ");
                sprintf(buffer, "%i-%i-%i", director->birthdate.tm_year + 1900, director->birthdate.tm_mon + 1, director->birthdate.tm_mday);
                stradd(response, buffer);
                stradd(response, "</li>");

                stradd(response, "<li>Startup: <ul><li>");
                stradd(response, "Name: ");
                stradd(response, director->startup.name);
                stradd(response, "</li><li>");
                stradd(response, "Country: ");
                stradd(response, director->startup.country);
                stradd(response, "</li></ul></li></ul>");

                stradd(response, "<form method=\"post\" action=\"");
                stradd(response, url);
                stradd(response, "\"><button type=\"submit\"><h1>Delete</h1></button>");

                stradd(response, "</body></html>");

                return 1;
            }
        } else if (http_method == http_method_post) {
            if (directors_remove(middleware->directors, directorId)) {
                strcpy(response, "<html><body><h2>Successfully deleted</h2><br><h1><a href=\"/directors\">Go back</a></h2></body></html>");
                return 1;
            }
        }
    } else if (strcmp(url, "/new-director") == 0) {
        response[0] = 0;

        stradd(response, "<html><body><h1>Add new director</h1><br>");
        stradd(response, "<form method=\"post\" action=\"/directors\">");
        stradd(response, "Name: <input type=\"text\" name=\"name\"><br><br>");
        stradd(response, "Surname: <input type=\"text\" name=\"surname\"><br><br>");
        stradd(response, "Salary: <input type=\"text\" name=\"salary\"><br><br>");
        stradd(response, "Rating: <input type=\"text\" name=\"rating\"><br><br>");
        stradd(response, "Birthdate: <input type=\"text\" name=\"birthdate\"><br><br>");
        stradd(response, "Startup name: <input type=\"text\" name=\"startup_name\"><br><br>");
        stradd(response, "Startup country: <input type=\"text\" name=\"startup_country\"><br><br>");
        stradd(response, "<button type=\"Submit\">Submit</button>");
        stradd(response, "</form></body></html>");

        return 1;
    }

    return 0;
}
Beispiel #9
0
void accept_thread(void *asdf)
{
	sigset_t sigs_to_block;
	int e, n;
	struct pollfd *acceptpfd = NULL;
	struct listen_t **acceptpl = NULL;
	int listen_n = 0;
	int poll_n = 0;
	struct listen_t *l;

	pthreads_profiling_reset("accept");
	
	sigemptyset(&sigs_to_block);
	sigaddset(&sigs_to_block, SIGALRM);
	sigaddset(&sigs_to_block, SIGINT);
	sigaddset(&sigs_to_block, SIGTERM);
	sigaddset(&sigs_to_block, SIGQUIT);
	sigaddset(&sigs_to_block, SIGHUP);
	sigaddset(&sigs_to_block, SIGURG);
	sigaddset(&sigs_to_block, SIGPIPE);
	sigaddset(&sigs_to_block, SIGUSR1);
	sigaddset(&sigs_to_block, SIGUSR2);
	pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL);
	
	/* start the accept thread, which will start server threads */
	hlog(LOG_INFO, "Accept thread starting...");
	
	/* we allocate a worker structure to be used within the accept thread
	 * for parsing incoming UDP packets and passing them on to the dupecheck
	 * thread.
	 */
	udp_worker = worker_alloc();
	udp_worker->id = 81;
	
	/* we also need a client structure to be used with incoming
	 * HTTP position uploads
	 */
	udp_pseudoclient = pseudoclient_setup(81);
	udp_pseudoclient->flags |= CLFLAGS_UDPSUBMIT;
	
	accept_reconfiguring = 1;
	while (!accept_shutting_down) {
		if (accept_reconfiguring) {
			accept_reconfiguring = 0;
			listen_n -= close_removed_listeners();
			
			/* start listening on the sockets */
			listen_n += open_missing_listeners();
			
			if (listen_n < 1) {
				hlog(LOG_CRIT, "Failed to listen on any ports.");
				exit(2);
			}
			
			/* reconfiguration must scan old clients against ACL */
			rescan_client_acls();
			
			/* how many are we polling */
			poll_n = 0;
			for (l = listen_list; (l); l = l->next)
				if (!l->corepeer)
					poll_n++;
			
			hlog(LOG_DEBUG, "Generating polling list for %d/%d listeners...", poll_n, listen_n);
			
			/* array of FDs for poll() */
			if (acceptpfd)
				hfree(acceptpfd);
			acceptpfd = hmalloc(poll_n * sizeof(*acceptpfd));
			
			/* array of listeners */
			if (acceptpl)
				hfree(acceptpl);
			acceptpl = hmalloc(poll_n * sizeof(*acceptpl));
			
			n = 0;
			for (l = listen_list; (l); l = l->next) {
				/* The accept thread does not poll() UDP sockets for core peers.
				 * Worker 0 takes care of that, and processes the incoming packets.
				 */
				if (l->corepeer) {
					hlog(LOG_DEBUG, "... %d: fd %d (%s) - not polled, is corepeer", n, (l->udp) ? l->udp->fd : l->fd, l->addr_s);
					continue;
				}
				
				int fd;
				if (l->udp) {
					l->udp->polled = 1;
					fd = l->udp->fd;
				} else {
					fd = l->fd;
				}
				
				hlog(LOG_DEBUG, "... %d: fd %d (%s)", n, fd, l->addr_s);
				acceptpfd[n].fd = fd;
				acceptpfd[n].events = POLLIN|POLLPRI|POLLERR|POLLHUP;
				acceptpl[n] = l;
				n++;
			}
			hlog(LOG_INFO, "Accept thread ready.");
			
			/* stop the dupechecking and uplink threads while adjusting
			 * the amount of workers... they walk the worker list, and
			 * might get confused when workers are stopped or started.
			 */
			if (workers_running != workers_configured) {
				uplink_stop();
				dupecheck_stop();
				workers_start();
				dupecheck_start();
				uplink_start();
			}
			
			/*
			 * generate UDP peer clients
			 */
			peerip_clients_close();
			if (peerip_config)
				peerip_clients_config();
			
			/* accept liveupgrade clients */
			if (liveupgrade_status)
				accept_liveupgrade_accept();
		}
		
		/* check for new connections */
		e = poll(acceptpfd, poll_n, 200);
		if (e == 0)
			continue;
		if (e < 0) {
			if (errno == EINTR)
				continue;
			hlog(LOG_ERR, "poll() on accept failed: %s (continuing)", strerror(errno));
			continue;
		}
		
		/* now, which socket was that on? */
		for (n = 0; n < poll_n; n++) {
			l = acceptpl[n];
			if (!(l) || (l->udp ? l->udp->fd : l->fd) != acceptpfd[n].fd) {
				hlog(LOG_CRIT, "accept_thread: polling list and listener list do mot match!");
				exit(1);
			}
			if (acceptpfd[n].revents) {
				if (l->udp)
					accept_udp_recv(l); /* receive UDP packets */
				else
					do_accept(l); /* accept a single connection */
			}
		}
	}
	
	if (accept_shutting_down == 2)
		worker_shutdown_clients = cJSON_CreateArray();
	
	hlog(LOG_DEBUG, "Accept thread shutting down listening sockets and worker threads...");
	uplink_stop();
	close_listeners();
	dupecheck_stop();
	http_shutting_down = 1;
	workers_stop(accept_shutting_down);
	hfree(acceptpfd);
	hfree(acceptpl);
	acceptpfd = NULL;
	acceptpl = NULL;
	
	/* free up the pseudo-client */
	client_free(udp_pseudoclient);
	udp_pseudoclient = NULL;
	
	/* free up the pseudo-worker structure, after dupecheck is long dead */
	worker_free_buffers(udp_worker);
	hfree(udp_worker);
	udp_worker = NULL;
}
static cJSON* process_task( cJSON* input )
{
  struct TaskCommandHandler* handler;
  UTV_RESULT result;
  UTV_BOOL failedRequest = UTV_FALSE;
  int idx;
  cJSON* requests;
  cJSON* request;
  cJSON* command;
  cJSON* inputs;
  cJSON* commandName;
  UTV_UINT32 commandNameLength;
  cJSON* output;
  cJSON* responses;
  cJSON* response;
  cJSON* outputs;

  responses = cJSON_CreateArray();

  requests = cJSON_GetObjectItem( input, "REQUESTS" );

  for ( idx = 0; idx < cJSON_GetArraySize( requests ); idx++ )
  {
    request = cJSON_GetArrayItem( requests, idx );
    command = cJSON_DetachItemFromObject( request, "COMMAND" );
    inputs = cJSON_GetObjectItem( request, "INPUTS" );
    commandName = cJSON_GetObjectItem( command, "NAME" );
    commandNameLength = UtvStrlen( (UTV_BYTE*) commandName->valuestring );

    response = cJSON_CreateObject();
    outputs = cJSON_CreateArray();

    cJSON_AddItemToObject( response, "COMMAND", command );

    if ( !failedRequest )
    {
      handler = s_handler_list;

      while ( handler != NULL )
      {
        if ( commandNameLength == UtvStrlen( handler->command_name ) )
        {
          if ( !UtvMemcmp( commandName->valuestring, handler->command_name, commandNameLength ) )
          {
            result = handler->command_handler( inputs, outputs );
            break;
          }
        }

        handler = handler->next;
      }

      if ( NULL == handler )
      {
        UtvMessage( UTV_LEVEL_WARN,
                    "%s: Unknown command \"%s\"",
                    __FUNCTION__,
                    commandName->valuestring );

        result = UTV_LIVE_SUPPORT_COMMAND_UNKNOWN;
      }

      failedRequest = ( result != UTV_OK );
    }
    else
    {
        UtvMessage( UTV_LEVEL_WARN,
                    "%s: Command \"%s\" not processed",
                    __FUNCTION__,
                    commandName->valuestring );

      result = UTV_LIVE_SUPPORT_COMMAND_NOT_PROCESSED;
    }

    cJSON_AddNumberToObject( response, "RESULT", result );
    cJSON_AddItemToObject( response, "OUTPUTS", outputs );
    cJSON_AddItemToArray( responses, response );
  }

  output = cJSON_CreateObject();
  cJSON_AddItemToObject( output, "RESPONSES", responses );

  return ( output );
}
Beispiel #11
0
bool Library::process_phrase(const char *loc_str, read_line &io, bool force, bool json)
{
	if (NULL==loc_str)
		return true;

	std::string query;

	
	analyze_query(loc_str, query);
	if (!query.empty())
		io.add_to_history(query.c_str());
	


	gsize bytes_read;
	gsize bytes_written;
	GError *err=NULL;
	char *str=NULL;
	if (!utf8_input)
		str=g_locale_to_utf8(loc_str, -1, &bytes_read, &bytes_written, &err);
	else
		str=g_strdup(loc_str);

	if (NULL==str) {
		fprintf(stderr, _("Can not convert %s to utf8.\n"), loc_str);
		fprintf(stderr, "%s\n", err->message);
		g_error_free(err);
		return false;
	}

	if (str[0]=='\0')
		return true;

  
	TSearchResultList res_list;


	switch (analyze_query(str, query)) {
	case qtFUZZY:
		LookupWithFuzzy(query, res_list);
		break;
	case qtREGEXP:
		LookupWithRule(query, res_list);
		break;
	case qtSIMPLE:
		SimpleLookup(str, res_list);
		if (res_list.empty())
			LookupWithFuzzy(str, res_list);
		break;
	case qtDATA:
		LookupData(query, res_list);
		break;
	default:
		/*nothing*/;
	}

	if (!res_list.empty()) {    
		/* try to be more clever, if there are
		   one or zero results per dictionary show all
		*/
		bool show_all_results=true;
		typedef std::map< string, int, std::less<string> > DictResMap;
		if (!force) {
			DictResMap res_per_dict;
			for(TSearchResultList::iterator ptr=res_list.begin(); ptr!=res_list.end(); ++ptr){
				std::pair<DictResMap::iterator, DictResMap::iterator> r = 
					res_per_dict.equal_range(ptr->bookname);
				DictResMap tmp(r.first, r.second);
				if (tmp.empty()) //there are no yet such bookname in map
					res_per_dict.insert(DictResMap::value_type(ptr->bookname, 1));
				else {
					++((tmp.begin())->second);
					if (tmp.begin()->second>1) {
						show_all_results=false;
						break;
					}
				}
			}
		}//if (!force)

		if (!show_all_results && !force) {
			printf(_("Found %d items, similar to %s.\n"), res_list.size(), 
			       utf8_output ? str : utf8_to_locale_ign_err(str).c_str());
			for (size_t i=0; i<res_list.size(); ++i) {
				string loc_bookname, loc_def;
				loc_bookname=utf8_to_locale_ign_err(res_list[i].bookname);
				loc_def=utf8_to_locale_ign_err(res_list[i].def);
				printf("%d)%s-->%s\n", i,
				       utf8_output ?  res_list[i].bookname.c_str() : loc_bookname.c_str(),
				       utf8_output ? res_list[i].def.c_str() : loc_def.c_str());
			}
			int choise;
			for (;;) {
				string str_choise;
				printf(_("Your choice[-1 to abort]: "));
				
				if(!stdio_getline(stdin, str_choise)){
					putchar('\n');
					exit(EXIT_SUCCESS);
				}
				sscanf(str_choise.c_str(), "%d", &choise);
				if (choise>=0 && choise<int(res_list.size())) { 
					sdcv_pager pager;
					print_search_result(pager.get_stream(), res_list[choise]);
					break;
				} else if (choise==-1)
					break;
				else
					printf(_("Invalid choise.\nIt must be from 0 to %d or -1.\n"), 
					       res_list.size()-1);	  
			}		
		} else {
			sdcv_pager pager(force);
			if (!json) {
				fprintf(pager.get_stream(), _("Found %d items, similar to %s.\n"),
					res_list.size(), utf8_output ? str : utf8_to_locale_ign_err(str).c_str());
				for (PSearchResult ptr=res_list.begin(); ptr!=res_list.end(); ++ptr)
					print_search_result(pager.get_stream(), *ptr);
			} else {
				char *out;
				cJSON *root,*fld;
				root=cJSON_CreateArray();
				for (PSearchResult ptr=res_list.begin(); ptr!=res_list.end(); ++ptr) {
					const TSearchResult & res = *ptr;
					string loc_bookname, loc_def, loc_exp;
					if(!utf8_output){
						loc_bookname=utf8_to_locale_ign_err(res.bookname);
						loc_def=utf8_to_locale_ign_err(res.def);
						loc_exp=utf8_to_locale_ign_err(res.exp);
					}
					cJSON_AddItemToArray(root,fld=cJSON_CreateObject());
					cJSON_AddStringToObject(fld, "dict", utf8_output ? res.bookname.c_str() : loc_bookname.c_str());
					cJSON_AddStringToObject(fld, "word", utf8_output ? res.def.c_str() : loc_def.c_str());
					cJSON_AddStringToObject(fld, "definition", utf8_output ? res.exp.c_str() : loc_exp.c_str());
				}
				out=cJSON_Print(root);
				cJSON_Delete(root);
				fprintf(pager.get_stream(), "%s", out);
				free(out);
			}
		}
    
	} else {
		string loc_str;
		if (!utf8_output)
			loc_str=utf8_to_locale_ign_err(str);
    
		printf(_("Nothing similar to %s, sorry :(\n"), utf8_output ? str : loc_str.c_str());
	}
	g_free(str);

	return true;
}
uint8 ALI_trade(ORDER_ST *order)
{
	struct MAP_ST *p;
	uint16 len;
	uint8 res;
	char *key,*value,*text;
	
	cJSON *root,*item,*arr;


	p = ALI_mapInsert("service",(char *)gatewayStr);
	p = ALI_mapInsert("partner",(char *)partner);
	p = ALI_mapInsert("seller_email",(char *)seller_email);
	p = ALI_mapInsert("_input_charset",(char *)charset);
	p = ALI_mapInsert("product_code","QR_CODE_OFFLINE");
	

	arr = cJSON_CreateArray();
	if(arr == NULL){
		print_ali("cJSON_CreateArray == NULL");
		return 0;
	}
	item = cJSON_CreateObject();
	if(item == NULL){
		print_ali("cJSON_CreateObject == NULL");
		cJSON_Delete(arr);
		return 0;
	}

	cJSON_AddItemToArray(arr,item);

    cJSON_AddStringToObject(item,"goodsName","Yibao");
    cJSON_AddStringToObject(item,"quantity","1");
	cJSON_AddStringToObject(item,"price","0.01");
	text = cJSON_Print(arr);
	cJSON_Delete(arr);
	print_ali("text=%s\r\n",text);

	p = ALI_mapInsert("total_fee","0.01");
	p = ALI_mapInsert("out_trade_no","yoc201507281214");
	p = ALI_mapInsert("subject","subject");
	p = ALI_mapInsert("goods_detail",text);
	free(text);


	text = ALI_buildRequestMysign(&head);

	//签名结果与签名方式加入请求提交参数组中
	p = ALI_mapInsert("sign",text);
	p = ALI_mapInsert("sign_type","MD5");
    text = ALI_createLinkString(&head);
	ALI_mapFree(&head);
	len = strlen(text);
	print_ali("ALI_trade:order=");
	Uart0PutStr(text,len);
	print_ali("\r\n");


	res = GPRS_httpPost(text,"https://mapi.alipay.com:80/gateway.do?_input_charset=utf-8");
	if(res == 0)
		print_ali("GPRS_http:FAIL GPRS_http:FAIL GPRS_http:FAIL GPRS_http:FAILres=%d\r\n\r\n",res);


	
}
Beispiel #13
0
cJSON *iguana_blockjson(struct supernet_info *myinfo,struct iguana_info *coin,struct iguana_block *block,int32_t txidsflag)
{
    char str[65],hexstr[1024]; int32_t i,len,size; struct iguana_txid *tx,T; struct iguana_msgzblock zmsg; struct iguana_msgblock *msg = (void *)&zmsg; struct iguana_zblock *zblock;
    bits256 hash2,nexthash2; uint8_t serialized[1024]; cJSON *array,*json = cJSON_CreateObject();
    jaddstr(json,"result","success");
    jaddstr(json,"hash",bits256_str(str,block->RO.hash2));
    jaddnum(json,"height",block->height);
    //jaddnum(json,"ipbits",block->fpipbits);
    jaddstr(json,"merkleroot",bits256_str(str,block->RO.merkle_root));
    jaddstr(json,"previousblockhash",bits256_str(str,block->RO.prev_block));
    if ( block->height > 0 )
    {
        nexthash2 = iguana_blockhash(coin,block->height+1);
        if ( bits256_nonz(nexthash2) != 0 )
            jaddstr(json,"nextblockhash",bits256_str(str,nexthash2));
    }
    jaddnum(json,"timestamp",block->RO.timestamp);
    jaddstr(json,"utc",utc_str(str,block->RO.timestamp));
    jaddnum(json,"nonce",block->RO.nonce);
    jaddnum(json,"version",block->RO.version);
    jaddnum(json,"numvouts",block->RO.numvouts);
    jaddnum(json,"numvins",block->RO.numvins);
    jaddnum(json,"recvlen",block->RO.recvlen);
    jaddnum(json,"hdrsi",block->hdrsi);
    jaddnum(json,"difficulty",PoW_from_compact(block->RO.bits,coin->chain->unitval));
    jaddnum(json,"bundlei",block->bundlei);
    jaddnum(json,"mainchain",block->mainchain);
    jaddnum(json,"valid",block->valid);
    jaddnum(json,"txn_count",block->RO.txn_count);
    
    jaddnum(json,"nBits",block->RO.bits);
    serialized[0] = ((uint8_t *)&block->RO.bits)[3];
    serialized[1] = ((uint8_t *)&block->RO.bits)[2];
    serialized[2] = ((uint8_t *)&block->RO.bits)[1];
    serialized[3] = ((uint8_t *)&block->RO.bits)[0];
    init_hexbytes_noT(hexstr,serialized,sizeof(uint32_t));
    jaddstr(json,"nBitshex",hexstr);
    if ( block->RO.allocsize == sizeof(struct iguana_zblock) )
    {
        zblock = (void *)block;
        memset(&zmsg,0,sizeof(zmsg));
        zmsg.zH.version = zblock->RO.version;
        zmsg.zH.merkle_root = zblock->RO.merkle_root;
        zmsg.zH.timestamp = zblock->RO.timestamp;
        zmsg.zH.bits = zblock->RO.bits;
        zmsg.zH.bignonce = zblock->zRO.bignonce;
        if ( iguana_rwvarint32(1,zmsg.zH.var_numelements,&zblock->zRO.numelements) != sizeof(zmsg.zH.var_numelements) )
            printf("unexpected varint size for zmsg.zH.numelements <- %d\n",zblock->zRO.numelements);
        for (i=0; i<ZCASH_SOLUTION_ELEMENTS; i++)
            zmsg.zH.solution[i] = zblock->zRO.solution[i];
        zmsg.txn_count = 0;//block->RO.txn_count;
        len = iguana_rwblock(myinfo,coin->symbol,coin->chain->zcash,coin->chain->auxpow,coin->chain->hashalgo,1,&hash2,serialized,&zmsg,IGUANA_MAXPACKETSIZE*2);
    }
    else
    {
        memset(msg,0,sizeof(&msg));
        msg->H.version = block->RO.version;
        msg->H.prev_block = block->RO.prev_block;
        msg->H.merkle_root = block->RO.merkle_root;
        msg->H.timestamp = block->RO.timestamp;
        msg->H.bits = block->RO.bits;
        msg->H.nonce = block->RO.nonce;
        msg->txn_count = 0;//block->RO.txn_count;
        len = iguana_rwblock(myinfo,coin->symbol,coin->chain->zcash,coin->chain->auxpow,coin->chain->hashalgo,1,&hash2,serialized,&zmsg,IGUANA_MAXPACKETSIZE*2);
    }
    init_hexbytes_noT(hexstr,serialized,len);
    jaddstr(json,"blockheader",hexstr);
    if ( txidsflag != 0 )
    {
        array = cJSON_CreateArray();
        for (i=0; i<block->RO.txn_count; i++)
        {
            if ( (tx= iguana_blocktx(coin,&T,block,i)) != 0 )
                jaddistr(array,bits256_str(str,tx->txid));
        }
        jadd(json,"tx",array);
        //printf("add txids[%d]\n",block->txn_count);
    }
    if ( (size= iguana_peerblockrequest(myinfo,coin,coin->blockspace,coin->blockspacesize,0,block->RO.hash2,0)) < 0 )
        jaddstr(json,"error","couldnt generate raw bytes for block");
    else jaddnum(json,"size",size);
    return(json);
}
Beispiel #14
0
cJSON *cJSON_CreateFloatArray(float *numbers,int count)			{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Beispiel #15
0
cJSON *cJSON_CreateStringArray(const char **strings,int count)	{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Beispiel #16
0
cJSON *cJSON_CreateFloatArray(const float *numbers,int count)	{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Beispiel #17
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);

}
Beispiel #18
0
// This is a function called back when a homegateway is discovered
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
        OCClientResponse * clientResponse)
{

    char resource_addr[64] = {0};
    char register_addr[64] = {0};
    char stringAddress[DEV_ADDR_SIZE_MAX];
    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
    {
        Serial.println("gw discovered correctly");
    }

    if (clientResponse)
    {
        if (clientResponse->result == OC_STACK_OK)
        {
            Serial.println("clientResponse ok");

            OCStackResult ret;
            OCDoHandle handle;
            cJSON *root = cJSON_CreateObject();
            cJSON *rep = cJSON_CreateArray();
            cJSON *format_rep, *format;
            char *jsonPayload;
            IPAddress ip = Ethernet.localIP();

		
            snprintf(resource_addr, sizeof(resource_addr), "coap://%d.%d.%d.%d:5683/oc/core?rt=com.intel", ip[0], ip[1], ip[2], ip[3]);
            cJSON_AddItemToObject(root, "oc", rep);
            cJSON_AddItemToArray(rep, format_rep=cJSON_CreateObject());
            cJSON_AddItemToObject(format_rep, "rep", format=cJSON_CreateObject());
            cJSON_AddStringToObject(format, "name", (char *)"fan");
            cJSON_AddStringToObject(format, "address", (char *)resource_addr);
            jsonPayload = cJSON_Print(root);
            cJSON_Delete(root);

            Serial.println(jsonPayload);
            OCCallbackData cbData;
            cbData.cb = registerReqCB;
            cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
            cbData.cd = NULL;
	    
            uint8_t a,b,c,d;
            OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d);
            snprintf(register_addr, sizeof(register_addr), "coap://%d.%d.%d.%d:5683/gw/sensor", a, b, c, d);
            ret = OCDoResource(&handle, OC_REST_PUT, register_addr, 0,
                       jsonPayload, OC_IPV4,
                       OC_LOW_QOS, &cbData, NULL, 0);

           if (ret != OC_STACK_OK)
           {
               Serial.println("register error");
               Serial.println(ret);
           }

           free(jsonPayload);
        }
    }

    return OC_STACK_DELETE_TRANSACTION;
}