Esempio n. 1
0
int json_object_update(json_t *object, json_t *other)
{
    void *iter;

    if(!json_is_object(object) || !json_is_object(other))
        return -1;

    iter = json_object_iter(other);
    while(iter) {
        const char *key;
        json_t *value;

        key = json_object_iter_key(iter);
        value = json_object_iter_value(iter);

        if(json_object_set_nocheck(object, key, value))
            return -1;

        iter = json_object_iter_next(other, iter);
    }

    return 0;
}
Esempio n. 2
0
symbols_t* drakvuf_get_symbols_from_rekall(const char *rekall_profile)
{

    symbols_t *ret = g_malloc0(sizeof(symbols_t));;
    json_object *root = json_object_from_file(rekall_profile);
    if(!root) {
        fprintf(stderr, "Rekall profile couldn't be opened!\n");
        goto err_exit;
    }

    json_object *functions = NULL;
    if (!json_object_object_get_ex(root, "$FUNCTIONS", &functions)) {
        PRINT_DEBUG("Rekall profile: no $FUNCTIONS section found\n");
        goto err_exit;
    }

    ret->count = json_object_object_length(functions);
    ret->symbols = g_malloc0(sizeof(symbols_t) * ret->count);

    struct json_object_iterator it = json_object_iter_begin(functions);
    struct json_object_iterator itEnd = json_object_iter_end(functions);
    uint32_t i=0;

    while (!json_object_iter_equal(&it, &itEnd) && i < ret->count) {
        ret->symbols[i].name = g_strdup(json_object_iter_peek_name(&it));
        ret->symbols[i].rva = json_object_get_int64(json_object_iter_peek_value(&it));
        i++;
        json_object_iter_next(&it);
    }

    json_object_put(functions);

    return ret;

    err_exit: free(ret);
    return NULL;
}
Esempio n. 3
0
static int bser_object(const bser_ctx_t *ctx, json_t *obj, void *data)
{
  size_t n;
  json_t *val;
  const char *key;
  void *iter;

  if (!is_bser_version_supported(ctx)) {
    return -1;
  }

  if (ctx->dump(&bser_object_hdr, sizeof(bser_object_hdr), data)) {
    return -1;
  }

  n = json_object_size(obj);
  if (bser_int(ctx, n, data)) {
    return -1;
  }

  iter = json_object_iter(obj);
  while (iter) {
    key = json_object_iter_key(iter);
    val = json_object_iter_value(iter);

    if (bser_bytestring(ctx, key, data)) {
      return -1;
    }
    if (w_bser_dump(ctx, val, data)) {
      return -1;
    }

    iter = json_object_iter_next(obj, iter);
  }

  return 0;
}
Esempio n. 4
0
static json_t *json_object_deep_copy(json_t *object)
{
    json_t *result;
    void *iter;

    result = json_object();
    if(!result)
        return NULL;

    iter = json_object_iter(object);
    while(iter)
    {
        const char *key;
        json_t *value;

        key = json_object_iter_key(iter);
        value = json_object_iter_value(iter);
        json_object_set_new_nocheck(result, key, json_deep_copy(value));

        iter = json_object_iter_next(object, iter);
    }

    return result;
}
Esempio n. 5
0
void MAPNEXT()
{
    stackpointer = map_safe_peek()->stk + 1;
    optind = map_safe_peek()->opt;
    switch (json_typeof(*(map_safe_peek()->stk)))
    {
        case JSON_OBJECT:
            json_object_iter_key(map_safe_peek()->itr);
            PUSH(maybe_deep(json_object_iter_value(map_safe_peek()->itr)));
            map_safe_peek()->itr = json_object_iter_next(*(map_safe_peek()->stk), map_safe_peek()->itr);
            if (!map_safe_peek()->itr)
                {map_safe_peek()->fin = 1;}
            break;
        case JSON_ARRAY:
            PUSH(maybe_deep(json_array_get(*(map_safe_peek()->stk), map_safe_peek()->lin)));
            map_safe_peek()->lin++;
            if (map_safe_peek()->lin >= json_array_size(*(map_safe_peek()->stk)))
                {map_safe_peek()->fin = 1;}
            break;
        default:
            err("parse error: type not mappable");
            map_safe_peek()->fin = 1;
    }
}
Esempio n. 6
0
static bool is_valid_enum_value(const json_t *member, json_int_t enumval){

    json_t *item = json_object_get(member, KEY_ITEM);
    assert(json_is_object(item));
    json_t *values = json_object_get(item, KEY_VALUES);
    assert(json_is_object(values));

    void *iter = json_object_iter(values);
    while (iter) {
        json_int_t labelint;
        json_t *label = json_object_iter_value(iter);
        assert(json_is_integer(label));
        labelint = json_integer_value(label);

        if (labelint == enumval){
            return true;
        }

        iter = json_object_iter_next(values, iter);
    }

    return false;

}
Esempio n. 7
0
int parse_json(const char *data) {
    json_error_t error;
    json_t * root = json_loads(data, 0, &error);
     
	if(!root) {
		fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
		return 1;
	}

    const char *key;
    json_t *value;

    void *iter = json_object_iter(root);
    while(iter)
    {
        key = json_object_iter_key(iter);
        value = json_object_iter_value(iter);
        fprintf(stderr, "CHERRY key:%s\n", key);
        if(json_is_object(value)) {
        }
        iter = json_object_iter_next(root, iter);
    } 
	return 0;
}
Esempio n. 8
0
static int ntop_zmq_receive(lua_State* vm) {
  NetworkInterface *ntop_interface;
  void *subscriber;
  int size;
  struct zmq_msg_hdr h;
  char *payload;
  int payload_len;
  zmq_pollitem_t item;
  int rc;

  lua_getglobal(vm, "zmq_subscriber");
  if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
    ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber");
    return(CONST_LUA_ERROR);
  }

  lua_getglobal(vm, "ntop_interface");
  if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) {
    handle_null_interface(vm);
    return(CONST_LUA_ERROR);
    // ntop_interface = ntop->getInterfaceId(0);
  }

  item.socket = subscriber;
  item.events = ZMQ_POLLIN;
  do {
    rc = zmq_poll(&item, 1, 1000);
    if (rc < 0 || !ntop_interface->isRunning()) return(CONST_LUA_PARAM_ERROR);
  } while (rc == 0);

  size = zmq_recv(subscriber, &h, sizeof(h), 0);

  if(size != sizeof(h) || h.version != MSG_VERSION) {
    ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version);
    return -1;
  }

  payload_len = h.size + 1;
  if((payload = (char*)malloc(payload_len)) != NULL) {
    size = zmq_recv(subscriber, payload, payload_len, 0);
    payload[h.size] = '\0';

    if(size > 0) {
      json_object *o = json_tokener_parse(payload);

      if(o != NULL) {
	struct json_object_iterator it = json_object_iter_begin(o);
	struct json_object_iterator itEnd = json_object_iter_end(o);

	while (!json_object_iter_equal(&it, &itEnd)) {
	  char *key   = (char*)json_object_iter_peek_name(&it);
	  const char *value = json_object_get_string(json_object_iter_peek_value(&it));

	  ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value);

	  json_object_iter_next(&it);
	}

	json_object_put(o);
      }

      lua_pushfstring(vm, "%s", payload);
      ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload);
      free(payload);
      return(CONST_LUA_OK);
    } else {
      free(payload);
      return(CONST_LUA_PARAM_ERROR);
    }
  } else
    return(CONST_LUA_PARAM_ERROR);
}
/* send a command to the server, handle callbacks (menus, getline, etc) and
   display data (map data, pline, player status, ...) and finally return the
   response to the command.

   A play_game response will longjmp() to the matching play_game request, so
   beware! */
json_t *
send_receive_msg(const char *const volatile msgtype, json_t *volatile jmsg)
{
    const char *volatile sendkey;
    char key[BUFSZ];
    char oldkey[BUFSZ];
    void *iter;
    volatile int retry_count = 3;

    if (conn_err && ex_jmp_buf_valid)
        longjmp(ex_jmp_buf, 1);

    /* quick connection sanity check and restoration attempt */
    if (!test_restore_connection())
        return NULL;

    if (!jmsg)
        return NULL;

    sendkey = msgtype;
    while (1) {
        /* send the message; keep the reference to jmsg */
        json_t *send_msg = json_pack("{sO}", sendkey, jmsg);
        if (!send_json_msg(send_msg)) {
            json_decref(send_msg);
            if (retry_count-- > 0 && restart_connection())
                continue;
            goto error;
        }
        json_decref(send_msg);

    receive_without_sending:
        ;
        /* receive the response */
        json_t *recv_msg = receive_json_msg();
        if (!recv_msg) {
            /* If no data is received, there must have been a network error.
               Presumably the send didn't succeed either and the sent data
               vanished, so reconnect. restart_connection() can longjmp back to
               play_game; if it doesn't, retry both send and receive. */
            if (retry_count-- > 0 && restart_connection())
                continue;
            goto error;
        }

        json_t *jdisplay = json_object_get(recv_msg, "display");
        if (jdisplay) {
            if (json_is_array(jdisplay))
                handle_display_list(jdisplay);
            else
                print_error
                    ("New display list doesn't have the right data type.");
            json_object_del(recv_msg, "display");
        }

        iter = json_object_iter(recv_msg);
        if (!iter) {
            print_error("Empty return object.");
            json_decref(recv_msg);
            json_decref(jmsg);
            return json_object();
        }

        /* The string returned by json_object_iter_key is only valid while
           recv_msg exists. Since we still want the value afterwards, it must
           be copied. */
        strncpy(key, json_object_iter_key(iter), BUFSZ - 1);

        if (!strcmp(key, "server_cancel")) {
            /* This message is special in that it can be called out of
               sequence, and has no response. */
            json_decref(recv_msg); /* free it */
            client_windowprocs.win_server_cancel();
            goto receive_without_sending;
        }
        if (!strcmp(key, "load_progress")) {
            /* This message is only called in-sequence, but it still has no
               response. */
            int progress;
            if (json_unpack(json_object_iter_value(iter), "{si!}",
                            "progress", &progress) != -1)
                client_windowprocs.win_load_progress(progress);
            json_decref(recv_msg); /* free it */
            goto receive_without_sending;
        }

        send_receive_recent_response = json_object_iter_value(iter);

        if (json_object_iter_next(recv_msg, iter))
            print_error("Too many JSON objects in response data.");

        /* keep only the core of the response and throw away the wrapper */
        json_incref(send_receive_recent_response);
        json_decref(recv_msg);

        if (strcmp(sendkey, "play_game") == 0) {
            /* We might need to longjmp back here. */
            if (setjmp(playgame_jmp_buf) == 0) {
                playgame_jmp_buf_valid = 1;
            } else {
                playgame_jmp_buf_valid = 0;
                /* key, sendkey might have any value right now, but we know what
                   they should be from the position in the control flow */
                sendkey = "play_game";
                memset(key, 0, sizeof key);
                strcpy(key, "play_game");
            }
        }

        /* If the response type doesn't match the request type then either:
           - this is a callback that needs to be handled first;
           - this is a request to longjmp() back to nhnet_play_game.

           To simplify the control flow, our longjmp back upon receiving a
           play_game response is unconditional, and ends up cancelling itself
           out if a play_game message gets a play_game response. This also
           guarantees that playgame_jmp_buf_valid is only set while
           playgame_jmp_buf is actually on the call stack. */
        if (strcmp(key, "play_game") == 0 && playgame_jmp_buf_valid)
            longjmp(playgame_jmp_buf, 1);

        if (strcmp(key, msgtype)) {
            json_t *srvmsg = send_receive_recent_response;
            /* The next line is unneccessary, but makes the control flow easier
               to follow in a debugger. */
            send_receive_recent_response = 0;
            json_t *newmsg = handle_netcmd(key, msgtype, srvmsg);
            if (!newmsg) {     /* server error */
                if (error_retry_ok && retry_count-- > 0 && restart_connection())
                    continue;  /* jmsg is still alive, use it again */
                goto error;
            }

            json_decref(jmsg);
            jmsg = newmsg;
            strcpy(oldkey, key);
            sendkey = oldkey;

            /* send the callback data to the server and get a new response */
            continue;
        }

        json_decref(jmsg);
        break;  /* only loop via continue */
    }

    json_t *response = send_receive_recent_response;
    send_receive_recent_response = 0;

    return response;

error:
    json_decref(jmsg);
    close(sockfd);
    sockfd = -1;
    conn_err = TRUE;
    playgame_jmp_buf_valid = 0;
    if (ex_jmp_buf_valid)
        longjmp(ex_jmp_buf, 1);
    return NULL;
}
Esempio n. 10
0
static void test_iterators()
{
    int i;
    json_t *object, *foo, *bar, *baz;
    const char *iter_keys[3];
    int have_key[3] = { 0, 0, 0 };
    json_t *iter_values[3];
    void *iter;

    if(json_object_iter(NULL))
        fail("able to iterate over NULL");

    if(json_object_iter_next(NULL, NULL))
        fail("able to increment an iterator on a NULL object");

    object = json_object();
    foo = json_string("foo");
    bar = json_string("bar");
    baz = json_string("baz");
    if(!object || !foo || !bar || !bar)
        fail("unable to create values");

    if(json_object_iter_next(object, NULL))
        fail("able to increment a NULL iterator");

    if(json_object_set(object, "a", foo) ||
       json_object_set(object, "b", bar) ||
       json_object_set(object, "c", baz))
        fail("unable to populate object");

    iter = json_object_iter(object);
    if(!iter)
        fail("unable to get iterator");
    iter_keys[0] = json_object_iter_key(iter);
    iter_values[0] = json_object_iter_value(iter);

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    iter_keys[1] = json_object_iter_key(iter);
    iter_values[1] = json_object_iter_value(iter);
	printf("values=%s\n", json_string_value(iter_values[1]));

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    iter_keys[2] = json_object_iter_key(iter);
    iter_values[2] = json_object_iter_value(iter);

    if(json_object_iter_next(object, iter) != NULL)
        fail("able to iterate over the end");

    /* Check that keys have correct values */
    for (i = 0; i < 3; i++) {
        if (strcmp(iter_keys[i], "a") == 0) {
            if (iter_values[i] != foo)
                fail("wrong value for iter key a");
            else
                have_key[0] = 1;
        } else if (strcmp(iter_keys[i], "b") == 0) {
            if (iter_values[i] != bar)
                fail("wrong value for iter key b");
            else
                have_key[1] = 1;
        } else if (strcmp(iter_keys[i], "c") == 0) {
            if (iter_values[i] != baz)
                fail("wrong value for iter key c");
            else
                have_key[2] = 1;
        }
    }

    /* Check that we got all keys */
    for(i = 0; i < 3; i++) {
        if(!have_key[i])
            fail("a key wasn't iterated over");
    }

    if(json_object_iter_at(object, "foo"))
        fail("json_object_iter_at() succeeds for non-existent key");

    iter = json_object_iter_at(object, "b");
    if(!iter)
        fail("json_object_iter_at() fails for an existing key");

    if(strcmp(json_object_iter_key(iter), "b"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != bar)
        fail("iterating failed: wrong value");

    if(json_object_iter_set(object, iter, baz))
        fail("unable to set value at iterator");

    if(strcmp(json_object_iter_key(iter), "b"))
        fail("json_object_iter_key() fails after json_object_iter_set()");
    if(json_object_iter_value(iter) != baz)
        fail("json_object_iter_value() fails after json_object_iter_set()");
    if(json_object_get(object, "b") != baz)
        fail("json_object_get() fails after json_object_iter_set()");

    json_decref(object);
    json_decref(foo);
    json_decref(bar);
    json_decref(baz);
}
Esempio n. 11
0
bool settings_read(void)
{
  bool rv;
  bool bind_defaults;
  bool nonexistent_ok;

  rv             = true;
  bind_defaults  = true;
  nonexistent_ok = false;
  
  /* Read and delete the old versions first if it exists. */
  settings_read_v1();

  if(settings_read_v2())
    {
      bind_defaults = false;
      nonexistent_ok = true; // If we managed to read the old .lua file, then failing to read the new .json file should not cause any error messages.
    }


  /* Read the new version if it exists. */
  char * json;
  int    json_size;

  snprintf(filename, sizeof filename, "%s", get_save_filename("settings.json"));
  if(read_file(filename, &json, &json_size) == true)
    {
      enum json_tokener_error e;
      struct json_object * obj;

      obj = json_tokener_parse_verbose(json, &e);
      if(obj != NULL)
        {
          bool ok;
          struct json_object_iterator it;
          struct json_object_iterator itEnd;
          int active_questline;

          ok    = true;
          it    = json_object_iter_begin(obj);
          itEnd = json_object_iter_end(obj);

          active_questline = globals.active_questline;

          while(ok == true && !json_object_iter_equal(&it, &itEnd))
            {
              const char *         name;
              struct json_object * value;
              enum json_type       type;
              bool                 dummy_boolean;
              
              name  = json_object_iter_peek_name(&it);
              value = json_object_iter_peek_value(&it);
              type = json_object_get_type(value);

              struct
              {
                const char *   name;
                enum json_type type;
                bool (*callback)(struct json_object * value, void * value_ptr);
                void *         value_ptr;
              } stuff[] =
                  {
                    { "Fullscreen",                 json_type_boolean, cb_bool,                 &globals.fullscreen                   },
                    { "OpenGL",                     json_type_boolean, cb_bool,                 &globals.opengl                       },
                    { "OpenGL_POT",                 json_type_boolean, cb_opengl_pot,           NULL                                  },               
                    { "OpenGL_compressed_textures", json_type_boolean, cb_bool,                 &globals.opengl_compressed_textures   },
                    { "SFX",                        json_type_boolean, cb_bool,                 &globals.use_sfx                      },
                    { "Music",                      json_type_boolean, cb_bool,                 &globals.use_music                    },
                    { "SFX_max_channels",           json_type_int,     cb_int,                  &globals.max_channels                 },
                    { "Sound_volume",               json_type_int,     cb_sound_volume,         NULL                                  },
                    { "Joysticks",                  json_type_boolean, cb_bool,                 &globals.use_joysticks                },
                    { "CaveSelection",              json_type_string,  cb_cave_selection,       NULL                                  },
                    { "CaveSelectionLevel",         json_type_int,     cb_cave_selection_level, NULL                                  },
                    { "ShowFPS",                    json_type_boolean, cb_bool,                 &globals.fps_counter_active           },
                    { "GameMode",                   json_type_string,  cb_game_mode,            NULL                                  },
                    { "ActiveQuestline",            json_type_int,     cb_int,                  &active_questline                     },
                    { "TitleMidarea",               json_type_string,  cb_title_midarea,        NULL                                  },
                    { "IronGirlMode",               json_type_boolean, cb_bool,                 &globals.iron_girl_mode               },
                    { "Locale",                     json_type_string,  cb_locale,               NULL                                  },
                    { "MapTilting",                 json_type_boolean, cb_bool,                 &globals.map_tilting                  },
                    { "SmoothClassicMode",          json_type_boolean, cb_bool,                 &globals.smooth_classic_mode          },
                    { "Bindings",                   json_type_array,   cb_bindings,             NULL                                  },
                    { "Themes",                     json_type_array,   cb_themes,               NULL                                  },
                    { "WriteSettings",              json_type_boolean, cb_bool,                 &globals.write_settings               },
                    { "TestsCompleted",             json_type_boolean, cb_bool,                 &dummy_boolean                        }, // Ignored.
                    { NULL,                         json_type_int,     NULL,                    NULL                                  }
                  };
              
              int ind;

              ind = -1;
              for(int i = 0; ind == -1 && stuff[i].name != NULL; i++)
                if(!strcmp(stuff[i].name, name))
                  ind = i;

              if(ind >= 0)
                {
                  if(stuff[ind].type == type)
                    {
                      ok = stuff[ind].callback(value, stuff[ind].value_ptr);

                      /* Don't bind the default keybindings if we were able to read them from the settings.json. */
                      if(ok == true && !strcmp(name, "Bindings"))
                        bind_defaults = false;
                    }
                  else
                    {
                      fprintf(stderr, "%s: Incorrect value type %s for '%s', expected %s.\n", filename, json_type_to_name(type), name, json_type_to_name(stuff[ind].type));
                      ok = false;
                    }
                }
              else
                {
                  fprintf(stderr, "%s: Failed to parse: unknown variable '%s'.\n", filename, name);
                  ok = false;
                }

              json_object_iter_next(&it);
            }

          if(ok == true)
            globals.active_questline = active_questline;
          else
            rv = false;
        }
      else
        {
          fprintf(stderr, "%s: Failed to parse: %d: %s\n", filename, (int) e, json_tokener_error_desc(e));
        }
      free(json);
    }
  else
    {
      if(nonexistent_ok == false)
        fprintf(stderr, "%s: Failed to read '%s'.\n", __FUNCTION__, filename);
    }


  if(bind_defaults)
    ui_bindings_default(true);

  if(globals.iron_girl_mode)
    theme_set(THEME_TRAIT, "iron-girl");
  
  return rv;
}
Esempio n. 12
0
void *la_codec_object_iter_next(la_codec_value_t *object, void *iter)
{
    return json_object_iter_next((json_t *) object, iter);
}
Esempio n. 13
0
static int uwsgi_mongrel2_json_parse(json_t * root, struct wsgi_request *wsgi_req) {

	char *json_val;
	char *query_string = NULL;
	size_t query_string_len = 0;
	size_t script_name_len = 0;
	void *json_iter;
	char *json_key;
	json_t *json_value;

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "METHOD"))) {
		if (!strcmp(json_val, "JSON")) {
			return -1;
		}
		wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_METHOD", 14, json_val, strlen(json_val));
	}

	// pretty easy, we get the file and we map it to wsgi_req->post_file, uWSGI read api will automatically use this
	if ((json_val = uwsgi_mongrel2_json_get_string(root, "x-mongrel2-upload-done"))) {
		wsgi_req->post_file = fopen(json_val, "r");
		if (!wsgi_req->post_file) {
			uwsgi_error_open(json_val);
			return -1;
		}
	}
	else if (uwsgi_mongrel2_json_get_string(root, "x-mongrel2-upload-start")) {
		return -1;
	}


	wsgi_req->uh->pktsize += uwsgi_mongrel2_json_add(wsgi_req, root, "VERSION", "SERVER_PROTOCOL", 15, NULL, NULL);
	wsgi_req->uh->pktsize += uwsgi_mongrel2_json_add(wsgi_req, root, "QUERY", "QUERY_STRING", 12, &query_string, &query_string_len);
	if (query_string == NULL) {
		// always set QUERY_STRING
		wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "QUERY_STRING", 12, "", 0);
	}

	// set SCRIPT_NAME to an empty value
	wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "SCRIPT_NAME", 11, "", 0);

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "PATH"))) {
		wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "PATH_INFO", 9, json_val + script_name_len, strlen(json_val + script_name_len));
		if (query_string_len) {
			char *request_uri = uwsgi_concat3n(json_val, strlen(json_val), "?", 1, query_string, query_string_len);
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_URI", 11, request_uri, strlen(json_val) + 1 + query_string_len);
			free(request_uri);
		}
		else {
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "REQUEST_URI", 11, json_val, strlen(json_val));
		}
	}

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "URL_SCHEME"))) {
                wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "UWSGI_SCHEME", 12, json_val, strlen(json_val));
        }

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "host"))) {
		char *colon = strchr(json_val, ':');
		if (colon) {
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_PORT", 11, colon + 1, strlen(colon + 1));
		}
		else {
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_PORT", 11, "80", 2);
		}
	}

	if ((json_val = uwsgi_mongrel2_json_get_string(root, "x-forwarded-for"))) {
		char *colon = strchr(json_val, ',');
		if (colon) {
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "REMOTE_ADDR", 11, colon + 1, (colon + 1) - json_val);
		}
		else {
			wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "REMOTE_ADDR", 11, json_val, strlen(json_val));
		}
	}


	if ((json_val = uwsgi_mongrel2_json_get_string(root, "content-length"))) {
		wsgi_req->post_cl = atoi(json_val);
	}

	wsgi_req->uh->pktsize += proto_base_add_uwsgi_var(wsgi_req, "SERVER_NAME", 11, uwsgi.hostname, uwsgi.hostname_len);

	json_iter = json_object_iter(root);

	while (json_iter) {
		json_key = (char *) json_object_iter_key(json_iter);
		// is it a header ?
		if (json_key[0] >= 97) {
			json_value = json_object_iter_value(json_iter);
			if (json_is_string(json_value)) {
				json_val = (char *) json_string_value(json_value);
				wsgi_req->uh->pktsize += proto_base_add_uwsgi_header(wsgi_req, json_key, strlen(json_key), json_val, strlen(json_val));
			}
		}
		json_iter = json_object_iter_next(root, json_iter);
	}

	return 0;

}
Esempio n. 14
0
struct conf *
conf_read(const char *filename) {

	json_t *j;
	json_error_t error;
	struct conf *conf;
	void *kv;

	/* defaults */
	conf = calloc(1, sizeof(struct conf));
	conf->redis_host = strdup("127.0.0.1");
	conf->redis_port = 6379;
	conf->http_host = strdup("0.0.0.0");
	conf->http_port = 7379;
	conf->http_max_request_size = 128*1024*1024;
	conf->http_threads = 4;
	conf->user = getuid();
	conf->group = getgid();
	conf->logfile = "webdis.log";
	conf->verbosity = WEBDIS_NOTICE;
	conf->daemonize = 0;
	conf->pidfile = "webdis.pid";
	conf->database = 0;
	conf->pool_size_per_thread = 2;

	j = json_load_file(filename, 0, &error);
	if(!j) {
		fprintf(stderr, "Error: %s (line %d)\n", error.text, error.line);
		return conf;
	}

	for(kv = json_object_iter(j); kv; kv = json_object_iter_next(j, kv)) {
		json_t *jtmp = json_object_iter_value(kv);

		if(strcmp(json_object_iter_key(kv), "redis_host") == 0 && json_typeof(jtmp) == JSON_STRING) {
			free(conf->redis_host);
			conf->redis_host = strdup(json_string_value(jtmp));
		} else if(strcmp(json_object_iter_key(kv), "redis_port") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->redis_port = (int)json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "redis_auth") == 0 && json_typeof(jtmp) == JSON_STRING) {
			conf->redis_auth = strdup(json_string_value(jtmp));
		} else if(strcmp(json_object_iter_key(kv), "http_host") == 0 && json_typeof(jtmp) == JSON_STRING) {
			free(conf->http_host);
			conf->http_host = strdup(json_string_value(jtmp));
		} else if(strcmp(json_object_iter_key(kv), "http_port") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->http_port = (int)json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "http_max_request_size") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->http_max_request_size = (size_t)json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "threads") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->http_threads = (int)json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "acl") == 0 && json_typeof(jtmp) == JSON_ARRAY) {
			conf->perms = conf_parse_acls(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "user") == 0 && json_typeof(jtmp) == JSON_STRING) {
			struct passwd *u;
			if((u = getpwnam(json_string_value(jtmp)))) {
				conf->user = u->pw_uid;
			}
		} else if(strcmp(json_object_iter_key(kv), "group") == 0 && json_typeof(jtmp) == JSON_STRING) {
			struct group *g;
			if((g = getgrnam(json_string_value(jtmp)))) {
				conf->group = g->gr_gid;
			}
		} else if(strcmp(json_object_iter_key(kv),"logfile") == 0 && json_typeof(jtmp) == JSON_STRING){
			conf->logfile = strdup(json_string_value(jtmp));
		} else if(strcmp(json_object_iter_key(kv),"verbosity") == 0 && json_typeof(jtmp) == JSON_INTEGER){
			int tmp = json_integer_value(jtmp);
			if(tmp < 0) conf->verbosity = WEBDIS_ERROR;
			else if(tmp > (int)WEBDIS_DEBUG) conf->verbosity = WEBDIS_DEBUG;
			else conf->verbosity = (log_level)tmp;
		} else if(strcmp(json_object_iter_key(kv), "daemonize") == 0 && json_typeof(jtmp) == JSON_TRUE) {
			conf->daemonize = 1;
		} else if(strcmp(json_object_iter_key(kv),"pidfile") == 0 && json_typeof(jtmp) == JSON_STRING){
			conf->pidfile = strdup(json_string_value(jtmp));
		} else if(strcmp(json_object_iter_key(kv), "websockets") == 0 && json_typeof(jtmp) == JSON_TRUE) {
			conf->websockets = 1;
		} else if(strcmp(json_object_iter_key(kv), "database") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->database = json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "pool_size") == 0 && json_typeof(jtmp) == JSON_INTEGER) {
			conf->pool_size_per_thread = json_integer_value(jtmp);
		} else if(strcmp(json_object_iter_key(kv), "default_root") == 0 && json_typeof(jtmp) == JSON_STRING) {
			conf->default_root = strdup(json_string_value(jtmp));
		}
	}

	json_decref(j);

	return conf;
}
Esempio n. 15
0
static qeocore_type_t *build_enum(const qeo_factory_t *factory, json_t *typedesc){

    qeocore_type_t    *qeoType  = NULL;
    qeocore_enum_constants_t vals = DDS_SEQ_INITIALIZER(qeocore_enum_constant_t);
    const char *enumstr = NULL;
    DDS_ReturnCode_t ddsret;

    assert(typedesc != NULL);
    assert(factory != NULL);

    do {
        json_t *type_enum = json_object_get(typedesc, KEY_ENUM);
        if ((NULL == type_enum) || !json_is_string(type_enum)) {
            qeo_log_e("Invalid type_enum (%p)", type_enum);
            return qeoType;
        }

        json_t *values = json_object_get(typedesc, KEY_VALUES);
        if ((NULL == values) || !json_is_object(values)) {
            qeo_log_e("Invalid values (%p)", values);
            return qeoType;
        }

        enumstr = json_string_value(type_enum);
        //Replace all "::" with ".", because there's a mismatch in topic definitions found in the TSM structs, with "." and the QDM topic definitions with "::"
        find_and_replace((char *) enumstr, "::", ".");

        if ((ddsret = dds_seq_require(&vals, json_object_size(values))) != DDS_RETCODE_OK){
            qeo_log_e("dds_seq_require failed (%d)", ddsret);
            return NULL;
        }

        void *iter = json_object_iter(values);
        while (iter) {
            json_int_t labelint;
            const char *name = json_object_iter_key(iter);
            json_t *label = json_object_iter_value(iter);
            if (!json_is_integer(label)){
                qeo_log_e("not a integer");
            }
            labelint = json_integer_value(label);
            if (labelint >= json_object_size(values)){
                qeo_log_e("Currently we only support 0,1,2..[n-1] as labels");     
                break;
            }

            DDS_SEQ_ITEM(vals, labelint).name = (char *)name;

            iter = json_object_iter_next(values, iter);
        }
    

        qeoType = qeocore_type_enum_new(enumstr, &vals);
        if (qeoType == NULL){
            qeo_log_e("Cannot register enum");
        }
        dds_seq_cleanup(&vals);

    } while(0);

    return qeoType;
}
Esempio n. 16
0
static void test_misc()
{
    json_t *object, *string, *other_string, *value;
    void *iter;

    object = json_object();
    string = json_string("test");
    other_string = json_string("other");

    if(!object)
        fail("unable to create object");
    if(!string || !other_string)
        fail("unable to create string");

    if(json_object_get(object, "a"))
        fail("value for nonexisting key");

    if(json_object_set(object, "a", string))
        fail("unable to set value");

    if(!json_object_set(object, NULL, string))
        fail("able to set NULL key");

    if(!json_object_set(object, "a", NULL))
        fail("able to set NULL value");

    iter = json_object_iter(object);
    if(!iter)
        fail("unable to get iterator");

    if(strcmp(json_object_iter_key(iter), "a"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != string)
        fail("iterating failed: wrong value");
    if(json_object_iter_next(object, iter) != NULL)
        fail("able to iterate over the end");

    /* invalid UTF-8 in key */
    if(!json_object_set(object, "a\xefz", string))
        fail("able to set invalid unicode key");

    value = json_object_get(object, "a");
    if(!value)
        fail("no value for existing key");
    if(value != string)
        fail("got different value than what was added");

    /* "a", "lp" and "px" collide in a five-bucket hashtable */
    if(json_object_set(object, "b", string) ||
       json_object_set(object, "lp", string) ||
       json_object_set(object, "px", string))
        fail("unable to set value");

    value = json_object_get(object, "a");
    if(!value)
        fail("no value for existing key");
    if(value != string)
        fail("got different value than what was added");

    if(json_object_set(object, "a", other_string))
        fail("unable to replace an existing key");

    value = json_object_get(object, "a");
    if(!value)
        fail("no value for existing key");
    if(value != other_string)
        fail("got different value than what was set");

    if(!json_object_del(object, "nonexisting"))
        fail("able to delete a nonexisting key");

    if(json_object_del(object, "px"))
        fail("unable to delete an existing key");

    if(json_object_del(object, "a"))
        fail("unable to delete an existing key");

    if(json_object_del(object, "lp"))
        fail("unable to delete an existing key");


    /* add many keys to initiate rehashing */

    if(json_object_set(object, "a", string))
        fail("unable to set value");

    if(json_object_set(object, "lp", string))
        fail("unable to set value");

    if(json_object_set(object, "px", string))
        fail("unable to set value");

    if(json_object_set(object, "c", string))
        fail("unable to set value");

    if(json_object_set(object, "d", string))
        fail("unable to set value");

    if(json_object_set(object, "e", string))
        fail("unable to set value");


    if(json_object_set_new(object, "foo", json_integer(123)))
        fail("unable to set new value");

    value = json_object_get(object, "foo");
    if(!json_is_integer(value) || json_integer_value(value) != 123)
        fail("json_object_set_new works incorrectly");

    if(!json_object_set_new(object, NULL, json_integer(432)))
        fail("able to set_new NULL key");

    if(!json_object_set_new(object, "foo", NULL))
        fail("able to set_new NULL value");

    json_decref(string);
    json_decref(other_string);
    json_decref(object);
}
Esempio n. 17
0
static void
ide_langserv_rename_provider_rename_cb (GObject      *object,
                                        GAsyncResult *result,
                                        gpointer      user_data)
{
  IdeLangservClient *client = (IdeLangservClient *)object;
  IdeLangservRenameProvider *self;
  g_autoptr(JsonNode) return_value = NULL;
  g_autoptr(GError) error = NULL;
  g_autoptr(GTask) task = user_data;
  g_autoptr(GPtrArray) ret = NULL;
  JsonObject *changes_by_uri = NULL;
  JsonObjectIter iter;
  const gchar *uri;
  IdeContext *context;
  JsonNode *changes;

  IDE_ENTRY;

  g_assert (IDE_IS_LANGSERV_CLIENT (client));
  g_assert (G_IS_ASYNC_RESULT (result));
  g_assert (G_IS_TASK (task));
  self = g_task_get_source_object (task);
  g_assert (IDE_IS_LANGSERV_RENAME_PROVIDER (self));

  if (!ide_langserv_client_call_finish (client, result, &return_value, &error))
    {
      g_task_return_error (task, g_steal_pointer (&error));
      IDE_EXIT;
    }

  if (!JCON_EXTRACT (return_value, "changes", JCONE_OBJECT (changes_by_uri)))
    IDE_EXIT;

  context = ide_object_get_context (IDE_OBJECT (self));

  ret = g_ptr_array_new_with_free_func (g_object_unref);

  json_object_iter_init (&iter, changes_by_uri);

  while (json_object_iter_next (&iter, &uri, &changes))
    {
      g_autoptr(GFile) gfile = g_file_new_for_uri (uri);
      g_autoptr(IdeFile) ifile = ide_file_new (context, gfile);
      JsonArray *array;
      guint length;

      if (!JSON_NODE_HOLDS_ARRAY (changes))
        continue;

      array = json_node_get_array (changes);
      length = json_array_get_length (array);

      for (guint i = 0; i < length; i++)
        {
          JsonNode *change = json_array_get_element (array, i);
          g_autoptr(IdeSourceLocation) begin_location = NULL;
          g_autoptr(IdeSourceLocation) end_location = NULL;
          g_autoptr(IdeSourceRange) range = NULL;
          g_autoptr(IdeProjectEdit) edit = NULL;
          const gchar *new_text = NULL;
          gboolean success;
          struct {
            gint line;
            gint column;
          } begin, end;

          success = JCON_EXTRACT (change,
            "range", "{",
              "start", "{",
                "line", JCONE_INT (begin.line),
                "character", JCONE_INT (begin.column),
              "}",
              "end", "{",
                "line", JCONE_INT (end.line),
                "character", JCONE_INT (end.column),
              "}",
            "}",
            "newText", JCONE_STRING (new_text)
          );

          if (!success)
            continue;

          begin_location = ide_source_location_new (ifile, begin.line, begin.column, 0);
          end_location = ide_source_location_new (ifile, end.line, end.column, 0);
          range = ide_source_range_new (begin_location, end_location);

          edit = g_object_new (IDE_TYPE_PROJECT_EDIT,
                               "range", range,
                               "replacement", new_text,
                               NULL);

          g_ptr_array_add (ret, g_steal_pointer (&edit));
        }
    }

  g_task_return_pointer (task, g_steal_pointer (&ret), (GDestroyNotify)g_ptr_array_unref);

  IDE_EXIT;
}
Esempio n. 18
0
/* 得到策略信息 */
struct policymsg get_policy_json(char *jsonfile)
{
	struct policymsg policyinfo;
    //const char *iter_keys[keycount];
	int i, size;
    void *iter;
	json_t *object;
    json_t *iter_values;
	json_error_t error;

	object = json_object();
	/* 读取策略 */
	object = json_load_file (jsonfile, 0, &error);
	policyinfo.size = json_object_size (object);
	//size = json_object_size (object);
	//printf("size=%d\n", size);
#if 0
	/* 取出object中的值 */
	//struct policy iter_get_value(json_t *object)
	char *result;
    result = json_dumps(object, JSON_PRESERVE_ORDER);
	printf("result=%s\n", result);
	/* 判断读取的jansson类型 */
	printf("判断是不是object类型\n");
	my_json_type(object);
	printf("size = %d\n", strlen(result));
#endif

	printf("得到策略值\n");
    iter = json_object_iter(object);
	i = 0;
	while(1)
	{
		strcpy (policyinfo.keyword[i], json_object_iter_key(iter));
		iter_values = json_object_iter_value(iter);
		strcpy (policyinfo.keycount[i],json_string_value(iter_values));
#if 0
		iter_keys[i] = json_object_iter_key(iter);
		iter_values[i] = json_object_iter_value(iter);
		printf("values[%d]=%s\n", i,json_string_value(iter_values[i]));
#endif

		if((iter = json_object_iter_next(object, iter)) == NULL)
		{
			 //printf("iterate end\n");
			 break;
		}
		i++;
	}

#if 0
	iter = json_object_iter_at(object, "b");
    if(iter)
	{
		iter_keys[i] = json_object_iter_key(iter);
		iter_values[i] = json_object_iter_value(iter);
		printf("values[%d]=%s\n", i,json_string_value(iter_values[i]));
        //printf("json_object_iter_at() printfs for an existing key\n");
	}
#endif

    json_decref(object);
	return policyinfo;
}
Esempio n. 19
0
/* 获取每个元素的值, 返回元素的结构体 */
struct policymsg iter_get_value(json_t *object)
{
	struct policymsg p;
    int i;
    json_t *iter_values[3];
    const char *iter_keys[3];
    void *iter;

	printf("判断是不是object类型\n");
	my_json_type(object);
	//printf("........\n");
#if 0
    if(json_object_iter(NULL))
	{
        printf("iterate NULL\n");
	}

    if(json_object_iter_next(NULL, NULL))
	{
        printf("iterator a NULL object\n");
	}
#endif 

    iter = json_object_iter(object);
	i = 0;
	while(1)
	{
		iter_keys[i] = json_object_iter_key(iter);
		iter_values[i] = json_object_iter_value(iter);
		//printf("values[%d]=%s\n", i,json_string_value(iter_values[i]));

		if((iter = json_object_iter_next(object, iter)) == NULL)
		{
			 //printf("iterate end\n");
			 break;
		}
		i++;
	}

	i=4;
	iter = json_object_iter_at(object, "b");
    if(iter)
	{
		iter_keys[i] = json_object_iter_key(iter);
		iter_values[i] = json_object_iter_value(iter);
		printf("values[%d]=%s\n", i,json_string_value(iter_values[i]));
        //printf("json_object_iter_at() printfs for an existing key\n");
	}

#if 0
    if(json_object_iter_set(object, iter, baz))
        printf("unable to set value at iterator");

    if(strcmp(json_object_iter_key(iter), "b"))
        printf("json_object_iter_key() printfs after json_object_iter_set()");
    if(json_object_iter_value(iter) != baz)
        printf("json_object_iter_value() printfs after json_object_iter_set()");
    if(json_object_get(object, "b") != baz)
        printf("json_object_get() printfs after json_object_iter_set()");
#endif

    json_decref(object);
	return p;
}
CCObject* NDKHelper::GetCCObjectFromJson(json_t *obj)
{
    if (obj == NULL)
        return NULL;
    
    if (json_is_object(obj))
    {
        CCDictionary *dictionary = new CCDictionary();
        //CCDictionary::create();
        
        const char *key;
        json_t *value;
        
        void *iter = json_object_iter(obj);
        while(iter)
        {
            key = json_object_iter_key(iter);
            value = json_object_iter_value(iter);
            
            dictionary->setObject(NDKHelper::GetCCObjectFromJson(value)->autorelease(), string(key));
            
            iter = json_object_iter_next(obj, iter);
        }
        
        return dictionary;
    }
    else if (json_is_array(obj))
    {
        size_t sizeArray = json_array_size(obj);
        CCArray *array = new CCArray();
        //CCArray::createWithCapacity(sizeArray);
        
        for (unsigned int i = 0; i < sizeArray; i++)
        {
            array->addObject(NDKHelper::GetCCObjectFromJson(json_array_get(obj, i))->autorelease());
        }
        
        return array;
    }
    else if (json_is_boolean(obj))
    {
        stringstream str;
        if (json_is_true(obj))
            str << true;
        else if (json_is_false(obj))
            str << false;
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_integer(obj))
    {
        stringstream str;
        str << json_integer_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_real(obj))
    {
        stringstream str;
        str << json_real_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
    else if (json_is_string(obj))
    {
        stringstream str;
        str << json_string_value(obj);
        
        CCString *ccString = new CCString(str.str());
        //CCString::create(str.str());
        return ccString;
    }
	else if (json_is_null(obj)) 
	{
		return new CCString("null");
	}
    
    return NULL;
}
Esempio n. 21
0
struct ast_json_iter *ast_json_object_iter_next(struct ast_json *object, struct ast_json_iter *iter)
{
	return json_object_iter_next((json_t *)object, iter);
}
Esempio n. 22
0
File: json.c Progetto: apoh/uwsgi
void uwsgi_json_config(char *file, char *magic_table[]) {

	size_t len = 0;
	char *json_data;


	const char *key;

	json_t *root;
	json_error_t error;
	json_t *config;
	json_t *config_value, *config_array_item;

	void *config_iter;

	char *object_asked = "uwsgi";
	char *colon;
	int i;

	if (uwsgi_check_scheme(file)) {
		colon = uwsgi_get_last_char(file, '/');
		colon = uwsgi_get_last_char(colon, ':');
	}
	else {
		colon = uwsgi_get_last_char(file, ':');
	}

	if (colon) {
		colon[0] = 0;
		if (colon[1] != 0) {
			object_asked = colon + 1;
		}
	}

	uwsgi_log_initial("[uWSGI] getting JSON configuration from %s\n", file);

	json_data = uwsgi_open_and_read(file, &len, 1, magic_table);

#ifdef JANSSON_MAJOR_VERSION
	root = json_loads(json_data, 0, &error);
#else
	root = json_loads(json_data, &error);
#endif

	if (!root) {
		uwsgi_log("error parsing JSON data: line %d %s\n", error.line, error.text);
		exit(1);
	}

	config = json_object_get(root, object_asked);

	if (!json_is_object(config)) {
		uwsgi_log("you must define a object named %s in your JSON data\n", object_asked);
		exit(1);
	}

	config_iter = json_object_iter(config);

	while (config_iter) {
		key = json_object_iter_key(config_iter);
		config_value = json_object_iter_value(config_iter);

		if (json_is_string(config_value)) {
			add_exported_option((char *) key, (char *) json_string_value(config_value), 0);
		}
		else if (json_is_true(config_value)) {
			add_exported_option((char *) key, strdup("1"), 0);
		}
		else if (json_is_false(config_value) || json_is_null(config_value)) {
			add_exported_option((char *) key, strdup("0"), 0);
		}
		else if (json_is_integer(config_value)) {
			add_exported_option((char *) key, uwsgi_num2str(json_integer_value(config_value)), 0);
		}
		else if (json_is_array(config_value)) {
			for (i = 0; i < (int) json_array_size(config_value); i++) {
				config_array_item = json_array_get(config_value, i);
				if (json_is_string(config_array_item)) {
					add_exported_option((char *) key, (char *) json_string_value(config_array_item), 0);
				}
				else if (json_is_true(config_array_item)) {
					add_exported_option((char *) key, strdup("1"), 0);
				}
				else if (json_is_false(config_array_item) || json_is_null(config_array_item)) {
					add_exported_option((char *) key, strdup("0"), 0);
				}
				else if (json_is_integer(config_array_item)) {
					add_exported_option((char *) key, uwsgi_num2str(json_integer_value(config_array_item)), 0);
				}
			}
		}

		config_iter = json_object_iter_next(config, config_iter);
	}

	if (colon) colon[0] = ':';

}
Esempio n. 23
0
static qeocore_type_t *build_object(const qeo_factory_t *factory, json_t *typedesc)
{
    qeocore_type_t    *qeoType  = NULL;
    const char        *name     = NULL;
    json_t            *value    = NULL;
    qeo_retcode_t     ret       = QEO_EFAIL;
    bool              iret      = true;
    const char        *topic    = NULL;

    assert(typedesc != NULL);
    assert(factory != NULL);

    do {
        json_t *type_topic = json_object_get(typedesc, KEY_TOPIC);
        if ((NULL == type_topic) || !json_is_string(type_topic)) {
            qeo_log_e("Invalid type_topic (%p)", type_topic);
            return qeoType;
        }

        json_t *properties = json_object_get(typedesc, KEY_PROPERTIES);
        if ((NULL == properties) || !json_is_object(properties)) {
            qeo_log_e("Invalid properties (%p)", properties);
            return qeoType;
        }

        topic = json_string_value(type_topic);
        //Replace all "::" with ".", because there's a mismatch in topic definitions found in the TSM structs, with "." and the QDM topic definitions with "::"
        find_and_replace((char *) topic, "::", ".");

        qeoType = qeocore_type_struct_new(topic);

        if (qeoType == NULL) {
            qeo_log_e("qeocore_type_struct_new failed for topic:%s", topic);
            break;
        }
        qeo_log_d("Registered new struct with name %s", topic);

        void *iter = json_object_iter(properties);
        while (iter) {
            name = json_object_iter_key(iter);
            if (name == NULL) {
                qeo_log_e("name == NULL");
                iret = false;
                break;
            }

            value = json_object_iter_value(iter);
            if (value == NULL) {
                qeo_log_e("value == NULL");
                iret = false;
                break;
            }

            if (!json_is_object(value)) {
                qeo_log_e("no json object");
                iret = false;
                break;
            }

            if (QEO_OK != object_add_member(factory, qeoType, name, value)) {
                qeo_log_e("object add member failed");
                iret = false;
                break;
            }

            iter = json_object_iter_next(properties, iter);
        }

        if (true != iret) {
            break;
        }

        if (QEO_OK != qeocore_type_register(factory, qeoType, topic)) {
            qeo_log_e("failed to register type: %s", topic);
        }

        ret = QEO_OK;
    } while (0);

    if (ret != QEO_OK) {
        qeocore_type_free(qeoType);
        qeoType = NULL;
    }

    return qeoType;
}
Esempio n. 24
0
static void test_iterators()
{
    json_t *object, *foo, *bar, *baz;
    void *iter;

    if(json_object_iter(NULL))
        fail("able to iterate over NULL");

    if(json_object_iter_next(NULL, NULL))
        fail("able to increment an iterator on a NULL object");

    object = json_object();
    foo = json_string("foo");
    bar = json_string("bar");
    baz = json_string("baz");
    if(!object || !foo || !bar || !bar)
        fail("unable to create values");

    if(json_object_iter_next(object, NULL))
        fail("able to increment a NULL iterator");

    if(json_object_set(object, "a", foo) ||
            json_object_set(object, "b", bar) ||
            json_object_set(object, "c", baz))
        fail("unable to populate object");

    iter = json_object_iter(object);
    if(!iter)
        fail("unable to get iterator");
    if(strcmp(json_object_iter_key(iter), "a"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != foo)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "b"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != bar)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "c"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != baz)
        fail("iterating failed: wrong value");

    if(json_object_iter_next(object, iter) != NULL)
        fail("able to iterate over the end");

    if(json_object_iter_at(object, "foo"))
        fail("json_object_iter_at() succeeds for non-existent key");

    iter = json_object_iter_at(object, "b");
    if(!iter)
        fail("json_object_iter_at() fails for an existing key");

    if(strcmp(json_object_iter_key(iter), "b"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != bar)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "c"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != baz)
        fail("iterating failed: wrong value");

    if(json_object_iter_set(object, iter, bar))
        fail("unable to set value at iterator");

    if(strcmp(json_object_iter_key(iter), "c"))
        fail("json_object_iter_key() fails after json_object_iter_set()");
    if(json_object_iter_value(iter) != bar)
        fail("json_object_iter_value() fails after json_object_iter_set()");
    if(json_object_get(object, "c") != bar)
        fail("json_object_get() fails after json_object_iter_set()");

    json_decref(object);
    json_decref(foo);
    json_decref(bar);
    json_decref(baz);
}
Esempio n. 25
0
int schema_traverse(const avro_schema_t schema, json_t *json, json_t *dft,
                    avro_value_t *current_val, int quiet, int strjson, size_t max_str_sz) {

    json = json ? json : dft;
    if (!json) {
        fprintf(stderr, "ERROR: Avro schema does not match JSON\n");
        return 1;
    }

    switch (schema->type) {
    case AVRO_RECORD:
    {
        if (!json_is_object(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON object for Avro record, got something else\n");
            return 1;
        }

        int len = avro_schema_record_size(schema), i;
        for (i=0; i<len; i++) {

            const char *name = avro_schema_record_field_name(schema, i);
            avro_schema_t field_schema = avro_schema_record_field_get_by_index(schema, i);

            json_t *json_val = json_object_get(json, name);
            json_t *dft = avro_schema_record_field_default_get_by_index(schema, i);

            avro_value_t field;
            avro_value_get_by_index(current_val, i, &field, NULL);

            if (schema_traverse(field_schema, json_val, dft, &field, quiet, strjson, max_str_sz))
                return 1;
        }
    } break;

    case AVRO_LINK:
        /* TODO */
        fprintf(stderr, "ERROR: AVRO_LINK is not implemented\n");
        return 1;
        break;

    case AVRO_STRING:
        if (!json_is_string(json)) {
            if (json && strjson) {
                /* -j specified, just dump the remaining json as string */
                char * js = json_dumps(json, JSON_COMPACT|JSON_SORT_KEYS|JSON_ENCODE_ANY);
                if (max_str_sz && (strlen(js) > max_str_sz))
                    js[max_str_sz] = 0; /* truncate the string - this will result in invalid JSON! */
                avro_value_set_string(current_val, js);
                free(js);
                break;
            }
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro string, got something else\n");
            return 1;
        } else {
            const char *js = json_string_value(json);
            if (max_str_sz && (strlen(js) > max_str_sz)) {
                /* truncate the string */
                char *jst = malloc(strlen(js));
                strcpy(jst, js);
                jst[max_str_sz] = 0;
                avro_value_set_string(current_val, jst);
                free(jst);
            } else
                avro_value_set_string(current_val, js);
        }
        break;

    case AVRO_BYTES:
        if (!json_is_string(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro string, got something else\n");
            return 1;
        }
        /* NB: Jansson uses null-terminated strings, so embedded nulls are NOT
           supported, not even escaped ones */
        const char *s = json_string_value(json);
        avro_value_set_bytes(current_val, (void *)s, strlen(s));
        break;

    case AVRO_INT32:
        if (!json_is_integer(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON integer for Avro int, got something else\n");
            return 1;
        }
        avro_value_set_int(current_val, json_integer_value(json));
        break;

    case AVRO_INT64:
        if (!json_is_integer(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON integer for Avro long, got something else\n");
            return 1;
        }
        avro_value_set_long(current_val, json_integer_value(json));
        break;

    case AVRO_FLOAT:
        if (!json_is_number(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON number for Avro float, got something else\n");
            return 1;
        }
        avro_value_set_float(current_val, json_number_value(json));
        break;

    case AVRO_DOUBLE:
        if (!json_is_number(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON number for Avro double, got something else\n");
            return 1;
        }
        avro_value_set_double(current_val, json_number_value(json));
        break;

    case AVRO_BOOLEAN:
        if (!json_is_boolean(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON boolean for Avro boolean, got something else\n");
            return 1;
        }
        avro_value_set_boolean(current_val, json_is_true(json));
        break;

    case AVRO_NULL:
        if (!json_is_null(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON null for Avro null, got something else\n");
            return 1;
        }
        avro_value_set_null(current_val);
        break;

    case AVRO_ENUM:
        // TODO ???
        break;

    case AVRO_ARRAY:
        if (!json_is_array(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON array for Avro array, got something else\n");
            return 1;
        } else {
            int i, len = json_array_size(json);
            avro_schema_t items = avro_schema_array_items(schema);
            avro_value_t val;
            for (i=0; i<len; i++) {
                avro_value_append(current_val, &val, NULL);
                if (schema_traverse(items, json_array_get(json, i), NULL, &val, quiet, strjson, max_str_sz))
                    return 1;
            }
        }
        break;

    case AVRO_MAP:
        if (!json_is_object(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON object for Avro map, got something else\n");
            return 1;
        } else {
            avro_schema_t values = avro_schema_map_values(schema);
            void *iter = json_object_iter(json);
            avro_value_t val;
            while (iter) {
                avro_value_add(current_val, json_object_iter_key(iter), &val, 0, 0);
                if (schema_traverse(values, json_object_iter_value(iter), NULL, &val, quiet, strjson, max_str_sz))
                    return 1;
                iter = json_object_iter_next(json, iter);
            }
        }
        break;

    case AVRO_UNION:
    {
        int i;
        avro_value_t branch;
        for (i=0; i<avro_schema_union_size(schema); i++) {
            avro_value_set_branch(current_val, i, &branch);
            avro_schema_t type = avro_schema_union_branch(schema, i);
            if (!schema_traverse(type, json, NULL, &branch, 1, strjson, max_str_sz))
                break;
        }
        if (i==avro_schema_union_size(schema)) {
            fprintf(stderr, "ERROR: No type in the Avro union matched the JSON type we got\n");
            return 1;
        }
        break;
    }
    case AVRO_FIXED:
        if (!json_is_string(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro fixed, got something else\n");
            return 1;
        }
        /* NB: Jansson uses null-terminated strings, so embedded nulls are NOT
           supported, not even escaped ones */
        const char *f = json_string_value(json);
        if (avro_value_set_fixed(current_val, (void *)f, strlen(f))) {
            fprintf(stderr, "ERROR: Setting Avro fixed value FAILED\n");
            return 1;
        }
        break;

    default:
        fprintf(stderr, "ERROR: Unknown type: %d\n", schema->type);
        return 1;
    }
    return 0;
}
Esempio n. 26
0
pweibo_user weibo_user_create_json(json_t* pJson)
{
    if (!pJson) {
        PERR("could not parse json!\n");
        return NULL; 
    }

    void *iter = json_object_iter(pJson);
    pweibo_user pUser = weibo_user_init();

    while (iter) {
        const char* key = json_object_iter_key(iter);
        //DEBUG("%s\n", key);
        json_t *value = json_object_iter_value(iter);
        if(!value) {
            iter = json_object_iter_next(pJson, iter);
            continue;
        }
        //DEBUG("%d\n", value->type);

        if (0 == strcmp("id", key)) {
            pUser->m_szID = g_string_new("");
            g_string_printf(pUser->m_szID, "%"JSON_INTEGER_FORMAT, json_integer_value(value));
        } else if (0 == strcmp("screen_name", key)) {
            pUser->m_szScreenName = g_string_new(json_string_value(value));
        } else if (0 == strcmp("name", key)) {
            pUser->m_szName = g_string_new(json_string_value(value));
        } else if (0 == strcmp("province", key)) {
            pUser->m_nProvince = json_integer_value(value);
        } else if (0 == strcmp("city", key)) {
            pUser->m_nCity = json_integer_value(value);
        } else if (0 == strcmp("location", key)) {
            pUser->m_szLocation = g_string_new(json_string_value(value));
        } else if (0 == strcmp("description", key)) {
            pUser->m_szDescription = g_string_new(json_string_value(value));
        } else if (0 == strcmp("url", key)) {
            pUser->m_szUrl = g_string_new(json_string_value(value));
        } else if (0 == strcmp("profile_image_url", key)) {
            pUser->m_szProfileImageUrl = g_string_new(json_string_value(value));
        } else if (0 == strcmp("domain", key)) {
            pUser->m_szDomain = g_string_new(json_string_value(value));
        } else if (0 == strcmp("gender", key)) {
            pUser->m_szGender = g_string_new(json_string_value(value));
        } else if (0 == strcmp("followers_count", key)) {
            pUser->m_nFollowersCount = json_integer_value(value);
        } else if (0 == strcmp("friends_count", key)) {
            pUser->m_nFriendsCount = json_integer_value(value);
        } else if (0 == strcmp("statuses_count", key)) {
            pUser->m_nStatusesCount = json_integer_value(value);
        } else if (0 == strcmp("favourites_count", key)) {
            pUser->m_nFavouritesCount = json_integer_value(value);
        } else if (0 == strcmp("created_at", key)) {
            pUser->m_szCreatedAt = g_string_new(json_string_value(value));
        } else if (0 == strcmp("following", key)) {
            pUser->m_bFollowing = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("allow_all_act_msg", key)) {
            pUser->m_bAllowAllActMsg = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("geo_enabled", key)) {
            pUser->m_bGeoEnabled = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("verified", key)) {
            pUser->m_bVerified = json_is_true(value) ? TRUE : FALSE;
        } else if (0 == strcmp("status", key)) {
            PERR("%s-->%d\n", key, value->type);
            POS();
            pUser->m_pFeed = weibo_feed_create_json(value);
            PERR("%d\n", pUser->m_pFeed);
            PERR("%s\n", ((pweibo_feed)(pUser->m_pFeed))->m_szID->str);
        }

        iter = json_object_iter_next(pJson, iter);
    }
    json_decref(pJson);

    return pUser;
}
Esempio n. 27
0
mlt_service SingleResourceLoader::get_asis_producer(JsonWrap js)
throw (Exception)
{
    json_t* defines = js.h;

    defines_tmp=js;

    json_t* je = json_object_get(defines, "resource");
    json_t* uuid_je = json_object_get(defines, "uuid");
    json_t* svc_je = json_object_get(defines, "service");

    assert( je && json_is_string(je) && strlen(json_string_value(je)));
    assert( svc_je && json_is_string(svc_je) && strlen(json_string_value(svc_je)));
    assert( uuid_je && json_is_string(uuid_je) && strlen(json_string_value(uuid_je)));

    mlt_producer obj = MLT_PRODUCER(MltLoader::pop_mlt_registry(json_string_value(uuid_je)));
    if (obj == NULL) {
        mlt_profile profile = mlt_profile_clone(global_profile);
        obj = mlt_factory_producer(profile, json_string_value(svc_je), json_string_value(je));
#ifdef DEBUG
        std::cout << mlt_producer_properties(obj);
#endif
    }

    if ( !obj ) {
        throw_error_v(ErrorRuntimeLoadFailed, "video producer load failed:%s", json_string_value(je));
    }

    mlt_properties props = mlt_producer_properties(obj);

    je = json_object_get(defines, "props");
    if (je && json_is_object(je) && json_object_size(je)) {

        json_t* inj = json_object_get(je,"in"), *outj = json_object_get(je,"out");
        assert(inj && outj && json_is_integer(inj) && json_is_integer(outj));

        mlt_producer_set_in_and_out(obj,json_integer_value(inj), json_integer_value(outj));

        void* it = json_object_iter(je);
        while(it) {
            const char* k = json_object_iter_key(it);
            json_t* prop_je = json_object_iter_value(it);
            it = json_object_iter_next(je, it);

            if ( json_is_object(prop_je) || json_is_array(prop_je))
                continue;

            if ( !strcmp(k,"in") || !strcmp(k,"out"))
                continue;

            switch(prop_je->type) {
            case JSON_INTEGER:
                mlt_properties_set_int64(props, k, json_integer_value(prop_je));
                break;
            case JSON_REAL:
                mlt_properties_set_double(props, k, json_real_value(prop_je));
                break;
            case JSON_STRING:
                mlt_properties_set(props, k, json_string_value(prop_je));
                break;
            case JSON_TRUE:
                mlt_properties_set_int(props,k, 1);
                break;
            case JSON_FALSE:
                mlt_properties_set_int(props,k, 0);
                break;
            default:
                break;
            }
        }
    }

    MltSvcWrap wrap(mlt_producer_service(obj), 1);
    producer_tmp  = obj;

    parse_filters();


    wrap.obj = NULL;
    return mlt_producer_service(obj);
}
Esempio n. 28
0
/*
 * process an assertion using the hosted verifier.
 *
 * TODO: local verification
 */
VerifyResult processAssertion(request_rec *r, const char *verifier_url,
                              const char *assertion)
{
  VerifyResult res = apr_pcalloc(r->pool, sizeof(struct _VerifyResult));
  json_tokener *tok = json_tokener_new();
  json_object *jobj = NULL;
  enum json_tokener_error jerr;

  char *assertionResult =
    verifyAssertionRemote(r, verifier_url, (char *) assertion);

  if (assertionResult) {
    jobj =
      json_tokener_parse_ex(tok, assertionResult, strlen(assertionResult));
    jerr = json_tokener_get_error(tok);

    if (json_tokener_success != jerr) {

      res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                        "malformed payload",
                                        json_tokener_error_desc(jerr));
      json_tokener_free(tok);
      return res;
    }

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                  ERRTAG
                  "Assertion (parsed) recieved is : %s",
                  json_object_to_json_string(jobj));
  }
  else {
    // XXX: verifyAssertionRemote should return specific error message.
    res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                      "communication error",
                                      "can't contact verification server");
    return res;
  }

  struct json_object_iterator it = json_object_iter_begin(jobj);
  struct json_object_iterator itEnd = json_object_iter_end(jobj);
  const char *reason = NULL;
  const char *status = "unknown";
  int success = 0;

  while (!json_object_iter_equal(&it, &itEnd)) {
    const char *key = json_object_iter_peek_name(&it);
    json_object *val = json_object_iter_peek_value(&it);

    if (strncmp("email", key, 6) == 0) {
      res->verifiedEmail = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("issuer", key, 7) == 0) {
      res->identityIssuer = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("audience", key, 9) == 0) {
      res->audience = apr_pstrdup(r->pool, json_object_get_string(val));
    }
    else if (strncmp("expires", key, 8) == 0) {
      apr_time_ansi_put(&res->expires, json_object_get_int64(val) / 1000);
    }
    else if (strncmp("reason", key, 7) == 0) {
      reason = json_object_get_string(val);
    }
    else if (strncmp("status", key, 7) == 0) {
      status = json_object_get_string(val);
      if (strncmp("okay", status, 5) == 0) {
        success = 1;
      }
    }
    json_object_iter_next(&it);
  }

  json_tokener_free(tok);

  // XXX: This is bad, doesn't catch multiple missing bits
  if (!res->verifiedEmail) {
    res->errorResponse = apr_pstrdup(r->pool, "Missing e-mail in assertion");
  }
  if (!res->identityIssuer) {
    res->errorResponse = apr_pstrdup(r->pool, "Missing issuer in assertion");
  }
  if (res->audience
      && strncmp(res->audience, r->server->server_hostname,
                 strlen(r->server->server_hostname)) != 0) {
    res->errorResponse =
      apr_psprintf(r->pool, "Audience %s doesn't match %s", res->audience,
                   r->server->server_hostname);
  }

  apr_time_t now = apr_time_now();
  if (res->expires && res->expires <= now) {
    char exp_time[APR_RFC822_DATE_LEN];
    apr_rfc822_date(exp_time, res->expires);
    res->errorResponse =
      apr_psprintf(r->pool, "Assertion expired on %s", exp_time);
  }

  if (!success) {
    if (reason) {
      res->errorResponse = apr_pstrdup(r->pool, reason);
    }
    else {
      res->errorResponse =
        apr_psprintf(r->pool, "Assertion failed with status '%s'", status);
    }
  }

  return res;
}
Esempio n. 29
0
void SyslogInput_JSON( char *syslog_string, struct _SyslogInput *SyslogInput )
{

    struct json_object *json_obj = NULL;
    struct json_object *tmp = NULL;

    struct json_object_iterator it;
    struct json_object_iterator itEnd;

    const char *val_str = NULL;

    uint16_t json_str_count=1;
    uint16_t a;

    bool has_message = false;

    char json_str[JSON_MAX_NEST][JSON_MAX_SIZE] = { { 0 } };

    memset(SyslogInput, 0, sizeof(_SyslogInput));

    memcpy(SyslogInput->syslog_message, "UNDEFINED\0", sizeof(SyslogInput->syslog_message));
    memcpy(SyslogInput->syslog_program, "UNDEFINED\0", sizeof(SyslogInput->syslog_program));
    memcpy(SyslogInput->syslog_time, "UNDEFINED\0", sizeof(SyslogInput->syslog_time));
    memcpy(SyslogInput->syslog_date, "UNDEFINED\0", sizeof(SyslogInput->syslog_date));
    memcpy(SyslogInput->syslog_tag, "UNDEFINED\0", sizeof(SyslogInput->syslog_tag));
    memcpy(SyslogInput->syslog_level, "UNDEFINED\0", sizeof(SyslogInput->syslog_level));
    memcpy(SyslogInput->syslog_priority, "UNDEFINED\0", sizeof(SyslogInput->syslog_priority));
    memcpy(SyslogInput->syslog_facility, "UNDEFINED\0", sizeof(SyslogInput->syslog_facility));
    memcpy(SyslogInput->syslog_host, "UNDEFINED\0", sizeof(SyslogInput->syslog_host));

    /* If the json isn't nested,  we can do this the easy way */

    if ( Syslog_JSON_Map->is_nested == false )
        {

            json_obj = json_tokener_parse(syslog_string);

            if ( json_obj == NULL )
                {

                    if ( syslog_string != NULL )
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON. Get: %s", __FILE__, __LINE__, syslog_string);
                        }
                    else
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON. Got NULL data.", __FILE__, __LINE__);
                        }


                    json_object_put(json_obj);
                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                    return;
                }


            __atomic_add_fetch(&counters->json_input_count, 1, __ATOMIC_SEQ_CST);

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_host, &tmp))
                {
                    strlcpy(SyslogInput->syslog_host, json_object_get_string(tmp), sizeof(SyslogInput->syslog_host));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_facility, &tmp))
                {
                    strlcpy(SyslogInput->syslog_facility, json_object_get_string(tmp), sizeof(SyslogInput->syslog_facility));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_priority, &tmp))
                {
                    strlcpy(SyslogInput->syslog_priority, json_object_get_string(tmp), sizeof(SyslogInput->syslog_priority));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_level, &tmp))
                {
                    strlcpy(SyslogInput->syslog_level, json_object_get_string(tmp), sizeof(SyslogInput->syslog_level));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_tag, &tmp))
                {
                    strlcpy(SyslogInput->syslog_tag, json_object_get_string(tmp), sizeof(SyslogInput->syslog_tag));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_date, &tmp))
                {
                    strlcpy(SyslogInput->syslog_date, json_object_get_string(tmp), sizeof(SyslogInput->syslog_date));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_time, &tmp))
                {
                    strlcpy(SyslogInput->syslog_time, json_object_get_string(tmp), sizeof(SyslogInput->syslog_time));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_program, &tmp))
                {
                    strlcpy(SyslogInput->syslog_program, json_object_get_string(tmp), sizeof(SyslogInput->syslog_program));
                }

            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_message, &tmp))
                {
                    snprintf(SyslogInput->syslog_message, sizeof(SyslogInput->syslog_message)," %s", json_object_get_string(tmp));
                    SyslogInput->syslog_message[ (sizeof(SyslogInput->syslog_message) -1 ) ] = '\0';
                    has_message = true;
                }

        }
    else
        {

            /* The raw syslog is the first "nested" level".  Copy that */

            strlcpy(json_str[0], syslog_string, sizeof(json_str[0]));
            json_obj = json_tokener_parse(syslog_string);

            if ( json_obj == NULL )
                {

                    if ( debug->debugmalformed )
                        {
                            Sagan_Log(WARN, "[%s, line %d] Libfastjson failed to decode JSON input. The log line was: \"%s\"", __FILE__, __LINE__, syslog_string);
                        }

                    json_object_put(json_obj);
                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                    return;
                }

            it = json_object_iter_begin(json_obj);
            itEnd = json_object_iter_end(json_obj);

            /* Search through all key/values looking for embedded JSON */

            while (!json_object_iter_equal(&it, &itEnd))
                {

                    struct json_object *const val = json_object_iter_peek_value(&it);
                    val_str = json_object_get_string(val);

                    if ( val_str[0] == '{' || val_str[1] == '{' )
                        {

                            /* If object looks like JSON, add it to array to be parsed later */

                            if ( json_str_count < JSON_MAX_NEST )
                                {
                                    strlcpy(json_str[json_str_count], val_str, sizeof(json_str[json_str_count]));
                                    json_str_count++;
                                }
                            else
                                {
                                    Sagan_Log(ERROR, "[%s, line %d] Detected JSON past max nest of %d! Skipping extra JSON.", __FILE__, __LINE__, JSON_MAX_NEST);
                                }
                        }

                    json_object_iter_next(&it);

                    /* Search through the nest to see if we can find out values */

                    for ( a = 0; a < json_str_count; a++ )
                        {

                            struct json_object *json_obj = NULL;
                            json_obj = json_tokener_parse(json_str[a]);

                            if ( json_obj == NULL )
                                {
                                    Sagan_Log(WARN, "[%s, line %d] Detected JSON nest but Libfastjson errors. The log line was: \"%s\"", __FILE__, __LINE__, json_str[a]);
                                    json_object_put(json_obj);
                                    __atomic_add_fetch(&counters->malformed_json_input_count, 1, __ATOMIC_SEQ_CST);
                                    return;
                                }

                            __atomic_add_fetch(&counters->json_input_count, 1, __ATOMIC_SEQ_CST);

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_message, &tmp))
                                {
                                    snprintf(SyslogInput->syslog_message, sizeof(SyslogInput->syslog_message)," %s", json_object_get_string(tmp));
                                    SyslogInput->syslog_message[ (sizeof(SyslogInput->syslog_message) -1 ) ] = '\0';
                                    has_message = true;
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_host, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_host, json_object_get_string(tmp), sizeof(SyslogInput->syslog_host));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_facility, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_facility, json_object_get_string(tmp), sizeof(SyslogInput->syslog_facility));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_priority, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_priority, json_object_get_string(tmp), sizeof(SyslogInput->syslog_priority));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_level, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_level, json_object_get_string(tmp), sizeof(SyslogInput->syslog_level));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_tag, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_tag, json_object_get_string(tmp), sizeof(SyslogInput->syslog_tag));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_date, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_date, json_object_get_string(tmp), sizeof(SyslogInput->syslog_date));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_time, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_time, json_object_get_string(tmp), sizeof(SyslogInput->syslog_time));
                                }

                            if ( json_object_object_get_ex(json_obj, Syslog_JSON_Map->syslog_map_program, &tmp))
                                {
                                    strlcpy(SyslogInput->syslog_program, json_object_get_string(tmp), sizeof(SyslogInput->syslog_program));
                                }

                        }

                }
        }


    if ( has_message == false )
        {
            Sagan_Log(WARN, "[%s, line %d] Received JSON which has no decoded 'message' value. The log line was: \"%s\"", __FILE__, __LINE__, syslog_string);
        }

    json_object_put(json_obj);
}
Esempio n. 30
0
int
jsonUnpackDict( json_t *dictObj, dictionary_t *outDict ) {
    void *iter;
    void *tmpOut;
    dictionary_t *tmpDict;
    genArray_t *tmpGenArray;
    int *tmpInt;
    float *tmpFloat;
    const char *key;
    json_t *value;
    int status = 0;

    if ( dictObj == NULL || outDict == NULL ) {
        rodsLog( LOG_ERROR,
                 "jsonUnpackDict: NULL input" );
        return USER__NULL_INPUT_ERR;
    }
    bzero( outDict, sizeof( dictionary_t ) );
    iter = json_object_iter( dictObj );
    while ( iter ) {
        json_type myType;

        key = json_object_iter_key( iter );
        value = json_object_iter_value( iter );
        myType = json_typeof( value );
        switch ( myType ) {
        case JSON_OBJECT:
            tmpDict = ( dictionary_t * ) calloc( 1, sizeof( dictionary_t ) );
            status = jsonUnpackDict( value, tmpDict );
            if ( status < 0 ) {
                free( tmpDict );
            }
            else {
                status = dictSetAttr( outDict, ( char * ) key, Dictionary_MS_T,
                                      tmpDict );
            }
            break;
        case JSON_ARRAY:
            tmpGenArray = ( genArray_t * ) calloc( 1, sizeof( genArray_t ) );
            status = jsonUnpackArray( value, tmpGenArray );
            if ( status < 0 ) {
                free( tmpGenArray );
            }
            else {
                status = dictSetAttr( outDict, ( char * ) key, GenArray_MS_T,
                                      tmpGenArray );
            }
            break;
        case JSON_STRING:
            tmpOut = strdup( json_string_value( value ) );
            status = dictSetAttr( outDict, ( char * ) key, STR_MS_T, tmpOut );
            break;
        case JSON_INTEGER:
            tmpInt = ( int * ) calloc( 1, sizeof( int ) );
            *tmpInt = ( int ) json_integer_value( value );
            status = dictSetAttr( outDict, ( char * ) key, INT_MS_T,
                                  ( void * ) tmpInt );
            break;
        case JSON_REAL:
            tmpFloat = ( float * ) calloc( 1, sizeof( float ) );
            *tmpFloat = ( float ) json_real_value( value );
            status = dictSetAttr( outDict, ( char * ) key, FLOAT_MS_T,
                                  ( void * ) tmpFloat );
            break;
        case JSON_TRUE:
            tmpInt = ( int * ) calloc( 1, sizeof( int ) );
            *tmpInt = 1;
            status = dictSetAttr( outDict, ( char * ) key, BOOL_MS_T,
                                  ( void * ) tmpInt );
            break;
        case JSON_FALSE:
            tmpInt = ( int * ) calloc( 1, sizeof( int ) );
            *tmpInt = 0;
            status = dictSetAttr( outDict, ( char * ) key, BOOL_MS_T,
                                  ( void * ) tmpInt );
            break;
        default:
            rodsLog( LOG_ERROR,
                     "ooiGenServReqFunc: myType %d not supported", myType );
            status = OOI_JSON_TYPE_ERR;
        }
        iter = json_object_iter_next( dictObj, iter );
    }
    if ( status < 0 ) {
        clearDictionary( outDict );
    }

    return status;
}