Example #1
0
// Fetch JSON from OpenWeatherMap
struct json_write_result *
owm_fetch_remote (const char method, const char * location, const char scale,
                  const char * file_cache_path, const char * api_key) {

    CURL * handle;
    CURLcode result;

    char * data = calloc(1, BUFFER_SIZE);
    static struct json_write_result written_result;
    written_result.data = data;
    written_result.position = 0;

    char url [256] = {'\0'};
    char * fetch_method;
    char * fetch_scale;

    switch ( method ) {
        case 'i':
            fetch_method = "id";
            break;

        default:
            fetch_method = "q";
            break;
    }

    switch ( scale ) {
        case 'i':
            fetch_scale = "imperial";
            break;

        default:
            fetch_scale = "metric";
            break;
    }

    handle = curl_easy_init();

    if ( handle ) {
        const char * provider =
            "http://api.openweathermap.org/data/2.5/weather";

        char * encoded_location = curl_easy_escape(handle, location, 0);

        snprintf(url, sizeof(url), "%s?%s=%s&units=%s&APPID=%s", provider,
                 fetch_method, encoded_location, fetch_scale, api_key);

        curl_easy_setopt(handle, CURLOPT_URL, url);
        curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data_buffer);
        curl_easy_setopt(handle, CURLOPT_WRITEDATA, &written_result);

        result = curl_easy_perform(handle);
        if ( result != CURLE_OK ) {
            fprintf(stderr, "Failed to retrieve data (%s)\n",
                    curl_easy_strerror(result));

            curl_easy_cleanup(handle);
            curl_free(encoded_location);
            exit(1);
        }

        curl_free(encoded_location);
    }

    if ( file_cache_path ) {
        json_error_t err;
        json_t * resjson = json_loads(written_result.data, 0, &err);
        size_t flags = JSON_PRESERVE_ORDER | JSON_INDENT(2);
        if ( resjson && json_dump_file(resjson, file_cache_path, flags) == -1 ) {
            fprintf(stderr, "Error caching file\n");
            exit(1);
        }
    } curl_easy_cleanup(handle);

    return &written_result;
}
Example #2
0
static void
rdv_peel(httpsrv_client_t *hcl) {
	const char	*response = NULL;
	json_error_t	error;
	json_t		*root;
	int		otype;

	if (hcl->method != HTTP_M_POST) {
		djb_error(hcl, 400, "peel 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, "peel requires length");
			return;
		}

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

	log_dbg("readbody: %s", hcl->readbody);
	root = json_loads(hcl->readbody, 0, &error);
	httpsrv_readbody_free(hcl);

	if (root == NULL) {
		log_dbg("libjansson error: line: %u msg: %s",
			error.line, error.text);
		djb_error(hcl, 400, "Invalid JSON");

	} else if (!json_is_object(root)) {
		log_dbg("JSON passed is not an object");
		djb_error(hcl, 400, "No Object in JSON");

	} else if (l_current_onion == NULL) {
		djb_error(hcl, 400, "Currently no onion");

	} else if (!ONION_IS_ONION(l_current_onion)) {
		djb_error(hcl, 400, "Onion is not an onion");

	} else {
		otype = ONION_TYPE(l_current_onion);
		log_dbg("onion_type: %s\n", rdv_onion_name(otype));

		switch (otype) {
		case BASE:
			response = rdv_peel_base();
			break;

		case POW:
			response = rdv_peel_pow();
			break;

		case CAPTCHA:
			response = rdv_peel_captcha(root);
			break;

		case SIGNED:
			response = rdv_peel_signed();
			break;

		case COLLECTION:
		default:
			djb_error(hcl, 400,
				 "Onion method not implemented yet");
			break;
		}

		if (response != NULL) {
			djb_presult(hcl, response);

			aprintf_free(response);
			response = NULL;
		} else {
			djb_error(hcl, 400, "Peeling failed");
		}
	}

	json_decref(root);
}
Example #3
0
static void
zyre_bridge_actor (zsock_t *pipe, void *args)
{

    // initialization
    ubx_block_t *b = (ubx_block_t *) args;
    struct zyre_bridge_info *inf = (struct zyre_bridge_info*) b->private_data;
    printf("[zyre_bridge]: actor started.\n");
    // send signal on pipe socket to acknowledge initialization
    zsock_signal (pipe, 0);

    bool terminated = false;
	zpoller_t *poller = zpoller_new (pipe, zyre_socket (inf->node), NULL);
	while (!terminated) {
		void *which = zpoller_wait (poller, -1);
		// handle msgs from main thread
		if (which == pipe) {
			zmsg_t *msg = zmsg_recv (which);
			if (!msg)
				break;              //  Interrupted
			// only react to TERM signal
			char *command = zmsg_popstr (msg);
			if (streq (command, "$TERM"))
				terminated = true;
			else {
				puts ("Invalid pipe message to actor");
			}
			free (command);
			zmsg_destroy (&msg);
		} else
		// handle msgs from zyre network
		if (which == zyre_socket (inf->node)) {
			zmsg_t *msg = zmsg_recv (which);
			if (!msg) {
				printf("[zyre_bridge]: interrupted!\n");
			}
			char *event = zmsg_popstr (msg);
			char *peer = zmsg_popstr (msg);
			char *name = zmsg_popstr (msg);

			if (streq (event, "ENTER"))
				printf ("[zyre_bridge]: %s has entered\n", name);
			else
			if (streq (event, "EXIT"))
				printf ("[zyre_bridge]: %s has exited\n", name);
			else
			if (streq (event, "SHOUT")) {
				printf ("[zyre_bridge]: SHOUT received from %s.\n", name);

				char *group = zmsg_popstr (msg);
				char *message = zmsg_popstr (msg);

				// load JSON msg
		    	json_t *m;
				json_error_t error;
				m= json_loads(message,0,&error);
				if(!m) {
					printf("Error parsing JSON payload! line %d, column %d: %s\n", error.line, error.column, error.text);
					json_decref(m);
				} else {
					printf("%s\n",message);
					if (json_object_get(m, "type")) {
						std::string type = json_dumps(json_object_get(m, "type"), JSON_ENCODE_ANY);
						type = type.substr(1, type.size()-2); // get rid of " characters
						printf("type: %s\n",json_dumps(json_object_get(m, "type"), JSON_ENCODE_ANY));

						for (int i=0; i < inf->input_type_list.size();i++)
						{
							//if (json_string_value(json_object_get(m, "type")) == inf->input_type_list[i]){
							//printf("type list, type : %s, %s \n", inf->input_type_list[i].c_str(), type.c_str());
							if (inf->input_type_list[i].compare(type) == 0) {
								ubx_type_t* type =  ubx_type_get(b->ni, "unsigned char");
								ubx_data_t ubx_msg;
								ubx_msg.data = (void *)json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY);
								printf("message: %s\n",json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY));
								ubx_msg.len = strlen(json_dumps(json_object_get(m, "payload"), JSON_ENCODE_ANY));
								ubx_msg.type = type;
								__port_write(inf->ports.zyre_in, &ubx_msg);
							}
						}
					} else {
						printf("Error parsing JSON string! Does not conform to msg model.\n");
					}
				}
				free (group);
				free (message);
			}
			else
			if (streq (event, "WHISPER")){
				char *message = zmsg_popstr (msg);
				printf ("%s: WHISPER \n%s\n", name, message);
				free (message);
			}
			else
			if (streq (event, "EVASIVE"))
				printf ("[zyre_bridge]: %s is being evasive\n", name);

			free (event);
			free (peer);
			free (name);
			zmsg_destroy (&msg);
		}
	}
	zpoller_destroy (&poller);
	//TODO: make parametrizable
	zclock_sleep (100);
}
Example #4
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;
}
Example #5
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;
}
Example #6
0
static void ZnpActorOnRequestAddDevice(PVOID pParam)
{
	char* message = (char*)pParam;
	char **znpSplitMessage;
	if (pZnpActor == NULL) return;
	json_t* payloadJson = NULL;
	json_t* paramsJson = NULL;
	json_t* durationJson = NULL;
	json_t* responseJson = NULL;
	json_t* statusJson = NULL;
	PACTORHEADER header;
	char* responseTopic;
	int duration = 0;
	char* responseMessage;
	BYTE nResult;
	znpSplitMessage = ActorSplitMessage(message);
	if (znpSplitMessage == NULL)
		return;
	// parse header to get origin of message
	header = ActorParseHeader(znpSplitMessage[0]);
	if (header == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		return;
	}
	//parse payload
	payloadJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	if (payloadJson == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	paramsJson = json_object_get(payloadJson, "params");
	if (paramsJson == NULL)
	{
		json_decref(payloadJson);
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	durationJson = json_object_get(paramsJson, "duration");
	if (durationJson == NULL)
	{
		json_decref(paramsJson);
		json_decref(payloadJson);
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	duration = json_integer_value(durationJson);
	json_decref(durationJson);
	json_decref(paramsJson);
	json_decref(payloadJson);
	// send add item command to znp
	nResult = ZnpZbPermitJoiningReq(0xFFFF, duration);
	//make response package
	responseJson = json_object();
	statusJson = json_object();
	json_t* requestJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	json_object_set(responseJson, "request", requestJson);
	json_decref(requestJson);
	json_t* resultJson;
	if (nResult == 0)
	{
		resultJson = json_string("status.success");
	}
	else
	{
		resultJson = json_string("status.failure");
	}
	json_object_set(statusJson, "status", resultJson);
	json_decref(resultJson);
	json_object_set(responseJson, "response", statusJson);
	json_decref(statusJson);
	responseMessage = json_dumps(responseJson, JSON_INDENT(4) | JSON_REAL_PRECISION(4));
	responseTopic = StrDup(header->origin);
	ActorFreeHeaderStruct(header);
	json_decref(responseJson);
	ActorFreeSplitMessage(znpSplitMessage);
//	ActorSend(pZnpActor, responseTopic, responseMessage, NULL, FALSE, responseTopic);
	ActorSend(pZnpActor, responseTopic, responseMessage, NULL, FALSE, "response");
	free(responseMessage);
	free(responseTopic);
}
Example #7
0
static int ps_websockets_callback (
	struct lws * wsi,
	enum lws_callback_reasons reason,
	void * user, void * in, size_t len) 
{
	ps_websockets_client * wsclient = (ps_websockets_client *) user;
	
	switch (reason) {
		case LWS_CALLBACK_CLIENT_ESTABLISHED: {
			wsclient->wsi = wsi;
			wsclient->messages = g_async_queue_new ();
			wsclient->buffer = NULL;
			wsclient->buflen = 0;
			wsclient->bufpending = 0;
			wsclient->bufoffset = 0;
			wsclient->session_timeout = 0;
			wsclient->destroy = 0;
			ps_mutex_init(&wsclient->mutex);
			
			lws_callback_on_writable(wsi);
			PS_LOG (LOG_INFO,"LWS_CALLBACK_CLIENT_ESTABLISHED\n");
			return 0;
		}

        case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: {
			PS_LOG (LOG_ERR,"LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
			return 0;
		}

        case LWS_CALLBACK_CLOSED: {
			
			PS_LOG (LOG_INFO,"LWS_CALLBACK_CLOSED: Websocket connection closed \n");
			if (wsclient != NULL) {
				gateway->transport_gone (&ps_websockets_transport, wsclient);
				
				ps_mutex_lock (&wsclient->mutex);
				wsclient->destroy = 1;
				wsclient->wsi = NULL;
				
				/* Remove message queue */
				if (wsclient->messages != NULL) {
					char * response = NULL;
					while ((response = g_async_queue_try_pop(wsclient->messages)) != NULL ) {
						g_free (response);
					}
					g_async_queue_unref (wsclient->messages);
				}
				g_free (wsclient->incoming);
				wsclient->incoming = NULL;
				g_free (wsclient->buffer);
				wsclient->buffer = NULL;
				wsclient->buflen = 0;
				wsclient->bufpending = 0;
				wsclient->bufoffset = 0;
				
				ps_mutex_unlock(&wsclient->mutex);
			}
			return 0;
		}

        case LWS_CALLBACK_CLIENT_RECEIVE: {
			if (wsclient == NULL || wsclient->wsi == NULL) {
				PS_LOG (LOG_ERR,"LWS_CALLBACK_CLIENT_RECEIVE: Invalid websocket client instance\n");
				return -1;
			}
			
			const size_t remaining = lws_remaining_packet_payload (wsi);
			
			if (wsclient->incoming == NULL) {
				wsclient->incoming = g_malloc0 (len+1);
				memcpy(wsclient->incoming, in, len);
				wsclient->incoming[len] = '\0';
				PS_LOG (LOG_VERB,"LWS_CALLBACK_CLIENT_RECEIVE: %s\n",wsclient->incoming);
			} else {
				size_t offset = strlen (wsclient->incoming);
				wsclient->incoming = g_realloc (wsclient->incoming, offset+len+1);
				wsclient->incoming[offset+len] = '\0';
				PS_LOG (LOG_VERB,"LWS_CALLBACK_CLIENT_RECEIVE: %s\n",wsclient->incoming+offset);
			}
			
			if (remaining > 0 || !lws_is_final_fragment (wsi)) {
				PS_LOG (LOG_VERB,"LWS_CALLBACK_CLIENT_RECEIVE: Waiting for more fragments\n");
				return 0;
			}
			
			json_error_t error;
			json_t * root = json_loads (wsclient->incoming, 0, &error);
			g_free (wsclient->incoming);
			wsclient->incoming = NULL;
			
			gateway->incoming_request(&ps_websockets_transport, wsclient, root, &error);
			return 0;
		}
            
        case LWS_CALLBACK_CLIENT_WRITEABLE : {
			if (wsclient == NULL || wsclient->wsi == NULL) {
				PS_LOG (LOG_ERR,"LWS_CALLBACK_CLIENT_WRITEABLE: Invalid websocket client instance\n");
				return -1;
			}
			if (!wsclient->destroy && !g_atomic_int_get(&stopping)) {
				
				ps_mutex_lock (&wsclient->mutex);
				
				/* Check if a pending/partial write to complete first */
				if (wsclient->buffer && wsclient->bufpending > 0 && wsclient->bufoffset > 0 && !wsclient->destroy && !g_atomic_int_get(&stopping)) {
					
					int sent = lws_write (wsi, wsclient->buffer + wsclient->bufoffset,
					wsclient->bufpending, LWS_WRITE_TEXT);
					
					if (sent > -1 && sent < wsclient->bufpending) {
						wsclient->bufpending -= sent;
						wsclient->bufoffset += sent;
					} else {
						wsclient->bufpending = 0;
						wsclient->bufoffset = 0;
					}
					
					lws_callback_on_writable (wsi);
					ps_mutex_unlock(&wsclient->mutex);
					return 0;
				}
				
				/* shoot all pending messages */
				char * response = g_async_queue_try_pop (wsclient->messages);
				
				if (response && !wsclient->destroy && !g_atomic_int_get(&stopping)) {
					
					int buflen = LWS_SEND_BUFFER_PRE_PADDING + strlen(response) + LWS_SEND_BUFFER_POST_PADDING;
					
					if (wsclient->buffer == NULL) {
						wsclient->buflen = buflen;
						wsclient->buffer = g_malloc0 (buflen);
					} else if (buflen > wsclient->buflen) {
						wsclient->buflen = buflen;
						wsclient->buffer = g_realloc (wsclient->buffer, buflen);
					}
					memcpy(wsclient->buffer + LWS_SEND_BUFFER_PRE_PADDING, response, strlen(response));
					int sent = lws_write (wsi, wsclient->buffer + LWS_SEND_BUFFER_PRE_PADDING, strlen(response), LWS_WRITE_TEXT);
					
					if (sent > -1 && sent < (int)strlen(response)) {
						wsclient->bufpending = strlen(response) - sent;
						wsclient->bufoffset = LWS_SEND_BUFFER_PRE_PADDING + sent;
					}
					
					g_free (response);
					lws_callback_on_writable (wsi);
					ps_mutex_unlock(&wsclient->mutex);
					return 0;
				}
				ps_mutex_unlock(&wsclient->mutex);
			}
			return 0;
			
		}

        default:
            break;
	}
	
	return 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;
}
Example #9
0
void *proof_of_work(void *arg){
    uint8_t flag = 0;
    FILE *flag_p, *params_p;

    while(1){
        flag_p = fopen("proof-flag", "r");
        if(flag_p == NULL){
            die("File open block failed.");
        }
        fread(&flag, 1, 1, flag_p);
        fclose(flag_p);
        if(flag){
            char *proof_resp, *params;
            uint8_t *raw_params = NULL;
            json_t *json_setup = NULL, *json_resp;
            json_error_t json_error;
            json_t *result = NULL;
            
            json_resp = json_loads(req, 0, &json_error);
            
            if(!json_resp){
                json_die(json_error.line, json_error.text);
            }

            //need to convert to proper format
            //for now i will just ust bock-data, which is the data being sent
            // params_p = fopen("params-solution", "r");
            params_p = fopen("block-data", "r");
            if(flag_p == NULL){
                die("File open block failed.");
            }

            fread(raw_params, 1, 8, params_p);
            fclose(params_p);

            params = endian_flip_32_bit_chunks(bytesToStringHex(raw_params));

            json_object_set(json_setup, "params", json_loads(params, 0, &json_error));

            printf("sending proof of work\n");
            printf("%s\n", json_string_value(json_setup));
            proof_resp = request(pool_url, json_string_value(json_setup));

            if(!proof_resp){
                die("proof_of_work repsonse failed check args");
            }

            printf("%s\n", proof_resp);

            json_resp = json_loads(proof_resp, 0, &json_error);
            result = json_object_get(json_resp, "result");

            json_decref(json_resp);
            json_decref(json_setup);
            printf("%s\n", json_string_value(result));
            //result should be true for a valid proof of work and false for an invalid proof of work

            flag = 0;
            fwrite(&flag, 1, 1, flag_p);
            fclose(flag_p);
        }        
    }
}
Example #10
0
static json_t *compat_json_loads(const char *input, json_error_t *error)
{
    return json_loads(input, 0, error);
}
Example #11
0
void read_config(void)
{
	json_t *jcfg, *cred_expire;
	json_error_t err;
	const char *tmp_str, *rpcuser, *rpcpass;
	char *file_data;

	file_data = read_commented_file(srv.config);
	if (!file_data)
		exit(1);

	jcfg = json_loads(file_data, &err);

	free(file_data);

	if (!jcfg) {
		applog(LOG_ERR, "%s: JSON parse failed", srv.config);
		exit(1);
	}

	if (!json_is_object(jcfg)) {
		applog(LOG_ERR, "top-level JSON value not an object");
		exit(1);
	}

	parse_listen(json_object_get(jcfg, "listen"));
	parse_database(json_object_get(jcfg, "database"));
	parse_memcached(json_object_get(jcfg, "memcached"));

	if (elist_empty(&srv.listeners)) {
		applog(LOG_ERR, "error: no listen addresses specified");
		exit(1);
	}

	tmp_str = json_string_value(json_object_get(jcfg, "pid"));
	if (tmp_str)
		srv.pid_file = strdup(tmp_str);

	tmp_str = json_string_value(json_object_get(jcfg, "forcehost"));
	if (tmp_str)
		srv.ourhost = strdup(tmp_str);

	tmp_str = json_string_value(json_object_get(jcfg, "log.requests"));
	if (tmp_str) {
		srv.req_log = strdup(tmp_str);
		srv.req_fd = open(srv.req_log,
				  O_WRONLY | O_CREAT | O_APPEND, 0666);
		if (srv.req_fd < 0) {
			syslogerr(srv.req_log);
			exit(1);
		}
	}

	tmp_str = json_string_value(json_object_get(jcfg, "log.shares"));
	if (tmp_str) {
		srv.share_log = strdup(tmp_str);
		srv.share_fd = open(srv.share_log,
				  O_WRONLY | O_CREAT | O_APPEND, 0666);
		if (srv.share_fd < 0) {
			syslogerr(srv.share_log);
			exit(1);
		}
	}

	if (json_is_true(json_object_get(jcfg, "longpoll.disable")))
		srv.disable_lp = true;

	cred_expire = json_object_get(jcfg, "auth.cred_cache.expire");
	if (json_is_integer(cred_expire))
		srv.cred_expire = json_integer_value(cred_expire);

	tmp_str = json_string_value(json_object_get(jcfg, "rpc.url"));
	if (!tmp_str) {
		applog(LOG_ERR, "error: no RPC URL specified");
		exit(1);
	}
	srv.rpc_url = strdup(tmp_str);

	rpcuser = json_string_value(json_object_get(jcfg, "rpc.user"));
	rpcpass = json_string_value(json_object_get(jcfg, "rpc.pass"));
	if (!rpcuser || !rpcpass) {
		applog(LOG_ERR, "error: no RPC user and/or password specified");
		exit(1);
	}
	if (asprintf(&srv.rpc_userpass, "%s:%s", rpcuser, rpcpass) < 0) {
		applog(LOG_ERR, "OOM");
		exit(1);
	}

	if (json_is_true(json_object_get(jcfg, "rpc.target.rewrite")))
		srv.easy_target = json_string(EASY_TARGET);

	if (!srv.pid_file) {
		if (!(srv.pid_file = strdup("/var/run/pushpoold.pid"))) {
			applog(LOG_ERR, "no core");
			exit(1);
		}
	}

	json_decref(jcfg);
}
Example #12
0
void receive_json_message(const std::string& topic_name, const std::string& json_message) {
    if (topic_name=="blit_images") {
        std::string image_format;

        std::string image_data;
        parse_json_image(json_message,
                         image_format,
                         image_data);

        std::istringstream iss(image_data);

        osg::ref_ptr<osg::Image> image;
        if (image_format.at(0)=='.') {
            image_format = image_format.substr(1);
        }
        osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(image_format);
        freemovr_assert_msg( rw!=NULL, "no ReaderWriter for image_format" );
        osgDB::ReaderWriter::ReadResult rr = rw->readImage(iss);
        freemovr_assert_msg( rr.success(), "bad image read");
        image = rr.takeImage();
        osg::ref_ptr<osg::Texture> texture = new osg::TextureRectangle(image);
        osg::ref_ptr<osg::StateSet> ss = _group->getOrCreateStateSet();
        ss->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
    } else if (topic_name=="sprite_image") {
        std::string image_format;

        std::string image_data;
        parse_json_image(json_message,
                         image_format,
                         image_data);
        std::istringstream iss(image_data);

        osg::ref_ptr<osg::Image> image;
        if (image_format.at(0)=='.') {
            image_format = image_format.substr(1);
        }
        osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(image_format);
        freemovr_assert_msg( rw!=NULL, "no ReaderWriter for image_format" );
        osgDB::ReaderWriter::ReadResult rr = rw->readImage(iss);
        freemovr_assert_msg( rr.success(), "bad image read");
        image = rr.takeImage();
        _load_sprite_image(image);
    } else if (topic_name=="sprite_pose") {
        json_t *root;
        json_error_t error;

        root = json_loads(json_message.c_str(), 0, &error);
        freemovr_assert_msg(root!=NULL,"error in JSON");

        json_t *data_json;

        data_json = json_object_get(root, "x");
        if(!json_is_number(data_json)){
            fprintf(stderr, "error: in %s(%d): expected number\n", __FILE__, __LINE__);
            throw std::runtime_error("error in json");
        }
        double x = json_number_value( data_json );

        data_json = json_object_get(root, "y");
        if(!json_is_number(data_json)){
            fprintf(stderr, "error: in %s(%d): expected number\n", __FILE__, __LINE__);
            throw std::runtime_error("error in json");
        }
        double y = json_number_value( data_json );

        data_json = json_object_get(root, "theta");
        if(!json_is_number(data_json)){
            fprintf(stderr, "error: in %s(%d): expected number\n", __FILE__, __LINE__);
            throw std::runtime_error("error in json");
        }
        double theta = json_number_value( data_json );
        if (theta!=0.0) {
            throw std::runtime_error("theta != 0.0 not implemented.");
        }

        osg::Vec3 newpos = osg::Vec3( x, _height-y, 0.0); // convert to our coord system
        sprite_pat->setPosition(newpos);
    } else {
        throw std::runtime_error("unknown topic_name");
    }
}
Example #13
0
json_t* authRequest(CURL *curl, Parameters params, std::string url, std::string request, std::string options) {
  // nonce
  struct timeval tv;
  gettimeofday(&tv, NULL);
  unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5;

  // check if options parameter is empty
  std::ostringstream oss;
  if (options.empty()) {
    oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\"}";
  }
  else {
    oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\", " << options << "}";
  }
  std::string tmpPayload = base64_encode(reinterpret_cast<const unsigned char*>(oss.str().c_str()), oss.str().length());

  oss.clear();
  oss.str("");

  oss << "X-BFX-PAYLOAD:" << tmpPayload;
  std::string payload;
  payload = oss.str();

  oss.clear();
  oss.str("");

  // build the signature
  unsigned char* digest;

  // Using sha384 hash engine
  digest = HMAC(EVP_sha384(), params.bitfinexSecret, strlen(params.bitfinexSecret), (unsigned char*)tmpPayload.c_str(), strlen(tmpPayload.c_str()), NULL, NULL);

  char mdString[SHA384_DIGEST_LENGTH+100];   // FIXME +100
  for (int i = 0; i < SHA384_DIGEST_LENGTH; ++i) {
    sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
  }
  oss.clear();
  oss.str("");
  oss << "X-BFX-SIGNATURE:" << mdString;

  // cURL headers
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, params.bitfinexApi);
  headers = curl_slist_append(headers, payload.c_str());
  headers = curl_slist_append(headers, oss.str().c_str());

  // cURL request
  CURLcode resCurl;
//  curl = curl_easy_init();
  if (curl) {
    std::string readBuffer;
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
    resCurl = curl_easy_perform(curl);
    json_t *root;
    json_error_t error;

    while (resCurl != CURLE_OK) {
      std::cout << "<Bitfinex> Error with cURL. Retry in 2 sec...\n" << std::endl;
      sleep(2.0);
      readBuffer = "";
      resCurl = curl_easy_perform(curl);
    }
    root = json_loads(readBuffer.c_str(), 0, &error);

    while (!root) {
      std::cout << "<Bitfinex> Error with JSON:\n" << error.text << ". Retrying..." << std::endl;
      readBuffer = "";
      resCurl = curl_easy_perform(curl);
      while (resCurl != CURLE_OK) {
        std::cout << "<Bitfinex> Error with cURL. Retry in 2 sec...\n" << std::endl;
        sleep(2.0);
        readBuffer = "";
        resCurl = curl_easy_perform(curl);
      }
      root = json_loads(readBuffer.c_str(), 0, &error);
    }
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return root;
  }
  else {
    std::cout << "<Bitfinex> Error with cURL init." << std::endl;
    return NULL;
  }
}
Example #14
0
json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) {

  // create nonce and POST data
  struct timeval tv;
  gettimeofday(&tv, NULL);
  unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5;

  std::string post_data = "";
  if (options.empty()) {
    post_data = "nonce=" + patch::to_string(nonce);
  }
  else {
    post_data = "nonce=" + patch::to_string(nonce) + "&" + options;
  }

  // Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data))
  // and base64 decoded secret API key
  std::string payload_for_signature = patch::to_string(nonce) + post_data;
  unsigned char digest[SHA256_DIGEST_LENGTH];
  SHA256((unsigned char*)payload_for_signature.c_str(), strlen(payload_for_signature.c_str()), (unsigned char*)&digest);
  int signature_data_length = request.length() + SHA256_DIGEST_LENGTH;
  unsigned char signature_data[signature_data_length];
  std::copy(request.begin(), request.end(), &signature_data[0]);
  memcpy(&signature_data[request.length()], &digest, SHA256_DIGEST_LENGTH);
  std::string decoded_key = base64_decode(params.krakenSecret);
  unsigned char* hmac_digest;
  hmac_digest = HMAC(EVP_sha512(), decoded_key.c_str(), decoded_key.length(), (unsigned char*)&signature_data, signature_data_length, NULL, NULL);
  std::string api_sign_header = base64_encode(reinterpret_cast<const unsigned char*>(hmac_digest), SHA512_DIGEST_LENGTH);

  // cURL header
  struct curl_slist* headers = NULL;
  std::string api = "API-KEY:" + std::string(params.krakenApi);
  std::string api_sig = "API-Sign:" + api_sign_header;
  headers = curl_slist_append(headers, api.c_str());
  headers = curl_slist_append(headers, api_sig.c_str());

  // cURL request
  CURLcode resCurl;
  if (params.curl) {
    std::string readBuffer;
    curl_easy_setopt(params.curl, CURLOPT_POST, 1L);
    curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, post_data.c_str());
    curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer);
    curl_easy_setopt(params.curl, CURLOPT_URL, (url+request).c_str());
    curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L);
    resCurl = curl_easy_perform(params.curl);
    json_t* root;
    json_error_t error;
    while (resCurl != CURLE_OK) {
      *params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
      sleep(2.0);
      readBuffer = "";
      resCurl = curl_easy_perform(params.curl);
    }
    root = json_loads(readBuffer.c_str(), 0, &error);

    while (!root) {
      *params.logFile << "<Kraken> Error with JSON:\n" << error.text << ". Retrying..." << std::endl;
      readBuffer = "";
      resCurl = curl_easy_perform(params.curl);
      while (resCurl != CURLE_OK) {
        *params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
        sleep(2.0);
        readBuffer = "";
        resCurl = curl_easy_perform(params.curl);
      }
      root = json_loads(readBuffer.c_str(), 0, &error);
    }
    curl_slist_free_all(headers);
    curl_easy_reset(params.curl);
    return root;
  }
  else {
    *params.logFile << "<Kraken> Error with cURL init." << std::endl;
    return NULL;
  }

  return NULL;
}
Example #15
0
json_t *json_rpc_call(const char *url, const char *userpass, const char *rpc_req)
{
	CURL *curl;
	json_t *val;
	int rc;
	struct data_buffer all_data = { };
	struct upload_buffer upload_data;
	json_error_t err = { };
	struct curl_slist *headers = NULL;
	char len_hdr[64];

	curl = curl_easy_init();
	if (!curl)
		return NULL;

	if (opt_protocol)
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_ENCODING, "");
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
	curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
	if (userpass) {
		curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
		curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	}
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	if (opt_protocol)
		printf("JSON protocol request:\n%s\n", rpc_req);

	upload_data.buf = rpc_req;
	upload_data.len = strlen(rpc_req);
	sprintf(len_hdr, "Content-Length: %lu",
		(unsigned long) upload_data.len);

	headers = curl_slist_append(headers,
		"Content-type: application/json");
	headers = curl_slist_append(headers, len_hdr);
	headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/

	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

	rc = curl_easy_perform(curl);
	if (rc)
		goto err_out;

	val = json_loads(all_data.buf, &err);
	if (!val) {
		fprintf(stderr, "JSON failed(%d): %s\n", err.line, err.text);
		goto err_out;
	}

	if (opt_protocol) {
		char *s = json_dumps(val, JSON_INDENT(3));
		printf("JSON protocol response:\n%s\n", s);
		free(s);
	}

	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_cleanup(curl);
	return val;

err_out:
	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_cleanup(curl);
	return NULL;
}
Example #16
0
void
request_work(char * url){
    char *init_resp;
    json_t *json_resp;
    json_error_t json_error;
    json_t *data_error = NULL, *result = NULL, *data = NULL, *target = NULL, *midstate = NULL;

    init_resp = request(url, req);
    if(!init_resp){
        die("initial repsonse failed check args");
    }

    json_resp = json_loads(init_resp, 0, &json_error);

    if(!json_resp){
        json_die(json_error.line, json_error.text);
    }

    data_error = json_object_get(json_resp, "error");

    json_data_error(json_integer_value(data_error), init_resp);

    //{"error": null, 
    //  "id": "curltest",
    //  "result":
    //  {"hash1": "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000",
    //    "data": "
    //000000029b39574cb8a5c25e94cdd844f7d3b942384af65fb264d5a000000000
    //000000008adb353c754fe07c40341728c5efe6e3782d994e0e3ebcb4879106de
    //94dd1db0533b2c461900db990000000000000080000000000000000000000000
    //0000000000000000000000000000000000000000000000000000000080020000",
    //    "target": "0000000000000000000000000000000000000000000000000000ffff00000000", 
    //    "midstate": "49bc9ada38ba6b43814a3275edfa09b796be70080d5c641d32b80776aef13f78"}
    //}

    result = json_object_get(json_resp, "result");
    data = json_object_get(result, "data");
    target = json_object_get(result, "target");
    midstate = json_object_get(result, "midstate");

    // printf("%s\n", json_string_value(midstate));

    if(!result || !data || !target || !midstate){
        fprintf(stderr, "%s\n", init_resp);
        die("initial repsonse format error");
    }

    //prefered that data is sent as big endien
    // data is in little endien hex format
    // printf("%s\n", json_string_value(data));
    // data must be back through the net work as little endien
    // data must be converted from string representation to bits
    
    //data_write((char *)json_string_value(data));
    
uint8_t *data_bytes = hexStringToBytes(endian_flip_32_bit_chunks(json_string_value(data)));
uint8_t *midstate_bytes = hexStringToBytes(endian_flip_32_bit_chunks(json_string_value(midstate)));
	
//    uint8_t *data_bytes = hexStringToBytes(endian_flip_32_bit_chunks(data_test));
//    uint8_t *midstate_bytes = hexStringToBytes(endian_flip_32_bit_chunks(midstate_test));
	
    uint8_t header_buffer[sizeof(data_bytes)+sizeof(midstate_bytes)];
    memcpy(header_buffer, midstate_bytes, sizeof(midstate_bytes));
    memcpy(header_buffer+sizeof(midstate_bytes), data_bytes, sizeof(data_bytes)); 

    write_segments(header_buffer);
    print_segment_info();

    //used for error printing
    printf("%s\n", init_resp); //for testing

    json_decref(json_resp);
    free(init_resp);

    // !! create thread for listening for success from miners
    // upon success send a proof of work to the network with params set to solution
    // eg. {"method":"getwork","params":["0000000141a0e898cf6554fd344a37b2917a6c7a6561c20733b09c8000009eef00000000d559e21 882efc6f76bbfad4cd13639f4067cd904fe4ecc3351dc9cc5358f1cd54db84e7a1b00b5acba97b6 0400000080000000000000000000000000000000000000000000000000000000000000000000000 0000000000080020000"],"id":1}
    // data must be back through the net work as little endien

}
Example #17
0
static void ZnpActorOnRequestRemoveDevice(PVOID pParam)
{
	char* message = (char*)pParam;
	char **znpSplitMessage;
	if (pZnpActor == NULL) return;
	json_t* payloadJson = NULL;
	json_t* paramsJson = NULL;
	json_t* deviceIdJson = NULL;
	json_t* responseJson = NULL;
	json_t* statusJson = NULL;
	char* responseTopic;
	char* deviceId = 0;
	char* responseMessage;
	BYTE nResult;
	PACTORHEADER header;
	znpSplitMessage = ActorSplitMessage(message);
	if (znpSplitMessage == NULL)
		return;
	// parse header to get origin of message
	header = ActorParseHeader(znpSplitMessage[0]);
	if (header == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		return;
	}
	//parse payload
	payloadJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	if (payloadJson == NULL)
	{
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	paramsJson = json_object_get(payloadJson, "params");
	if (paramsJson == NULL)
	{
		json_decref(payloadJson);
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	deviceIdJson = json_object_get(paramsJson, "deviceId");
	if (deviceIdJson == NULL)
	{
		json_decref(paramsJson);
		json_decref(payloadJson);
		ActorFreeSplitMessage(znpSplitMessage);
		ActorFreeHeaderStruct(header);
		return;
	}
	deviceId = StrDup(json_string_value(deviceIdJson));
	json_decref(deviceIdJson);
	json_decref(paramsJson);
	json_decref(payloadJson);
	// assume that result always success
	nResult = 0;
	// do something here due to remove command
	printf("Device %s has been removed\n", deviceId);
	//make response package
	responseJson = json_object();
	statusJson = json_object();
	json_t* requestJson = json_loads(znpSplitMessage[1], JSON_DECODE_ANY, NULL);
	json_object_set(responseJson, "request", requestJson);
	json_decref(requestJson);
	json_t* resultJson;
	if (nResult == 0)
	{
		resultJson = json_string("status.success");
	}
	else
	{
		resultJson = json_string("status.failure");
	}
	json_object_set(statusJson, "status", resultJson);
	json_decref(resultJson);
	json_object_set(responseJson, "response", statusJson);
	json_decref(statusJson);
	responseMessage = json_dumps(responseJson, JSON_INDENT(4) | JSON_REAL_PRECISION(4));
	json_decref(responseJson);
	ActorFreeSplitMessage(znpSplitMessage);
	//responseTopic = ActorMakeTopicName(NULL, header->origin, NULL);
	responseTopic = StrDup(header->origin);
	ActorFreeHeaderStruct(header);
//	ActorSend(pZnpActor, responseTopic, responseMessage, NULL, FALSE, responseTopic);
	ActorSend(pZnpActor, responseTopic, responseMessage, NULL, FALSE, "response");
	free(responseMessage);
	free(responseTopic);
}
Example #18
0
json_t* authRequest(CURL *curl, Parameters params, std::string url, std::string options) {
  // nonce
  struct timeval tv;
  gettimeofday(&tv, NULL);
  unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5;

  std::ostringstream oss;
  oss << nonce << params.bitstampClientId << params.bitstampApi;
  unsigned char* digest;

  // Using sha256 hash engine
  digest = HMAC(EVP_sha256(), params.bitstampSecret, strlen(params.bitstampSecret), (unsigned char*)oss.str().c_str(), strlen(oss.str().c_str()), NULL, NULL);

  char mdString[SHA256_DIGEST_LENGTH+100];  // FIXME +100
  for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
    sprintf(&mdString[i*2], "%02X", (unsigned int)digest[i]);
  }

  oss.clear();
  oss.str("");

  oss << "key=" << params.bitstampApi << "&signature=" << mdString << "&nonce=" << nonce << "&" << options;
  std::string postParams = oss.str().c_str();

  CURLcode resCurl;  // cURL request
  // curl = curl_easy_init();
  if (curl) {
    std::string readBuffer;
    // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_POST,1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str());
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
    resCurl = curl_easy_perform(curl);
    json_t *root;
    json_error_t error;

    while (resCurl != CURLE_OK) {
      std::cout << "<Bitstamp> Error with cURL. Retry in 2 sec...\n" << std::endl;
      sleep(2.0);
      readBuffer = "";
      resCurl = curl_easy_perform(curl);
    }
    root = json_loads(readBuffer.c_str(), 0, &error);

    while (!root) {
      std::cout << "<Bitstamp> Error with JSON in authRequest:\n" << "Error: : " << error.text << ".  Retrying..." << std::endl;
      readBuffer = "";
      resCurl = curl_easy_perform(curl);
      while (resCurl != CURLE_OK) {
        std::cout << "<Bitstamp> Error with cURL. Retry in 2 sec...\n" << std::endl;
        sleep(2.0);
        readBuffer = "";
        resCurl = curl_easy_perform(curl);
      }
      root = json_loads(readBuffer.c_str(), 0, &error);
    }
    curl_easy_reset(curl);
    return root;
  }
  else {
    std::cout << "<Bitstamp> Error with cURL init." << std::endl;
    return NULL;
  }
}
/*
 * register the client with the OP using Dynamic Client Registration
 */
static apr_byte_t oidc_metadata_client_register(request_rec *r, oidc_cfg *cfg,
		oidc_provider_t *provider, json_t **j_client, const char **response) {

	/* get a handle to the directory config */
	oidc_dir_cfg *dir_cfg = ap_get_module_config(r->per_dir_config,
			&auth_openidc_module);

	/* assemble the JSON registration request */
	json_t *data = json_object();
	json_object_set_new(data, "client_name",
			json_string(provider->client_name));
	json_object_set_new(data, "redirect_uris",
			json_pack("[s]", cfg->redirect_uri));

	json_t *response_types = json_array();
	apr_array_header_t *flows = oidc_proto_supported_flows(r->pool);
	int i;
	for (i = 0; i < flows->nelts; i++) {
		json_array_append_new(response_types,
				json_string(((const char**) flows->elts)[i]));
	}
	json_object_set_new(data, "response_types", response_types);

	if (provider->client_contact != NULL) {
		json_object_set_new(data, "contacts",
				json_pack("[s]", provider->client_contact));
	}

	if (provider->client_jwks_uri) {
		json_object_set_new(data, "jwks_uri",
				json_string(provider->client_jwks_uri));
	} else if (cfg->public_keys != NULL) {
		json_object_set_new(data, "jwks_uri",
				json_string(
						apr_psprintf(r->pool, "%s?jwks=rsa",
								cfg->redirect_uri)));
	}

	if (provider->id_token_signed_response_alg != NULL) {
		json_object_set_new(data, "id_token_signed_response_alg",
				json_string(provider->id_token_signed_response_alg));
	}
	if (provider->id_token_encrypted_response_alg != NULL) {
		json_object_set_new(data, "id_token_encrypted_response_alg",
				json_string(provider->id_token_encrypted_response_alg));
	}
	if (provider->id_token_encrypted_response_enc != NULL) {
		json_object_set_new(data, "id_token_encrypted_response_enc",
				json_string(provider->id_token_encrypted_response_enc));
	}

	if (provider->userinfo_signed_response_alg != NULL) {
		json_object_set_new(data, "userinfo_signed_response_alg",
				json_string(provider->userinfo_signed_response_alg));
	}
	if (provider->userinfo_encrypted_response_alg != NULL) {
		json_object_set_new(data, "userinfo_encrypted_response_alg",
				json_string(provider->userinfo_encrypted_response_alg));
	}
	if (provider->userinfo_encrypted_response_enc != NULL) {
		json_object_set_new(data, "userinfo_encrypted_response_enc",
				json_string(provider->userinfo_encrypted_response_enc));
	}

	json_object_set_new(data, "initiate_login_uri",
			json_string(cfg->redirect_uri));

	json_object_set_new(data, "logout_uri",
			json_string(
					apr_psprintf(r->pool, "%s?logout=%s", cfg->redirect_uri,
							OIDC_GET_STYLE_LOGOUT_PARAM_VALUE)));

	if (cfg->default_slo_url != NULL) {
		json_object_set_new(data, "post_logout_redirect_uris",
				json_pack("[s]", cfg->default_slo_url));
	}

	if (provider->registration_endpoint_json != NULL) {

		json_error_t json_error;
		json_t *json = json_loads(provider->registration_endpoint_json, 0,
				&json_error);

		if (json == NULL) {

			oidc_error(r, "JSON parsing returned an error: %s",
					json_error.text);

		} else {

			if (!json_is_object(json)) {

				oidc_error(r, "parsed JSON did not contain a JSON object");

			} else {

				oidc_util_json_merge(json, data);

			}

			json_decref(json);
		}
	}

	/* dynamically register the client with the specified parameters */
	if (oidc_util_http_post_json(r, provider->registration_endpoint_url, data,
			NULL, provider->registration_token, provider->ssl_validate_server, response,
			cfg->http_timeout_short, cfg->outgoing_proxy,
			dir_cfg->pass_cookies) == FALSE) {
		json_decref(data);
		return FALSE;
	}
	json_decref(data);

	/* decode and see if it is not an error response somehow */
	return oidc_util_decode_json_and_check_error(r, *response, j_client);
}
        cocos2d::Ref *CCNdkBridge::callNative(cocos2d::__Dictionary *params, CCError **pError) {
            cocos2d::__Dictionary *methodParams = params;

            json_t *toBeSentJson = CCJsonHelper::getJsonFromCCObject(methodParams);
            json_t *retJsonParams = NULL;

#if (LOG_JSON == 1)
            CCStoreUtils::logDebug(TAG, __String::createWithFormat(
                    "to native JSON: %s", json_dumps(toBeSentJson, JSON_COMPACT | JSON_ENSURE_ASCII))->getCString());
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
            JniMethodInfo t;

            if (JniHelper::getStaticMethodInfo(t,
                                               CLASS_NAME,
                                               "receiveCppMessage",
                                               "(Ljava/lang/String;)Ljava/lang/String;")) {

                char* jsonStrLocal = json_dumps(toBeSentJson, JSON_COMPACT | JSON_ENSURE_ASCII);
                std::string jsonStr(jsonStrLocal);
                free(jsonStrLocal);

                jstring stringArg1 = t.env->NewStringUTF(jsonStr.c_str());
                jstring retString = (jstring) t.env->CallStaticObjectMethod(t.classID, t.methodID, stringArg1);

                t.env->DeleteLocalRef(stringArg1);
                t.env->DeleteLocalRef(t.classID);

                const char *nativeString = t.env->GetStringUTFChars(retString, 0);
                std::string retParamsStr(nativeString);
                t.env->ReleaseStringUTFChars(retString, nativeString);


                const char *jsonCharArray = retParamsStr.c_str();

                json_error_t error;
                retJsonParams = json_loads(jsonCharArray, 0, &error);

                if (!retJsonParams) {
                    fprintf(stderr, "error: at line #%d: %s\n", error.line, error.text);
                    return __Dictionary::create();
                }
            }
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
            retJsonParams = soomla::CCNdkBridgeIos::receiveCppMessage(toBeSentJson);
#endif

#if (LOG_JSON == 1)
            CCStoreUtils::logDebug(TAG, __String::createWithFormat(
                    "from native JSON: %s", json_dumps(retJsonParams, JSON_COMPACT | JSON_ENSURE_ASCII))->getCString());
#endif

            json_decref(toBeSentJson);
            Ref *retParams = CCJsonHelper::getCCObjectFromJson(retJsonParams);

            if (retJsonParams) {
                json_decref(retJsonParams);
            }

            if (pError != nullptr) {
                CCError *error = CCError::createWithObject(retParams);
                if (error != NULL) {
                    *pError = error;
                }
            }

            return retParams;
        }
Example #21
0
int main(int argc, char*argv[]) {

	char* test = (char *) malloc(500*sizeof(char));

    json_error_t error;
	json_t *root;
	json_t *data;
	json_t *j_type;
	json_t *j_data;
	json_t *phone;

	const char *type;
	const char *customer_phone;

	int server_sockfd, client_sockfd;
	int server_len, client_len;

	struct sockaddr_in server_address;
	struct sockaddr_in client_address;

	server_sockfd = socket(PF_INET, SOCK_STREAM, 0);
	server_address.sin_family = PF_INET;
	// server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);
	server_address.sin_port = htons(9733);
	server_len = sizeof(server_address);

	bind(server_sockfd, (struct sockaddr *)&server_address, server_len);

	listen(server_sockfd, 5);

	while (1) {
		test = (char *) malloc(500*sizeof(char));
		printf("server waitting\n");
		client_len = sizeof(client_address);
		client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
		
		read(client_sockfd, test, 500);

		root = json_loads(test, 0, &error);

		free(test);

		if(!root) {
	        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
	        // Response error to client
			response_data(0, json_object(), client_sockfd);

    	} else {
	    	j_type = json_object_get(root, "type");
	    	j_data = json_object_get(root, "data");

	    	if (!j_type || !j_data) {
				response_data(0, json_object(), client_sockfd);

	    	} else {
	    		type = json_string_value(j_type);
		    	printf("Type: %s\n", type);
		    	if (strcmp(type, "gcustomerinfo") == 0) {
		    		const char * phone = get_value(root, "phone");
		    		json_t *data = get_customer(phone);

					response_data(1, data, client_sockfd);
		    	
		    	} else if (strcmp(type, "pcustomerinfo") == 0) {
		    		const char * name = get_value(root, "name");
		    		const char * email = get_value(root, "email");
		    		const char * address = get_value(root, "address");
		    		const char * phone = get_value(root, "phone");
		    		const char * gender = get_value(root, "gender");

		    		json_t *data = new_customer(name, email, address, phone, gender, "test");

		    		response_data(1, data, client_sockfd);

		    	} else if (strcmp(type, "ucustomerinfo") == 0) {
		    		const char * id = get_value(root, "id");
		    		const char * name = get_value(root, "name");
		    		const char * email = get_value(root, "email");
		    		const char * address = get_value(root, "address");
		    		const char * gender = get_value(root, "gender");

		    		json_t *data = update_customer(id, name, email, address, gender);

		    		response_data(1, data, client_sockfd);

		    	} else if (strcmp(type, "porder") == 0) {
		    		const char * customer_id = get_value(root, "id");
		    		const char * message = get_value(root, "message");

		    		json_t *data = new_order(customer_id, message);

		    		response_data(1, data, client_sockfd);

		    	} else if (strcmp(type, "porderdetail") == 0) {
		    		const char * order_id = get_value(root, "oid");
		    		const char * product_id = get_value(root, "pid");
		    		const char * quantity = get_value(root, "quantity");

		    		json_t *data = new_order_detail(order_id, product_id, quantity);

		    		response_data(1, data, client_sockfd);

		    	// Default
		    	} else {
		    		response_data(0, json_object(), client_sockfd);
		    	}
	    	}
    	}

		close(client_sockfd);
	}
}
Example #22
0
options initOptions(const char *jsonFile, int *success)
{
	
	options tempOpt;
	json_t *tempJsonHandle, *optionsData;
	json_error_t errorHandle;
	
	tempJsonHandle = json_loads(jsonFile,0, &errorHandle);
	if(!tempJsonHandle)
	{
		fprintf(stderr, "json_loads has failed : %s \n", errorHandle.text);
		*success = FAIL;
		return tempOpt;
	
	}
	
	optionsData = json_array_get(tempJsonHandle, 0);
	if(!json_is_object(optionsData))
	{
		fprintf(stderr,"json_object_get failed, didn't get an object\n");
		*success = FAIL;
		json_decref(tempJsonHandle);
		return tempOpt;
	
	}
	
	tempOpt.SCREEN_WIDTH = json_integer_value(json_object_get(optionsData,"SCREEN_WIDTH"));
	tempOpt.SCREEN_HEIGHT = json_integer_value(json_object_get(optionsData,"SCREEN_HEIGHT"));
	tempOpt.title_img = json_string_value(json_object_get(optionsData,"TITLE_IMG"));
	tempOpt.start_button = json_string_value(json_object_get(optionsData,"START_IMG"));
	tempOpt.quit_button = json_string_value(json_object_get(optionsData,"QUIT_IMG"));
	tempOpt.corpses_path = json_string_value(json_object_get(optionsData,"CORPSE_PATH"));
	tempOpt.sprite_path = json_string_value(json_object_get(optionsData,"SPRITE_PATH"));
	tempOpt.buttons_path = json_string_value(json_object_get(optionsData,"BUTTON_PATH"));
	tempOpt.map_path = json_string_value(json_object_get(optionsData,"MAP_PATH"));
	tempOpt.title = json_string_value(json_object_get(optionsData, "TITLE"));
	tempOpt.SAMPLE_SIZE = json_integer_value(json_object_get(optionsData,"SAMPLE_SIZE"));
	tempOpt.SAMPLE_FREQUENCY = json_integer_value(json_object_get(optionsData,"SAMPLE_FREQUENCY"));
	tempOpt.NO_CHANNELS = json_integer_value(json_object_get(optionsData,"NO_CHANNELS"));
	tempOpt.R_COL = json_integer_value(json_object_get(optionsData,"BG_COLOR_R"));
	tempOpt.G_COL = json_integer_value(json_object_get(optionsData,"BG_COLOR_G"));
	tempOpt.B_COL = json_integer_value(json_object_get(optionsData,"BG_COLOR_B"));
	tempOpt.A_COL = json_integer_value(json_object_get(optionsData,"BG_COLOR_A"));
	tempOpt.NO_BUTTONS = json_integer_value(json_object_get(optionsData,"NO_BUTTONS"));
	tempOpt.NO_CORPSES= json_integer_value(json_object_get(optionsData,"NO_CORPSES"));
	tempOpt.NO_SPRITES= json_integer_value(json_object_get(optionsData,"NO_SPRITES"));
	tempOpt.NO_SOUNDS= json_integer_value(json_object_get(optionsData,"NO_SOUNDS"));
	tempOpt.QUIT_OFFSET= json_integer_value(json_object_get(optionsData,"QUIT_OFFSET"));
	tempOpt.OTHER_OFFSET= json_integer_value(json_object_get(optionsData,"OTHER_OFFSET"));
	tempOpt.BUTTON_TRANSPARENCY= json_integer_value(json_object_get(optionsData,"BUTTON_TRANSPARENCY"));
	tempOpt.NO_UNITS = json_integer_value(json_object_get(optionsData,"NO_UNITS"));
	tempOpt.SQUAD_SIZE = json_integer_value(json_object_get(optionsData,"SQUAD_SIZE"));
	tempOpt.HP_PER_SIDE = json_integer_value(json_object_get(optionsData,"HP_OF_SIDE"));
	tempOpt.ROF = json_integer_value(json_object_get(optionsData,"ROF"));
	tempOpt.FRAMES_PER_ANIM = json_integer_value(json_object_get(optionsData,"FRAMES_PER_ANIM"));
	tempOpt.ACCURACY_DEVIATION = json_integer_value(json_object_get(optionsData,"ACCURACY_DEVIATION"));
	tempOpt.MG_RANGE = json_integer_value(json_object_get(optionsData,"MG_RANGE"));
	tempOpt.ARTILLERY_BARRAGE = json_integer_value(json_object_get(optionsData,"ARTILLERY_BARRAGE"));
	tempOpt.SCALE_FACTOR = json_number_value(json_object_get(optionsData,"SCALE_FACTOR"));
	tempOpt.STARTING_POINTS = json_integer_value(json_object_get(optionsData,"STARTING_POINTS"));
	tempOpt.MAX_ARMY_SIZE = json_integer_value(json_object_get(optionsData,"MAX_ARMY_SIZE"));
	tempOpt.ARTILLERY_SCALE_FACTOR = json_number_value(json_object_get(optionsData,"ARTILLERY_SCALE_FACTOR"));
	

	
	return tempOpt;
}
Example #23
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;
	}
	
}
/*
 * This function is called in a new thread to process a client that connects. It
 * handles the protocol and all that other fun stuff to translate messages the
 * clients send into a push notification we can send out.
 */
void *client_interface_connection_handler(void *connection) {
    if(connection == NULL) return NULL;

    int sock = *((int *) connection);

    printf("Client connected.\n");

    char *msg_buf = calloc(config_get_number("Client_Max_Msg_Size") + 1, sizeof(char));
    char *msg_buf_write_ptr = msg_buf;

    long bytes_read_total = 0;
    long bytes_read = 0;

    // read one byte at a time
    while((bytes_read = read(sock, msg_buf_write_ptr, 1)) > 0) {
        bytes_read_total += bytes_read;

        // check if we have \n
        if(strcmp(msg_buf_write_ptr, "\n") == 0) {
//            printf("Received \\n.\n");
            break;
        }

        msg_buf_write_ptr += bytes_read;

        // have we got MAX_CLIENT_MSG_SIZE bytes and no \n?
        if(bytes_read_total == config_get_number("Client_Max_Msg_Size")) {
            write(sock, "err", 3);
            printf(ANSI_COLOR_RED
                   "Client tried to write too much request data - potential"
                   "buffer overflow exploit attempt!\n" ANSI_RESET);

            write(sock, "overflow", 8);

            // Close socket
            free(msg_buf);
            close(sock);

            pthread_exit(NULL);
        }
    }

//    printf("Read %li bytes from client.\n%s\n", bytes_read_total, msg_buf);

    // try and parse JSON
    json_error_t json_error;
    json_t *parsed = json_loads(msg_buf, 0, &json_error);
    free(msg_buf);

    if(!parsed) {
        write(sock, "err", 3);
        printf("Error parsing JSON at line %i: %s\n", json_error.line, json_error.text);

        // free memory, close socket
        free(msg_buf);
        close(sock);

        pthread_exit(NULL);
    } else {
        if(!json_is_object(parsed)) {
            write(sock, "err_type", 8);
            printf("Expected JSON object, got %i", parsed->type);

            // free memory, close socket
            free(parsed);
            close(sock);

            pthread_exit(NULL);
        }
    }

    // allocate memory for the message
    push_msg *message = malloc(sizeof(push_msg));
    memset(message, 0x00, sizeof(push_msg));

    if(message == NULL) {
        write(sock, "nomem", 5);

        printf("Could not allocate push_msg object!\n");

        // free memory, close socket
        free(parsed);
        close(sock);

        pthread_exit(NULL);
    }

    message->text = copy_json_info(json_object_get(parsed, "text"));
    message->sound = copy_json_info(json_object_get(parsed, "sound"));
    message->badgeNumber = (int) json_integer_value(json_object_get(parsed, "badge"));
    message->custPayload = copy_json_info(json_object_get(parsed, "custom"));
    message->deviceID = copy_json_info(json_object_get(parsed, "key"));
    message->buttonTitle = copy_json_info(json_object_get(parsed, "btnTitle"));
    message->localized_template = copy_json_info(json_object_get(parsed, "localized_text"));
    message->localized_arguments.argument0 = copy_json_info(json_object_get(parsed, "localized_arg0"));
    message->localized_arguments.argument1 = copy_json_info(json_object_get(parsed, "localized_arg1"));
    message->localized_arguments.argument2 = copy_json_info(json_object_get(parsed, "localized_arg2"));
    message->localized_arguments.argument3 = copy_json_info(json_object_get(parsed, "localized_arg3"));

    write(sock, "ok", 2);

    // Free memory, close socket
    free(parsed);
    close(sock);

//    printf("Text: %s\nDevice: %s\n", message->text, message->deviceID);

    int error = msg_queue_insert(message); // shove message into queue
    if(error) {
        printf("Error adding to queue: %i\n\n", error);
    }

    fflush(stdout);

    pthread_exit(NULL);
}
Example #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);
}
/**
 * This function updates the old token with new attributes,
 * removes deleted attributes and expiration times.
 *
 * @param cls the ego entry
 * @param tc task context
 */
static void
handle_token_update (void *cls,
                     const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  char *token_header;
  char *token_payload;
  char *token_payload_json;
  char *new_token;
  char *new_payload_str;
  char *new_payload_base64;
  char *sig_str;
  char *key;
  char *padding;
  const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key;
  struct EgoEntry *ego_entry = cls;
  struct GNUNET_GNSRECORD_Data token_record;
  struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
  struct GNUNET_CRYPTO_EcdsaSignature sig;
  struct GNUNET_HashCode key_hash;
  struct GNUNET_TIME_Relative token_rel_exp;
  struct GNUNET_TIME_Relative token_ttl;
  struct GNUNET_TIME_Absolute token_exp;
  struct GNUNET_TIME_Absolute token_nbf;
  struct GNUNET_TIME_Absolute new_exp;
  struct GNUNET_TIME_Absolute new_iat;
  struct GNUNET_TIME_Absolute new_nbf;
  json_t *payload_json;
  json_t *value;
  json_t *cur_value;
  json_t *new_payload_json;
  json_t *token_nbf_json;
  json_t *token_exp_json;
  json_error_t json_err;

  priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego);

  //Note: We need the token expiration time here. Not the record expiration
  //time.
  //There are two types of tokens: Token that expire on GNS level with
  //an absolute expiration time. Those are basically tokens that will
  //be automatically revoked on (record)expiration.
  //Tokens stored with relative expiration times will expire on the token level (token expiration)
  //but this service will reissue new tokens that can be retrieved from GNS
  //automatically.

  token_header = strtok (token, ".");

  token_payload = strtok (NULL, ".");

  GNUNET_STRINGS_base64_decode (token_payload,
                                strlen (token_payload),
                                &token_payload_json);

  payload_json = json_loads (token_payload_json, JSON_DECODE_ANY, &json_err);
  GNUNET_free (token_payload_json);

  token_exp_json = json_object_get (payload_json, "exp");
  token_nbf_json = json_object_get (payload_json, "nbf");
  token_exp.abs_value_us = json_integer_value(token_exp_json);
  token_nbf.abs_value_us = json_integer_value(token_nbf_json);
  token_rel_exp = GNUNET_TIME_absolute_get_difference (token_nbf, token_exp);

  token_ttl = GNUNET_TIME_absolute_get_remaining (token_exp);
  if (0 != GNUNET_TIME_absolute_get_remaining (token_exp).rel_value_us)
  {
    //This token is not yet expired! Save and skip
    if (min_rel_exp.rel_value_us > token_ttl.rel_value_us)
    {
      min_rel_exp = token_ttl;
    }
    json_decref (payload_json);
    GNUNET_free (token);
    token = NULL;
    GNUNET_free (label);
    label = NULL;
    GNUNET_NAMESTORE_zone_iterator_next (ns_it);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Token is expired. Create a new one\n");
  new_exp = GNUNET_TIME_relative_to_absolute (token_rel_exp);
  new_nbf = GNUNET_TIME_absolute_get ();
  new_iat = new_nbf;
  new_payload_json = json_object();
  json_object_foreach(payload_json, key, value) {
    if (0 == strcmp (key, "exp"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_exp.abs_value_us));
    }
    else if (0 == strcmp (key, "nbf"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_nbf.abs_value_us));
    }
    else if (0 == strcmp (key, "iat"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_iat.abs_value_us));
    }
    else if ((0 == strcmp (key, "iss"))
             || (0 == strcmp (key, "aud"))
             || (0 == strcmp (key, "sub"))
             || (0 == strcmp (key, "rnl")))
    {
      json_object_set (new_payload_json, key, value);
    }
    else {
      GNUNET_CRYPTO_hash (key,
                          strlen (key),
                          &key_hash);
      //Check if attr still exists. omit of not
      if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains (ego_entry->attr_map,
                                                               &key_hash))
      {
        cur_value = GNUNET_CONTAINER_multihashmap_get (ego_entry->attr_map,
                                                       &key_hash);
        json_object_set (new_payload_json, key, cur_value);
      }
    }
  }

  // reassemble and set
  new_payload_str = json_dumps (new_payload_json, JSON_COMPACT);
  json_decref (payload_json);
  json_decref (new_payload_json);
  GNUNET_STRINGS_base64_encode (new_payload_str,
                                strlen (new_payload_str),
                                &new_payload_base64);
  //Remove padding
  padding = strtok(new_payload_base64, "=");
  while (NULL != padding)
    padding = strtok(NULL, "=");

  GNUNET_asprintf (&new_token, "%s,%s", token_header, new_payload_base64);
  purpose =
    GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
                   strlen (new_token));
  purpose->size =
    htonl (strlen (new_token) + sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose));
  purpose->purpose = htonl(GNUNET_SIGNATURE_PURPOSE_GNUID_TOKEN);
  memcpy (&purpose[1], new_token, strlen (new_token));
  if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_sign (priv_key,
                                             purpose,
                                             &sig))
    GNUNET_break(0);
  GNUNET_free (new_token);
  sig_str = GNUNET_STRINGS_data_to_string_alloc (&sig,
                                                 sizeof (struct GNUNET_CRYPTO_EcdsaSignature));
  GNUNET_asprintf (&new_token, "%s.%s.%s",
                   token_header, new_payload_base64, sig_str);
  GNUNET_free (sig_str);
  GNUNET_free (new_payload_str);
  GNUNET_free (new_payload_base64);
  GNUNET_free (purpose);

  token_record.data = new_token;
  token_record.data_size = strlen (new_token);
  token_record.expiration_time = new_exp.abs_value_us;
  token_record.record_type = GNUNET_GNSRECORD_TYPE_ID_TOKEN;
  token_record.flags = GNUNET_GNSRECORD_RF_NONE | GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
  ns_qe = GNUNET_NAMESTORE_records_store (ns_handle,
                                          priv_key,
                                          label,
                                          1,
                                          &token_record,
                                          &store_token_cont,
                                          ego_entry);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, ">>> Updating Token w/ %s\n", new_token);
  GNUNET_free (new_token);
  GNUNET_free (token);
  token = NULL;
  GNUNET_free (label);
  label = NULL;
}
Example #27
0
/* step */
void zyre_bridge_step(ubx_block_t *b)
{
    struct zyre_bridge_info *inf = (struct zyre_bridge_info*) b->private_data;

	/* Read data from port */
	ubx_port_t* port = inf->ports.zyre_out;
	assert(port != 0);

	char * tmp_str = (char*) malloc(inf->max_msg_length*sizeof(char*));

	ubx_data_t msg;
	checktype(port->block->ni, port->in_type, "unsigned char", port->name, 1);
	msg.type = port->in_type;
	msg.len = inf->max_msg_length;
	msg.data = tmp_str;
	//msg.data = inf->msg_buffer;

    int counter = 0;
    while (counter < inf->max_send) {
    	int read_bytes = __port_read(port, &msg);

    	//printf("zyrebridge: read bytes: %d\n",read_bytes);
    	//printf("step: read strlen: %lu\n",strlen((char*) msg.data));

    	if (read_bytes <= 0) {
    		//printf("zyre_bridge: No data recieved from port\n");
    		free(tmp_str);
    		return;
    	}
//    	printf("zyrebridge: read bytes: %d\n",read_bytes);
    	// port_read returns byte array. Need to add 0 termination manually to the string.
    	tmp_str[read_bytes] = '\0';

    	// create json object and...
    	json_t *pl;
		json_error_t error;
		pl= json_loads(tmp_str,0,&error);
		if(!pl) {
			printf("Error parsing JSON payload! line %d, column %d: %s\n", error.line, error.column, error.text);
			json_decref(pl);
			free(tmp_str);
			return;
		}
//    	printf("[zyrebridge] retrieving msg: %s\n", json_dumps(pl, JSON_ENCODE_ANY));
		// ...check for its type and embed it into msg envelope
		json_t *new_msg;
		new_msg = json_object();
		json_object_set(new_msg, "payload", pl);
		json_object_set(new_msg, "metamodel", json_string("SHERPA"));
		if(json_object_get(pl, "@worldmodeltype") == 0) {
			printf("[zyrebridge] retrieving msg: %s\n", json_dumps(pl, JSON_ENCODE_ANY));
			printf("[zyrebridge] Error parsing RSG payload! @worldmodeltype is missing.\n");
			json_decref(pl);
			free(tmp_str);
			return;
		}

		std::string tmp_type = json_string_value(json_object_get(pl, "@worldmodeltype")); //can segfault
		char *send_msg = NULL;
		int found = 0;
		for (int i=0; i < inf->output_type_list.size();i++)
		{
			if (tmp_type.compare(inf->output_type_list[i])) {
				found = 1;
				// need to handle exception for updates generated from RSG due to local updates
				if (tmp_type.compare("RSGUpdate") == 0) {
					json_object_set(new_msg, "model", json_string("RSGUpdate"));
					json_object_set(new_msg, "type", json_string("RSGUpdate_global"));

					//  If used with mediator, add send_request envelope
					ubx_data_t *dmy;
					dmy = ubx_config_get_data(b, "mediator");
					int mediator;
					mediator = *(int*) dmy->data;
					if (mediator == 1) {
						zuuid_t *query_uuid = zuuid_new ();
						assert (query_uuid);
						json_t *recip = json_array();
						assert((recip)&&(json_array_size(recip)==0));
						send_msg = send_request(zuuid_str(query_uuid),zyre_uuid(inf->node),recip,1000,"send_remote",new_msg);
					}
					else {
						send_msg = json_dumps(new_msg, JSON_ENCODE_ANY);
					}
				} else {
					json_object_set(new_msg, "model", json_string(tmp_type.c_str()));
					json_object_set(new_msg, "type", json_string(tmp_type.c_str()));
					send_msg = json_dumps(new_msg, JSON_ENCODE_ANY);
				}
				break;
			}
		}
		if (found == 0) {
			printf("[zyre_bridge] WARNING: Unknown output type: %s!\n",tmp_type.c_str());
		}

		printf("[zyrebridge] sending msg: %s\n", send_msg);
    	zyre_shouts(inf->node, inf->group, "%s", send_msg);
    	counter++;

    	json_decref(pl);
    	json_decref(new_msg);
    }

    free(tmp_str);
    return;
}
Example #28
0
int
udf_cask_smd_accept_fn(char *module, as_smd_item_list_t *items, void *udata, uint32_t accept_opt)
{
	if (accept_opt & AS_SMD_ACCEPT_OPT_CREATE) {
		cf_debug(AS_UDF, "(doing nothing in UDF accept cb for module creation)");
		return 0;
	}

	cf_debug(AS_UDF, "UDF CASK accept fn : n items %d", items->num_items);

	// For each item in the list, see if the current version
	// is different from the curretly stored version
	// and if the new item is new, write to the storage directory
	for (int i = 0; i < items->num_items ; i++) {

		as_smd_item_t *item = items->item[i];

		if (item->action == AS_SMD_ACTION_SET) {

			json_error_t json_err;
			json_t *item_obj = json_loads(item->value, 0 /*flags*/, &json_err);

			/*item->key is name */
			json_t *content64_obj = json_object_get(item_obj, "content64");
			const char *content64_str = json_string_value(content64_obj);

			// base 64 decode it
			uint32_t encoded_len = strlen(content64_str);
			uint32_t decoded_len = cf_b64_decoded_buf_size(encoded_len) + 1;
			char *content_str = cf_malloc(decoded_len);

			if (! cf_b64_validate_and_decode(content64_str, encoded_len, (uint8_t*)content_str, &decoded_len)) {
				cf_info(AS_UDF, "invalid script on accept, will not register %s", item->key);
				cf_free(content_str);
				json_decref(content64_obj);
				json_decref(item_obj);
				continue;
			}

			content_str[decoded_len] = 0;

			cf_debug(AS_UDF, "pushing to %s, %d bytes [%s]", item->key, decoded_len, content_str);
			mod_lua_wrlock(&mod_lua);

			// content_gen is actually a hash. Not sure if it's filled out or what.
			unsigned char       content_gen[256]    = {0};
			int e = file_write(item->key, (uint8_t *) content_str, decoded_len, content_gen);
			cf_free(content_str);
			json_decref(content64_obj);
			json_decref(item_obj);
			if ( e ) {
				mod_lua_unlock(&mod_lua);
				cf_info(AS_UDF, "invalid script on accept, will not register %s", item->key);
				continue;
			}
			// Update the cache
			as_module_event ame = {
				.type           = AS_MODULE_EVENT_FILE_ADD,
				.data.filename  = item->key
			};
			as_module_update(&mod_lua, &ame);
			mod_lua_unlock(&mod_lua);
		}
		else if (item->action == AS_SMD_ACTION_DELETE) {
			cf_debug(AS_UDF, "received DELETE SMD action %d key %s", item->action, item->key);

			mod_lua_wrlock(&mod_lua);
			file_remove(item->key);

			// fixes potential cache issues
			as_module_event e = {
				.type           = AS_MODULE_EVENT_FILE_REMOVE,
				.data.filename  = item->key
			};
			as_module_update(&mod_lua, &e);

			mod_lua_unlock(&mod_lua);

		}
		else {
Example #29
0
void dbload()
{
    // If the file doesn't exist, there is no DB to load
    if(!FileExists(dbpath))
        return;

    dprintf("Loading database...");
    DWORD ticks = GetTickCount();

    // Multi-byte (UTF8) file path converted to UTF16
    WString databasePathW = StringUtils::Utf8ToUtf16(dbpath);

    // Decompress the file if compression was enabled
    bool useCompression = !settingboolget("Engine", "DisableDatabaseCompression");
    LZ4_STATUS lzmaStatus = LZ4_INVALID_ARCHIVE;
    {
        lzmaStatus = LZ4_decompress_fileW(databasePathW.c_str(), databasePathW.c_str());

        // Check return code
        if(useCompression && lzmaStatus != LZ4_SUCCESS && lzmaStatus != LZ4_INVALID_ARCHIVE)
        {
            dputs("\nInvalid database file!");
            return;
        }
    }

    // Read the database file
    Handle hFile = CreateFileW(databasePathW.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if(!hFile)
    {
        dputs("\nFailed to open database file!");
        return;
    }

    unsigned int jsonFileSize = GetFileSize(hFile, 0);
    if(!jsonFileSize)
    {
        dputs("\nEmpty database file!");
        return;
    }

    Memory<char*> jsonText(jsonFileSize + 1);
    DWORD read = 0;
    if(!ReadFile(hFile, jsonText(), jsonFileSize, &read, 0))
    {
        dputs("\nFailed to read database file!");
        return;
    }
    hFile.Close();

    // Deserialize JSON
    JSON root = json_loads(jsonText(), 0, 0);

    if(lzmaStatus != LZ4_INVALID_ARCHIVE && useCompression)
        LZ4_compress_fileW(databasePathW.c_str(), databasePathW.c_str());

    // Validate JSON load status
    if(!root)
    {
        dputs("\nInvalid database file (JSON)!");
        return;
    }

    // Finally load all structures
    CommentCacheLoad(root);
    LabelCacheLoad(root);
    BookmarkCacheLoad(root);
    FunctionCacheLoad(root);
    LoopCacheLoad(root);
    BpCacheLoad(root);

    // Free root
    json_decref(root);
    dprintf("%ums\n", GetTickCount() - ticks);
}
Example #30
0
// Read JSON into a weather struct
struct weather *
owm_read (struct json_write_result * json) {

    json_error_t error;
    json_t * root = json_loads(json->data, 0, &error);
    free(json->data);

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

    static struct weather fetched_weather;

    const char * root_key;
    json_t * root_value;
    json_object_foreach(root, root_key, root_value) {
        switch ( root_key[0] ) {
            case 'c':
                if ( json_typeof(root_value) == (signed )JSON_OBJECT ) {
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(root_value, sub_key, sub_value) {
                        if ( root_key[1] == 'l' ) {
                            fetched_weather.clouds =
                                json_number_value(sub_value);
                        } else if ( root_key[2] == 'o' ) {
                            if ( sub_key[1] == 'o' ) {
                                fetched_weather.longitude =
                                    json_number_value(sub_value);
                            } else if ( sub_key[1] == 'a' ) {
                                fetched_weather.latitude =
                                    json_number_value(sub_value);
                            }
                        }
                    }
                } break;

            case 'd':
                fetched_weather.dt = json_integer_value(root_value);
                break;

            case 'i':
                fetched_weather.id = json_integer_value(root_value);
                break;

            case 'm':
                if ( root_key[1] == 'e' ) {
                    fprintf(stderr, "%s\n", json_string_value(root_value));
                    free(root);
                    exit(1);
                } else if ( json_typeof(root_value) == (signed )JSON_OBJECT ) {
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(root_value, sub_key, sub_value) {
                        switch ( sub_key[0] ) {
                            case 't':
                                if ( strlen(sub_key) == 4 ) {
                                    fetched_weather.temperature =
                                        json_number_value(sub_value);
                                } else if ( sub_key[6] == 'i' ) {
                                    fetched_weather.temp_min =
                                        json_number_value(sub_value);
                                } else if ( sub_key[6] == 'a' ) {
                                    fetched_weather.temp_max =
                                        json_number_value(sub_value);
                                } break;

                            case 'p':
                                fetched_weather.pressure =
                                    json_number_value(sub_value);
                                break;

                            case 'h':
                                fetched_weather.humidity =
                                    json_number_value(sub_value);
                                break;
                        }
                    }
                } break;

            case 'n':
                fetched_weather.name = json_string_value(root_value);
                if ( !fetched_weather.name ) {
                    fetched_weather.name = "Unavailable";
                } break;

            case 's':
                if ( json_typeof(root_value) == (signed )JSON_OBJECT ) {
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(root_value, sub_key, sub_value) {
                        switch ( root_key[1] ) {
                            case 'y':
                                switch ( sub_key[4] ) {
                                    case 'i':
                                        fetched_weather.sunrise =
                                            json_integer_value(sub_value);
                                        break;

                                    case 'e':
                                        fetched_weather.sunset =
                                            json_integer_value(sub_value);
                                        break;

                                    case 't':
                                        fetched_weather.country =
                                            json_string_value(sub_value);

                                        if ( !fetched_weather.country ) {
                                            fetched_weather.country =
                                                "Unavailable";
                                        } break;
                                } break;

                            case 'n':
                                fetched_weather.precipitation_3h =
                                    json_number_value(sub_value);
                                break;
                        }
                    }
                } break;

            case 'w':
                if ( json_typeof(root_value) == (signed )JSON_ARRAY ) {
                    json_t * weather = json_array_get(root_value, 0);
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(weather, sub_key, sub_value) {
                        switch ( sub_key[1] ) {
                            case 'd':
                                fetched_weather.weather_code =
                                    json_integer_value(sub_value);
                                break;

                            case 'e':
                                fetched_weather.condition =
                                    json_string_value(sub_value);

                                if ( !fetched_weather.condition ) {
                                    fetched_weather.condition = "Unavailable";
                                } break;
                        }
                    }
                } else if ( json_typeof(root_value) == (signed )JSON_OBJECT ) {
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(root_value, sub_key, sub_value) {
                        switch ( sub_key[0] ) {
                            case 's':
                                fetched_weather.wind_speed =
                                    json_number_value(sub_value);
                                break;

                            case 'g':
                                fetched_weather.wind_gust =
                                    json_number_value(sub_value);
                                break;

                            case 'd':
                                fetched_weather.wind_direction =
                                    json_number_value(sub_value);
                                break;
                        }
                    }
                } break;

            case 'r':
                if ( json_typeof(root_value) == (signed )JSON_OBJECT ) {
                    const char * sub_key;
                    json_t * sub_value;
                    json_object_foreach(root_value, sub_key, sub_value) {
                        if ( sub_key[0] == '3' ) {
                            fetched_weather.precipitation_3h =
                                json_number_value(sub_value);
                        }
                    }
                } break;
        }