Esempio n. 1
0
/* OVS DB echo request handler. When OVS DB sends
 * "echo" request to the client, client should generate
 * "echo" replay with the same content received in the
 * request */
static int ovs_db_table_echo_cb(const ovs_db_t *pdb, yajl_val jnode) {
  yajl_val jparams;
  yajl_val jid;
  yajl_gen jgen;
  size_t resp_len = 0;
  const char *resp = NULL;
  const char *params_path[] = {"params", NULL};
  const char *id_path[] = {"id", NULL};
  yajl_gen_status yajl_gen_ret;

  if ((jgen = yajl_gen_alloc(NULL)) == NULL)
    return -1;

  /* check & get request attributes */
  if ((jparams = yajl_tree_get(jnode, params_path, yajl_t_array)) == NULL ||
      ((jid = yajl_tree_get(jnode, id_path, yajl_t_any)) == NULL)) {
    OVS_ERROR("parse echo request failed");
    goto yajl_gen_failure;
  }

  /* generate JSON echo response */
  OVS_YAJL_CALL(yajl_gen_map_open, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "result");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "error");
  OVS_YAJL_CALL(yajl_gen_null, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jid);

  OVS_YAJL_CALL(yajl_gen_map_close, jgen);
  OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&resp,
                &resp_len);

  /* send the response */
  OVS_DEBUG("response: %s", resp);
  if (ovs_db_data_send(pdb, resp, resp_len) < 0) {
    OVS_ERROR("send echo reply failed");
    goto yajl_gen_failure;
  }
  /* clean up and return success */
  yajl_gen_clear(jgen);
  return 0;

yajl_gen_failure:
  /* release memory */
  yajl_gen_clear(jgen);
  return -1;
}
Esempio n. 2
0
void VertexServer_requestHandler(void *arg)  
{  
	VertexServer *self = (VertexServer *)arg;
	VertexServer_setupYajl(self); 
	
	HttpResponse_setContentType_(self->httpResponse, "application/json;charset=utf-8");

	int result = VertexServer_process(self);
	Datum *content = HttpResponse_content(self->httpResponse);
	
	if (result == 0)
	{
		if (!Datum_size(content)) 
		{
			Datum_setCString_(content, "null");
		}
		Datum_nullTerminate(content); 
	}
	else
	{
		if (!Datum_size(content)) 
		{
			Datum_setCString_(content, "\"unknown error\"");
		}
		Datum_nullTerminate(content); 
		
		yajl_gen_clear(self->yajl);
		yajl_gen_datum(self->yajl, content);
		Datum_setYajl_(content, self->yajl);
				
		if(self->debug) { Log_Printf_("REQUEST ERROR: %s\n", Datum_data(content)); }
	}
}
Esempio n. 3
0
static int write_all(struct asfd *asfd)
{
	int ret=-1;
	size_t w=0;
	size_t len=0;
	const unsigned char *buf;
	struct iobuf wbuf;

	yajl_gen_get_buf(yajl, &buf, &len);
	while(len)
	{
		w=len;
		if(w>ASYNC_BUF_LEN) w=ASYNC_BUF_LEN;
		iobuf_set(&wbuf, CMD_GEN /* not used */, (char *)buf, w);
		if((ret=asfd->write(asfd, &wbuf)))
			break;
		buf+=w;
		len-=w;
	}
	if(!ret && !pretty_print)
	{
		iobuf_set(&wbuf, CMD_GEN /* not used */, (char *)"\n", 1);
		ret=asfd->write(asfd, &wbuf);
	}

	yajl_gen_clear(yajl);
	return ret;
}
Esempio n. 4
0
xlw::XlfOper HttpProtocol::Execute(const char* name, bool sendCaller, xlw::XlfOper* args, int argc)
{
	REQUEST_CONTEXT context;
	context.hEvent = CreateEvent(0, 1, 0, 0);
	context.hConnect = WinHttpConnect(hSession, host, urlc.nPort, 0);
	int flags = WINHTTP_FLAG_BYPASS_PROXY_CACHE;
	if(urlc.nScheme == INTERNET_SCHEME_HTTPS)
		flags |= WINHTTP_FLAG_SECURE;
	context.hRequest = WinHttpOpenRequest(context.hConnect, L"POST", path, 0, 0, 0, 
		flags);
	context.conf.beautify = 0;
	context.conf.indentString = "";
	context.g = yajl_gen_alloc(&context.conf, 0);
	context.px = xlw::XlfOper();
	//context.px->xltype = xltypeNil | xlbitDLLFree;
	GenerateRequest(context.g, name, sendCaller, args, argc);
	const unsigned char * buf;
    unsigned int len = 0;
    yajl_gen_get_buf(context.g, &buf, &len);
	BOOL res = FALSE;
	res = WinHttpSendRequest(context.hRequest, 0, 0, (LPVOID) buf, len, len, (DWORD_PTR) &context);
	if(!res) {
		const char* err = "#Could not connect to server";
		Log::Error(err);
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	// TODO timeout/background
	res = WinHttpReceiveResponse(context.hRequest, 0);
	if(!res) {
		const char* err = "#Error retrieving server response";
		Log::Error(err);
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	// Check http response code
	DWORD status;
	DWORD statusLength = 4;
	res = WinHttpQueryHeaders(context.hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,
		NULL, &status, &statusLength, 0);
	if(!res || status != 200) {
		Log::Error("Status code: %d", status);
		const char* err = "#Server returned an error";
		WinHttpCloseHandle(context.hRequest);
		WinHttpCloseHandle(context.hConnect);
		context.px = xlw::XlfOper(err);
		return context.px;
	}
	ReadData(&context);
	WinHttpCloseHandle(context.hRequest);
	WinHttpCloseHandle(context.hConnect);
    yajl_gen_clear(context.g);
	yajl_gen_free(context.g);
	//context.px->xltype |= xlbitDLLFree;
	return context.px;
}
Esempio n. 5
0
static int js_to_string(lua_State *L) {
    yajl_gen* gen;
    const unsigned char *buf;
    size_t len;

    lua_pushcfunction(L, js_generator);
    /* convert_me, {extra}, ?, js_gen */
    if ( lua_istable(L, 2) ) {
        /* Be sure printer is not defined: */
        lua_pushliteral(L, "printer");
        lua_pushnil(L);
        lua_rawset(L, 2);
        lua_pushvalue(L, 2);
        /* convert_me, {extra}, ?, js_gen, {extra} */
    } else {
        lua_newtable(L);
        /* convert_me, {extra}, ?, js_gen, {} */
    }
    lua_call(L, 1, 1);
    /* convert_me, {extra}, ?, gen_ud */
    lua_pushcfunction(L, js_generator_value);
    /* convert_me, {extra}, ?, gen_ud, js_gen_val */
    lua_pushvalue(L, -2);
    /* convert_me, {extra}, ?, gen_ud, js_gen_val, gen_ud */
    lua_pushvalue(L, 1);
    /* convert_me, {extra}, ?, gen_ud, js_gen_val, gen_ud, convert_me */
    lua_call(L, 2, 0);
    /* convert_me, {extra}, ?, gen_ud */
    gen = js_check_generator(L, -1);
    yajl_gen_get_buf(*gen, &buf, &len);
    /* Copy into results: */
    lua_pushlstring(L, (char*)buf, len);
    yajl_gen_clear(*gen);
    return 1;
}
Esempio n. 6
0
/*
 * Format (prometheus/alertmanager v1):
 *
 * [{
 *   "labels": {
 *     "alertname": "collectd_cpu",
 *     "instance":  "host.example.com",
 *     "severity":  "FAILURE",
 *     "service":   "collectd",
 *     "cpu":       "0",
 *     "type":      "wait"
 *   },
 *   "annotations": {
 *     "summary": "...",
 *     // meta
 *   },
 *   "startsAt": <rfc3339 time>,
 *   "endsAt": <rfc3339 time>, // not used
 * }]
 */
int format_json_notification(char *buffer, size_t buffer_size, /* {{{ */
                             notification_t const *n) {
  yajl_gen g;
  unsigned char const *out;
#if HAVE_YAJL_V2
  size_t unused_out_len;
#else
  unsigned int unused_out_len;
#endif

  if ((buffer == NULL) || (n == NULL))
    return EINVAL;

#if HAVE_YAJL_V2
  g = yajl_gen_alloc(NULL);
  if (g == NULL)
    return -1;
#if COLLECT_DEBUG
  yajl_gen_config(g, yajl_gen_beautify, 1);
  yajl_gen_config(g, yajl_gen_validate_utf8, 1);
#endif

#else /* !HAVE_YAJL_V2 */
  yajl_gen_config conf = {0};
#if COLLECT_DEBUG
  conf.beautify = 1;
  conf.indentString = "  ";
#endif
  g = yajl_gen_alloc(&conf, NULL);
  if (g == NULL)
    return -1;
#endif

  if (format_alert(g, n) != 0) {
    yajl_gen_clear(g);
    yajl_gen_free(g);
    return -1;
  }

  /* copy to output buffer */
  yajl_gen_get_buf(g, &out, &unused_out_len);
  sstrncpy(buffer, (void *)out, buffer_size);

  yajl_gen_clear(g);
  yajl_gen_free(g);
  return 0;
} /* }}} format_json_notification */
Esempio n. 7
0
std::vector<char> LKStreamTranslator::process(const std::vector<char> &chunk)
{
	std::vector<char> retval;
	
	// We work with C strings here, because YAJL
	const char *str = chunk.data();
	size_t len = chunk.size();
	
	// Abort if the string is empty anyways
	if(len == 0)
		return retval;
	
	// Skip any BOM if there is one
	const unsigned char bom[] = {0xEF, 0xBB, 0xBF};
	if(len >= 3 && memcmp(bom, str, 3) == 0)
	{
		str += 3;
		len -= 3;
	}
	
	// Abort if it had nothing but a BOM
	if(len == 0)
		return retval;
	
	// KanColle specific: most datablobs are prefixed with "svdata=", that's
	// needed for the game to work, but we can't parse with it left in
	const char *svdata = "svdata=";
	if(memcmp(svdata, str, (size_t)std::min(strlen(svdata), len)) == 0)
	{
		str += strlen(svdata);
		len -= strlen(svdata);
		
		retval.insert(retval.end(), svdata, svdata + strlen(svdata));
	}
	
	if(len > 0)
	{
		if(yajl_parse(ctx.parser, (const unsigned char *)str, len) != yajl_status_ok)
		{
			unsigned char *error = yajl_get_error(ctx.parser, true, (const unsigned char *)str, len);
			std::string error_string((const char *)error);
			yajl_free_error(ctx.parser, error);
			
			throw std::runtime_error("JSON Parsing Error: " + error_string);
		}
		
		const unsigned char *buf;
		size_t buf_len;
		yajl_gen_get_buf(ctx.gen, &buf, &buf_len);
		
		if(buf_len > 0)
		{
			retval.insert(retval.end(), buf, buf + buf_len);
			yajl_gen_clear(ctx.gen);
		}
	}
	
	return retval;
}
Esempio n. 8
0
void galleryd::response::generate(galleryd::request &req, galleryd::queue &q)
{
    yajl_gen_clear(handle_);
    yajl_gen_map_open(handle_);

    try
    {

    if(req.method == "status")
    {
        constexpr const unsigned char key_states[] = {'s', 't', 'a', 't', 'e'};

        yajl_gen_string(handle_, key_states, sizeof(key_states));
        yajl_gen_array_open(handle_);
        for(auto state : q.status(req.items, req.category))
            yajl_gen_integer(handle_, state);
        yajl_gen_array_close(handle_);
    }

    else if(req.method == "add")
    {
        q.add(req.items, req.category);
    }

    else if(req.method == "open")
    {
        auto path = q.open(req.items, req.category);
        if(not path.empty())
        {
            path += '/';
            path += req.items[0];

            if(fork() == 0)
            {
                int fd = open("/dev/null", O_WRONLY);
                dup2(fd, 2);  // redirect stderr
                execl("/usr/bin/geeqie", "/usr/bin/geeqie", "-r", path.c_str(), nullptr);
                exit(1); // in case execl returns with an error
            }
        }
        else
        {
            // TODO error handling
        }
    }

    }
    catch(const std::exception &e)
    {
        constexpr const unsigned char key_error[] = {'e', 'r', 'r', 'o', 'r'};
        const char  *err = e.what();
        const size_t len = strlen(err);

        yajl_gen_string(handle_, key_error, sizeof(key_error));
        yajl_gen_string(handle_, reinterpret_cast<const unsigned char *>(err), len);
    }

    yajl_gen_map_close(handle_);
}
Esempio n. 9
0
static int lyajl_gen_get_buf (lua_State *L) {
  const unsigned char *buf;
  size_t len;
  luvit_generator_t *generator = generator_get(L, 1);
  yajl_gen_get_buf(generator->gen, &buf, &len);
  lua_pushlstring(L, (const char*)buf, len);
  yajl_gen_clear(generator->gen);
  return 1;
}
Esempio n. 10
0
rc_ReturnCode_t swi_sms_Register(swi_sms_ReceptionCB_t callback, const char* senderPatternPtr,
    const char* messagePatternPtr, swi_sms_regId_t *regIdPtr)
{
  rc_ReturnCode_t res;
  char *payload;
  size_t payloadLen;
  const char *senderP, *messageP;
  cb_list_t *entry;
  yajl_gen gen;
  int regId;

  if (callback == NULL || regIdPtr == NULL)
    return RC_BAD_PARAMETER;

  senderP = senderPatternPtr ? senderPatternPtr : "";
  messageP = messagePatternPtr ? messagePatternPtr : "";

  YAJL_GEN_ALLOC(gen);

  yajl_gen_array_open(gen);

  YAJL_GEN_STRING(senderP, "sender pattern");
  YAJL_GEN_STRING(messageP, "message pattern");

  yajl_gen_array_close(gen);

  YAJL_GEN_GET_BUF(payload, payloadLen);

  res = send_reg_payload(payload, payloadLen, &regId);

  if (res != RC_OK)
    goto quit;

  pthread_mutex_lock(&handler_lock);
  if (!cb_list)
  {
    cb_list = malloc(sizeof(cb_list_t));
    entry = cb_list;
  }
  else
  {
    for (entry = cb_list; entry->next; entry = entry->next)
      ;
    entry->next = malloc(sizeof(cb_list_t));
    entry = entry->next;
  }
  entry->regId = regId;
  entry->cb = callback;
  entry->payload = strndup(payload, payloadLen);
  entry->next = NULL;
  *regIdPtr = entry;
  pthread_mutex_unlock(&handler_lock);
quit:
  yajl_gen_clear(gen);
  yajl_gen_free(gen);
  return res;
}
Esempio n. 11
0
rc_ReturnCode_t swi_sms_Unregister(swi_sms_regId_t regId)
{
  rc_ReturnCode_t res;
  char *payload, *respPayload;
  size_t payloadLen;
  uint32_t respPayloadLen;
  cb_list_t *entry, *tmp;
  yajl_gen gen;

  for (entry = cb_list; entry; entry = entry->next)
    if (entry == regId)
      break;
  if (entry == NULL)
    return RC_BAD_PARAMETER;

  YAJL_GEN_ALLOC(gen);

  YAJL_GEN_INTEGER(entry->regId, "regId");

  YAJL_GEN_GET_BUF(payload, payloadLen);

  res = emp_send_and_wait_response(EMP_UNREGISTERSMSLISTENER, 0, payload, payloadLen, &respPayload, &respPayloadLen);
  yajl_gen_clear(gen);
  yajl_gen_free(gen);

  if (res != RC_OK)
  {
    SWI_LOG("SMS", ERROR, "Error while unregister sms, res=%d\n", res);
    SWI_LOG("SMS", ERROR, "got error msg=%s\n", respPayload);
    goto quit;
  }

  pthread_mutex_lock(&handler_lock);
  if (cb_list == regId)
  {
    free(cb_list);
    cb_list = NULL;
  }
  else
  {
    for (entry = cb_list; entry; entry = entry->next)
    {
      if (entry->next == regId)
      {
    break;
      }
    }
    tmp = entry->next;
    entry->next = tmp->next;
    free(tmp->payload);
    free(tmp);
  }
  pthread_mutex_unlock(&handler_lock);
quit:
  free(respPayload);
  return res;
}
Esempio n. 12
0
static void json_print(FILE *f, yajl_gen yajl)
{
	const unsigned char *buf;
	size_t len;
	yajl_gen_get_buf(yajl, &buf, &len);
	fputs((char*)buf, f);
	fputc('\n', f);
	yajl_gen_clear(yajl);
}
Esempio n. 13
0
void Datum_appendYajl_(Datum *self, yajl_gen y)
{
	const unsigned char *jsonBuffer;
	size_t jsonBufferLength;
		
	yajl_gen_get_buf(y, &jsonBuffer, &jsonBufferLength);
	
	Datum_appendBytes_size_(self, jsonBuffer, (size_t)jsonBufferLength);
	yajl_gen_clear(y);
}
Esempio n. 14
0
void Datum_setYajl_(Datum *self, yajl_gen y)
{
	const unsigned char *jsonBuffer;
	size_t jsonBufferLength;
		
	yajl_gen_get_buf(y, &jsonBuffer, &jsonBufferLength);
	
	Datum_setData_size_(self, (char *)jsonBuffer, (size_t)jsonBufferLength);
	yajl_gen_clear(y);
}
Esempio n. 15
0
rc_ReturnCode_t swi_sms_Send(const char *recipientPtr, const char* messagePtr, swi_sms_Format_t format)
{
  rc_ReturnCode_t res;
  char *payload, *respPayload;
  const char *smsFormat = "";
  size_t payloadLen;
  uint32_t respPayloadLen;
  yajl_gen gen;

  if (recipientPtr == NULL || messagePtr == NULL || format < SWI_SMS_7BITS || format > SWI_SMS_UCS2)
    return RC_BAD_PARAMETER;

  switch(format)
  {
    case SWI_SMS_7BITS:
      smsFormat = "7bits";
      break;
    case SWI_SMS_8BITS:
      smsFormat = "8bits";
      break;
    case SWI_SMS_UCS2:
      smsFormat = "ucs2";
      break;
    default:
      break;
  }

  YAJL_GEN_ALLOC(gen);

  yajl_gen_array_open(gen);

  YAJL_GEN_STRING(recipientPtr, "recipientPtr");
  YAJL_GEN_STRING(messagePtr, "messagePtr");
  YAJL_GEN_STRING(smsFormat, "smsFormat");

  yajl_gen_array_close(gen);

  YAJL_GEN_GET_BUF(payload, payloadLen);

  res = emp_send_and_wait_response(EMP_SENDSMS, 0, payload, payloadLen, &respPayload, &respPayloadLen);
  yajl_gen_clear(gen);
  yajl_gen_free(gen);

  if (res != RC_OK)
  {
    SWI_LOG("SMS", ERROR, "error while sending sms, res=%d\n", res);
    SWI_LOG("SMS", ERROR, "got error msg=%s\n", respPayload);
  }
  free(respPayload);
  return res;
}
Esempio n. 16
0
veBool pubnub_atPublishN(struct PubnubAt* nubat, char const *buf, size_t buf_len)
{
	struct PubnubRequest *nubreq;
	u8 const *json;
	size_t json_len;

	/* allocate request */
	if (!nubat->g) {
		nubat->g = yajl_gen_alloc(NULL);
		if (!nubat->g)
			return veFalse;
	}

	nubreq = (struct PubnubRequest *) ve_malloc(sizeof(struct PubnubRequest));
	if (!nubreq) {
		/* reuse the nubat->q next time */
		return veFalse;
	}

	pubnub_req_init(&nubat->nub, nubreq, 512, 512);

	/* build json data.. */
	if (yajl_gen_string(nubat->g, (u8*) buf, buf_len) != yajl_gen_status_ok) {
		ve_error("json: not a valid string");
		goto error;
	}

	if (yajl_gen_get_buf(nubat->g, &json, &json_len) != yajl_gen_status_ok) {
		ve_error("json: could not get buf");
		return veFalse;
	}

	/* sent it */
	if (pubnub_publish(nubreq, (char*) json, publish_callback) != RET_OK) {
		ve_error("could not pubnub_publish");
		goto error;
	}

	yajl_gen_clear(nubat->g);	/* empty buffers */
	yajl_gen_free(nubat->g);
	nubat->g = NULL;
	return veTrue;

error:
	pubnub_req_deinit(nubreq);
	ve_free(nubreq);
	yajl_gen_free(nubat->g);
	nubat->g = NULL;

	return veFalse;
}
Esempio n. 17
0
void reformat(ErlDrvPort port, char* buf, int len)
{
    yajl_handle hand;
    /* generator config */
    yajl_gen_config conf = { 1, "  " };
	yajl_gen g;
    yajl_status stat;
    /* allow comments */
    yajl_parser_config cfg = { 1, 1 };

    g = yajl_gen_alloc(&conf, NULL);

    /* ok.  open file.  let's read and parse */
    hand = yajl_alloc(&callbacks, &cfg, NULL, (void *) g);
    
    /* read file data, pass to parser */
    stat = yajl_parse(hand, (unsigned char*) buf, len);

    if (stat != yajl_status_ok &&
        stat != yajl_status_insufficient_data)
    {
        char* err = (char*) yajl_get_error(hand, 1, (unsigned char*) buf, len);
        int len = strlen(err);

        ErlDrvTermData msg[] = {
            ERL_DRV_ATOM, driver_mk_atom("error"), 
            ERL_DRV_BUF2BINARY, (ErlDrvTermData) err, (ErlDrvUInt) len,
            ERL_DRV_TUPLE, 2
        };

        driver_send_term(port, driver_caller(port), msg, sizeof(msg) / sizeof(msg[0]));
    } else {
        const unsigned char* json;
        unsigned int len;
        yajl_gen_get_buf(g, &json, &len);

        ErlDrvTermData msg[] = {
            ERL_DRV_ATOM, driver_mk_atom("ok"),
            ERL_DRV_BUF2BINARY, (ErlDrvTermData) json, (ErlDrvUInt) len,
            ERL_DRV_TUPLE, 2
        };

        driver_send_term(port, driver_caller(port), msg, sizeof(msg) / sizeof(msg[0]));

        yajl_gen_clear(g);
    }

    yajl_gen_free(g);
    yajl_free(hand);
}
Esempio n. 18
0
int main(int argc, char ** argv)
{
    yajl_handle hand;
    yajl_status stat;
    yajl_parser_config cfg = { 1, 1 };

    int done = 0;

    hand = yajl_alloc(&callbacks, &cfg, NULL, (void *) g);
        
    while (!done) {
        rd = fread((void *) fileData, 1, sizeof(fileData) - 1, stdin);
        
        if (rd == 0) {
            if (!feof(stdin)) {
                fprintf(stderr, "error on file read.\n");
                break;
            }
            done = 1;
        }
        fileData[rd] = 0;
        
        if (done)
            /* parse any remaining buffered data */
            stat = yajl_parse_complete(hand);
        else
            /* read file data, pass to parser */
            stat = yajl_parse(hand, fileData, rd);

        if (stat != yajl_status_ok &&
            stat != yajl_status_insufficient_data)
        {
            unsigned char * str = yajl_get_error(hand, 1, fileData, rd);
            fprintf(stderr, (const char *) str);
            yajl_free_error(hand, str);
        } else {
            const unsigned char * buf;
            unsigned int len;
            yajl_gen_get_buf(g, &buf, &len);
            fwrite(buf, 1, len, stdout);
            yajl_gen_clear(g);
        }
    }

    yajl_gen_free(g);
    yajl_free(hand);
    
    return 0;
}
Esempio n. 19
0
static package
bf_generate_json(Var arglist, Byte next, void *vdata, Objid progr)
{
    yajl_gen g;
    yajl_gen_config cfg = { 0, "" };

    struct generate_context gctx;
    gctx.mode = MODE_COMMON_SUBSET;

    const char *buf;
    unsigned int len;

    Var json;

    package pack;

    if (1 < arglist.v.list[0].v.num) {
	if (!mystrcasecmp(arglist.v.list[2].v.str, "common-subset")) {
	    gctx.mode = MODE_COMMON_SUBSET;
	} else if (!mystrcasecmp(arglist.v.list[2].v.str, "embedded-types")) {
	    gctx.mode = MODE_EMBEDDED_TYPES;
	} else {
	    free_var(arglist);
	    return make_error_pack(E_INVARG);
	}
    }

    g = yajl_gen_alloc(&cfg, NULL);

    if (yajl_gen_status_ok == generate(g, arglist.v.list[1], &gctx)) {
	yajl_gen_get_buf(g, (const unsigned char **)&buf, &len);

	json.type = TYPE_STR;
	json.v.str = str_dup(buf);

	pack = make_var_pack(json);
    } else {
	pack = make_error_pack(E_INVARG);
    }

    yajl_gen_clear(g);
    yajl_gen_free(g);

    free_var(arglist);
    return pack;
}
Esempio n. 20
0
/*
 * Document-method: encode
 *
 * call-seq: encode(obj[, io[, &block]])
 *
 * +obj+ is the Ruby object to encode to JSON
 *
 * +io+ is an optional IO used to stream the encoded JSON string to.
 * If +io+ isn't specified, this method will return the resulting JSON string. If +io+ is specified, this method returns nil
 *
 * If an optional block is passed, it's called when encoding is complete and passed the resulting JSON string
 *
 * It should be noted that you can reuse an instance of this class to continue encoding multiple JSON
 * to the same stream. Just continue calling this method, passing it the same IO object with new/different
 * ruby objects to encode. This is how streaming is accomplished.
 */
static VALUE rb_yajl_encoder_encode(int argc, VALUE * argv, VALUE self) {
    yajl_encoder_wrapper * wrapper;
    const unsigned char * buffer;
    unsigned int len;
    VALUE obj, io, blk, outBuff;

    GetEncoder(self, wrapper);

    rb_scan_args(argc, argv, "11&", &obj, &io, &blk);

    if (blk != Qnil) {
        wrapper->on_progress_callback = blk;
    }

    /* begin encode process */
    yajl_encode_part(wrapper, obj, io);

    /* just make sure we output the remaining buffer */
    yajl_gen_get_buf(wrapper->encoder, &buffer, &len);
    outBuff = rb_str_new((const char *)buffer, len);
#ifdef HAVE_RUBY_ENCODING_H
    rb_enc_associate(outBuff, utf8Encoding);
#endif
    yajl_gen_clear(wrapper->encoder);

    if (io != Qnil) {
        rb_io_write(io, outBuff);
        if (wrapper->terminator != 0 && wrapper->terminator != Qnil) {
            rb_io_write(io, wrapper->terminator);
        }
        return Qnil;
    } else if (blk != Qnil) {
        rb_funcall(blk, intern_call, 1, outBuff);
        if (wrapper->terminator != 0) {
            rb_funcall(blk, intern_call, 1, wrapper->terminator);
        }
        return Qnil;
    } else {
        if (wrapper->terminator != 0 && wrapper->terminator != Qnil) {
            rb_str_concat(outBuff, wrapper->terminator);
        }
        return outBuff;
    }
    return Qnil;
}
Esempio n. 21
0
void wankelEncoder_flush(yajl_gen g, VALUE io, int write_buffer_size) {
	VALUE rbBuffer;
    yajl_gen_status status;
    const unsigned char * buffer;
    size_t len;
	
	if (io != Qnil) {
		status = yajl_gen_get_buf(g, &buffer, &len);
		yajl_helper_check_gen_status(status);
		
		if (len >= (size_t)write_buffer_size) {
			rbBuffer = rb_str_new((const char *)buffer, len);
			rb_enc_associate(rbBuffer, rb_utf8_encoding());
			rb_io_write(io, rbBuffer);
			yajl_gen_clear(g);
		}
	}
}
Esempio n. 22
0
/*
 * Document-method: encode
 *
 * call-seq: encode(obj[, io])
 *
 * +obj+ is the Ruby object to encode to JSON
 *
 * +io+ is an optional IO used to stream the encoded JSON string to. If no io
 *      is specified the resulting JSON string is returned. If io is specified,
 *      this method returns nil
 */
static VALUE wankelEncoder_encode(int argc, VALUE * argv, VALUE self) {
	VALUE obj, io, options;
	yajl_gen g;
	yajl_alloc_funcs alloc_funcs;
	yajl_gen_status status;
	int write_buffer_size;
    const unsigned char * buffer;
    size_t len;

	rb_scan_args(argc, argv, "11", &obj, &io);
	options = rb_iv_get(self, "@options");
	
	alloc_funcs.malloc = yajl_helper_malloc;
	alloc_funcs.realloc = yajl_helper_realloc;
	alloc_funcs.free = yajl_helper_free;
	g = yajl_gen_alloc(&alloc_funcs);
	
	yajl_gen_configure(g, options);
	
	if (io != Qnil && !rb_respond_to(io, intern_io_write)) {
		rb_raise(e_encodeError, "output must be a an IO");
	}
	
	write_buffer_size = FIX2INT(rb_hash_aref(options, ID2SYM(rb_intern("write_buffer_size"))));
	
	yajl_encode_part(g, obj, io, write_buffer_size);
	
	// TODO: add terminator here if desired
	if (io == Qnil) {
		status = yajl_gen_get_buf(g, &buffer, &len);
		yajl_helper_check_gen_status(status);
	    io = rb_str_new((const char *)buffer, len);
		rb_enc_associate(io, rb_utf8_encoding());
		yajl_gen_clear(g);
		yajl_gen_free(g);
		return io;
	} else {
		wankelEncoder_flush(g, io, 1);
		yajl_gen_free(g);
		return Qnil;
	}	
	return self;
}
Esempio n. 23
0
swi_status_t swi_sys_Reboot(const char* reasonPtr)
{
  char *payload = NULL;
  size_t payloadLen = 0;
  swi_status_t res;
  yajl_gen gen;

  YAJL_GEN_ALLOC(gen);

  if (reasonPtr == NULL)
    goto emp_send;

  YAJL_GEN_STRING(reasonPtr, "reasonPtr");
  YAJL_GEN_GET_BUF(payload, payloadLen);
emp_send:
  res = emp_send_and_wait_response(EMP_REBOOT, 0, payload, payloadLen, NULL, NULL);
  yajl_gen_clear(gen);
  yajl_gen_free(gen);
  return res;
}
Esempio n. 24
0
void writejson(FILE * out, char *stamp, char *line, size_t len, int fragment)
{
	yajl_gen g;

	const unsigned char *buf;
	size_t buflen;

	g = yajl_gen_alloc(NULL);

	yajl_gen_config(g, yajl_gen_beautify, 0);
	yajl_gen_config(g, yajl_gen_validate_utf8, 1);

	chk(yajl_gen_map_open(g));

	chk(yajl_gen_string(g, (const unsigned char *)"timestamp", 9));
	chk(yajl_gen_string(g, (const unsigned char *)stamp, TIMESTAMP));

	chk(yajl_gen_string(g, (const unsigned char *)"message", 7));
	chk(yajl_gen_string(g, (const unsigned char *)line, len));

	if (fragment >= 0) {
		char fragmentStr[30];

		snprintf(fragmentStr, 30, "%d", fragment);

		chk(yajl_gen_string(g, (const unsigned char *)"fragmentId", 10));
		chk(yajl_gen_number(g, fragmentStr, strlen(fragmentStr)));
	}

	chk(yajl_gen_map_close(g));

	yajl_gen_get_buf(g, &buf, &buflen);
	fwrite(buf, 1, buflen, out);
	yajl_gen_clear(g);
	yajl_gen_free(g);

	putc('\n', out);
}
Esempio n. 25
0
void yajl_encode_part(void * wrapper, VALUE obj, VALUE io) {
    VALUE str, outBuff, otherObj;
    yajl_encoder_wrapper * w = wrapper;
    yajl_gen_status status;
    int idx = 0;
    const unsigned char * buffer;
    const char * cptr;
    unsigned int len;

    if (io != Qnil || w->on_progress_callback != Qnil) {
        status = yajl_gen_get_buf(w->encoder, &buffer, &len);
        if (len >= WRITE_BUFSIZE) {
            outBuff = rb_str_new((const char *)buffer, len);
            if (io != Qnil) {
                rb_io_write(io, outBuff);
            } else if (w->on_progress_callback != Qnil) {
                rb_funcall(w->on_progress_callback, intern_call, 1, outBuff);
            }
            yajl_gen_clear(w->encoder);
        }
    }

    switch (TYPE(obj)) {
        case T_HASH:
            status = yajl_gen_map_open(w->encoder);

            /* TODO: itterate through keys in the hash */
            VALUE keys = rb_funcall(obj, intern_keys, 0);
            VALUE entry, keyStr;
            for(idx=0; idx<RARRAY_LEN(keys); idx++) {
                entry = rb_ary_entry(keys, idx);
                keyStr = rb_funcall(entry, intern_to_s, 0); /* key must be a string */
                /* the key */
                yajl_encode_part(w, keyStr, io);
                /* the value */
                yajl_encode_part(w, rb_hash_aref(obj, entry), io);
            }

            status = yajl_gen_map_close(w->encoder);
            break;
        case T_ARRAY:
            status = yajl_gen_array_open(w->encoder);
            for(idx=0; idx<RARRAY_LEN(obj); idx++) {
                otherObj = rb_ary_entry(obj, idx);
                yajl_encode_part(w, otherObj, io);
            }
            status = yajl_gen_array_close(w->encoder);
            break;
        case T_NIL:
            status = yajl_gen_null(w->encoder);
            break;
        case T_TRUE:
            status = yajl_gen_bool(w->encoder, 1);
            break;
        case T_FALSE:
            status = yajl_gen_bool(w->encoder, 0);
            break;
        case T_FIXNUM:
        case T_FLOAT:
        case T_BIGNUM:
            str = rb_funcall(obj, intern_to_s, 0);
            cptr = RSTRING_PTR(str);
            len = RSTRING_LEN(str);
            if (memcmp(cptr, "NaN", 3) == 0 || memcmp(cptr, "Infinity", 8) == 0 || memcmp(cptr, "-Infinity", 9) == 0) {
                rb_raise(cEncodeError, "'%s' is an invalid number", cptr);
            }
            status = yajl_gen_number(w->encoder, cptr, len);
            break;
        case T_STRING:
            cptr = RSTRING_PTR(obj);
            len = RSTRING_LEN(obj);
            status = yajl_gen_string(w->encoder, (const unsigned char *)cptr, len);
            break;
        default:
            if (rb_respond_to(obj, intern_to_json)) {
                str = rb_funcall(obj, intern_to_json, 0);
                cptr = RSTRING_PTR(str);
                len = RSTRING_LEN(str);
                status = yajl_gen_number(w->encoder, cptr, len);
            } else {
                str = rb_funcall(obj, intern_to_s, 0);
                cptr = RSTRING_PTR(str);
                len = RSTRING_LEN(str);
                status = yajl_gen_string(w->encoder, (const unsigned char *)cptr, len);
            }
            break;
    }
}
Esempio n. 26
0
int ovs_db_table_cb_register(ovs_db_t *pdb, const char *tb_name,
                             const char **tb_column,
                             ovs_db_table_cb_t update_cb,
                             ovs_db_result_cb_t result_cb, unsigned int flags) {
  yajl_gen jgen;
  yajl_gen_status yajl_gen_ret;
  ovs_callback_t *new_cb = NULL;
  char uid_str[OVS_UID_STR_SIZE];
  char *params;
  size_t params_len;
  int ovs_db_ret = 0;

  /* sanity check */
  if (pdb == NULL || tb_name == NULL || update_cb == NULL)
    return -1;

  /* allocate new update callback */
  if ((new_cb = calloc(1, sizeof(*new_cb))) == NULL)
    return -1;

  /* init YAJL generator */
  if ((jgen = yajl_gen_alloc(NULL)) == NULL) {
    sfree(new_cb);
    return -1;
  }

  /* add new callback to front */
  new_cb->table.call = update_cb;
  new_cb->uid = ovs_uid_generate();
  ovs_db_callback_add(pdb, new_cb);

  /* make update notification request
   * [<db-name>, <json-value>, <monitor-requests>] */
  OVS_YAJL_CALL(yajl_gen_array_open, jgen);
  {
    OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, OVS_DB_DEFAULT_DB_NAME);

    /* uid string <json-value> */
    snprintf(uid_str, sizeof(uid_str), "%" PRIX64, new_cb->uid);
    OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, uid_str);

    /* <monitor-requests> */
    OVS_YAJL_CALL(yajl_gen_map_open, jgen);
    {
      OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, tb_name);
      OVS_YAJL_CALL(yajl_gen_array_open, jgen);
      {
        /* <monitor-request> */
        OVS_YAJL_CALL(yajl_gen_map_open, jgen);
        {
          if (tb_column) {
            /* columns within the table to be monitored */
            OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "columns");
            OVS_YAJL_CALL(yajl_gen_array_open, jgen);
            for (; *tb_column; tb_column++)
              OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, *tb_column);
            OVS_YAJL_CALL(yajl_gen_array_close, jgen);
          }
          /* specify select option */
          OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "select");
          {
            OVS_YAJL_CALL(yajl_gen_map_open, jgen);
            {
              OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "initial");
              OVS_YAJL_CALL(yajl_gen_bool, jgen,
                            flags & OVS_DB_TABLE_CB_FLAG_INITIAL);
              OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "insert");
              OVS_YAJL_CALL(yajl_gen_bool, jgen,
                            flags & OVS_DB_TABLE_CB_FLAG_INSERT);
              OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "delete");
              OVS_YAJL_CALL(yajl_gen_bool, jgen,
                            flags & OVS_DB_TABLE_CB_FLAG_DELETE);
              OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "modify");
              OVS_YAJL_CALL(yajl_gen_bool, jgen,
                            flags & OVS_DB_TABLE_CB_FLAG_MODIFY);
            }
            OVS_YAJL_CALL(yajl_gen_map_close, jgen);
          }
        }
        OVS_YAJL_CALL(yajl_gen_map_close, jgen);
      }
      OVS_YAJL_CALL(yajl_gen_array_close, jgen);
    }
    OVS_YAJL_CALL(yajl_gen_map_close, jgen);
  }
  OVS_YAJL_CALL(yajl_gen_array_close, jgen);

  /* make a request to subscribe to given table */
  OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&params,
                &params_len);
  if (ovs_db_send_request(pdb, "monitor", params, result_cb) < 0) {
    OVS_ERROR("Failed to subscribe to \"%s\" table", tb_name);
    ovs_db_ret = (-1);
  }

yajl_gen_failure:
  /* release memory */
  yajl_gen_clear(jgen);
  return ovs_db_ret;
}
Esempio n. 27
0
int 
main(int argc, char ** argv)
{
    yajl_handle hand;
    static unsigned char fileData[65536];
    /* generator config */
    yajl_gen_config conf = { 1, "  " };
	yajl_gen g;
    yajl_status stat;
    size_t rd;
    /* allow comments */
    yajl_parser_config cfg = { 1, 1 };
    int retval = 0, done = 0;

    /* check arguments.*/
    int a = 1;
    while ((a < argc) && (argv[a][0] == '-') && (strlen(argv[a]) > 1)) {
        int i;
        for ( i=1; i < strlen(argv[a]); i++) {
            switch (argv[a][i]) {
                case 'm':
                    conf.beautify = 0;
                    break;
                case 'u':
                    cfg.checkUTF8 = 0;
                    break;
                default:
                    fprintf(stderr, "unrecognized option: '%c'\n\n", argv[a][i]);
                    usage(argv[0]);
            }
        }
        ++a;
    }
    if (a < argc) {
        usage(argv[0]);
    }
    
    g = yajl_gen_alloc(&conf, NULL);

    /* ok.  open file.  let's read and parse */
    hand = yajl_alloc(&callbacks, &cfg, NULL, (void *) g);
        
	while (!done) {
        rd = fread((void *) fileData, 1, sizeof(fileData) - 1, stdin);
        
        if (rd == 0) {
            if (!feof(stdin)) {
                fprintf(stderr, "error on file read.\n");
                retval = 1;
                break;
            }
            done = 1;
        }
        fileData[rd] = 0;
        
        if (done)
            /* parse any remaining buffered data */
            stat = yajl_parse_complete(hand);
        else
            /* read file data, pass to parser */
            stat = yajl_parse(hand, fileData, rd);

        if (stat != yajl_status_ok &&
            stat != yajl_status_insufficient_data)
        {
            unsigned char * str = yajl_get_error(hand, 1, fileData, rd);
            fprintf(stderr, "%s", (const char *) str);
            yajl_free_error(hand, str);
            retval = 1;
            break;
        } else {
            const unsigned char * buf;
            unsigned int len;
            yajl_gen_get_buf(g, &buf, &len);
            fwrite(buf, 1, len, stdout);
            yajl_gen_clear(g);
        }
    }

    yajl_gen_free(g);
    yajl_free(hand);
    
    return retval;
}
Esempio n. 28
0
static axa_json_res_t
add_whit(axa_emsg_t *emsg, yajl_gen g, struct axa_strbuf *yajl_sb, nmsg_input_t nmsg_input, axa_p_whit_t *whit, size_t whit_len)
{
	axa_json_res_t json_res;

	json_res = add_channel(emsg, g, whit->hdr.ch);
	if (json_res != AXA_JSON_RES_SUCCESS)
		return (json_res);

	switch (whit->hdr.type) {
	case AXA_P_WHIT_NMSG: {
		struct axa_strbuf *sb;
		nmsg_message_t msg;
		axa_w2n_res_t wres;
		nmsg_res nres;
		const char *vname, *mname;
		char *nmsg_json = NULL;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_nmsg_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu", whit_len, sizeof(axa_p_whit_nmsg_t));
			return (AXA_JSON_RES_FAILURE);
		}

		wres = axa_whit2nmsg(emsg, nmsg_input, &msg, whit, whit_len);
		if (wres != AXA_W2N_RES_SUCCESS) {
			return (AXA_JSON_RES_FAILURE);
		}

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}

		if(AXA_P2H_IDX(whit->nmsg.hdr.field_idx) < AXA_NMSG_IDX_RSVD) {
			const char *field_name;
			nres = nmsg_message_get_field_name(msg, whit->nmsg.hdr.field_idx, &field_name);
			if (nres == nmsg_res_success) {
				add_yajl_string(g, "field");
				add_yajl_string(g, field_name);
			} else {
				add_yajl_string(g, "field_idx");
				add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.field_idx));
			}
		}

		if (AXA_P2H_IDX(whit->nmsg.hdr.val_idx) < AXA_NMSG_IDX_RSVD) {
			add_yajl_string(g, "val_idx");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.val_idx));
		}

		vname = nmsg_msgmod_vid_to_vname(AXA_P2H_IDX(whit->nmsg.hdr.vid));
		if (vname != NULL) {
			add_yajl_string(g, "vname");
			add_yajl_string(g, vname);
		} else {
			add_yajl_string(g, "vid");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.vid));
		}

		mname = nmsg_msgmod_msgtype_to_mname(
				AXA_P2H16(whit->nmsg.hdr.vid),
				AXA_P2H16(whit->nmsg.hdr.type));
		if (mname != NULL) {
			add_yajl_string(g, "mname");
			add_yajl_string(g, mname);
		} else {
			add_yajl_string(g, "msgtype");
			add_yajl_integer(g, AXA_P2H_IDX(whit->nmsg.hdr.type));
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->nmsg.hdr.ts.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		axa_strbuf_reset(sb);
		axa_strbuf_append(sb, "%s.%09u", when,
				AXA_P2H32(whit->nmsg.hdr.ts.tv_nsec));
		add_yajl_string(g, sb->data);

		nres = nmsg_message_to_json(msg, &nmsg_json);
		if (nres == nmsg_res_success) {
			add_yajl_string(g, "nmsg");
			add_yajl_integer(g, 0);

			yajl_gen_clear(g);
			axa_strbuf_clip(yajl_sb, axa_strbuf_len(yajl_sb)-1);
			axa_strbuf_append(yajl_sb, "%s", nmsg_json);
			free(nmsg_json);
		}

		axa_strbuf_destroy(&sb);
		nmsg_message_destroy(&msg);

		return (AXA_JSON_RES_SUCCESS);
	}
	case AXA_P_WHIT_IP: {
		struct axa_strbuf *sb;
		struct nmsg_ipdg dg;
		nmsg_res res;
		struct tm tm;
		time_t t;
		char when[32];

		if (whit_len < sizeof(axa_p_whit_ip_t)) {
			axa_pemsg(emsg, "whit_len %zu < %zu",
					whit_len, sizeof(axa_p_whit_ip_t));
			return (AXA_JSON_RES_FAILURE);
		}

		add_yajl_string(g, "time");
		t = AXA_P2H32(whit->ip.hdr.tv.tv_sec);
		gmtime_r(&t, &tm);
		strftime(when, sizeof(when), "%Y-%m-%d %T", &tm);

		sb = axa_strbuf_init();
		if (sb == NULL) {
			axa_pemsg(emsg, "could not allocate axa_strbuf");
			return (AXA_JSON_RES_MEMFAIL);
		}
		axa_strbuf_append(sb, "%s.%06u", when,
				AXA_P2H32(whit->ip.hdr.tv.tv_usec));
		add_yajl_string(g, sb->data);
		axa_strbuf_destroy(&sb);

		res = nmsg_ipdg_parse_pcap_raw(&dg, DLT_RAW, whit->ip.b, whit_len - offsetof(axa_p_whit_ip_t, b));
		if (res != nmsg_res_success || dg.len_network == 0) {
			add_yajl_string(g, "parse_error");
			add_yajl_bool(g, true);

			return (AXA_JSON_RES_SUCCESS);
		}

		add_yajl_string(g, "af");
		switch(dg.proto_network) {
		case AF_INET: {
			struct ip *ip_hdr;
			char addr_str[INET_ADDRSTRLEN];

			add_yajl_string(g, "IPv4");

			if (dg.network != NULL && dg.len_network >= sizeof(ip_hdr)) {
				ip_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_src, addr_str, sizeof(addr_str)));
				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET, &ip_hdr->ip_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip_hdr->ip_ttl);
			}
			break;
		}
		case AF_INET6: {
			struct ip6_hdr *ip6_hdr;
			char addr_str[INET6_ADDRSTRLEN];
			
			add_yajl_string(g, "IPv6");

			if (dg.network != NULL && dg.len_network >= sizeof(ip6_hdr)) {
				ip6_hdr = (void*)dg.network;

				add_yajl_string(g, "src");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_src, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "dst");
				add_yajl_string(g, inet_ntop(AF_INET6, &ip6_hdr->ip6_dst, addr_str, sizeof(addr_str)));

				add_yajl_string(g, "ttl");
				add_yajl_integer(g, ip6_hdr->ip6_hlim);

			}
			break;
		}
		default:
			add_yajl_integer(g, dg.proto_network);
			return (AXA_JSON_RES_SUCCESS);
		} /* switch */

		add_yajl_string(g, "proto");
		switch(dg.proto_transport) {
		case IPPROTO_ICMP:
			add_yajl_string(g, "ICMP");
			break;
		case IPPROTO_ICMPV6:
			add_yajl_string(g, "ICMPv6");
			break;
		case IPPROTO_TCP:
			add_yajl_string(g, "TCP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct tcphdr)) {
				struct tcphdr *tcp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(tcp_hdr->th_dport));

				add_yajl_string(g, "flags");
				add_yajl_array(g);
				if ((tcp_hdr->th_flags & TH_FIN) != 0)
					add_yajl_string(g, "FIN");
				if ((tcp_hdr->th_flags & TH_SYN) != 0)
					add_yajl_string(g, "SYN");
				if ((tcp_hdr->th_flags & TH_ACK) != 0)
					add_yajl_string(g, "ACK");
				if ((tcp_hdr->th_flags & TH_RST) != 0)
					add_yajl_string(g, "RST");
				close_yajl_array(g);
			}
			break;
		case IPPROTO_UDP:
			add_yajl_string(g, "UDP");
			if (dg.transport != NULL && dg.len_transport >= sizeof(struct udphdr)) {
				struct udphdr *udp_hdr = (void*)dg.transport;

				add_yajl_string(g, "src_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_sport));

				add_yajl_string(g, "dst_port");
				add_yajl_integer(g, ntohs(udp_hdr->uh_dport));

			}
			break;
		default:
			add_yajl_integer(g, dg.proto_transport);
			break;
		} /* switch */

		if (dg.payload != NULL) {
			base64_encodestate b64;
			char *b64_str;
			size_t b64_str_len;

			base64_init_encodestate(&b64);
			b64_str = alloca(2 * dg.len_payload + 1);
			AXA_ASSERT(b64_str != NULL);

			b64_str_len = base64_encode_block((void*)dg.payload,
					dg.len_payload, b64_str, &b64);
			b64_str_len += base64_encode_blockend(b64_str + b64_str_len, &b64);

			add_yajl_string(g, "payload");
			add_yajl_string_len(g, b64_str, b64_str_len);
		}

		return (AXA_JSON_RES_SUCCESS);
	}
	default:
		axa_pemsg(emsg, "unknown whit hdr type: %d", whit->hdr.type);
		return (AXA_JSON_RES_FAILURE);
	}
}
Esempio n. 29
0
int ovs_db_send_request(ovs_db_t *pdb, const char *method, const char *params,
                        ovs_db_result_cb_t cb) {
  int ret = 0;
  yajl_gen_status yajl_gen_ret;
  yajl_val jparams;
  yajl_gen jgen;
  ovs_callback_t *new_cb = NULL;
  uint64_t uid;
  char uid_buff[OVS_UID_STR_SIZE];
  const char *req = NULL;
  size_t req_len = 0;
  struct timespec ts;

  /* sanity check */
  if (!pdb || !method || !params)
    return -1;

  if ((jgen = yajl_gen_alloc(NULL)) == NULL)
    return -1;

  /* try to parse params */
  if ((jparams = yajl_tree_parse(params, NULL, 0)) == NULL) {
    OVS_ERROR("params is not a JSON string");
    yajl_gen_clear(jgen);
    return -1;
  }

  /* generate method field */
  OVS_YAJL_CALL(yajl_gen_map_open, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "method");
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, method);

  /* generate params field */
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "params");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);
  yajl_tree_free(jparams);

  /* generate id field */
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
  uid = ovs_uid_generate();
  snprintf(uid_buff, sizeof(uid_buff), "%" PRIX64, uid);
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, uid_buff);

  OVS_YAJL_CALL(yajl_gen_map_close, jgen);

  if (cb) {
    /* register result callback */
    if ((new_cb = calloc(1, sizeof(*new_cb))) == NULL)
      goto yajl_gen_failure;

    /* add new callback to front */
    sem_init(&new_cb->result.sync, 0, 0);
    new_cb->result.call = cb;
    new_cb->uid = uid;
    ovs_db_callback_add(pdb, new_cb);
  }

  /* send the request */
  OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&req, &req_len);
  OVS_DEBUG("%s", req);
  if (!ovs_db_data_send(pdb, req, req_len)) {
    if (cb) {
      /* wait for result */
      clock_gettime(CLOCK_REALTIME, &ts);
      ts.tv_sec += OVS_DB_SEND_REQ_TIMEOUT;
      if (sem_timedwait(&new_cb->result.sync, &ts) < 0) {
        OVS_ERROR("%s() no replay received within %d sec", __FUNCTION__,
                  OVS_DB_SEND_REQ_TIMEOUT);
        ret = (-1);
      }
    }
  } else {
    OVS_ERROR("ovs_db_data_send() failed");
    ret = (-1);
  }

yajl_gen_failure:
  if (new_cb) {
    /* destroy callback */
    sem_destroy(&new_cb->result.sync);
    ovs_db_callback_remove(pdb, new_cb);
  }

  /* release memory */
  yajl_gen_clear(jgen);
  return (yajl_gen_ret != yajl_gen_status_ok) ? (-1) : ret;
}
Esempio n. 30
0
int 
main(int argc, char ** argv)
{
    yajl_handle hand;
    static unsigned char fileData[65536];
    /* generator config */
    yajl_gen g;
    yajl_status stat;
    size_t rd;
    int retval = 0;
    int a = 1;

    g = yajl_gen_alloc(NULL);
    yajl_gen_config(g, yajl_gen_beautify, 1);
    yajl_gen_config(g, yajl_gen_validate_utf8, 1);

    /* ok.  open file.  let's read and parse */
    hand = yajl_alloc(&callbacks, NULL, (void *) g);
    /* and let's allow comments by default */
    yajl_config(hand, yajl_allow_comments, 1);

    /* check arguments.*/
    while ((a < argc) && (argv[a][0] == '-') && (strlen(argv[a]) > 1)) {
        unsigned int i;
        for ( i=1; i < strlen(argv[a]); i++) {
            switch (argv[a][i]) {
                case 'm':
                    yajl_gen_config(g, yajl_gen_beautify, 0);
                    break;
                case 'u':
                    yajl_config(hand, yajl_dont_validate_strings, 1);
                    break;
                default:
                    fprintf(stderr, "unrecognized option: '%c'\n\n",
                            argv[a][i]);
                    usage(argv[0]);
            }
        }
        ++a;
    }
    if (a < argc) {
        usage(argv[0]);
    }


    for (;;) {
        rd = fread((void *) fileData, 1, sizeof(fileData) - 1, stdin);

        if (rd == 0) {
            if (!feof(stdin)) {
                fprintf(stderr, "error on file read.\n");
                retval = 1;
            }
            break;
        }
        fileData[rd] = 0;

        stat = yajl_parse(hand, fileData, rd);

        if (stat != yajl_status_ok) break;

        {
            const unsigned char * buf;
            size_t len;
            yajl_gen_get_buf(g, &buf, &len);
            //fwrite(buf, 1, len, stdout);
            std::cout << "Buf => " << buf << std::endl;
            yajl_gen_clear(g);
        }
    }

    stat = yajl_complete_parse(hand);

    if (stat != yajl_status_ok) {
        unsigned char * str = yajl_get_error(hand, 1, fileData, rd);
        fprintf(stderr, "%s", (const char *) str);
        yajl_free_error(hand, str);
        retval = 1;
    }

    yajl_gen_free(g);
    yajl_free(hand);

    return retval;
}