Esempio n. 1
0
static json_t *read_json_pretty_pdu(w_jbuffer_t *jr, w_stm_t stm, json_error_t *jerr)
{
  char *nl;
  int r;
  json_t *res;

  // Assume newline is at the end of what we have
  nl = jr->buf + jr->wpos;
  r = (int)(nl - (jr->buf + jr->rpos));
  res = json_loadb(jr->buf + jr->rpos, r, 0, jerr);
  if (!res) {
    // Maybe we can fill more data into the buffer and retry?
    if (!fill_buffer(jr, stm)) {
      // No, then error is terminal
      return NULL;
    }
    // Recompute end of buffer
    nl = jr->buf + jr->wpos;
    r = (int)(nl - (jr->buf + jr->rpos));
    // And try parsing this
    res = json_loadb(jr->buf + jr->rpos, r, 0, jerr);
  }

  // update read pos to look beyond this point
  jr->rpos += r + 1;

  return res;
}
Esempio n. 2
0
/* Parse the JSON document printed by qemu-img info --output json. */
static void
parse_json (guestfs_h *g, void *treevp, const char *input, size_t len)
{
  json_t **tree_ret = treevp;
  json_error_t err;

  assert (*tree_ret == NULL);

  /* If the input is completely empty, return a magic value to the
   * caller.  'qemu-img info' will return an error, but this will let
   * us catch the case where it does not.
   */
  if (len == 0) {
    *tree_ret = PARSE_JSON_NO_OUTPUT;
    return;
  }

  debug (g, "%s: qemu-img info JSON output:\n%.*s\n", __func__, (int) len, input);

  *tree_ret = json_loadb (input, len, 0, &err);
  if (*tree_ret == NULL) {
    if (strlen (err.text) > 0)
      error (g, _("qemu-img info: JSON parse error: %s"), err.text);
    else
      error (g, _("qemu-img info: unknown JSON parse error"));
  }
}
Esempio n. 3
0
static
void recv_frame_cb(wslay_event_context_ptr ctx,
                   const struct wslay_event_on_msg_recv_arg *arg,
                   void *user_data) {
    (void) ctx;
    if (arg->opcode != WSLAY_TEXT_FRAME) {
        return;
    }

    DSLink *link = user_data;
    json_error_t err;
    json_t *obj = json_loadb((char *) arg->msg, arg->msg_length,
                             JSON_PRESERVE_ORDER, &err);
    if (!obj) {
        log_err("Failed to parse JSON payload: %.*s\n",
                (int) arg->msg_length, arg->msg);
        goto exit;
    } else {
        log_debug("Message received: %.*s\n",
                  (int) arg->msg_length, arg->msg);
    }

    json_t *reqs = json_object_get(obj, "requests");
    if (link->is_responder && reqs) {
        size_t index;
        json_t *value;
        json_array_foreach(reqs, index, value) {
            if (dslink_request_handle(link, value) != 0) {
                log_err("Failed to handle request\n");
            }
        }
    }
Esempio n. 4
0
static void load_wrong_args()
{
    json_t *json;
    json_error_t error;

    json = json_loads(NULL, 0, &error);
    if (json)
        fail("json_loads should return NULL if the first argument is NULL");

    json = json_loadb(NULL, 0, 0, &error);
    if (json)
        fail("json_loadb should return NULL if the first argument is NULL");

    json = json_loadf(NULL, 0, &error);
    if (json)
        fail("json_loadf should return NULL if the first argument is NULL");

    json = json_loadfd(-1, 0, &error);
    if (json)
        fail("json_loadfd should return NULL if the first argument is < 0");

    json = json_load_file(NULL, 0, &error);
    if (json)
        fail("json_load_file should return NULL if the first argument is NULL");
}
Esempio n. 5
0
static json_t *read_json_pdu(w_jbuffer_t *jr, int fd, json_error_t *jerr)
{
  char *nl;
  int r;
  json_t *res;

  /* look for a newline; that indicates the end of
   * a json packet */
  nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos);

  // If we don't have a newline, we need to fill the
  // buffer
  while (!nl) {
    if (!fill_buffer(jr, fd)) {
      return NULL;
    }
    nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos);
  }

  // buflen
  r = nl - (jr->buf + jr->rpos);
  res = json_loadb(jr->buf + jr->rpos, r, 0, jerr);

  // update read pos to look beyond this point
  jr->rpos += r + 1;

  return res;
}
Esempio n. 6
0
void
on_read_cb(struct bufferevent *bev, void *arg)
{
	char			*str = NULL;
	size_t			n_read_out;
	json_error_t		error;
	json_t			*jmsg = NULL;

	while (evbuffer_get_length(bufferevent_get_input(bev)) > 0) {
		if ((str = evbuffer_readln(bufferevent_get_input(bev),
		    &n_read_out, EVBUFFER_EOL_LF)) == NULL) {
			return;
		}
	//	printf("str: %d <> %s\n\n\n", strlen(str), str);
		if ((jmsg = json_loadb(str, n_read_out, 0, &error)) == NULL) {
			jlog(L_ERROR, "json_loadb: %s", error.text);
			bufferevent_free(bufev_sock);
			return;
		}

		free(str);
		dispatch_op(jmsg);
		json_decref(jmsg);
	}
}
Esempio n. 7
0
void process_pull_msg(zmq_msg_t * payload_msg) {
	char * type = NULL;

	json_t * payload = json_loadb(zmq_msg_data(payload_msg),
		zmq_msg_size(payload_msg), 0, NULL);
	if(payload == NULL)
		return;

	if(get_values(payload,
		"type", JSON_STRING, 1, &type,
		NULL) != 0) {
		json_decref(payload);
		return;
	}

	if(strcmp(type, "command") == 0)
		process_cmd(payload);
	else if(strcmp(type, "host_check_processed") == 0 ||
		strcmp(type, "service_check_processed") == 0)
		process_status(payload);
	else if(strcmp(type, "acknowledgement") == 0)
		process_acknowledgement(payload);
	else if(strcmp(type, "comment_add") == 0)
		process_comment(payload);
	else if(strcmp(type, "downtime_add") == 0)
		process_downtime(payload);
	else if(strcmp(type, "state_data") == 0)
		process_bulkstate(payload);
	return;
}
Esempio n. 8
0
static json_t *read_json_pdu(w_jbuffer_t *jr, w_stm_t stm, json_error_t *jerr)
{
  char *nl;
  int r;
  json_t *res;

  /* look for a newline; that indicates the end of
   * a json packet */
  nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos);

  // If we don't have a newline, we need to fill the
  // buffer
  while (!nl) {
    if (!fill_buffer(jr, stm)) {
      if (errno == 0 && stm == w_stm_stdin()) {
        // Ugly-ish hack to support the -j CLI option.  This allows
        // us to consume a JSON input that doesn't end with a newline.
        // We only allow this on EOF when reading from stdin
        nl = jr->buf + jr->wpos;
        break;
      }
      return NULL;
    }
    nl = memchr(jr->buf + jr->rpos, '\n', jr->wpos - jr->rpos);
  }

  // buflen
  r = (int)(nl - (jr->buf + jr->rpos));
  res = json_loadb(jr->buf + jr->rpos, r, 0, jerr);

  // update read pos to look beyond this point
  jr->rpos += r + 1;

  return res;
}
Esempio n. 9
0
struct ast_json *ast_json_load_buf(const char *buffer, size_t buflen, struct ast_json_error *error)
{
	json_error_t jansson_error = {};
	struct ast_json *r = (struct ast_json *)json_loadb(buffer, buflen, 0, &jansson_error);
	copy_error(error, &jansson_error);
	return r;
}
Esempio n. 10
0
void read_stream(char const* str,size_t len){
	//ちら見せ
	printf("length: %zu\n",len);
	assert(str[0] != '\r');
	
	json_t *json;
	json_error_t err;
	json = json_loadb(str,len,0,&err);
	if(json){
		json_t *text,*created_at,*user,*user_name,*screen_name;
		text = json_object_get(json,"text");
		user = json_object_get(json,"user");
		created_at = json_object_get(json,"created_at");
		if(text && user && created_at){
			user_name = json_object_get(user,"name");
			screen_name = json_object_get(user,"screen_name");
			if(user_name && screen_name){
				printf("%s @%s\t\t%s\n",json_string_value(user_name),json_string_value(screen_name),json_string_value(created_at));
				printf("%s\n",json_string_value(text));
			}
		}
	}
	else{
		printf("%s\n",err.text);
	}
	printf("===================---------------\n");
	fflush(stdout);
}
Esempio n. 11
0
int ftw_socket_inbox_recv(struct ftw_incoming_request *incoming, json_t **json_msg, size_t flags,
    int64 *err_line, int64 *err_column, int64 *err_position, LStrHandle err_source, LStrHandle err_hint)
{
    json_error_t err;
    int rc;

    /*  Preconditions expected of LabVIEW. */
    ftw_assert(incoming && incoming->msg_ptr && incoming->inbox && json_msg);

    /*  Notify async receive thread that it can pipeline the next message into the LVEvent. */
    nn_sem_post(&incoming->inbox->msg_acknowledged);

    *json_msg = json_loadb(incoming->msg_ptr, incoming->msg_len, flags, &err);

    rc = nn_freemsg(incoming->msg_ptr);
    ftw_assert(rc == 0);

    /*  Invalid JSON in the buffer is an error condition indicated by NULL. */
    if (*json_msg == NULL) {
        *err_line = err.line;
        *err_column = err.column;
        *err_position = err.position;
        ftw_support_CStr_to_LStrHandle(&err_source, err.source, sizeof(err.source));
        ftw_support_CStr_to_LStrHandle(&err_hint, err.text, sizeof(err.text));
        *json_msg = json_object();
    }

    return rc;
}
Esempio n. 12
0
/*
 * Returns -1 if error happens in parsing data or data contains error
 * message. In this case, the calling function should simply return
 * to up layer.
 *
 * Returns 0 otherwise, and root is set to the root node, object set
 * to the root node's containing object.
 */
static int
handle_ret_common (char *data, size_t len, json_t **object, GError **error)
{
    int err_code;
    const char *err_msg;
    json_error_t jerror;

    g_return_val_if_fail (object != 0, -1);

    *object=json_loadb(data,len,0,&jerror);
    if (*object == NULL) {
        setjetoge(&jerror,*error);
        json_decref (*object);
        return -1;
    }

    if (json_object_get (*object, "err_code")) {
        err_code = json_integer_value(json_object_get (*object, "err_code"));
        err_msg = json_string_value(json_object_get (*object, "err_msg"));
        g_set_error (error, DFT_DOMAIN,
                     err_code, "%s", err_msg);
        json_decref (*object);
        return -1;
    }

    return 0;
}
Esempio n. 13
0
// called when we've read some data
// parse incoming data, call registered callbacks
void rapid_api_read_handler(rapid_api_ctx *ctx, uint8_t *read_buf, ssize_t bytes_read) {

  // handle incremental parsing of JSON
  if (ctx->json_buf) {
    // append what we've read
    ctx->json_buf = realloc(ctx->json_buf, ctx->json_buf_len + bytes_read);
    memcpy((ctx->json_buf + ctx->json_buf_len), read_buf, bytes_read);
    ctx->json_buf_len += bytes_read;
  } else {
    ctx->json_buf = malloc(bytes_read);
    ctx->json_buf_len = bytes_read;
    memcpy(ctx->json_buf, read_buf, bytes_read);
  }
  
  // debug
  char *s = malloc(ctx->json_buf_len + 1);
  memcpy(s, ctx->json_buf, ctx->json_buf_len);
  s[ctx->json_buf_len] = '\0';
  printf("json %u: '%s'\n", ctx->json_buf_len, s);

  // decode JSON text
  json_t *root;
  json_error_t json_err;
  // JSON_DISABLE_EOF_CHECK == allow extra data at the end of a valid JSON object
  root = json_loadb(ctx->json_buf, ctx->json_buf_len, JSON_DISABLE_EOF_CHECK, &json_err);

  if (root == NULL) {
    // decoding failed
    // probably ok, just incomplete
    // printf("Failed to decode JSON\n");
    return;
  }

  // decoding success. remove the parsed json from the buffer
  // number of bytes decoded lives in json_err.position
  // https://github.com/akheron/jansson/issues/49
  size_t bytes_decoded = json_err.position;
  if (bytes_decoded < ctx->json_buf_len) {
    // remove decoded bytes from front of buffer
    size_t remaining_bytes = ctx->json_buf_len - bytes_decoded;    
    memmove(ctx->json_buf, ctx->json_buf + bytes_decoded, remaining_bytes);
    ctx->json_buf = realloc(ctx->json_buf, remaining_bytes);
    ctx->json_buf_len = remaining_bytes;
  } else {
    // done with json buffer, nothing left
    free(ctx->json_buf);
    ctx->json_buf = NULL;
    ctx->json_buf_len = 0;
  }
  
  // we seem to have a valid JSON object now. let's turn it into a rapid message
  rapid_message *msg = rapid_alloc_message();
  if (rapid_parse_message(root, msg)) {
    printf("Got message with command: %s\n", msg->command);
  }
  rapid_free_message(msg);
  
  json_decref(root);
}
Esempio n. 14
0
int
parse_metric_object (const char *       json_string,
                     size_t             json_length,
                     json_t **          json_root)
{
    json_t *            json_metric;
    json_t *            json_value;

    json_error_t        json_error;

    int                 status;

    const char *        metric;
    long                value;

    *json_root = json_loadb (json_string, json_length, 0, &json_error);
    if (*json_root == NULL) {
        log_error ("evbuffer_copyout() failed.");
        status = EVHTP_RES_400;
        goto exit;
    }

    if (!json_is_object (*json_root)) {
        status = EVHTP_RES_400;
        goto json_decref;
    }

    json_metric = json_object_get (*json_root, "metric");
    if (!json_is_string (json_metric)) {
        status = EVHTP_RES_400;
        goto json_decref;
    }
    metric = json_string_value (json_metric);
    if (strlen (metric) == 0) {
        status = EVHTP_RES_400;
        goto json_decref;
    }

    json_value = json_object_get (*json_root, "value");
    if (!json_is_integer (json_value)) {
        status = EVHTP_RES_400;
        goto json_decref;
    }

    value = json_integer_value (json_value);
    if (value < 0 || value > 10) {
        status = EVHTP_RES_400;
        goto json_decref;
    }

    return (0);

  json_decref:
    json_decref (*json_root);

  exit:
    return (status);
}
Esempio n. 15
0
void BinWriter::writeExecutable(const char *path, const char *sjson, int jsonSize)
{
    json_error_t jerror;
    json_t       *json = json_loadb(sjson, jsonSize, 0, &jerror);

    lmAssert(json, "Error loading Assembly json: %s\n %s %i\n", jerror.source, jerror.text, jerror.line);

    writeExecutable(path, json);
}
Esempio n. 16
0
const char *LSCompiler::readAssemblyUID(const utArray<unsigned char>& rawjson)
{
    json_error_t jerror;
    json_t *json = json_loadb((const char*)rawjson.ptr(), rawjson.size(), JSON_DISABLE_EOF_CHECK, &jerror);

    const char* uid = json_string_value(json_object_get(json, "uid"));

    return uid;
}
Esempio n. 17
0
Status
JsonFile::decode(const std::string &data)
{
    json_error_t error;
    json_t *root = json_loadb(data.data(), data.size(), loadFlags, &error);
    if (!root)
        return ABC_ERROR(ABC_CC_JSONError, error.text);
    reset(root);
    return Status();
}
Esempio n. 18
0
static kbool_t ParseJson(KonohaContext *kctx, struct JsonBuf *jsonbuf, const char *text, size_t length, KTraceInfo *trace)
{
	json_error_t err;
	json_t* obj = json_loadb(text, length, 0, &err);
	if(obj != NULL) {
		SetJsonBuf_NewRef(jsonbuf, obj);
		return true;
	}
	return false;
}
static char *ngx_http_acme_json_request(ngx_conf_t *cf, void *conf, char *url, ngx_http_acme_http_method_t http_method,
        json_t *request_json, json_t **response_json, ngx_http_acme_slist_t **response_headers)
{
    ngx_str_t response_data;
    ngx_str_t request_data;
    char *tmp;

    json_error_t error;

    /* Convert request_json to string to provide it to the following method */
    request_data = (ngx_str_t)ngx_null_string;
    if(!json_is_null(request_json)) {
        tmp = json_dumps(request_json, 0);
        if(tmp == NULL) {
            ngx_log_error(NGX_LOG_ERR, cf->log, 0, "Error while creating request string from JSON\n");
            return NGX_CONF_ERROR;
        } else {
            request_data.data = (u_char *)tmp;
            request_data.len = ngx_strlen(tmp);
        }
    }

    /* Make request */
    if(ngx_http_acme_plain_request(cf, conf, url, http_method, request_data, &response_data, response_headers) != NGX_CONF_OK) {
        ngx_log_error(NGX_LOG_ERR, cf->log, 0, "Error while making request\n");
        return NGX_CONF_ERROR;
    }

    /* Now all the returned JSON is in the data variable */

    /*
     * Parsing returned JSON
     */

    /* Begin Jansson part */

    if(response_data.len <= 0) {
        *response_json = json_null();
    } else {
        *response_json = json_loadb((char *) response_data.data, response_data.len, 0, &error);
    }
    free(response_data.data);
    ngx_str_null(&response_data);

    if(*response_json == NULL)
    {
        ngx_log_error(NGX_LOG_ERR, cf->log, 0,
                "Error parsing JSON: on line %d: %s\n", error.line, error.text);
        return NGX_CONF_ERROR;
    }

    /* End Jansson part */

    return NGX_CONF_OK;
} /* ngx_http_acme_json_request */
Esempio n. 20
0
int ev_handler(struct mg_connection *conn, enum mg_event ev) {
    switch (ev) {
        case MG_AUTH: return MG_TRUE;
        case MG_REQUEST:
        {
            //mg_printf_data(conn, "Hello! Requested URI is [%s]", conn->uri);
            info("Requested URI:REQ is [%s]:[%s]", conn->uri, conn->request_method);

            mg_send_header(conn, "Content-Type", "application/json");

            json_t* jobj_req = NULL;
            json_error_t jerror;
            if (cmpuri(conn->request_method,"POST")){
                jobj_req = json_loadb(conn->content, conn->content_len, 0, &jerror);
                if (!jobj_req){
                    mg_printf_data(conn,"json error on line %d: %s\n", jerror.line, jerror.text);
                    mg_send_status(conn, 400);
                    info("error parsing json POST, json error on line %d: %s\n", jerror.line, jerror.text);
                    return MG_TRUE;
                }
            }

            json_t* jobj_resp = json_object();
            int status = 404; //allow handler to choose response status

            status = root_handler(conn, jobj_req, jobj_resp);

            //free request
            if (jobj_req){
                json_decref(jobj_req);
                jobj_req = NULL;
            }

            //dump response
            char * jstr = json_dumps(jobj_resp, 0);
            json_decref(jobj_resp);
            jobj_resp = NULL;

            if (status == 404){
                char* errmsg = "{\"error\":\"No handler for URI found.\"}";
                mg_send_data(conn, errmsg, strlen(errmsg));
                mg_send_status(conn, 404);
            }
            else {
                mg_send_data(conn, jstr, strlen(jstr));
                mg_send_status(conn, status);
            }
            free(jstr);

            return MG_TRUE;
        }
        default: return MG_FALSE;
    }
}
Esempio n. 21
0
void pss_response(void *spss, req_store_t * req_store, void *sweb, void *sgraph)
{

	zmsg_t *msg = zmsg_recv(spss);
	zframe_t *null = zmsg_unwrap(msg);
	zframe_destroy(&null);
	json_error_t error;
	printf("\nbroker:spss received: %s\n",
	       (const char *)zframe_data(zmsg_first(msg)));
	const char *data;
	size_t data_size = zframe_size(zmsg_first(msg));
	data = zframe_data(zmsg_first(msg));

	json_t *pss_resp_json = json_loadb(data,
					   data_size, 0, &error);
	zmsg_destroy(&msg);

	//identify the request
	int32_t requestId =
	    json_integer_value(json_object_get(pss_resp_json, "requestId"));

	req_t *req = request_store_req(req_store, requestId);

	json_t *response = json_object_get(pss_resp_json, "response");
	json_incref(response);
	json_decref(pss_resp_json);

	const char *resp_type =
	    json_string_value(json_object_get(response, "type"));

	const char *req_type =
	    json_string_value(json_object_get
			      (json_object_get
			       (json_object_get(req->request, "clientRequest"),
				"request"), "type"));
	if ((strcmp(resp_type, "searchResponse") == 0)
	    && (strcmp(req_type, "searchRequest") == 0))

		pss_response_searchResponse(req, response, requestId, sgraph);

	else if ((strcmp(resp_type, "newNodeResponse") == 0)
		 && (strcmp(req_type, "newNode") == 0))
		pss_response_newNodeResponse(req, response, requestId, sweb,
					     req_store);

	else if ((strcmp(resp_type, "delNode") == 0)
		 && (strcmp(req_type, "delNode") == 0))
		pss_response_delNode(req, response, requestId, sweb, req_store);

	else {

	}

}
Esempio n. 22
0
json_t *pc_body_json_decode(const char *data, size_t offset, size_t len)
{
    json_error_t error;
    json_t *res = json_loadb(data + offset, len - offset, 0, &error);

    if (!res) {
        pc_lib_log(PC_LOG_ERROR, "pc_body_json_decode - json decode error: %s", error.text);
    }

    return res;
}
Esempio n. 23
0
TR_MSG *tr_msg_decode(char *jbuf, size_t buflen)
{
  TR_MSG *msg=NULL;
  json_t *jmsg = NULL;
  json_error_t rc;
  json_t *jtype=NULL;
  json_t *jbody=NULL;
  const char *mtype = NULL;

  if (NULL == (jmsg = json_loadb(jbuf, buflen, JSON_DISABLE_EOF_CHECK, &rc))) {
    tr_debug("tr_msg_decode(): error loading object");
    return NULL;
  }

  if (!(msg = malloc(sizeof(TR_MSG)))) {
    tr_debug("tr_msg_decode(): Error allocating TR_MSG structure.");
    json_decref(jmsg);
    return NULL;
  }
 
  memset(msg, 0, sizeof(TR_MSG));

  if ((NULL == (jtype = json_object_get(jmsg, "msg_type"))) ||
      (NULL == (jbody = json_object_get(jmsg, "msg_body")))) {
    tr_debug("tr_msg_decode(): Error parsing message header.");
    json_decref(jmsg);
    tr_msg_free_decoded(msg);
    return NULL;
  }

  mtype = json_string_value(jtype);

  if (0 == strcmp(mtype, "tid_request")) {
    msg->msg_type = TID_REQUEST;
    tr_msg_set_req(msg, tr_msg_decode_tidreq(jbody));
  }
  else if (0 == strcmp(mtype, "tid_response")) {
    msg->msg_type = TID_RESPONSE;
    tr_msg_set_resp(msg, tr_msg_decode_tidresp(jbody));
  }
  else if (0 == strcmp(mtype, "trp_update")) {
    msg->msg_type = TRP_UPDATE;
    tr_msg_set_trp_upd(msg, tr_msg_decode_trp_upd(NULL, jbody)); /* null talloc context for now */
  }
  else if (0 == strcmp(mtype, "trp_request")) {
    msg->msg_type = TRP_UPDATE;
    tr_msg_set_trp_req(msg, tr_msg_decode_trp_req(NULL, jbody)); /* null talloc context for now */
  }
  else {
    msg->msg_type = TR_UNKNOWN;
    msg->msg_rep = NULL;
  }
  return msg;
}
Esempio n. 24
0
void JsonReader::parse(const string& data) {
    json_error_t error;
    json_t *parsed;
    parsed = json_loadb(data.c_str(), data.size(), JSON_REJECT_DUPLICATES, &error);
    if (!parsed) {
        stringstream ss;
        ss << "JsonReader::parse failed on line " << error.line << " column " << error.column;
        ss << " with message " << error.text;
        throw std::runtime_error(ss.str());
    }
    _root = makeJsonPtr(parsed);
}
Esempio n. 25
0
cxJson cxJsonCreate(cxString json)
{
    CX_ASSERT(json != NULL, "args error");
    cxJson this = CX_CREATE(cxJson);
    json_error_t error = {0};
    if(cxStringLength(json) <= 0){
        return this;
    }
    this->json = json_loadb(cxStringBody(json), cxStringLength(json), JSON_DECODE_ANY, &error);
    CX_ASSERT(this->json != NULL, "cxJson load error (%d:%d) %s:%s",error.line,error.column,error.source,error.text);
    return this;
}
Esempio n. 26
0
json_t *pc__json_decode(const char *data, size_t offset, size_t len) {
  json_error_t error;

  json_t *res = json_loadb(data + offset, len - offset, 0, &error);

  if(res == NULL) {
    fprintf(stderr, "Fail to decode json: %s\n", error.text);
    return NULL;
  }

  return res;
}
Esempio n. 27
0
int pc__handshake_resp(pc_client_t *client,
                                const char *data, size_t len) {
  json_error_t error;
  json_t *res = json_loadb(data, len, 0, &error);

  if(res == NULL) {
    fprintf(stderr, "Fail to parse handshake package. %s\n", error.text);
    return -1;
  }

  json_int_t code = json_integer_value(json_object_get(res, "code"));
  if(code != PC_HANDSHAKE_OK) {
    fprintf(stderr, "Handshake fail, code: %d.\n", (int)code);
    return -1;
  }

  json_t *sys = json_object_get(res, "sys");
  if(sys) {
    // setup heartbeat
    json_int_t hb = json_integer_value(json_object_get(sys, "heartbeat"));
    if(hb < 0) {
      // no need heartbeat
      client->heartbeat = -1;
      client->timeout = -1;
    } else {
      client->heartbeat = hb > 0 ? hb : PC_DEFAULT_HEARTBEAT;
      json_int_t to = json_integer_value(json_object_get(sys, "timeout"));
      client->timeout = to > client->heartbeat ? to : PC_DEFAULT_TIMEOUT;
      uv_timer_set_repeat(&client->heartbeat_timer, client->heartbeat);
      uv_timer_set_repeat(&client->timeout_timer, client->timeout);
    }

    // setup route dictionary
    json_t *dics = json_object_get(sys, "dictionary");
    if(dics) {
      //TODO: dictionary name?
      client->route_to_code = NULL;
      client->code_to_route = NULL;
    }
  }

  json_t *user = json_object_get(res, "user");
  int status = 0;
  if(client->handshake_cb) {
    status = client->handshake_cb(client, user);
  }

  if(!status) {
    pc__handshake_ack(client);
  }

  return 0;
}
Esempio n. 28
0
static
void handle_conn(Broker *broker, HttpRequest *req, Socket *sock) {
    json_error_t err;

    json_t *body;
    {
        const char *start = strchr(req->body, '{');
        const char *end = strrchr(req->body, '}');
        if (!(start && end)) {
            goto exit;
        }
        body = json_loadb(start, end - start + 1, 0, &err);
        if (!body) {
            broker_send_internal_error(sock);
            goto exit;
        }
    }

    const char *dsId = broker_http_param_get(&req->uri, "dsId");
    if (!dsId) {
        goto exit;
    }
    log_info("%s connecting \n", dsId);
    const char *token = broker_http_param_get(&req->uri, "token");
    json_t *resp = broker_handshake_handle_conn(broker, dsId, token, body);
    json_decref(body);
    if (!resp) {
        broker_send_internal_error(sock);
        goto exit;
    }

    char *data = json_dumps(resp, JSON_INDENT(2));
    json_decref(resp);
    if (!data) {
        broker_send_internal_error(sock);
        goto exit;
    }

    char buf[1024];
    int len = snprintf(buf, sizeof(buf) - 1,
                       CONN_RESP, (int) strlen(data), data);
    buf[len] = '\0';
    dslink_free(data);
    dslink_socket_write(sock, buf, (size_t) len);

exit:
    return;
}
Esempio n. 29
0
static json_t *wunder_json_load(char *json, size_t length) {
	json_t *root;
	json_error_t error;
	
	if(!(root = json_loadb(json, length, 0, &error))) {
		fprintf(stderr, "[-] wunder/json: parsing error: line %d: %s\n", error.line, error.text);
		return NULL;
	}
	
	if(!json_is_object(root)) {
		fprintf(stderr, "[-] wunder/json: root is not an object\n");
		return NULL;
	}
	
	return root;
}
Esempio n. 30
0
int json_to_frame(void *sp, void *set, void *msg_data, size_t msg_len) {
  int rc=-1;
  json_t *json;
  json_error_t error;
  const char *key;
  json_t *value;

  json = json_loadb(msg_data, msg_len, 0, &error);
  if (!json) {
    fprintf(stderr,"JSON decoding error: %s\n", error.text);
    goto done;
  }

  kv_set_clear(set);
  json_object_foreach(json, key, value) {
    kv_adds(set, key, json_string_value(value));
  }