Пример #1
0
static struct watchman_query_result *
watchman_query_json(struct watchman_connection *conn,
                    json_t *query,
                    struct timeval *timeout,
                    struct watchman_error *error)
{
    struct watchman_query_result *result = NULL;
    struct watchman_query_result *res = NULL;

    if (watchman_send(conn, query, error)) {
        return NULL;
    }
    /* parse the result */
    json_t *obj = watchman_read_with_timeout(conn, timeout, error);
    if (!obj) {
        return NULL;
    }
    JSON_ASSERT(json_is_object, obj, "Failed to send watchman query %s");

    json_t *jerror = json_object_get(obj, "error");
    if (jerror) {
        watchman_err(error, WATCHMAN_ERR_WATCHMAN_REPORTED,
                     "Error result from watchman: %s",
                     json_string_value(jerror));
        goto done;
    }

    res = calloc(1, sizeof(*res));

    json_t *files = json_object_get(obj, "files");
    JSON_ASSERT(json_is_array, files, "Bad files %s");

    int nr = json_array_size(files);
    res->stats = calloc(nr, sizeof(*res->stats));

    int i;
    for (i = 0; i < nr; ++i) {
        struct watchman_stat *stat = res->stats + i;
        json_t *statobj = json_array_get(files, i);
        if (json_is_string(statobj)) {
            /* then hopefully we only requested names */
            stat->name = strdup(json_string_value(statobj));
            res->nr++;
            continue;
        }

        JSON_ASSERT(json_is_object, statobj, "must be object: %s");

        json_t *name = json_object_get(statobj, "name");
        JSON_ASSERT(json_is_string, name, "name must be string: %s");
        stat->name = strdup(json_string_value(name));

        WRITE_BOOL_STAT(stat, statobj, exists);
        WRITE_INT_STAT(stat, statobj, ctime);
        WRITE_INT_STAT(stat, statobj, ctime_ms);
        WRITE_INT_STAT(stat, statobj, ctime_us);
        WRITE_INT_STAT(stat, statobj, ctime_ns);
        WRITE_INT_STAT(stat, statobj, dev);
        WRITE_INT_STAT(stat, statobj, gid);
        WRITE_INT_STAT(stat, statobj, ino);
        WRITE_INT_STAT(stat, statobj, mode);
        WRITE_INT_STAT(stat, statobj, mtime);
        WRITE_INT_STAT(stat, statobj, mtime_ms);
        WRITE_INT_STAT(stat, statobj, mtime_us);
        WRITE_INT_STAT(stat, statobj, mtime_ns);
        WRITE_INT_STAT(stat, statobj, nlink);
        WRITE_INT_STAT(stat, statobj, size);
        WRITE_INT_STAT(stat, statobj, uid);

        WRITE_STR_STAT(stat, statobj, cclock);
        WRITE_STR_STAT(stat, statobj, oclock);

        WRITE_FLOAT_STAT(stat, statobj, ctime_f);
        WRITE_FLOAT_STAT(stat, statobj, mtime_f);

        /* the one we have to do manually because we don't
         * want to use the name "new" */
        json_t *newer = json_object_get(statobj, "new");
        if (newer) {
            stat->newer = json_is_true(newer);
        }
        res->nr++;
    }

    json_t *version = json_object_get(obj, "version");
    JSON_ASSERT(json_is_string, version, "Bad version %s");
    res->version = strdup(json_string_value(version));

    json_t *clock = json_object_get(obj, "clock");
    JSON_ASSERT(json_is_string, clock, "Bad clock %s");
    res->clock = strdup(json_string_value(clock));

    json_t *fresh = json_object_get(obj, "is_fresh_instance");
    JSON_ASSERT(json_is_boolean, fresh, "Bad is_fresh_instance %s");
    res->is_fresh_instance = json_is_true(fresh);

    result = res;
    res = NULL;
done:
    if (res) {
        watchman_free_query_result(res);
    }
    json_decref(obj);
    return result;
}
Пример #2
0
void Skin::load()
{
	json_error_t error;
	json_t *root = json_load_file(filename.c_str(), 0, &error);

	auto getString = [root](const json_t* obj, const char* str) -> std::string
	{
		json_t *value = json_object_get(obj, str);
		if (!json_is_string(value))
			throw std::runtime_error("error: " + std::string(str) + "was expected to be a string");
		return std::string(json_string_value(value));

	};


	auto getColor = [root](const json_t* obj, const char* str) -> Color
	{
		Color result;
		json_t *value = json_object_get(obj, str);

		if (!json_is_array(value))
			throw std::runtime_error("error: " + std::string(str) + "was expected to be an arry");

		for (int i = 0; i < json_array_size(value); i++)
			result[i] = json_integer_value(json_array_get(value, i)); // this should check for error

		return result;

	};

	if (!root)
		throw std::runtime_error("error: on line " + std::to_string(error.line) + ": " + std::string(error.text));

	if (!json_is_array(root))
		throw std::runtime_error("error: root is not an array");


	for (int i = 0; i < json_array_size(root); i++)
	{
		json_t *data = json_array_get(root, i);

		if (!json_is_object(data))
			throw std::runtime_error("error: entry at " + std::to_string(i + 1) + " was expected to be a object");


		Entry entry;

		entry.name = getString(data, "name");
		entry.bgColor = getColor(data, "bgColor");
		entry.fontColor = getColor(data, "fontColor");


		/*
		json_t *layers = json_object_get(data, "layers");
		if (!json_is_array(layers))
			throw std::runtime_error("error: layers is not an array");

		for (int i = 0; i < json_array_size(layers); i++)
		{
			json_t *layer = json_array_get(layers, i);
		}
		*/
	}
}
Пример #3
0
uint8_t _main_flight(json_t *data) {
    json_t *_source, *_destination, *_set_start, *_set_end, *_pilot, *_task;
    const char *source;
    char *destination, *pilot;
    size_t set_start, set_end;

    _source = json_object_get(data, "source");
    _destination = json_object_get(data, "destination");
    _set_start = json_object_get(data, "set_start");
    _set_end = json_object_get(data, "set_end");
    _pilot = json_object_get(data, "pilot");
    _task = json_object_get(data, "task");

    if (!json_is_string(_source)) {
        fprintf(stderr, "{\"error\": \"No source file provided\"}");
        return 0;
    }

    source = json_string_value(_source);

    if (!json_is_string(_destination)) {
        destination = calloc(strlen(source) + 1, sizeof(char));
        strcpy(destination, source);
        dirname(destination);
    } else {
        destination = (char *) json_string_value(_destination);
    }

    if (!json_is_string(_pilot)) {
        pilot = (char *) json_string_value(_pilot);
    }

    char out_file_1[strlen(destination) + 20];
    char out_file_2[strlen(destination) + 20];
    char out_file_3[strlen(destination) + 20];
    char out_file_4[strlen(destination) + 20];
    sprintf(out_file_1, "%s%s", destination, "/track.js");
    sprintf(out_file_2, "%s%s", destination, "/track.kml");
    sprintf(out_file_3, "%s%s", destination, "/track_earth.kml");
    sprintf(out_file_4, "%s%s", destination, "/track_split.kml");

    char *igc_file = load_file(source);
    if (igc_file != NULL) {
        coordinate_set_t *set = NEW(coordinate_set_t, 1);
        coordinate_set_init(set);

        task_t *read_task = NULL;
        coordinate_set_parse_igc(set, igc_file, &read_task);

        size_t initial_length = set->length;
        coordinate_set_trim(set);
        coordinate_set_repair(set);
        coordinate_set_simplify(set, 1500);
        coordinate_set_extrema(set);

        json_t *_section = json_object_get(data, "section");
        size_t section;
        if (_section) {
            section = json_integer_value(_section);
            coordinate_set_select_section(set, section, 0);
        }

        if (set->subset_count == 1) {

            task_t *task = parse_task(_task);
            if (!task) {
                task = read_task;
            }

            distance_map_t *map = NEW(distance_map_t, 1);
            distance_map_init(map, set);

            char *ids;

            printf("{");
            printf("\"validated\": %d,", validate_file(source));
            printf("\"total_points\": %d,", initial_length);
            printf("\"sets\": %d,", set->subset_count);
            printf("\"date\": \"%04d-%02d-%02d\",", set->year, set->month, set->day);
            printf("\"start_time\": %d,", set->first->timestamp);
            printf("\"duration\": %d,", set->last->timestamp - set->first->timestamp);
            printf("\"points\": %d,", set->length);
            printf("\"stats\": {", set->length);
            printf("\"height\" : {\"min\": %d, \"max\": %d},", set->first->ele, set->last->ele);
            printf("\"speed\" : {\"min\": %d, \"max\": %d},", set->first->speed, set->last->speed);
            printf("\"climb_rate\" : {\"min\": %d, \"max\": %d}", set->first->climb_rate, set->last->climb_rate);
            printf("},");
            printf("\"task\": {", set->length);

            task_t *od, *or, *tr, *ft;

            od = distance_map_score_open_distance_3tp(map);
            or = distance_map_score_out_and_return(map);
            tr = distance_map_score_triangle(map, 0.28);
            ft = distance_map_score_triangle(map, 0);

            format_task(od, "open_distance", OPEN_DISTANCE);
            printf(",");

            format_task(or, "out_and_return", OUT_AND_RETURN);
            printf(",");

            format_task(tr, "triangle", TRIANGLE);
            printf(",");

            format_task(ft, "flat_triangle", FLAT_TRIANGLE);

            if (task) {
                printf(",");
                format_task(task, "declared", task->type);
                printf(", \"complete\": %d", task_completes_task(task, set));
            }

            printf("}, \"output\": {\"js\": \"%s\",\"kml\": \"%s\",\"earth\": \"%s\"}", out_file_1, out_file_2, out_file_3);

            formatter_t *formatter;

            formatter = NEW(formatter_t, 1);
            formatter_js_init(formatter, set, 1, od, or, tr, ft);
            formatter_js_output(formatter, out_file_1);
            free(formatter);

            formatter = NEW(formatter_t, 1);
            formatter_kml_init(formatter, set, pilot ?: "N/A", od, or, tr, ft, task);
            formatter_kml_output(formatter, out_file_2);
            free(formatter);

            formatter = NEW(formatter_t, 1);
            formatter_kml_earth_init(formatter, set, pilot ?: "N/A", od, or, tr, ft, task);
            formatter_kml_earth_output(formatter, out_file_3);
            free(formatter);

            printf("}");

            if (od) {
                task_deinit(od);
            }
            if (or) {
                task_deinit(or);
            }
            if (tr) {
                task_deinit(tr);
            }
            distance_map_deinit(map);

        } else {
Пример #4
0
static void * ps_gstsink_handler (void * data) {
	PS_LOG (LOG_VERB, "Joining GstSink handler thread..\n");
	ps_gstsink_message * msg = NULL;
	int error_code = 0;
	char * error_cause = g_malloc0(1024);
	if (error_cause == NULL) {
		PS_LOG(LOG_FATAL,"Memory error!\n");
		return NULL;
	}
	
	json_t * root = NULL;
	while (g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		msg = g_async_queue_pop(messages);
		if (msg == NULL) continue;
		if (msg == &exit_message) break;
		if (msg->handle == NULL) {
			ps_gstsink_message_free(msg);
			continue;
		}
		ps_gstsink_session * session = NULL;
		ps_mutex_lock (&sessions_mutex);
		if (g_hash_table_lookup(sessions, msg->handle) != NULL) {
			session = (ps_gstsink_session *)msg->handle->plugin_handle;
		}
		ps_mutex_unlock (&sessions_mutex);
		if (!session) {
			PS_LOG (LOG_ERR, "no session associated with this handle...\n");
			ps_gstsink_message_free (msg);
			continue;
		}
		if (session->destroyed) {
			ps_gstsink_message_free (msg);
			continue;
		}
		
		error_code = 0;
		root = NULL;
		if (msg->message == NULL) {
			PS_LOG (LOG_ERR, "No message??\n");
			error_code = PS_GSTSINK_ERROR_NO_MESSAGE;
			g_snprintf(error_cause, 512, "%s","No Message??");
			goto error;
		}
		root = msg->message;
		json_t * request = json_object_get(root, "request");
		if (!request) {
			PS_LOG (LOG_ERR, "Missing element (request)\n");
			error_code = PS_GSTSINK_ERROR_MISSING_ELEMENT;
			g_snprintf (error_cause, 512, "Missing element (request)");
			goto error;
		}
		if (!json_is_string(request)) {
			PS_LOG (LOG_ERR, "Invalid element (request must be a string)\n");
			error_code = PS_GSTSINK_ERROR_MISSING_ELEMENT;
			g_snprintf (error_cause, 512, "Invalid element (request must be string)");
			goto error;
		}
		const char * request_text = json_string_value (request);
		json_t * result = NULL;
		//const char * sdp_type = NULL;
		char * sdp = NULL;
		
		if(!strcasecmp(request_text, "start")) {
			if(!msg->sdp) {
				PS_LOG(LOG_ERR, "Missing SDP offer\n");
				error_code = PS_GSTSINK_ERROR_MISSING_ELEMENT;
				g_snprintf(error_cause, 512, "Missing SDP offer");
				goto error;
			}
			
			guint64 id = 100;
			if(strstr(msg->sdp, "m=audio")) {
				PS_LOG (LOG_VERB, "Audio requested\n");
			}
			if(strstr(msg->sdp, "m=video")) {
				PS_LOG (LOG_VERB, "Video requested\n");
			}
			session->recorder = TRUE;
			/* We need to prepare an answer */
			int opus_pt = 0, vp8_pt = 0;
			char * opus_dir = NULL;
			char * vp8_dir = NULL;
			opus_dir = ps_get_opus_dir (msg->sdp);
			vp8_dir = ps_get_vp8_dir (msg->sdp);
			PS_LOG (LOG_VERB, "Audio direction: %s, Video direction: %s\n", opus_dir, vp8_dir);
			opus_pt = ps_get_opus_pt(msg->sdp);
			PS_LOG(LOG_VERB, "Opus payload type is %d\n", opus_pt);
			vp8_pt = ps_get_vp8_pt(msg->sdp);
			PS_LOG(LOG_VERB, "VP8 payload type is %d\n", vp8_pt);
			char sdptemp[1024], audio_mline[256], video_mline[512];
			if(opus_pt > 0 && opus_dir != NULL) {
				if (!strcasecmp(opus_dir, "sendrecv") || !strcasecmp(opus_dir, "sendonly")){
					g_snprintf(audio_mline, 256, sdp_a_template,
						opus_pt,						/* Opus payload type */
						"recvonly",						/* FIXME to check a= line */
						opus_pt); 						/* Opus payload type */
					session->play_audio = TRUE;
				} else {
					g_snprintf(audio_mline, 256, sdp_a_template,
						opus_pt,						/* Opus payload type */
						"inactive",						/* FIXME to check a= line */
						opus_pt); 						/* Opus payload type */
				}
			} else {
				audio_mline[0] = '\0';
			}
			if(vp8_pt > 0 && vp8_dir != NULL) {
				if (!strcasecmp(vp8_dir, "sendrecv") || !strcasecmp(vp8_dir, "sendonly")){
					g_snprintf(video_mline, 512, sdp_v_template,
						vp8_pt,							/* VP8 payload type */
						"recvonly",						/* FIXME to check a= line */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt); 						/* VP8 payload type */
					session->play_video = TRUE;
				} else {
					g_snprintf(video_mline, 512, sdp_v_template,
						vp8_pt,							/* VP8 payload type */
						"inactive",						/* FIXME to check a= line */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt, 						/* VP8 payload type */
						vp8_pt); 						/* VP8 payload type */
				}
			} else {
				video_mline[0] = '\0';
			}
			g_snprintf(sdptemp, 1024, sdp_template,
				ps_get_real_time(),			/* We need current time here */
				ps_get_real_time(),			/* We need current time here */
				"PacketServo",		/* Playout session */
				audio_mline,					/* Audio m-line, if any */
				video_mline);					/* Video m-line, if any */
			sdp = g_strdup(sdptemp);
			PS_LOG(LOG_VERB, "Going to answer this SDP:\n%s\n", sdp);
			/* Done! */
			result = json_object();
			json_object_set_new(result, "status", json_string("recording"));
			json_object_set_new(result, "id", json_integer(id));
		} else if (!strcasecmp(request_text,"stop")) {
			session->active = FALSE;
			/* Set gst pipeline to paused or set to null? */
			/* session->aplayer?; session->vplayer?; */
			session->recorder = FALSE;
			/* Done */
			result = json_object();
			json_object_set_new(result, "status", json_string("stopped"));
			//gateway->close_pc(session->handle);
		} else {
			PS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
			error_code = PS_GSTSINK_ERROR_INVALID_REQUEST;
			g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
			goto error;
		}
		
		/* Any SDP to handle? */
		if (msg->sdp) {
			session->firefox = strstr(msg->sdp, "Mozilla") ? TRUE : FALSE;
			PS_LOG (LOG_VERB, "This is involving negotiation (%s) as well: \n%s\n", msg->sdp_type, msg->sdp);
		}
		
		/* Prepare JSON event */
		json_t * event = json_object();
		json_object_set_new (event, "recordplay", json_string("event"));
		if (result != NULL) json_object_set_new (event, "result", result);
		char * event_text = json_dumps (event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref (event);
		PS_LOG (LOG_VERB, "Pushing event: %s\n",event_text);
		if(!sdp) {
			int ret = gateway->push_event(msg->handle, &ps_gstsink_plugin, msg->transaction, event_text, NULL, NULL);
			PS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
		} else {
			const char *type = session->recorder ? "answer" : "offer";
			/* How long will the gateway take to push the event? */
			g_atomic_int_set(&session->hangingup, 0);
			gint64 start = ps_get_monotonic_time();
			int res = gateway->push_event(msg->handle, &ps_gstsink_plugin, msg->transaction, event_text, type, sdp);
			PS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
				res, ps_get_monotonic_time()-start);
			g_free(sdp);
		}
		
		g_free (event_text);
		ps_gstsink_message_free (msg);
		continue;
		
error:
		{
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "recordplay", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
			json_decref(event);
			PS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
			int ret = gateway->push_event(msg->handle, &ps_gstsink_plugin, msg->transaction, event_text, NULL, NULL);
			PS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			g_free(event_text);
			ps_gstsink_message_free(msg);
		}
		
	}
	g_free(error_cause);
	PS_LOG (LOG_VERB, "Leaving GstSink handler thread..\n");
	return NULL;
}
/* Thread to handle incoming messages */
static void *janus_source_handler(void *data) {
	JANUS_LOG(LOG_VERB, "Joining SourcePlugin handler thread\n");
	janus_source_message *msg = NULL;
	int error_code = 0;
	char *error_cause = g_malloc0(512);
	json_t *root = NULL;
	while (g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		msg = g_async_queue_pop(messages);
		if (msg == NULL)
			continue;
		if (msg == &exit_message)
			break;
		if (msg->handle == NULL) {
			janus_source_message_free(msg);
			continue;
		}
		janus_source_session *session = NULL;
		janus_mutex_lock(&sessions_mutex);
		if (g_hash_table_lookup(sessions, msg->handle) != NULL) {
			session = (janus_source_session *)msg->handle->plugin_handle;
		}
		janus_mutex_unlock(&sessions_mutex);
		if (!session) {
			JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
			janus_source_message_free(msg);
			continue;
		}
		if (session->destroyed) {
			janus_source_message_free(msg);
			continue;
		}
		/* Handle request */
		error_code = 0;
		root = msg->message;
		if (msg->message == NULL) {
			JANUS_LOG(LOG_ERR, "No message??\n");
			error_code = JANUS_SOURCE_ERROR_NO_MESSAGE;
			g_snprintf(error_cause, 512, "%s", "No message??");
			goto error;
		}
		if (!json_is_object(root)) {
			JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: not an object");
			goto error;
		}
		/* Parse request */
		const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
		const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
		json_t *audio = json_object_get(root, "audio");
		if (audio && !json_is_boolean(audio)) {
			JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
			goto error;
		}
		json_t *video = json_object_get(root, "video");
		if (video && !json_is_boolean(video)) {
			JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
			goto error;
		}
		json_t *bitrate = json_object_get(root, "bitrate");
		if (bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
			JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
			goto error;
		}
		json_t *record = json_object_get(root, "record");
		if (record && !json_is_boolean(record)) {
			JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
			goto error;
		}
		json_t *recfile = json_object_get(root, "filename");
		if (recfile && !json_is_string(recfile)) {
			JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
			goto error;
		}
		
		json_t *id = json_object_get(root, "id");
		if(id && !json_is_string(id)) {
				JANUS_LOG(LOG_ERR, "Invalid element (id should be a string)\n");
				error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
				g_snprintf(error_cause, 512, "Invalid value (id should be positive string)");
				goto error;
		}
		/* Enforce request */
		if (audio) {
			session->audio_active = json_is_true(audio);
			JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false");
		}
		if (video) {
			if (!session->video_active && json_is_true(video)) {
				/* Send a PLI */
				JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n");
				char buf[12];
				memset(buf, 0, 12);
				janus_rtcp_pli((char *)&buf, 12);
				gateway->relay_rtcp(session->handle, 1, buf, 12);
			}
			session->video_active = json_is_true(video);
			JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false");
		}
		if (bitrate) {
			session->bitrate = json_integer_value(bitrate);
			JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate);
			if (session->bitrate > 0) {
				/* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */
				char buf[24];
				memset(buf, 0, 24);
				janus_rtcp_remb((char *)&buf, 24, session->bitrate);
				JANUS_LOG(LOG_VERB, "Sending REMB\n");
				gateway->relay_rtcp(session->handle, 1, buf, 24);
				/* FIXME How should we handle a subsequent "no limit" bitrate? */
			}
		}
		if(id) {
			session->id = g_strdup(json_string_value(id));			
		}


		if (!audio && !video && !bitrate && !record && !id && !msg_sdp) {
			JANUS_LOG(LOG_ERR, "No supported attributes (audio, video, bitrate, record, id, jsep) found\n");
			error_code = JANUS_SOURCE_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Message error: no supported attributes (audio, video, bitrate, record, id, jsep) found");
			goto error;
		}

		/* Prepare JSON event */
		json_t *event = json_object();
		json_object_set_new(event, "source", json_string("event"));
		json_object_set_new(event, "result", json_string("ok"));
		if(!msg_sdp) {
			int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			json_decref(event);
		}
		else {
			/* Forward the same offer to the gateway, to start the source plugin */
			const char *type = NULL;
			if (!strcasecmp(msg_sdp_type, "offer"))
				type = "answer";
			if (!strcasecmp(msg_sdp_type, "answer"))
				type = "offer";
			/* Any media direction that needs to be fixed? */
			char *sdp = g_strdup(msg_sdp);
			if (strstr(sdp, "a=recvonly")) {
				/* Turn recvonly to inactive, as we simply bounce media back */
				sdp = janus_string_replace(sdp, "a=recvonly", "a=inactive");
			}
			else if (strstr(sdp, "a=sendonly")) {
				/* Turn sendonly to recvonly */
				sdp = janus_string_replace(sdp, "a=sendonly", "a=recvonly");
				/* FIXME We should also actually not echo this media back, though... */
			}
			/* Make also sure we get rid of ULPfec, red, etc. */
			if (strstr(sdp, "ulpfec")) {
				/* FIXME This really needs some better code */
				sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:97 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:97 apt=101\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:98 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:98 apt=116\r\n", "");
				sdp = janus_string_replace(sdp, " 116", "");
				sdp = janus_string_replace(sdp, " 117", "");
				sdp = janus_string_replace(sdp, " 96", "");
				sdp = janus_string_replace(sdp, " 97", "");
				sdp = janus_string_replace(sdp, " 98", "");
			}
			json_t *jsep = json_pack("{ssss}", "type", type, "sdp", sdp);
			sdp = janus_source_do_codec_negotiation(session, sdp);
			
			/* How long will the gateway take to push the event? */
			g_atomic_int_set(&session->hangingup, 0);
			gint64 start = janus_get_monotonic_time();
			int res = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, jsep);
			JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
				res, janus_get_monotonic_time() - start);
			g_free(sdp);
			/* We don't need the event and jsep anymore */
			json_decref(event);
			json_decref(jsep);
		}
		janus_source_message_free(msg);
		continue;

	error:
		{
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "source", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			int ret = gateway->push_event(msg->handle, &janus_source_plugin, msg->transaction, event, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			janus_source_message_free(msg);
			/* We don't need the event anymore */
			json_decref(event);
		}
	}
	g_free(error_cause);
	JANUS_LOG(LOG_VERB, "Leaving SourcePlugin handler thread\n");
	return NULL;
}
Пример #6
0
/* Call the simple functions not covered by other tests of the public API */
static void run_tests()
{
    json_t *value;

    value = json_boolean(1);
    if(!json_is_true(value))
        fail("json_boolean(1) failed");
    json_decref(value);

    value = json_boolean(-123);
    if(!json_is_true(value))
        fail("json_boolean(-123) failed");
    json_decref(value);

    value = json_boolean(0);
    if(!json_is_false(value))
        fail("json_boolean(0) failed");
    if(json_boolean_value(value) != 0)
        fail("json_boolean_value failed");
    json_decref(value);


    value = json_integer(1);
    if(json_typeof(value) != JSON_INTEGER)
        fail("json_typeof failed");

    if(json_is_object(value))
        fail("json_is_object failed");

    if(json_is_array(value))
        fail("json_is_array failed");

    if(json_is_string(value))
        fail("json_is_string failed");

    if(!json_is_integer(value))
        fail("json_is_integer failed");

    if(json_is_real(value))
        fail("json_is_real failed");

    if(!json_is_number(value))
        fail("json_is_number failed");

    if(json_is_true(value))
        fail("json_is_true failed");

    if(json_is_false(value))
        fail("json_is_false failed");

    if(json_is_boolean(value))
        fail("json_is_boolean failed");

    if(json_is_null(value))
        fail("json_is_null failed");

    json_decref(value);


    value = json_string("foo");
    if(!value)
        fail("json_string failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set(value, "barr"))
        fail("json_string_set failed");
    if(strcmp(json_string_value(value), "barr"))
        fail("invalid string value");
    if (json_string_length(value) != 4)
        fail("invalid string length");

    if(json_string_setn(value, "hi\0ho", 5))
        fail("json_string_set failed");
    if(memcmp(json_string_value(value), "hi\0ho\0", 6))
        fail("invalid string value");
    if (json_string_length(value) != 5)
        fail("invalid string length");

    json_decref(value);

    value = json_string(NULL);
    if(value)
        fail("json_string(NULL) failed");

    /* invalid UTF-8  */
    value = json_string("a\xefz");
    if(value)
        fail("json_string(<invalid utf-8>) failed");

    value = json_string_nocheck("foo");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set_nocheck(value, "barr"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "barr"))
        fail("invalid string value");
    if (json_string_length(value) != 4)
        fail("invalid string length");

    if(json_string_setn_nocheck(value, "hi\0ho", 5))
        fail("json_string_set failed");
    if(memcmp(json_string_value(value), "hi\0ho\0", 6))
        fail("invalid string value");
    if (json_string_length(value) != 5)
        fail("invalid string length");

    json_decref(value);

    /* invalid UTF-8 */
    value = json_string_nocheck("qu\xff");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "qu\xff"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    if(json_string_set_nocheck(value, "\xfd\xfe\xff"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "\xfd\xfe\xff"))
        fail("invalid string value");
    if (json_string_length(value) != 3)
        fail("invalid string length");

    json_decref(value);


    value = json_integer(123);
    if(!value)
        fail("json_integer failed");
    if(json_integer_value(value) != 123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.0)
        fail("invalid number value");

    if(json_integer_set(value, 321))
        fail("json_integer_set failed");
    if(json_integer_value(value) != 321)
        fail("invalid integer value");
    if(json_number_value(value) != 321.0)
        fail("invalid number value");

    json_decref(value);

    value = json_real(123.123);
    if(!value)
        fail("json_real failed");
    if(json_real_value(value) != 123.123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.123)
        fail("invalid number value");

    if(json_real_set(value, 321.321))
        fail("json_real_set failed");
    if(json_real_value(value) != 321.321)
        fail("invalid real value");
    if(json_number_value(value) != 321.321)
        fail("invalid number value");

    json_decref(value);

    value = json_true();
    if(!value)
        fail("json_true failed");
    json_decref(value);

    value = json_false();
    if(!value)
        fail("json_false failed");
    json_decref(value);

    value = json_null();
    if(!value)
        fail("json_null failed");
    json_decref(value);

    /* Test reference counting on singletons (true, false, null) */
    value = json_true();
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");

    value = json_false();
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");

    value = json_null();
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
}
Пример #7
0
static void runtest_keys_valid(const char *base_fn)
{
	char *fn = NULL;

	fn = test_filename(base_fn);
	json_t *data = read_json(fn);
	assert(json_is_array(data));

	size_t n_tests = json_array_size(data);
	unsigned int i;

	for (i = 0; i < n_tests; i++) {
		json_t *inner;

		inner = json_array_get(data, i);
		assert(json_is_array(inner));

		json_t *j_base58 = json_array_get(inner, 0);
		json_t *j_payload = json_array_get(inner, 1);
		assert(json_is_string(j_base58));
		assert(json_is_string(j_payload));

		json_t *j_meta = json_array_get(inner, 2);
		assert(json_is_object(j_meta));

		json_t *j_addrtype = json_object_get(j_meta, "addrType");
		assert(!j_addrtype || json_is_string(j_addrtype));

		json_t *j_compress = json_object_get(j_meta, "isCompressed");
		assert(!j_compress || json_is_true(j_compress) ||
		       json_is_false(j_compress));

		bool is_privkey = json_is_true(json_object_get(j_meta, "isPrivkey"));
		bool is_testnet = json_is_true(json_object_get(j_meta, "isTestnet"));

		if (is_privkey) {
			test_privkey_valid_enc(
				json_string_value(j_base58),
				hex2str(json_string_value(j_payload)),
				json_is_true(j_compress),
				is_testnet);
			test_privkey_valid_dec(
				json_string_value(j_base58),
				hex2str(json_string_value(j_payload)),
				json_is_true(j_compress),
				is_testnet);
		} else {
			test_pubkey_valid_enc(
				json_string_value(j_base58),
				hex2str(json_string_value(j_payload)),
				json_string_value(j_addrtype),
				is_testnet);
			test_pubkey_valid_dec(
				json_string_value(j_base58),
				hex2str(json_string_value(j_payload)),
				json_string_value(j_addrtype),
				is_testnet);
		}
	}

	free(fn);
	json_decref(data);
}
Пример #8
0
/* Thread to handle incoming messages */
static void *janus_echotest_handler(void *data) {
	JANUS_LOG(LOG_VERB, "Joining EchoTest handler thread\n");
	janus_echotest_message *msg = NULL;
	int error_code = 0;
	char *error_cause = g_malloc0(512);
	if(error_cause == NULL) {
		JANUS_LOG(LOG_FATAL, "Memory error!\n");
		return NULL;
	}
	json_t *root = NULL;
	while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		msg = g_async_queue_pop(messages);
		if(msg == NULL)
			continue;
		if(msg == &exit_message)
			break;
		if(msg->handle == NULL) {
			janus_echotest_message_free(msg);
			continue;
		}
		janus_echotest_session *session = NULL;
		janus_mutex_lock(&sessions_mutex);
		if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
			session = (janus_echotest_session *)msg->handle->plugin_handle;
		}
		janus_mutex_unlock(&sessions_mutex);
		if(!session) {
			JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
			janus_echotest_message_free(msg);
			continue;
		}
		if(session->destroyed) {
			janus_echotest_message_free(msg);
			continue;
		}
		/* Handle request */
		error_code = 0;
		root = NULL;
		JANUS_LOG(LOG_VERB, "Handling message: %s\n", msg->message);
		if(msg->message == NULL) {
			JANUS_LOG(LOG_ERR, "No message??\n");
			error_code = JANUS_ECHOTEST_ERROR_NO_MESSAGE;
			g_snprintf(error_cause, 512, "%s", "No message??");
			goto error;
		}
		json_error_t error;
		root = json_loads(msg->message, 0, &error);
		if(!root) {
			JANUS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
			error_code = JANUS_ECHOTEST_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
			goto error;
		}
		if(!json_is_object(root)) {
			JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_JSON;
			g_snprintf(error_cause, 512, "JSON error: not an object");
			goto error;
		}
		/* Parse request */
		json_t *audio = json_object_get(root, "audio");
		if(audio && !json_is_boolean(audio)) {
			JANUS_LOG(LOG_ERR, "Invalid element (audio should be a boolean)\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (audio should be a boolean)");
			goto error;
		}
		json_t *video = json_object_get(root, "video");
		if(video && !json_is_boolean(video)) {
			JANUS_LOG(LOG_ERR, "Invalid element (video should be a boolean)\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (video should be a boolean)");
			goto error;
		}
		json_t *bitrate = json_object_get(root, "bitrate");
		if(bitrate && (!json_is_integer(bitrate) || json_integer_value(bitrate) < 0)) {
			JANUS_LOG(LOG_ERR, "Invalid element (bitrate should be a positive integer)\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (bitrate should be a positive integer)");
			goto error;
		}
		json_t *record = json_object_get(root, "record");
		if(record && !json_is_boolean(record)) {
			JANUS_LOG(LOG_ERR, "Invalid element (record should be a boolean)\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (record should be a boolean)");
			goto error;
		}
		json_t *recfile = json_object_get(root, "filename");
		if(recfile && !json_is_string(recfile)) {
			JANUS_LOG(LOG_ERR, "Invalid element (filename should be a string)\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Invalid value (filename should be a string)");
			goto error;
		}
		/* Enforce request */
		if(audio) {
			session->audio_active = json_is_true(audio);
			JANUS_LOG(LOG_VERB, "Setting audio property: %s\n", session->audio_active ? "true" : "false");
		}
		if(video) {
			if(!session->video_active && json_is_true(video)) {
				/* Send a PLI */
				JANUS_LOG(LOG_VERB, "Just (re-)enabled video, sending a PLI to recover it\n");
				char buf[12];
				memset(buf, 0, 12);
				janus_rtcp_pli((char *)&buf, 12);
				gateway->relay_rtcp(session->handle, 1, buf, 12);
			}
			session->video_active = json_is_true(video);
			JANUS_LOG(LOG_VERB, "Setting video property: %s\n", session->video_active ? "true" : "false");
		}
		if(bitrate) {
			session->bitrate = json_integer_value(bitrate);
			JANUS_LOG(LOG_VERB, "Setting video bitrate: %"SCNu64"\n", session->bitrate);
			if(session->bitrate > 0) {
				/* FIXME Generate a new REMB (especially useful for Firefox, which doesn't send any we can cap later) */
				char buf[24];
				memset(buf, 0, 24);
				janus_rtcp_remb((char *)&buf, 24, session->bitrate);
				JANUS_LOG(LOG_VERB, "Sending REMB\n");
				gateway->relay_rtcp(session->handle, 1, buf, 24);
				/* FIXME How should we handle a subsequent "no limit" bitrate? */
			}
		}
		if(record) {
			if(msg->sdp) {
				session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
				session->has_video = (strstr(msg->sdp, "m=video") != NULL);
			}
			gboolean recording = json_is_true(record);
			const char *recording_base = json_string_value(recfile);
			JANUS_LOG(LOG_VERB, "Recording %s (base filename: %s)\n", recording ? "enabled" : "disabled", recording_base ? recording_base : "not provided");
			if(!recording) {
				/* Not recording (anymore?) */
				if(session->arc) {
					janus_recorder_close(session->arc);
					JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
					janus_recorder_free(session->arc);
				}
				session->arc = NULL;
				if(session->vrc) {
					janus_recorder_close(session->vrc);
					JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
					janus_recorder_free(session->vrc);
				}
				session->vrc = NULL;
			} else {
				/* We've started recording, send a PLI and go on */
				char filename[255];
				gint64 now = janus_get_real_time();
				if(session->has_audio) {
					/* FIXME We assume we're recording Opus, here */
					memset(filename, 0, 255);
					if(recording_base) {
						/* Use the filename and path we have been provided */
						g_snprintf(filename, 255, "%s-audio", recording_base);
						session->arc = janus_recorder_create(NULL, "opus", filename);
						if(session->arc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this EchoTest user!\n");
						}
					} else {
						/* Build a filename */
						g_snprintf(filename, 255, "echotest-%p-%"SCNi64"-audio", session, now);
						session->arc = janus_recorder_create(NULL, "opus", filename);
						if(session->arc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this EchoTest user!\n");
						}
					}
				}
				if(session->has_video) {
					/* FIXME We assume we're recording VP8, here */
					memset(filename, 0, 255);
					if(recording_base) {
						/* Use the filename and path we have been provided */
						g_snprintf(filename, 255, "%s-video", recording_base);
						session->vrc = janus_recorder_create(NULL, "vp8", filename);
						if(session->vrc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this EchoTest user!\n");
						}
					} else {
						/* Build a filename */
						g_snprintf(filename, 255, "echotest-%p-%"SCNi64"-video", session, now);
						session->vrc = janus_recorder_create(NULL, "vp8", filename);
						if(session->vrc == NULL) {
							/* FIXME We should notify the fact the recorder could not be created */
							JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this EchoTest user!\n");
						}
					}
					/* Send a PLI */
					JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
					char buf[12];
					memset(buf, 0, 12);
					janus_rtcp_pli((char *)&buf, 12);
					gateway->relay_rtcp(session->handle, 1, buf, 12);
				}
			}
		}
		/* Any SDP to handle? */
		if(msg->sdp) {
			JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg->sdp_type, msg->sdp);
			session->has_audio = (strstr(msg->sdp, "m=audio") != NULL);
			session->has_video = (strstr(msg->sdp, "m=video") != NULL);
		}

		if(!audio && !video && !bitrate && !record && !msg->sdp) {
			JANUS_LOG(LOG_ERR, "No supported attributes (audio, video, bitrate, record, jsep) found\n");
			error_code = JANUS_ECHOTEST_ERROR_INVALID_ELEMENT;
			g_snprintf(error_cause, 512, "Message error: no supported attributes (audio, video, bitrate, record, jsep) found");
			goto error;
		}

		json_decref(root);
		/* Prepare JSON event */
		json_t *event = json_object();
		json_object_set_new(event, "echotest", json_string("event"));
		json_object_set_new(event, "result", json_string("ok"));
		char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref(event);
		JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
		if(!msg->sdp) {
			int ret = gateway->push_event(msg->handle, &janus_echotest_plugin, msg->transaction, event_text, NULL, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
		} else {
			/* Forward the same offer to the gateway, to start the echo test */
			const char *type = NULL;
			if(!strcasecmp(msg->sdp_type, "offer"))
				type = "answer";
			if(!strcasecmp(msg->sdp_type, "answer"))
				type = "offer";
			/* Any media direction that needs to be fixed? */
			char *sdp = g_strdup(msg->sdp);
			if(strstr(sdp, "a=recvonly")) {
				/* Turn recvonly to inactive, as we simply bounce media back */
				sdp = janus_string_replace(sdp, "a=recvonly", "a=inactive");
			} else if(strstr(sdp, "a=sendonly")) {
				/* Turn sendonly to recvonly */
				sdp = janus_string_replace(sdp, "a=sendonly", "a=recvonly");
				/* FIXME We should also actually not echo this media back, though... */
			}
			/* Make also sure we get rid of ULPfec, red, etc. */
			if(strstr(sdp, "ulpfec")) {
				/* FIXME This really needs some better code */
				sdp = janus_string_replace(sdp, "a=rtpmap:116 red/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:117 ulpfec/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:96 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:96 apt=100\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:97 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:97 apt=101\r\n", "");
				sdp = janus_string_replace(sdp, "a=rtpmap:98 rtx/90000\r\n", "");
				sdp = janus_string_replace(sdp, "a=fmtp:98 apt=116\r\n", "");
				sdp = janus_string_replace(sdp, " 116", "");
				sdp = janus_string_replace(sdp, " 117", "");
				sdp = janus_string_replace(sdp, " 96", "");
				sdp = janus_string_replace(sdp, " 97", "");
				sdp = janus_string_replace(sdp, " 98", "");
			}
			/* How long will the gateway take to push the event? */
			g_atomic_int_set(&session->hangingup, 0);
			gint64 start = janus_get_monotonic_time();
			int res = gateway->push_event(msg->handle, &janus_echotest_plugin, msg->transaction, event_text, type, sdp);
			JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (took %"SCNu64" us)\n",
				res, janus_get_monotonic_time()-start);
			g_free(sdp);
		}
		g_free(event_text);
		janus_echotest_message_free(msg);
		continue;
		
error:
		{
			if(root != NULL)
				json_decref(root);
			/* Prepare JSON error event */
			json_t *event = json_object();
			json_object_set_new(event, "echotest", json_string("event"));
			json_object_set_new(event, "error_code", json_integer(error_code));
			json_object_set_new(event, "error", json_string(error_cause));
			char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
			json_decref(event);
			JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
			int ret = gateway->push_event(msg->handle, &janus_echotest_plugin, msg->transaction, event_text, NULL, NULL);
			JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
			g_free(event_text);
			janus_echotest_message_free(msg);
		}
	}
	g_free(error_cause);
	JANUS_LOG(LOG_VERB, "Leaving EchoTest handler thread\n");
	return NULL;
}
Пример #9
0
static void put_playlist_patch(sp_playlist *playlist,
                               struct evhttp_request *request,
                               void *userdata) {
  struct state *state = userdata;
  struct evbuffer *buf = evhttp_request_get_input_buffer(request);
  size_t buflen = evbuffer_get_length(buf);

  if (buflen == 0) {
    send_error(request, HTTP_BADREQUEST, "No body");
    return;
  }

  // Read request body
  json_error_t loads_error;
  json_t *json = read_request_body_json(request, &loads_error);

  if (json == NULL) {
    send_error(request, HTTP_BADREQUEST,
               loads_error.text ? loads_error.text : "Unable to parse JSON");
    return;
  }

  if (!json_is_array(json)) {
    json_decref(json);
    send_error(request, HTTP_BADREQUEST, "Not valid JSON array");
    return;
  }

  // Handle empty array
  int num_tracks = json_array_size(json);

  if (num_tracks == 0) {
    send_reply(request, HTTP_OK, "OK", NULL);
    return;
  }

  sp_track **tracks = calloc(num_tracks, sizeof (sp_track *));
  int num_valid_tracks = 0;

  for (int i = 0; i < num_tracks; i++) {
    json_t *item = json_array_get(json, i);

    if (!json_is_string(item)) {
      json_decref(item);
      continue;
    }

    char *uri = strdup(json_string_value(item));
    sp_link *track_link = sp_link_create_from_string(uri);
    free(uri);

    if (track_link == NULL)
      continue;

    if (sp_link_type(track_link) != SP_LINKTYPE_TRACK) {
      sp_link_release(track_link);
      continue;
    }

    sp_track *track = sp_link_as_track(track_link);
    
    if (track == NULL)
      continue;

    tracks[num_valid_tracks++] = track;
  }

  json_decref(json);
  
  // Bail if no tracks could be read from input
  if (num_valid_tracks == 0) {
    send_error(request, HTTP_BADREQUEST, "No valid tracks");
    free(tracks);
    return;
  }

  tracks = realloc(tracks, num_valid_tracks * sizeof (sp_track *));

  // Apply diff
  apr_pool_t *pool = state->pool;
  svn_diff_t *diff;
  svn_error_t *diff_error = diff_playlist_tracks(&diff, playlist, tracks, 
                                                 num_valid_tracks, pool); 

  if (diff_error != SVN_NO_ERROR) {
    free(tracks);
    svn_handle_error2(diff_error, stderr, false, "Diff");
    send_error(request, HTTP_BADREQUEST, "Search failed");
    return;
  }

  svn_error_t *apply_error = diff_playlist_tracks_apply(diff, playlist, tracks,
                                                        num_valid_tracks,
                                                        state->session);

  if (apply_error != SVN_NO_ERROR) {
    free(tracks);
    svn_handle_error2(apply_error, stderr, false, "Updating playlist");
    send_error(request, HTTP_BADREQUEST, "Could not apply diff");
    return;
  }

  if (!sp_playlist_has_pending_changes(playlist)) {
    free(tracks);
    get_playlist(playlist, request, NULL);
    return;
  }

  free(tracks);
  register_playlist_callbacks(playlist, request, &get_playlist,
                              &playlist_update_in_progress_callbacks, NULL);
}
Пример #10
0
static qeojson_writer_t *qeojson_writer_open(const qeo_factory_t    *factory,
                                             qeojson_writer_type_t  writer_type,
                                             void                   *listener,
                                             const char             *json_type,
                                             uintptr_t              userdata)
{
    qeo_retcode_t                   ret                 = QEO_EFAIL;
    qeojson_writer_t                *jsonwriter         = NULL;
    qeocore_type_t                  *typedesc           = NULL;
    json_writer_dispatcher_cookie_t *dc                 = NULL;
    json_t                          *jsonTypeDesc       = NULL;
    json_t                          *behavior           = NULL;
    const char                      *expected_behaviour = NULL;
    int                             flags               = QEOCORE_EFLAG_NONE;
    qeocore_writer_listener_t       l = { 0 };

    if ((NULL == factory) || (NULL == json_type)) {
        return NULL;
    }


    do {
        dc = calloc(1, sizeof(json_writer_dispatcher_cookie_t));
        if (NULL == dc) {
            break;
        }

        dc->userdata = userdata;

        switch (writer_type) {
            case QEOJSON_WRITER_TYPE_EVENT_WRITER:
                flags = QEOCORE_EFLAG_EVENT_DATA;
                expected_behaviour = "event";
                qeo_json_event_writer_listener_t *event_listener = (qeo_json_event_writer_listener_t *) listener;
                dc->etype           = QEO_ETYPE_EVENT_DATA;
                dc->listener.event  = *event_listener;
                if (NULL != event_listener->on_policy_update) {
                    l.on_policy_update = qeojson_core_writer_policy_update_callback_dispatcher;
                }
                break;

            case QEOJSON_WRITER_TYPE_STATE_WRITER:
                flags = QEOCORE_EFLAG_STATE_DATA;
                expected_behaviour = "state";
                qeo_json_state_writer_listener_t *state_listener = (qeo_json_state_writer_listener_t *)listener;
                dc->etype           = QEO_ETYPE_STATE_DATA;
                dc->listener.state  = *state_listener;
                if (NULL != state_listener->on_policy_update) {
                    l.on_policy_update = qeojson_core_writer_policy_update_callback_dispatcher;
                }

                break;
        }

        jsonTypeDesc = json_loads(json_type, 0, NULL);
        if (NULL == jsonTypeDesc) {
            break;
        }

        if (!json_is_object(jsonTypeDesc)) {
            break;
        }

        behavior = json_object_get(jsonTypeDesc, KEY_BEHAVIOR);

        if (!json_is_string(behavior)) {
            break;
        }


        if (0 != strcmp(json_string_value(behavior), expected_behaviour)) {
            qeo_log_e("not matching expected behaviour %s", expected_behaviour);
            break;
        }

        jsonwriter = calloc(1, sizeof(qeojson_writer_t));
        if (jsonwriter == NULL) {
            break;
        }

        jsonwriter->policy_cache = json_object();
        json_object_set_new(jsonwriter->policy_cache, "users", json_array());

        jsonwriter->policy = json_object();
        json_object_set_new(jsonwriter->policy, "users", json_array());

#ifdef __USE_GNU
        /* compile with -D_GNU_SOURCE */
#ifndef NDEBUG
        jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
#else
        jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
#endif
#else
        jsonwriter->policy_mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
#endif

        typedesc = types_from_json(factory, jsonTypeDesc);
        if (NULL == typedesc) {
            qeo_log_e("typedesc == NULL");
            break;
        }

        dc->typedesc        = jsonTypeDesc;
        l.userdata          = (uintptr_t)dc;
        dc->jsonwriter      = jsonwriter;
        jsonwriter->writer  = qeocore_writer_open(factory,                          // factory
                                                  typedesc,                         // type
                                                  NULL,                             // callback dispatcher
                                                  flags,                            // flags
                                                  &l,                               // callback cookie
                                                  NULL);                            // return code
        qeocore_type_free(typedesc);
        if (NULL == jsonwriter->writer) {
            break;
        }


        ret = QEO_OK;
    } while (0);


    if (QEO_OK != ret) {
        json_decref(jsonTypeDesc);
        qeojson_writer_close(jsonwriter);
        jsonwriter = NULL;
        free(dc);
    }


    return jsonwriter;
}
Пример #11
0
sint32 cmdline_for_sprite(const char **argv, sint32 argc)
{
    gOpenRCT2Headless = true;
    if (argc == 0)
        return -1;

    if (_strcmpi(argv[0], "details") == 0) {
        if (argc < 2) {
            fprintf(stdout, "usage: sprite details <spritefile> [idx]\n");
            return -1;
        } else if (argc == 2) {
            const char *spriteFilePath = argv[1];

            if (!sprite_file_open(spriteFilePath)) {
                fprintf(stderr, "Unable to open input sprite file.\n");
                return -1;
            }

            printf("sprites: %u\n", spriteFileHeader.num_entries);
            printf("data size: %u\n", spriteFileHeader.total_size);

            sprite_file_close();
            return 1;
        } else {
            const char *spriteFilePath = argv[1];
            sint32 spriteIndex = atoi(argv[2]);

            if (!sprite_file_open(spriteFilePath)) {
                fprintf(stderr, "Unable to open input sprite file.\n");
                return -1;
            }

            if (spriteIndex < 0 || spriteIndex >= (sint32)spriteFileHeader.num_entries) {
                sprite_file_close();
                fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex);
                return -1;
            }

            rct_g1_element *g1 = &spriteFileEntries[spriteIndex];
            printf("width: %d\n", g1->width);
            printf("height: %d\n", g1->height);
            printf("x offset: %d\n", g1->x_offset);
            printf("y offset: %d\n", g1->y_offset);
            printf("data offset: %p\n", g1->offset);

            sprite_file_close();
            return 1;
        }
    } else if (_strcmpi(argv[0], "export") == 0) {
        if (argc < 4) {
            fprintf(stdout, "usage: sprite export <spritefile> <idx> <output>\n");
            return -1;
        }

        const char *spriteFilePath = argv[1];
        sint32 spriteIndex = atoi(argv[2]);
        const char *outputPath = argv[3];

        if (!sprite_file_open(spriteFilePath)) {
            fprintf(stderr, "Unable to open input sprite file.\n");
            return -1;
        }

        if (spriteIndex < 0 || spriteIndex >= (sint32)spriteFileHeader.num_entries) {
            fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex);
            return -1;
        }

        if (!sprite_file_export(spriteIndex, outputPath)) {
            fprintf(stderr, "Could not export\n");
            sprite_file_close();
            return -1;
        }

        sprite_file_close();
        return 1;
    } else if (_strcmpi(argv[0], "exportall") == 0) {
        if (argc < 3) {
            fprintf(stdout, "usage: sprite exportall <spritefile> <output directory>\n");
            return -1;
        }

        const char *spriteFilePath = argv[1];
        char outputPath[MAX_PATH];

        if (!sprite_file_open(spriteFilePath)) {
            fprintf(stderr, "Unable to open input sprite file.\n");
            return -1;
        }

        safe_strcpy(outputPath, argv[2], MAX_PATH);
        path_end_with_separator(outputPath, MAX_PATH);

        if (!platform_ensure_directory_exists(outputPath)){
            fprintf(stderr, "Unable to create directory.\n");
            return -1;
        }

        sint32 maxIndex = (sint32)spriteFileHeader.num_entries;
        sint32 numbers = (sint32)floor(log(maxIndex));
        size_t pathLen = strlen(outputPath);

        if (pathLen >= (size_t)(MAX_PATH - numbers - 5)) {
            fprintf(stderr, "Path too long.\n");
            return -1;
        }

        for (sint32 x = 0; x < numbers; x++){
            outputPath[pathLen + x] = '0';
        }
        safe_strcpy(outputPath + pathLen + numbers, ".png", MAX_PATH - pathLen - numbers);

        for (sint32 spriteIndex = 0; spriteIndex < maxIndex; spriteIndex++){

            if (spriteIndex % 100 == 99){
                // Status indicator
                printf("\r%d / %d, %d%%", spriteIndex, maxIndex, spriteIndex / maxIndex);
            }

            // Add to the index at the end of the file name
            char *counter = outputPath + pathLen + numbers - 1;
            (*counter)++;
            while (*counter > '9'){
                *counter = '0';
                counter--;
                (*counter)++;
            }

            if (!sprite_file_export(spriteIndex, outputPath)) {
                fprintf(stderr, "Could not export\n");
                sprite_file_close();
                return -1;
            }
        }

        sprite_file_close();
        return 1;

    } else if (_strcmpi(argv[0], "create") == 0) {
        if (argc < 2) {
            fprintf(stderr, "usage: sprite create <spritefile>\n");
            return -1;
        }

        const char *spriteFilePath = argv[1];

        spriteFileHeader.num_entries = 0;
        spriteFileHeader.total_size = 0;
        sprite_file_save(spriteFilePath);

        sprite_file_close();
        return 1;
    } else if (_strcmpi(argv[0], "append") == 0) {
        if (argc != 3 && argc != 5) {
            fprintf(stderr, "usage: sprite append <spritefile> <input> [<x offset> <y offset>]\n");
            return -1;
        }


        const char *spriteFilePath = argv[1];
        const char *imagePath = argv[2];
        sint16 x_offset = 0;
        sint16 y_offset = 0;

        if (argc == 5)
        {
            char *endptr;

            x_offset = strtol(argv[3], &endptr, 0);
            if (*endptr != 0)
            {
                fprintf(stderr, "X offset must be an integer\n");
                return -1;
            }

            y_offset = strtol(argv[4], &endptr, 0);
            if (*endptr != 0)
            {
                fprintf(stderr, "Y offset must be an integer\n");
                return -1;
            }
        }

        rct_g1_element spriteElement;
        uint8 *buffer;

        sint32 bufferLength;
        if (!sprite_file_import(imagePath, x_offset, y_offset, &spriteElement, &buffer, &bufferLength, gSpriteMode))

            return -1;

        if (!sprite_file_open(spriteFilePath)) {
            fprintf(stderr, "Unable to open input sprite file.\n");
            return -1;
        }

        spriteFileHeader.num_entries++;
        spriteFileHeader.total_size += bufferLength;
        spriteFileEntries = realloc(spriteFileEntries, spriteFileHeader.num_entries * sizeof(rct_g1_element));

        sprite_entries_make_relative();
        spriteFileData = realloc(spriteFileData, spriteFileHeader.total_size);
        sprite_entries_make_absolute();

        spriteFileEntries[spriteFileHeader.num_entries - 1] = spriteElement;
        memcpy(spriteFileData + (spriteFileHeader.total_size - bufferLength), buffer, bufferLength);
        spriteFileEntries[spriteFileHeader.num_entries - 1].offset = spriteFileData + (spriteFileHeader.total_size - bufferLength);

        free(buffer);
        if (!sprite_file_save(spriteFilePath))
            return -1;

        return 1;
    } else if (_strcmpi(argv[0], "build") == 0) {
        if (argc < 3) {
            fprintf(stdout, "usage: sprite build <spritefile> <sprite description file> [silent]\n");
            return -1;
        }

        const char *spriteFilePath = argv[1];
        const char *spriteDescriptionPath = argv[2];
        char* directoryPath = path_get_directory(spriteDescriptionPath);

        json_error_t error;
        json_t* sprite_list=json_load_file(spriteDescriptionPath, JSON_REJECT_DUPLICATES, &error);

        if (sprite_list == NULL)
        {
            fprintf(stderr, "Error parsing sprite description file: %s at line %d column %d\n", error.text, error.line, error.column);
            return -1;
        }

        if (!json_is_array(sprite_list))
        {
            fprintf(stderr, "Error: expected array\n");
            json_decref(sprite_list);
            return -1;
        }

        bool silent = (argc >= 4 && strcmp(argv[3], "silent") == 0);

        spriteFileHeader.num_entries = 0;
        spriteFileHeader.total_size = 0;
        sprite_file_save(spriteFilePath);

        fprintf(stdout, "Building: %s\n", spriteFilePath);

        size_t i;
        json_t* sprite_description;

        json_array_foreach(sprite_list, i, sprite_description)
        {
            if(!json_is_object(sprite_description))
            {
                fprintf(stderr, "Error: expected object for sprite %lu\n", (unsigned long)i);
                json_decref(sprite_list);
                return -1;
            }

            json_t* path = json_object_get(sprite_description,"path");
            if(!path || !json_is_string(path))
            {
                fprintf(stderr, "Error: no path provided for sprite %lu\n", (unsigned long)i);
                json_decref(sprite_list);
                return -1;
            }
            // Get x and y offsets, if present
            json_t* x_offset = json_object_get(sprite_description, "x_offset");
            json_t* y_offset = json_object_get(sprite_description, "y_offset");


            // Resolve absolute sprite path
            char *imagePath = platform_get_absolute_path(json_string_value(path), directoryPath);

            rct_g1_element spriteElement;
            uint8 *buffer;
            int bufferLength;

            if (!sprite_file_import(imagePath, x_offset==NULL ? 0 : json_integer_value(x_offset), y_offset==NULL ? 0 : json_integer_value(y_offset), &spriteElement, &buffer, &bufferLength, gSpriteMode))
            {
                fprintf(stderr, "Could not import image file: %s\nCanceling\n", imagePath);
                json_decref(sprite_list);
                free(imagePath);
                return -1;
            }

            if (!sprite_file_open(spriteFilePath))
            {
                fprintf(stderr, "Unable to open sprite file: %s\nCanceling\n", spriteFilePath);
                json_decref(sprite_list);
                free(imagePath);
                return -1;
            }

            spriteFileHeader.num_entries++;
            spriteFileHeader.total_size += bufferLength;
            spriteFileEntries = realloc(spriteFileEntries, spriteFileHeader.num_entries * sizeof(rct_g1_element));

            sprite_entries_make_relative();
            spriteFileData = realloc(spriteFileData, spriteFileHeader.total_size);
            sprite_entries_make_absolute();

            spriteFileEntries[spriteFileHeader.num_entries - 1] = spriteElement;
            memcpy(spriteFileData + (spriteFileHeader.total_size - bufferLength), buffer, bufferLength);
            spriteFileEntries[spriteFileHeader.num_entries - 1].offset = spriteFileData + (spriteFileHeader.total_size - bufferLength);

            free(buffer);

            if (!sprite_file_save(spriteFilePath))
            {
                fprintf(stderr, "Could not save sprite file: %s\nCanceling\n", imagePath);
                json_decref(sprite_list);
                free(imagePath);
                return -1;
            }

            if (!silent)
                fprintf(stdout, "Added: %s\n", imagePath);

            free(imagePath);
            sprite_file_close();

        }

        json_decref(sprite_list);
        free(directoryPath);

        fprintf(stdout, "Finished\n");
        return 1;
    } else {
Пример #12
0
tABC_CC ABC_LoginServerOtpPending(std::list<DataChunk> users, std::list<bool> &isPending, tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    HttpReply reply;
    std::string url = ABC_SERVER_ROOT "/otp/pending/check";
    ServerReplyJson replyJson;
    JsonArray arrayJson;
    json_t *pJSON_Root = NULL;
    char *szPost = NULL;
    std::map<std::string, bool> userMap;
    std::list<std::string> usersEncoded;

    std::string param;
    for (const auto &u : users)
    {
        std::string username = base64Encode(u);
        param += (username + ",");
        userMap[username] = false;
        usersEncoded.push_back(username);
    }

    // create the post data
    pJSON_Root = json_pack("{ss}", "l1s", param.c_str());
    szPost = ABC_UtilStringFromJSONObject(pJSON_Root, JSON_COMPACT);

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, url, szPost));

    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

    arrayJson = replyJson.results();
    if (arrayJson)
    {
        size_t rows = arrayJson.size();
        for (size_t i = 0; i < rows; i++)
        {
            json_t *pJSON_Row = arrayJson[i].get();
            ABC_CHECK_ASSERT((pJSON_Row && json_is_object(pJSON_Row)), ABC_CC_JSONError, "Error parsing JSON array element object");

            json_t *pJSON_Value = json_object_get(pJSON_Row, "login");
            ABC_CHECK_ASSERT((pJSON_Value && json_is_string(pJSON_Value)), ABC_CC_JSONError, "Error otp/pending/login JSON");
            std::string username(json_string_value(pJSON_Value));

            pJSON_Value = json_object_get(pJSON_Row, ABC_SERVER_JSON_OTP_PENDING);
            ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error otp/pending/pending JSON");
            if (json_is_true(pJSON_Value))
            {
                userMap[username] = json_is_true(pJSON_Value);;
            }
        }
    }
    isPending.clear();
    for (auto &username: usersEncoded) {
        isPending.push_back(userMap[username]);
    }

exit:
    ABC_FREE_STR(szPost);
    if (pJSON_Root)      json_decref(pJSON_Root);

    return cc;
}
Пример #13
0
/**
 * Helper function for getting CarePackage or LoginPackage.
 */
static
tABC_CC ABC_LoginServerGetString(const Lobby &lobby, tABC_U08Buf LP1, tABC_U08Buf LRA1,
                                 const char *szURL, const char *szField, char **szResponse, tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    HttpReply reply;
    ServerReplyJson replyJson;
    json_t  *pJSON_Value    = NULL;
    json_t  *pJSON_Root     = NULL;
    char    *szPost         = NULL;

    // create the post data with or without LP1
    if (LP1.data() == NULL && LRA1.data() == NULL)
    {
        pJSON_Root = json_pack("{ss}",
            ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str());
    }
    else
    {
        if (LP1.data() == NULL)
        {
            pJSON_Root = json_pack("{ssss}",
                ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str(),
                ABC_SERVER_JSON_LRA1_FIELD, base64Encode(LRA1).c_str());
        }
        else
        {
            pJSON_Root = json_pack("{ssss}",
                ABC_SERVER_JSON_L1_FIELD, base64Encode(lobby.authId()).c_str(),
                ABC_SERVER_JSON_LP1_FIELD, base64Encode(LP1).c_str());
        }
    }
    {
        auto key = lobby.otpKey();
        if (key)
            json_object_set_new(pJSON_Root, ABC_SERVER_JSON_OTP_FIELD, json_string(key->totp().c_str()));
    }
    szPost = ABC_UtilStringFromJSONObject(pJSON_Root, JSON_COMPACT);

    // send the command
    ABC_CHECK_NEW(AirbitzRequest().post(reply, szURL, szPost));

    // Check the results, and store json if successful
    ABC_CHECK_NEW(replyJson.decode(reply.body));
    ABC_CHECK_NEW(replyJson.ok());

    // get the care package
    pJSON_Value = replyJson.results().get();
    ABC_CHECK_ASSERT((pJSON_Value && json_is_object(pJSON_Value)), ABC_CC_JSONError, "Error parsing server JSON care package results");

    pJSON_Value = json_object_get(pJSON_Value, szField);
    ABC_CHECK_ASSERT((pJSON_Value && json_is_string(pJSON_Value)), ABC_CC_JSONError, "Error care package JSON results");
    ABC_STRDUP(*szResponse, json_string_value(pJSON_Value));

exit:
    if (pJSON_Root)     json_decref(pJSON_Root);
    ABC_FREE_STR(szPost);

    return cc;
}
Пример #14
0
int
main (int argc, char *argv[])
{

  CURL *handle;
  CURLcode result;
  struct curl_httppost *post = NULL;
  struct curl_httppost *lastptr = NULL;
  char *data;
  char *file;
 // data = malloc (BUFFER_SIZE);
 // struct write_result write_result = {
 //   .data = data,
 //   .pos = 0
 // };


  short int indx = argc - 1;
  unsigned int i;
  char *text;
  json_t *root;
  json_error_t error;
  json_t *links;

  if (argc == 1 || strcmp (argv[1], "--help") == 0
      || strcmp (argv[1], "-h") == 0)
    {
      printf ("Usage: %s file_1.png file_2.png .... file_n.png\n\n", argv[0]);
      return 0;
    }

    while (indx != 0)
    {
     // data = malloc (BUFFER_SIZE);
      data = malloc (BUFFER_SIZE);
      struct write_result write_result = {
       .data = data,
       .pos = 0
      };


      file = argv[(argc - indx)];
      //handle = curl_easy_init();
      handle = curl_easy_init ();
      if (!handle)
       {
        printf ("something is wrong!");
        return 2;
       }


      printf ("test: %s \n\n", file);





      //if (handle){

      /* Fill in the file upload field */
      curl_formadd (&post,
		    &lastptr,
		    CURLFORM_COPYNAME, "key",
		    CURLFORM_COPYCONTENTS, "0426cb779599180503fd02a0e134ff03",
		    CURLFORM_END);

      curl_formadd (&post,
		    &lastptr,
		    CURLFORM_COPYNAME, "image",
		    CURLFORM_FILE, file, CURLFORM_END);






      curl_easy_setopt (handle, CURLOPT_URL,
			"http://api.imgur.com/2/upload.json");
      curl_easy_setopt (handle, CURLOPT_WRITEFUNCTION, write_response);
      curl_easy_setopt (handle, CURLOPT_WRITEDATA, &write_result);
      curl_easy_setopt (handle, CURLOPT_HTTPPOST, post);



      result = curl_easy_perform (handle);
      curl_formfree (post);
      post = NULL;
      lastptr = NULL;
      curl_easy_cleanup (handle);
     // curl_global_cleanup ();
      data[write_result.pos] = '\0';
      printf("debug1\n");
      text = data;
      data = NULL;
      root = json_loads (text, 0, &error);
      free (text);
      text = NULL;
      if (!root)
	{
	  fprintf (stderr, "error: on line %d: %s\n", error.line, error.text);
	  return 1;
	}



      json_t *original, *date, *name;
      const char *message_text;
      if (!json_object_get (root, "upload"))
	{
	  printf ("nope\n");
	}


      original = json_object_get (root, "upload");


      original = json_object_get (original, "links");

      original = json_object_get (original, "original");
      if (!json_is_string (original))
	{
	  fprintf (stderr, "error: commit %d: message is not a string\n",
		   i + 1);
	  return 1;
	}

      message_text = json_string_value (original);
      printf ("file %s uploaded — %s\n", file, message_text);
      //free(message_text);
      // }
      indx--;
    }
  curl_global_cleanup ();
  return 0;
}
Пример #15
0
/*
 * check to see if JSON provider metadata is valid
 */
static apr_byte_t oidc_metadata_provider_is_valid(request_rec *r,
		json_t *j_provider, const char *issuer) {

	/* get the "issuer" from the provider metadata and double-check that it matches what we looked for */
	json_t *j_issuer = json_object_get(j_provider, "issuer");
	if ((j_issuer == NULL) || (!json_is_string(j_issuer))) {
		oidc_error(r,
				"provider (%s) JSON metadata did not contain an \"issuer\" string",
				issuer);
		return FALSE;
	}

	/* check that the issuer matches */
	if (issuer != NULL) {
		if (oidc_util_issuer_match(issuer, json_string_value(j_issuer)) == FALSE) {
			oidc_warn(r,
					"requested issuer (%s) does not match the \"issuer\" value in the provider metadata file: %s",
					issuer, json_string_value(j_issuer));
			//return FALSE;
		}
	}

	/* verify that the provider supports the a flow that we implement */
	json_t *j_response_types_supported = json_object_get(j_provider,
			"response_types_supported");
	if ((j_response_types_supported != NULL)
			&& (json_is_array(j_response_types_supported))) {
		int i = 0;
		for (i = 0; i < json_array_size(j_response_types_supported); i++) {
			json_t *elem = json_array_get(j_response_types_supported, i);
			if (!json_is_string(elem)) {
				oidc_error(r,
						"unhandled in-array JSON non-string object type [%d]",
						elem->type);
				continue;
			}
			if (oidc_proto_flow_is_supported(r->pool, json_string_value(elem)))
				break;
		}
		if (i == json_array_size(j_response_types_supported)) {
			oidc_warn(r,
					"could not find a supported response type in provider metadata (%s) for entry \"response_types_supported\"; assuming that \"code\" flow is supported...",
					issuer);
			//return FALSE;
		}
	} else {
		oidc_warn(r,
				"provider (%s) JSON metadata did not contain a \"response_types_supported\" array; assuming that \"code\" flow is supported...",
				issuer);
		// TODO: hey, this is required-by-spec stuff right?
	}

	/* verify that the provider supports a response_mode that we implement */
	json_t *response_modes_supported = json_object_get(j_provider,
			"response_modes_supported");
	if ((response_modes_supported != NULL)
			&& (json_is_array(response_modes_supported))) {
		int i = 0;
		for (i = 0; i < json_array_size(response_modes_supported); i++) {
			json_t *elem = json_array_get(response_modes_supported, i);
			if (!json_is_string(elem)) {
				oidc_error(r,
						"unhandled in-array JSON non-string object type [%d]",
						elem->type);
				continue;
			}
			if ((apr_strnatcmp(json_string_value(elem), "fragment") == 0)
					|| (apr_strnatcmp(json_string_value(elem), "query") == 0)
					|| (apr_strnatcmp(json_string_value(elem), "form_post") == 0))
				break;
		}
		if (i == json_array_size(response_modes_supported)) {
			oidc_warn(r,
					"could not find a supported response mode in provider metadata (%s) for entry \"response_modes_supported\"",
					issuer);
			return FALSE;
		}
	} else {
		oidc_debug(r,
				"provider (%s) JSON metadata did not contain a \"response_modes_supported\" array; assuming that \"fragment\" and \"query\" are supported",
				issuer);
	}

	/* check the required authorization endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"authorization_endpoint", TRUE) == FALSE)
		return FALSE;

	/* check the optional token endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"token_endpoint", FALSE) == FALSE)
		return FALSE;

	/* check the optional user info endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"userinfo_endpoint", FALSE) == FALSE)
		return FALSE;

	/* check the optional JWKs URI */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"jwks_uri", FALSE) == FALSE)
		return FALSE;

	/* find out what type of authentication the token endpoint supports (we only support post or basic) */
	json_t *j_token_endpoint_auth_methods_supported = json_object_get(
			j_provider, "token_endpoint_auth_methods_supported");
	if ((j_token_endpoint_auth_methods_supported == NULL)
			|| (!json_is_array(j_token_endpoint_auth_methods_supported))) {
		oidc_debug(r,
				"provider (%s) JSON metadata did not contain a \"token_endpoint_auth_methods_supported\" array, assuming \"client_secret_basic\" is supported",
				issuer);
	} else {
		int i;
		for (i = 0;
				i < json_array_size(j_token_endpoint_auth_methods_supported);
				i++) {
			json_t *elem = json_array_get(
					j_token_endpoint_auth_methods_supported, i);
			if (!json_is_string(elem)) {
				oidc_warn(r,
						"unhandled in-array JSON object type [%d] in provider (%s) metadata for entry \"token_endpoint_auth_methods_supported\"",
						elem->type, issuer);
				continue;
			}
			if (strcmp(json_string_value(elem), "client_secret_post") == 0) {
				break;
			}
			if (strcmp(json_string_value(elem), "client_secret_basic") == 0) {
				break;
			}
		}
		if (i == json_array_size(j_token_endpoint_auth_methods_supported)) {
			oidc_error(r,
					"could not find a supported value [client_secret_post|client_secret_basic] in provider (%s) metadata for entry \"token_endpoint_auth_methods_supported\"",
					issuer);
			return FALSE;
		}
	}

	return TRUE;
}
Пример #16
0
/**
 * Loads the settings for a specific account using the given key
 * If no settings file exists for the given user, defaults are created
 *
 * @param login         Access to the account sync dir
 * @param ppSettings    Location to store ptr to allocated settings (caller must free)
 * @param pError        A pointer to the location to store the error if there is one
 */
tABC_CC ABC_AccountSettingsLoad(const Login &login,
                                tABC_AccountSettings **ppSettings,
                                tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;
    AutoCoreLock lock(gCoreMutex);

    tABC_AccountSettings *pSettings = NULL;
    json_t *pJSON_Root = NULL;
    json_t *pJSON_Value = NULL;
    bool bExists = false;
    auto filename = login.syncDir() + ACCOUNT_SETTINGS_FILENAME;

    ABC_CHECK_NULL(ppSettings);

    ABC_CHECK_RET(ABC_FileIOFileExists(filename.c_str(), &bExists, pError));
    if (true == bExists)
    {
        // load and decrypted the file into a json object
        ABC_CHECK_RET(ABC_CryptoDecryptJSONFileObject(filename.c_str(),
            toU08Buf(login.dataKey()), &pJSON_Root, pError));
        //ABC_DebugLog("Loaded settings JSON:\n%s\n", json_dumps(pJSON_Root, JSON_INDENT(4) | JSON_PRESERVE_ORDER));

        // allocate the new settings object
        ABC_NEW(pSettings, tABC_AccountSettings);
        pSettings->szFirstName = NULL;
        pSettings->szLastName = NULL;
        pSettings->szNickname = NULL;

        // get the first name
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_FIRST_NAME_FIELD);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT(json_is_string(pJSON_Value), ABC_CC_JSONError, "Error parsing JSON string value");
            ABC_STRDUP(pSettings->szFirstName, json_string_value(pJSON_Value));
        }

        // get the last name
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_LAST_NAME_FIELD);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT(json_is_string(pJSON_Value), ABC_CC_JSONError, "Error parsing JSON string value");
            ABC_STRDUP(pSettings->szLastName, json_string_value(pJSON_Value));
        }

        // get the nickname
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_NICKNAME_FIELD);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT(json_is_string(pJSON_Value), ABC_CC_JSONError, "Error parsing JSON string value");
            ABC_STRDUP(pSettings->szNickname, json_string_value(pJSON_Value));
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_PIN_FIELD);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT(json_is_string(pJSON_Value), ABC_CC_JSONError, "Error parsing JSON string value");
            ABC_STRDUP(pSettings->szPIN, json_string_value(pJSON_Value));
        }

        // get name on payments option
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_NAME_ON_PAYMENTS_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON boolean value");
        pSettings->bNameOnPayments = json_is_true(pJSON_Value) ? true : false;

        // get minutes auto logout
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_MINUTES_AUTO_LOGOUT_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON integer value");
        pSettings->minutesAutoLogout = (int) json_integer_value(pJSON_Value);

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_RECOVERY_REMINDER_COUNT);
        if (pJSON_Value) {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON integer value");
            pSettings->recoveryReminderCount = (int) json_integer_value(pJSON_Value);
        } else {
            pSettings->recoveryReminderCount = 0;
        }

        // get language
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_LANGUAGE_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_string(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON string value");
        ABC_STRDUP(pSettings->szLanguage, json_string_value(pJSON_Value));

        // get currency num
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_NUM_CURRENCY_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON integer value");
        pSettings->currencyNum = (int) json_integer_value(pJSON_Value);

        // get advanced features
        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_ADVANCED_FEATURES_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON boolean value");
        pSettings->bAdvancedFeatures = json_is_true(pJSON_Value) ? true : false;

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_DAILY_SPEND_LIMIT_ENABLED);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON boolean value");
            pSettings->bDailySpendLimit = json_is_true(pJSON_Value) ? true : false;
        }
        else
        {
            pSettings->bDailySpendLimit = false;
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_DAILY_SPEND_LIMIT_SATOSHIS);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON daily spend satoshi value");
            pSettings->dailySpendLimitSatoshis = (int64_t) json_integer_value(pJSON_Value);
        }
        else
        {
            pSettings->dailySpendLimitSatoshis = 0;
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_SPEND_REQUIRE_PIN_ENABLED);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON boolean value");
            pSettings->bSpendRequirePin = json_is_true(pJSON_Value) ? true : false;
        }
        else
        {
            // Default to PIN required
            pSettings->bSpendRequirePin = true;
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_DISABLE_PIN_LOGIN);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_boolean(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON boolean value");
            pSettings->bDisablePINLogin = json_is_true(pJSON_Value) ? true : false;
        }
        else
        {
            // Default to PIN login allowed
            pSettings->bDisablePINLogin = false;
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_PIN_LOGIN_COUNT);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON pin login count");
            pSettings->pinLoginCount = json_integer_value(pJSON_Value);
        }
        else
        {
            // Default to PIN login allowed
            pSettings->pinLoginCount = 0;
        }

        pJSON_Value = json_object_get(pJSON_Root, JSON_ACCT_SPEND_REQUIRE_PIN_SATOSHIS);
        if (pJSON_Value)
        {
            ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON daily spend satoshi value");
            pSettings->spendRequirePinSatoshis = (int64_t) json_integer_value(pJSON_Value);
        }
        else
        {
            // Default PIN requirement to 50mb
            pSettings->spendRequirePinSatoshis = DEF_REQUIRE_PIN_SATOSHIS;
        }


        // get the denomination object
        json_t *pJSON_Denom = json_object_get(pJSON_Root, JSON_ACCT_BITCOIN_DENOMINATION_FIELD);
        ABC_CHECK_ASSERT((pJSON_Denom && json_is_object(pJSON_Denom)), ABC_CC_JSONError, "Error parsing JSON object value");

        // get denomination satoshi display size (e.g., 100,000 would be milli-bit coin)
        pJSON_Value = json_object_get(pJSON_Denom, JSON_ACCT_SATOSHI_FIELD);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON integer value");
        pSettings->bitcoinDenomination.satoshi = json_integer_value(pJSON_Value);

        // get denomination type
        pJSON_Value = json_object_get(pJSON_Denom, JSON_ACCT_LABEL_TYPE);
        ABC_CHECK_ASSERT((pJSON_Value && json_is_integer(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON integer value");
        pSettings->bitcoinDenomination.denominationType = json_integer_value(pJSON_Value);

        // get the exchange rates array
        json_t *pJSON_Sources = json_object_get(pJSON_Root, JSON_ACCT_EX_RATE_SOURCES_FIELD);
        ABC_CHECK_ASSERT((pJSON_Sources && json_is_array(pJSON_Sources)), ABC_CC_JSONError, "Error parsing JSON array value");

        // get the number of elements in the array
        pSettings->exchangeRateSources.numSources = (int) json_array_size(pJSON_Sources);
        if (pSettings->exchangeRateSources.numSources > 0)
        {
            ABC_ARRAY_NEW(pSettings->exchangeRateSources.aSources,
                          pSettings->exchangeRateSources.numSources, tABC_ExchangeRateSource*);
        }
Пример #17
0
/*
 * parse the JSON provider metadata in to a oidc_provider_t struct but do not override values already set
 */
apr_byte_t oidc_metadata_provider_parse(request_rec *r, json_t *j_provider,
		oidc_provider_t *provider) {

	if (provider->issuer == NULL) {
		/* get the "issuer" from the provider metadata */
		oidc_json_object_get_string(r->pool, j_provider, "issuer",
				&provider->issuer, NULL);
	}

	if (provider->authorization_endpoint_url == NULL) {
		/* get a handle to the authorization endpoint */
		oidc_json_object_get_string(r->pool, j_provider,
				"authorization_endpoint", &provider->authorization_endpoint_url,
				NULL);
	}

	if (provider->token_endpoint_url == NULL) {
		/* get a handle to the token endpoint */
		oidc_json_object_get_string(r->pool, j_provider, "token_endpoint",
				&provider->token_endpoint_url, NULL);
	}

	if (provider->userinfo_endpoint_url == NULL) {
		/* get a handle to the user_info endpoint */
		oidc_json_object_get_string(r->pool, j_provider, "userinfo_endpoint",
				&provider->userinfo_endpoint_url, NULL);
	}

	if (provider->jwks_uri == NULL) {
		/* get a handle to the jwks_uri endpoint */
		oidc_json_object_get_string(r->pool, j_provider, "jwks_uri",
				&provider->jwks_uri, NULL);
	}

	if (provider->registration_endpoint_url == NULL) {
		/* get a handle to the client registration endpoint */
		oidc_json_object_get_string(r->pool, j_provider,
				"registration_endpoint", &provider->registration_endpoint_url,
				NULL);
	}

	if (provider->check_session_iframe == NULL) {
		/* get a handle to the check session iframe */
		oidc_json_object_get_string(r->pool, j_provider, "check_session_iframe",
				&provider->check_session_iframe, NULL);
	}

	if (provider->end_session_endpoint == NULL) {
		/* get a handle to the end session endpoint */
		oidc_json_object_get_string(r->pool, j_provider, "end_session_endpoint",
				&provider->end_session_endpoint, NULL);
	}

	if (provider->token_endpoint_auth == NULL) {

		/* find a supported token_endpoint_auth_method in the provider metadata */
		json_t *j_token_endpoint_auth_methods_supported = json_object_get(
				j_provider, "token_endpoint_auth_methods_supported");

		const char *token_endpoint_auth = NULL;

		/* loop through the array provided by the issuer and see if there's a supported method */
		if ((j_token_endpoint_auth_methods_supported != NULL)
				&& (json_is_array(j_token_endpoint_auth_methods_supported))) {
			int i;
			for (i = 0;
					i < json_array_size(j_token_endpoint_auth_methods_supported);
					i++) {
				json_t *elem = json_array_get(
						j_token_endpoint_auth_methods_supported, i);
				if (!json_is_string(elem)) {
					oidc_error(r,
							"unhandled in-array JSON object type [%d] in provider metadata for entry \"token_endpoint_auth_methods_supported\"",
							elem->type);
					continue;
				}

				/* take first supported method and prefer post over basic */
				if ((apr_strnatcmp(json_string_value(elem),
						"client_secret_post") == 0)
						|| (apr_strnatcmp(json_string_value(elem),
								"client_secret_basic") == 0)) {
					token_endpoint_auth = json_string_value(elem);
					break;
				}
			}
		}

		/* store the method if found */
		if (token_endpoint_auth != NULL) {
			provider->token_endpoint_auth = apr_pstrdup(r->pool,
					token_endpoint_auth);
		}
	}

	return TRUE;
}
Пример #18
0
int seamule_easy_main(struct seamule_t *seamule, int argc, char *argv[], seamule_process *process) {
    json_t *jobs = NULL;
    json_t *first_job = NULL;
    json_t *payload = NULL;
    json_t *id = NULL;
    json_t *result = NULL;
    json_error_t error;

    jobs = request_jobs(seamule);
    if (!jobs) {
        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
        goto error;
    }

    if (!json_is_array(jobs)) {
        fprintf(stderr, "error: root is not an array\n");
        goto error;
    }

    if (json_array_size(jobs) == 0) {
        first_job = create_job(seamule);
    } else {
        first_job = json_array_get(jobs, 0);
    }

    if (!first_job) {
        fprintf(stderr, "error: root is empty\n");
        goto error;
    }

    if (!json_is_object(first_job)) {
        fprintf(stderr, "error: job %d is not an object\n", 1);
        goto error;
    }

    id = json_object_get(first_job, "id");
    if (!json_is_string(id)) {
        fprintf(stderr, "error: job id is not a string\n");
        goto error;
    }

    payload = json_object_get(first_job, "payload");

    result = process(payload);

    if (result) {
        send_result(seamule, json_string_value(id), result);
        json_decref(result);
    }

    json_decref(id);
    json_decref(jobs);
    json_decref(first_job);
    json_decref(payload);

    return 0;

    error:
    if (id)
        json_decref(id);
    if (jobs)
        json_decref(jobs);
    if (first_job)
        json_decref(first_job);
    return 1;
}
Пример #19
0
static char *request(const char *url) {
    CURL *curl = NULL;
    CURLcode status;
    struct curl_slist *headers = NULL;
    char *data = NULL;
    long code;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (!curl) {
        goto error;
    }

    data = malloc(BUFFER_SIZE);
    if (!data) {
        goto error;
    }

    struct write_result write_result = {
            .data = data,
            .pos = 0
    };

    curl_easy_setopt(curl, CURLOPT_URL, url);

    /* GitHub commits API v3 requires a User-Agent header */
    headers = curl_slist_append(headers, "User-Agent: Jansson-Tutorial");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);

    status = curl_easy_perform(curl);
    if (status != 0) {
        fprintf(stderr, "error: unable to request data from %s:\n", url);
        fprintf(stderr, "%s\n", curl_easy_strerror(status));
        goto error;
    }

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
    if (code != 200) {
        fprintf(stderr, "error: server responded with code %ld\n", code);
        goto error;
    }

    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    curl_global_cleanup();

    /* zero-terminate the result */
    data[write_result.pos] = '\0';

    return data;

    error:
    if (data) {
        free(data);
    }
    if (curl) {
        curl_easy_cleanup(curl);
    }
    if (headers) {
        curl_slist_free_all(headers);
    }
    curl_global_cleanup();
    return NULL;
}

int main(int argc, char *argv[]) {
    size_t i;
    char *text;
    char url[URL_SIZE];

    json_t *root;
    json_error_t error;

    if (argc != 3) {
        fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
        fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
        return 2;
    }

    snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);

    printf("Query url: %s\n", url);

    text = request(url);
    if (!text) {
        return 1;
    }

    root = json_loads(text, 0, &error);
    free(text);

    if (!root) {
        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
        return 1;
    }

    if (!json_is_array(root)) {
        fprintf(stderr, "error: root is not an array\n");
        json_decref(root);
        return 1;
    }

    for (i = 0; i < json_array_size(root); i++) {
        json_t *data, *sha, *commit, *message;
        const char *message_text;

        data = json_array_get(root, i);
        if (!json_is_object(data)) {
            fprintf(stderr, "error: commit data %d is not an object\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        sha = json_object_get(data, "sha");
        if (!json_is_string(sha)) {
            fprintf(stderr, "error: commit %d: sha is not a string\n", (int) (i + 1));
            return 1;
        }

        commit = json_object_get(data, "commit");
        if (!json_is_object(commit)) {
            fprintf(stderr, "error: commit %d: commit is not an object\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        message = json_object_get(commit, "message");
        if (!json_is_string(message)) {
            fprintf(stderr, "error: commit %d: message is not a string\n", (int) (i + 1));
            json_decref(root);
            return 1;
        }

        message_text = json_string_value(message);
        printf("%.8s %.*s\n",
               json_string_value(sha),
               newline_offset(message_text),
               message_text);
    }

    json_decref(root);
    return 0;
}
Пример #20
0
static json_t *
provision(const clevis_provision_f *funcs,
          const json_t *cfg, const clevis_buf_t *key)
{
  struct curl_slist *headers = NULL;
  clevis_buf_t *okey = NULL;
  struct state state = {};
  const char *url = NULL;
  json_t *data = NULL;
  json_t *tmp = NULL;
  CURL *curl = NULL;
  CURLcode res;

  /* Setup the return data. */
  data = json_object();
  if (!data)
    goto error;

  tmp = json_object_get(cfg, "url");
  if (!json_is_string(tmp))
    goto error;
  url = json_string_value(tmp);
  if (strcasestr(url, "https://") != url)
    goto error;

  if (json_object_set(data, "url", tmp) < 0)
    goto error;

  if (json_object_set_new(data, "format", json_string("binary")) < 0)
    goto error;
  tmp = json_object_get(cfg, "format");
  if (json_is_string(tmp) && json_object_set(data, "format", tmp) < 0)
    goto error;

  okey = clevis_buf_rand(key->len);
  if (!okey)
    goto error;

  if (json_object_set_new(data, "ct", funcs->encrypt(okey, key)) < 0)
    goto error;

  /* Setup the transfer buffer. */
  tmp = json_object_get(cfg, "format");
  headers = header(json_string_value(tmp), content_types);
  state.buf = unparse(okey, json_string_value(tmp));
  if (!state.buf)
    goto error;

  /* Use HTTP PUT to store the key. */
  curl = curl_easy_init();
  if (!curl)
    goto error;

  curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) state.buf->len);
  curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(curl, CURLOPT_READDATA, &state);
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  curl_easy_setopt(curl, CURLOPT_URL, url);

  res = curl_easy_perform(curl);
  if (res != CURLE_OK)
    goto error;

  curl_slist_free_all(headers);
  clevis_buf_free(state.buf);
  curl_easy_cleanup(curl);
  clevis_buf_free(okey);
  return data;

error:
  curl_slist_free_all(headers);
  clevis_buf_free(state.buf);
  curl_easy_cleanup(curl);
  clevis_buf_free(okey);
  json_decref(data);
  return NULL;
}
Пример #21
0
struct ps_plugin_result * ps_gstsink_handle_message (ps_plugin_session * handle, char * transaction, char * message, char * sdp_type, char * sdp) {
	if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
		return ps_plugin_result_new(PS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
	
	int error_code = 0;
	char error_cause[512];
	json_t * root = NULL;
	json_t * response = NULL;
	
	if (message == NULL) {
		PS_LOG (LOG_ERR, "No message??\n");
		error_code = PS_GSTSINK_ERROR_NO_MESSAGE;
		g_snprintf (error_cause, 512, "%s", "No message");
		goto error;
	}
	PS_LOG (LOG_VERB, "Handling message: %s\n", message);
	ps_gstsink_session * session = (ps_gstsink_session *) handle->plugin_handle;
	
	if(!session) {
		PS_LOG(LOG_ERR, "No session associated with this handle...\n");
		error_code = PS_GSTSINK_ERROR_UNKNOWN_ERROR;
		g_snprintf(error_cause, 512, "%s", "session associated with this handle...");
		goto error;
	}
	if(session->destroyed) {
		PS_LOG(LOG_ERR, "Session has already been destroyed...\n");
		error_code = PS_GSTSINK_ERROR_UNKNOWN_ERROR;
		g_snprintf(error_cause, 512, "%s", "Session has already been destroyed...");
		goto error;
	}
	json_error_t error;
	root = json_loads(message, 0, &error);
	if(!root) {
		PS_LOG(LOG_ERR, "JSON error: on line %d: %s\n", error.line, error.text);
		error_code = PS_GSTSINK_ERROR_INVALID_JSON;
		g_snprintf(error_cause, 512, "JSON error: on line %d: %s", error.line, error.text);
		goto error;
	}
	if(!json_is_object(root)) {
		PS_LOG(LOG_ERR, "JSON error: not an object\n");
		error_code = PS_GSTSINK_ERROR_INVALID_JSON;
		g_snprintf(error_cause, 512, "JSON error: not an object");
		goto error;
	}
	
	json_t * request = json_object_get (root, "request");
	if (!request) {
		PS_LOG (LOG_ERR, "Missing element (request)\n");
		error_code = PS_GSTSINK_ERROR_MISSING_ELEMENT;
		g_snprintf (error_cause, 512, "Missing element (request)");
		goto error;
	}
	if (!json_is_string(request)) {
		PS_LOG (LOG_ERR, "Invalid element (request should be a string)\n");
		error_code = PS_GSTSINK_ERROR_INVALID_ELEMENT;
		g_snprintf (error_cause, 512, "Invalid element (request should be a string)");
		goto error;
	}
	
	const char * request_text = json_string_value (request);
	if (!strcasecmp(request_text, "list")) {
		json_t * list = json_array();
		PS_LOG(LOG_VERB, "Request for list of recordings\n");
		json_t * ml = json_object();
		json_object_set_new(ml, "id", json_integer(100));
		json_object_set_new(ml, "name", json_string("test"));
		json_object_set_new(ml, "date", json_string("06/06/2016"));
		json_object_set_new(ml, "audio", json_string("true"));
		json_object_set_new(ml, "video", json_string("true"));
		json_array_append_new(list, ml);
		response = json_object();
		json_object_set_new(response, "recordplay", json_string("list"));
		json_object_set_new(response, "list", list);
		goto plugin_response;
	} else if(!strcasecmp(request_text, "configure")) {
		json_t *video_bitrate_max = json_object_get(root, "video-bitrate-max");
		if(video_bitrate_max) {
			if(!json_is_integer(video_bitrate_max) || json_integer_value(video_bitrate_max) < 0) {
				PS_LOG(LOG_ERR, "Invalid element (video-bitrate-max should be a positive integer)\n");
				error_code = PS_GSTSINK_ERROR_INVALID_ELEMENT;
				g_snprintf(error_cause, 512, "Invalid element (video-bitrate-max should be a positive integer)");
				goto error;
			}
			session->video_bitrate = json_integer_value(video_bitrate_max);
			PS_LOG(LOG_VERB, "Video bitrate has been set to %"SCNu64"\n", session->video_bitrate);
		}
		json_t *video_keyframe_interval= json_object_get(root, "video-keyframe-interval");
		if(video_keyframe_interval) {
			if(!json_is_integer(video_keyframe_interval) || json_integer_value(video_keyframe_interval) < 0) {
				PS_LOG(LOG_ERR, "Invalid element (video-keyframe-interval should be a positive integer)\n");
				error_code = PS_GSTSINK_ERROR_INVALID_ELEMENT;
				g_snprintf(error_cause, 512, "Invalid element (video-keyframe-interval should be a positive integer)");
				goto error;
			}
			session->video_keyframe_interval = json_integer_value(video_keyframe_interval);
			PS_LOG(LOG_VERB, "Video keyframe interval has been set to %u\n", session->video_keyframe_interval);
		}
		response = json_object();
		json_object_set_new(response, "recordplay", json_string("configure"));
		json_object_set_new(response, "status", json_string("ok"));
		/* Return a success, and also let the client be aware of what changed, to allow crosschecks */
		json_t *settings = json_object();
		json_object_set_new(settings, "video-keyframe-interval", json_integer(session->video_keyframe_interval)); 
		json_object_set_new(settings, "video-bitrate-max", json_integer(session->video_bitrate)); 
		json_object_set_new(response, "settings", settings); 
		goto plugin_response;
	} else if (!strcasecmp(request_text, "start") || !strcasecmp(request_text,"stop")) {
		ps_gstsink_message * msg = g_malloc0(sizeof(ps_gstsink_message));
		if (msg==NULL) {
			PS_LOG (LOG_FATAL, "Memory Error!\n");
			error_code = PS_GSTSINK_ERROR_UNKNOWN_ERROR;
			g_snprintf (error_cause, 512, "Memory Error");
			goto error;
		}
		g_free (message);
		msg->handle = handle;
		msg->transaction = transaction;
		msg->message = root;
		msg->sdp_type = sdp_type;
		msg->sdp = sdp;
		
		g_async_queue_push (messages, msg);
		
		return ps_plugin_result_new (PS_PLUGIN_OK_WAIT, NULL);
	} else {
		PS_LOG (LOG_VERB, "Unknown request '%s'\n", request_text);
		error_code = PS_GSTSINK_ERROR_INVALID_REQUEST;
		g_snprintf (error_cause, 512, "Unknown request '%s'",request_text);
		goto error;
	}

plugin_response:
	{
		if(!response) {
			error_code = PS_GSTSINK_ERROR_UNKNOWN_ERROR;
			g_snprintf(error_cause, 512, "Invalid response");
			goto error;
		}
		if(root != NULL)
			json_decref(root);
		g_free(transaction);
		g_free(message);
		g_free(sdp_type);
		g_free(sdp);

		char *response_text = json_dumps(response, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref(response);
		ps_plugin_result *result = ps_plugin_result_new(PS_PLUGIN_OK, response_text);
		g_free(response_text);
		return result;
	}
		
error:
	{
		if (root != NULL) json_decref(root);
		g_free(transaction);
		g_free(message);
		g_free(sdp_type);
		g_free(sdp);
		
		json_t * event = json_object();
		json_object_set_new(event, "recordplay", json_string("event"));
		json_object_set_new(event, "error_code", json_integer(error_code));
		json_object_set_new(event, "error", json_string(error_cause));
		char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref(event);
		ps_plugin_result *result = ps_plugin_result_new(PS_PLUGIN_OK, event_text);
		g_free(event_text);
		return result;
	}
	
}
Пример #22
0
int la_pull_run(la_pull_t *puller)
{
    CURLcode ret;
    json_t *changes;
    json_error_t json_error;
    long status;
    int i, len;

    if (init_changes_feed(puller) != 0)
        return -1;
    
    ret = curl_easy_perform(puller->curl);
    if (ret != CURLE_OK)
    {
        debug("curl_easy_perform %d\n", ret);
        return -1;
    }
    
    if (curl_easy_getinfo(puller->curl, CURLINFO_RESPONSE_CODE, &status) != CURLE_OK)
    {
        return -1;
    }
    curl_easy_cleanup(puller->curl);
       
    if (status != 200)
    {
        debug("got response code %ld\n", status);
        return -1;
    }
        
    changes = json_loadb(la_buffer_data(puller->buffer), la_buffer_size(puller->buffer), 0, &json_error);
    la_buffer_clear(puller->buffer);
    if (changes == NULL || !json_is_object(changes))
        return -1;
    
    if (puller->last_seq != NULL)
        free(puller->last_seq);
    puller->last_seq = NULL;
    json_t *last_seq = json_object_get(changes, "last_seq");
    if (last_seq != NULL)
        puller->last_seq = json_dumps(last_seq, 0);
    
    json_t *results = json_object_get(changes, "results");
    if (results == NULL || !json_is_array(results))
    {
        json_decref(changes);
        return -1;
    }

    len = json_array_size(results);
    debug("got %d changes\n", len);
    for (i = 0; i < len; i++)
    {
        la_codec_error_t codec_error;
        la_db_get_result ret;
        la_rev_t rev, thatrev;
        json_t *key, *changes_array, *change_obj, *revobj, *seq;
        json_t *change = json_array_get(results, i);
        if (change == NULL || !json_is_object(change))
            continue;
        key = json_object_get(change, "id");
        if (key == NULL || !json_is_string(key))
            continue;
        debug("handling document %s\n", json_string_value(key));
        seq = json_object_get(change, "seq");
        if (seq == NULL || (!json_is_integer(seq) && !json_is_string(seq)))
            continue;
        changes_array = json_object_get(change, "changes");
        if (changes_array == NULL || !json_is_array(changes_array) || json_array_size(changes_array) == 0)
            continue;
        change_obj = json_array_get(changes_array, 0);
        if (change_obj == NULL || !json_is_object(change_obj))
            continue;
        revobj = json_object_get(change_obj, "rev");
        if (revobj == NULL || !json_is_string(revobj))
            continue;
        debug("changed revision %s\n", json_string_value(revobj));
        la_rev_scan(json_string_value(revobj), &thatrev);
        ret = la_db_get(puller->db, json_string_value(key), NULL, NULL, &rev, &codec_error);
        if (ret == LA_DB_GET_ERROR)
            continue;
        debug("get local result %d rev %s\n", ret, ret == LA_DB_GET_OK ? la_rev_string(rev) : "");
        if (ret == LA_DB_GET_NOT_FOUND || memcmp(&rev.rev.rev, &thatrev.rev.rev, LA_OBJECT_REVISION_LEN) != 0)
        {
            // Rev is missing, fetch it.
            la_codec_error_t codec_error;
            la_buffer_t *urlbuf = la_buffer_new(256);
            char *path = url_encode(json_string_value(key));
            la_buffer_appendf(urlbuf, "%s/%s?revs=true&rev=%s", puller->urlbase, path, json_string_value(revobj));
            char *url = la_buffer_string(urlbuf);
            free(path);
            
            debug("fetching %s\n", url);
            la_buffer_destroy(urlbuf);
            CURL *fetch = curl_easy_init();
            la_storage_rev_t *remote_revs = NULL;
            la_storage_rev_t *local_revs = NULL;
            uint64_t mystart;
            int j, revslen;
            
            if (fetch == NULL)
            {
                free(url);
                continue;
            }
            
            if (curl_easy_setopt(fetch, CURLOPT_URL, url) != CURLE_OK)
            {
                free(url);
                curl_easy_cleanup(fetch);
                continue;
            }
            free(url);
            if (puller->user != NULL)
            {
                if (curl_easy_setopt(fetch, CURLOPT_USERNAME, puller->user) != CURLE_OK)
                {
                    curl_easy_cleanup(fetch);
                    continue;
                }
            }
            if (puller->password != NULL)
            {
                if (curl_easy_setopt(fetch, CURLOPT_USERPWD, puller->password) != CURLE_OK)
                {
                    curl_easy_cleanup(fetch);
                    continue;
                }
            }
            curl_easy_setopt(fetch, CURLOPT_WRITEFUNCTION, pull_write_cb);
            curl_easy_setopt(fetch, CURLOPT_WRITEDATA, puller);
            if (curl_easy_perform(fetch) != CURLE_OK)
            {
                curl_easy_cleanup(fetch);
                continue;
            }
            curl_easy_cleanup(fetch);
            
            json_t *object = json_loadb(la_buffer_data(puller->buffer), la_buffer_size(puller->buffer), 0, &json_error);
            la_buffer_clear(puller->buffer);
            if (object == NULL || !json_is_object(object))
            {
                debug("didn't get object back from server %p %d\n", object, object ? json_typeof(object) : -1);
                debug("%s", json_error.text);
                continue;
            }
            
            json_t *_revisions = json_object_get(object, "_revisions");
            if (_revisions == NULL || !json_is_object(_revisions))
            {
                debug("didn't find _revisions\n");
                json_decref(object);
                continue;
            }
            json_incref(_revisions);
            json_object_del(object, "_revisions");
            
            json_t *_revisions_start = json_object_get(_revisions, "start");
            if (_revisions_start == NULL || !json_is_integer(_revisions_start))
            {
                debug("didn't find revisions/start\n");
                json_decref(_revisions);
                json_decref(object);
                continue;
            }
            
            json_t *_revisions_ids = json_object_get(_revisions, "ids");
            if (_revisions_ids == NULL || !json_is_array(_revisions_ids))
            {
                debug("didn't find revisions/ids\n");
                json_decref(_revisions);
                json_decref(object);
                continue;
            }
            
            revslen = json_array_size(_revisions_ids);
            debug("%d remote revisions\n", revslen);
            remote_revs = malloc(sizeof(la_storage_rev_t) * revslen);
            if (remote_revs == NULL)
            {
                json_decref(_revisions);
                json_decref(object);
                continue;
            }
            for (j = 0; j < revslen; j++)
            {
                la_storage_scan_rev(json_string_value(json_array_get(_revisions_ids, j)), &remote_revs[j]);
            }

            // Fetch local revisions of the object, if it exists.
            int myrevcount = 0;
            if (ret == LA_DB_GET_OK)
            {
                myrevcount = la_db_get_allrevs(puller->db, json_string_value(key), &mystart, &local_revs);
                
                if (myrevcount > 0 && local_revs != NULL)
                {
                    la_storage_rev_t *r = realloc(local_revs, (myrevcount + 1) * sizeof(la_storage_rev_t));
                    if (r == NULL)
                    {
                        json_decref(_revisions);
                        json_decref(object);
                        free(local_revs);
                        continue;
                    }
                    local_revs = r;
                    memmove(&local_revs[1], local_revs, sizeof(la_storage_rev_t) * myrevcount);
                    myrevcount++;
                }
                else
                {
                    local_revs = malloc(sizeof(la_storage_rev_t));
                    if (local_revs == NULL)
                    {
                        json_decref(object);
                        continue;
                    }
                    myrevcount = 1;
                }
                memcpy(&local_revs[0], &rev.rev, sizeof(la_storage_rev_t));
            }
            else
            {
                // If it doesn't exist, just set it.
                debug("value never there, just adding it\n");
                la_codec_value_t *value = la_codec_from_json(object);
                la_db_put_result putresult = la_db_replace(puller->db, json_string_value(key), &thatrev, value, &remote_revs[1], revslen - 1);
                if (putresult != LA_DB_PUT_OK)
                {
                    debug("failed to add the doc %d\n", putresult);
                }
                la_codec_decref(value);
                json_decref(object);
                json_decref(_revisions);
                continue;
            }
            
            // There will be three cases:
            //
            //  1. Our current version is part of the history of the remote version (we are behind).
            //     To resolve, take the remote version and the history.
            //
            //  2. Our history contains (some of) the remote history (we are ahead).
            //     To resolve, do nothing.
            //
            //  3. Our history diverges (we have a fork).
            //     To resolve, invoke the conflict handler.
            
            if (la_storage_revs_overlap(local_revs, myrevcount, remote_revs, revslen))
            {
                debug("overwriting local version\n");
                free(local_revs);
                // Just insert the document and revision history.
                la_codec_value_t *value = la_codec_from_json(object);
                la_db_replace(puller->db, json_string_value(key), &thatrev, value, &remote_revs[1], revslen - 1);
                la_codec_decref(value);
            }
            else if (!la_storage_revs_overlap(remote_revs, revslen, local_revs, myrevcount))
            {
                debug("handling conflict...\n");
                free(local_revs);
                // We are conflicting.
                la_codec_value_t *myvalue;
                if (la_db_get(puller->db, json_string_value(key), NULL, &myvalue, NULL, &codec_error) != LA_DB_GET_OK)
                {
                    la_codec_decref(myvalue);
                    json_decref(_revisions);
                    json_decref(object);
                    continue;
                }
                la_codec_value_t *theirvalue = la_codec_from_json(object);
                la_codec_value_t *mergedvalue = NULL;
                
                switch (puller->resolver(json_string_value(key), myvalue, theirvalue, &mergedvalue, puller->resolver_baton))
                {
                    case LA_PULL_RESOLVE_TAKE_MINE:
                        break; // Nothing
                        
                    case LA_PULL_RESOLVE_TAKE_THEIRS:
                        la_db_replace(puller->db, json_string_value(key), &thatrev, theirvalue, &remote_revs[1], revslen - 1);
                        break;
                        
                    case LA_PULL_RESOLVE_TAKE_MERGED:
                        la_db_put(puller->db, json_string_value(key), &rev, mergedvalue, NULL);
                        break;
                }
                
                la_codec_decref(myvalue);
                la_codec_decref(theirvalue);
                if (mergedvalue != NULL)
                    la_codec_decref(mergedvalue);
                free(remote_revs);
            }
            else
            {
                debug("doing nothing, we are ahead of the server");
            }
            // Otherwise, we are ahead. Do nothing.
        }
    }
    json_decref(changes);
 
    if ((puller->options & LA_PULL_CONTINUOUS) != 0)
    {
        init_changes_feed(puller);
    }
    return 0;
}
Пример #23
0
int janssonmod_set(unsigned int append, struct sip_msg* msg, char* type_in,
		 char* path_in, char* value_in, char* result_in)
{
	str type_s;
	str value_s;
	str path_s;

	pv_spec_t* result_pv;
	pv_value_t result_val;

	if (fixup_get_svalue(msg, (gparam_p)type_in, &type_s) != 0){
		ERR("cannot get type string value\n");
		return -1;
	}

	if (fixup_get_svalue(msg, (gparam_p)value_in, &value_s) != 0){
		ERR("cannot get value string\n");
		return -1;
	}

	if (fixup_get_svalue(msg, (gparam_p)path_in, &path_s) != 0){
		ERR("cannot get path string value\n");
		return -1;
	}

	result_pv = (pv_spec_t *)result_in;

	if(pv_get_spec_value(msg, result_pv, &result_val)!=0
			|| result_val.flags != PV_VAL_STR) {
		result_val.flags = PV_VAL_STR;
		result_val.rs.s = "{}";
		result_val.rs.len = strlen("{}");
	}

/*
	ALERT("type is: %.*s\n", type_s.len, type_s.s);
	ALERT("path is: %.*s\n", path_s.len, path_s.s);
	ALERT("value is: %.*s\n", value_s.len, value_s.s);
	ALERT("result is: %.*s\n", result_val.rs.len, result_val.rs.s);
*/

	char* result = result_val.rs.s;

	json_t* result_json = NULL;
	json_t* value = NULL;
	char* freeme = NULL;
	json_error_t parsing_error = {0};
	char* endptr;

	/* check the type */
	if(STR_EQ_STATIC(type_s, "object") || STR_EQ_STATIC(type_s, "obj")){
		value = json_loads(value_s.s, JSON_REJECT_DUPLICATES, &parsing_error);
		if(value && !json_is_object(value)) {
			ERR("value to add is not an object - \"%s\"\n", path_s.s);
			goto fail;
		}

	}else if(STR_EQ_STATIC(type_s, "array")) {
		value = json_loads(value_s.s, JSON_REJECT_DUPLICATES, &parsing_error);
		if(value && !json_is_array(value)) {
			ERR("value to add is not an array - \"%s\"\n", path_s.s);
			goto fail;
		}

	}else if(STR_EQ_STATIC(type_s, "string")
				|| STR_EQ_STATIC(type_s, "str")) {
		value = json_string(value_s.s);
		if(!value || !json_is_string(value)) {
			ERR("value to add is not a string - \"%s\"\n", path_s.s);
			goto fail;
		}

	}else if(STR_EQ_STATIC(type_s, "integer")
				|| STR_EQ_STATIC(type_s, "int")) {
		long long i = strtoll(value_s.s, &endptr, 10);
		if(*endptr != '\0') {
			ERR("parsing int failed for \"%s\" - \"%s\"\n", path_s.s, value_s.s);
			goto fail;
		}
		value = json_integer(i);
		if(!value || !json_is_integer(value)) {
			ERR("value to add is not an integer \"%s\"\n", path_s.s);
			goto fail;
		}

	}else if(STR_EQ_STATIC(type_s, "real")) {
		double d = strtod(value_s.s, &endptr);
		if(*endptr != '\0') {
			ERR("parsing real failed for \"%s\" - \"%s\"\n", path_s.s, value_s.s);
			goto fail;
		}
		value = json_real(d);
		if(!value || !json_is_real(value)) {
			ERR("value to add is not a real \"%s\"\n", path_s.s);
			goto fail;
		}

	}else if(STR_EQ_STATIC(type_s, "true")) {
		value = json_true();

	}else if(STR_EQ_STATIC(type_s, "false")) {
		value = json_false();

	}else if(STR_EQ_STATIC(type_s, "null")) {
		value = json_null();

	} else {
		ERR("unrecognized input type\n");
		goto fail;
	}

	if(!value) {
		ERR("parsing failed for \"%s\"\n", value_s.s);
		ERR("value error at line %d: %s\n",
				parsing_error.line, parsing_error.text);
		goto fail;
	}

	char* path = path_s.s;

	result_json = json_loads(result, JSON_REJECT_DUPLICATES, &parsing_error);

	if(!result_json) {
		ERR("result has json error at line %d: %s\n",
				parsing_error.line, parsing_error.text);
		goto fail;
	}

	if(json_path_set(result_json, path, value, append)<0) {
		goto fail;
	}

	if(jansson_to_val(&result_val, &freeme, result_json)<0) goto fail;

	result_pv->setf(msg, &result_pv->pvp, (int)EQ_T, &result_val);

	if(freeme) free(freeme);
	json_decref(result_json);
	return 1;

fail:
	if(freeme) free(freeme);
	json_decref(result_json);
	return -1;
}
Пример #24
0
bool ParamComboBox :: SetValueFromJSON (const json_t * const value_p)
{
	bool success_flag  = false;

	switch (bpw_param_p -> pa_type)
		{
			case PT_STRING:
			case PT_FILE_TO_READ:
			case PT_FILE_TO_WRITE:
			case PT_DIRECTORY:
				{
					if (json_is_string (value_p))
						{
							const char *value_s = json_string_value (value_p);

							pcb_combo_box_p -> setCurrentText (value_s);
							success_flag  = true;
						}
				}
				break;

			case PT_CHAR:
				{
					if (json_is_string (value_p))
						{
							const char *value_s = json_string_value (value_p);
							char c [2];

							*c = *value_s;
							* (c + 1) = '\0';

							pcb_combo_box_p -> setCurrentText (c);
							success_flag  = true;
						}
				}
				break;

			case PT_BOOLEAN:
				{
					if (json_is_true (value_p))
						{
							pcb_combo_box_p -> setCurrentText ("true");
						}
					else if (json_is_true (value_p))
						{
							pcb_combo_box_p -> setCurrentText ("false");
						}
				}
				break;

			case PT_SIGNED_INT:
			case PT_UNSIGNED_INT:
				{
					if (json_is_integer (value_p))
						{
							QString s;
							int value = json_integer_value (value_p);

							s.setNum (value);
							pcb_combo_box_p -> setCurrentText (s);

							success_flag = true;
						}
				}
				break;

			case PT_SIGNED_REAL:
			case PT_UNSIGNED_REAL:
				{
					if (json_is_number (value_p))
						{
							QString s;
							double value = json_number_value (value_p);

							s.setNum (value);
							pcb_combo_box_p -> setCurrentText (s);

							success_flag = true;
						}
				}
				break;

			default:
				break;
		}


	return success_flag;
}
Пример #25
0
static void
rdv_gen_request(httpsrv_client_t *hcl) {
	json_error_t	error;
	json_t		*root;
	const char	*server = NULL;
	bool		secure = false;

	if (hcl->method != HTTP_M_POST) {
		djb_error(hcl, 400, "gen_request requires a POST");
		return;
	}

	/* No body yet? Then allocate some memory to get it */
	if (hcl->readbody == NULL) {
		if (hcl->headers.content_length == 0) {
			djb_error(hcl, 400, "gen_request requires length");
			return;
		}

		if (httpsrv_readbody_alloc(hcl, 2, 0) < 0) {
			log_dbg("httpsrv_readbody_alloc() failed");
		}

		return;
	}

	log_dbg("data: %s", hcl->readbody);

	root = json_loads(hcl->readbody, 0, &error);
	httpsrv_readbody_free(hcl);

	if (root == NULL) {
		log_dbg("JSON load failed");
		return;

	} else if (json_is_object(root)) {
		json_t *server_val, *secure_val;

		secure_val = json_object_get(root, "secure");
		if (secure_val != NULL && json_is_true(secure_val)) {
			secure = true;
		}

		server_val = json_object_get(root, "server");

		if (server_val != NULL && json_is_string(server_val)) {
			server = json_string_value(server_val);
		}
	}

	if (server != NULL) {
		rdv_gen_request_aux(hcl, server, secure);
	} else {
		djb_error(hcl, 400, "POST data conundrum");

		if (root == NULL) {
			log_dbg("data: %s, error: line: %u, msg: %s",
				hcl->readbody, error.line, error.text);
		}
	}

	json_decref(root);
}
Пример #26
0
 /* --------------------------------------------------------------------------------------------
  * See whether the managed value is string.
 */
 bool IsString() const
 {
     return json_is_string(m_Ptr);
 }
Пример #27
0
CCObject* NDKHelper::GetCCObjectFromJson(json_t *obj)
{
    if (obj == NULL)
        return NULL;
    
    if (json_is_object(obj))
    {
        CCDictionary *dictionary = new CCDictionary();
        //CCDictionary::create();
        
        const char *key;
        json_t *value;
        
        void *iter = json_object_iter(obj);
        while(iter)
        {
            key = json_object_iter_key(iter);
            value = json_object_iter_value(iter);
            
            dictionary->setObject(NDKHelper::GetCCObjectFromJson(value)->autorelease(), string(key));
            
            iter = json_object_iter_next(obj, iter);
        }
        
        return dictionary;
    }
    else if (json_is_array(obj))
    {
        size_t sizeArray = json_array_size(obj);
        CCArray *array = new CCArray();
        //CCArray::createWithCapacity(sizeArray);
        
        for (unsigned int i = 0; i < sizeArray; i++)
        {
            array->addObject(NDKHelper::GetCCObjectFromJson(json_array_get(obj, i))->autorelease());
        }
        
        return array;
    }
    else if (json_is_boolean(obj))
    {
        stringstream str;
        if (json_is_true(obj))
            str << true;
        else if (json_is_false(obj))
            str << false;
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_integer(obj))
    {
        stringstream str;
        str << json_integer_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_real(obj))
    {
        stringstream str;
        str << json_real_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_string(obj))
    {
        stringstream str;
        str << json_string_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    
    return NULL;
}
Пример #28
0
int parse_status_json(json_t *status_root, status **status_ptr){
    json_t *idstr = json_object_get(status_root, "id_str");
    if(!json_is_string(idstr))
        return -1;
    json_t *textstr = json_object_get(status_root, "text");
    if(!json_is_string(textstr))
        return -1;

    status *st = newstatus();
    st->id = strdup(json_string_value(idstr));
    //json_decref(idstr);
    const char *text = json_string_value(textstr);
    st->wtext = malloc(sizeof(wchar_t)*(TWEET_MAX_LEN+1));
    mbstowcs(st->wtext, text, TWEET_MAX_LEN+1);
    //json_decref(textstr);
    st->length = wcslen(st->wtext);
    parse_user_json(json_object_get(status_root, "user"),&(st->composer));

    //printf("\n@%s --  %ls\n", st->composer->screen_name, st->wtext);

    json_t *entities = json_object_get(status_root, "entities");
    if(!entities)
        return -1;

    entity *prev = NULL;
    for(int i = 0; i < ENTITY_TYPE_COUNT; i++){
        json_t *entities_array = json_object_get(entities,entities_keys[i]);
        if(json_is_array(entities_array) && json_array_size(entities_array) > 0){
            for(int j = 0; j < json_array_size(entities_array); ++j){
                json_t *entity_root = json_array_get(entities_array, j);
                if(!entity_root)
                    continue;

                entity *et = newentity();
                et->type = entity_types[i];
                if(parse_entity_json(entity_root,et,st) < 0)
                    destroy_entity(et);
                else{
                    st->entity_count ++;
                    if(!(st->entities))
                        st->entities = et;
                    else
                        prev->next = et;
                    prev = et;
                }
            }
        }
    }

    split_status_entities(st);
    
    json_t *retweeted_status_root = json_object_get(status_root,"retweeted_status");
    if(retweeted_status_root){ 
        int result = parse_status_json(retweeted_status_root,&(st->retweeted_status));
        if(result == -1)
            st->retweeted_status = NULL;
    }
    /*
    for(entity *et = st->entities;et;et=et->next)
        printf("%ls ",et->text);
    printf("\n");
    */

    *status_ptr = st;

    return 0;
}
Пример #29
0
int jt_stats_unpacker(json_t *root, void **data)
{
	json_t *params;
	json_t *iface, *samples, *err_mean, *err_max, *err_sd;
	json_t *mts, *tv_sec, *tv_nsec;

	struct jt_msg_stats *stats;

	params = json_object_get(root, "p");
	assert(params);
	assert(JSON_OBJECT == json_typeof(params));
	assert(0 < json_object_size(params));

	stats = malloc(sizeof(struct jt_msg_stats));

	/* FIXME: this json_get_object() inteface sucks bricks,
	 * but the unpack API doesn't seem to work right now (jansson-2.7). :(
	 */
	iface = json_object_get(params, "iface");
	if (!json_is_string(iface)) {
		goto unpack_fail;
	}
	snprintf(stats->iface, MAX_IFACE_LEN, "%s", json_string_value(iface));

	samples = json_object_get(params, "s");
	if (!json_is_array(samples)) {
		goto unpack_fail;
	}

	stats->sample_count = json_array_size(samples);
	stats->samples =
	    malloc(stats->sample_count * sizeof(struct stats_sample));

	int i;
	for (i = 0; i < stats->sample_count; i++) {
		json_t *s = json_array_get(samples, i);
		assert(json_is_object(s));
		json_t *t;

		t = json_object_get(s, "rx");
		assert(json_is_integer(t));
		stats->samples[i].rx = json_integer_value(t);

		t = json_object_get(s, "tx");
		assert(json_is_integer(t));
		stats->samples[i].tx = json_integer_value(t);

		t = json_object_get(s, "rxP");
		assert(json_is_integer(t));
		stats->samples[i].rxPkt = json_integer_value(t);

		t = json_object_get(s, "txP");
		assert(json_is_integer(t));
		stats->samples[i].txPkt = json_integer_value(t);
	}

	/* get the stats sampling time error */
	err_mean = json_object_get(params, "whoosh_err_mean");
	if (!json_is_integer(err_mean)) {
		goto unpack_fail_free_samples;
	}
	stats->err.mean = json_integer_value(err_mean);

	err_max = json_object_get(params, "whoosh_err_max");
	if (!json_is_integer(err_max)) {
		goto unpack_fail_free_samples;
	}
	stats->err.max = json_integer_value(err_max);

	err_sd = json_object_get(params, "whoosh_err_sd");
	if (!json_is_integer(err_sd)) {
		goto unpack_fail_free_samples;
	}
	stats->err.sd = json_integer_value(err_sd);

	/* get the message timestamp */
	mts = json_object_get(params, "t");
	if (!json_is_object(mts)) {
		goto unpack_fail_free_samples;
	}

	tv_sec = json_object_get(mts, "tv_sec");
	if (!json_is_integer(tv_sec)) {
		goto unpack_fail_free_samples;
	}
	stats->mts.tv_sec = json_integer_value(tv_sec);

	tv_nsec = json_object_get(mts, "tv_nsec");
	if (!json_is_integer(tv_nsec)) {
		goto unpack_fail_free_samples;
	}
	stats->mts.tv_nsec = json_integer_value(tv_nsec);

	*data = stats;
	json_object_clear(params);
	return 0;

unpack_fail_free_samples:
	free(stats->samples);
unpack_fail:
	free(stats);
	return -1;
}
Пример #30
0
static int unpack(scanner_t *s, json_t *root, va_list *ap)
{
    switch(s->token)
    {
        case '{':
            return unpack_object(s, root, ap);

        case '[':
            return unpack_array(s, root, ap);

        case 's':
            if(!json_is_string(root)) {
                set_error(s, "<validation>", "Expected string, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY)) {
                const char **str;

                str = va_arg(*ap, const char **);
                if(!str) {
                    set_error(s, "<args>", "NULL string argument");
                    return -1;
                }

                *str = json_string_value(root);
            }
            return 0;

        case 'i':
            if(!json_is_integer(root)) {
                set_error(s, "<validation>", "Expected integer, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, int*) = (int) json_integer_value(root);

            return 0;

        case 'I':
            if(!json_is_integer(root)) {
                set_error(s, "<validation>", "Expected integer, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, json_int_t*) = json_integer_value(root);

            return 0;

        case 'b':
            if(!json_is_boolean(root)) {
                set_error(s, "<validation>", "Expected true or false, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, int*) = json_is_true(root);

            return 0;

        case 'f':
            if(!json_is_real(root)) {
                set_error(s, "<validation>", "Expected real, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, double*) = json_real_value(root);

            return 0;

        case 'F':
            if(!json_is_number(root)) {
                set_error(s, "<validation>", "Expected real or integer, got %s",
                          type_name(root));
                return -1;
            }

            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, double*) = json_number_value(root);

            return 0;

        case 'O':
            if(!(s->flags & JSON_VALIDATE_ONLY))
                json_incref(root);
            /* Fall through */

        case 'o':
            if(!(s->flags & JSON_VALIDATE_ONLY))
                *va_arg(*ap, json_t**) = root;

            return 0;

        case 'n':
            /* Never assign, just validate */
            if(!json_is_null(root)) {
                set_error(s, "<validation>", "Expected null, got %s",
                          type_name(root));
                return -1;
            }
            return 0;

        default:
            set_error(s, "<format>", "Unexpected format character '%c'",
                      s->token);
            return -1;
    }
}