Beispiel #1
0
json_value* GetApplicationSettings() {
    static json_value* ret = new json_value();
    static bool settings_fetched = false;
    if (settings_fetched)
        return ret;
    settings_fetched = true;
    LOG_DEBUG << "Fetching settings from settings.json file";

    std::string settingsFile = GetExecutableDirectory() + "\\settings.json";
    std::string contents = GetFileContents(settingsFile);
    if (contents.empty()) {
        LOG_WARNING << "Error opening settings.json file";
        return ret;
    }

    json_settings settings;
    memset(&settings, 0, sizeof(json_settings));
    char error[256];
    json_value* json_parsed = json_parse_ex(&settings, contents.c_str(),
                                            &error[0]);
    if (json_parsed == 0) {
        LOG_WARNING << "Error while parsing settings.json file: " << error;
        return ret;
    }
    ret = json_parsed;
    return ret;
}
Beispiel #2
0
int
main()
{
  char* cfgtext = slurp("silo.cfg");
  char* err = calloc(2048, sizeof(char));
  json_settings settings = { 0 };
  json_value* js = json_parse_ex(&settings, cfgtext, strlen(cfgtext), err);
  free(cfgtext);
  if(js == NULL) {
    ERR(silo, "Parse error: %s", err);
    free(err);
    return 1;
  }
  TRACE(silo, "type: %d", js->type);
  TRACE(silo, "none (%d), obj (%d), array (%d), integer (%d), double (%d), "
        "string (%d), bool (%d), null (%d)", json_none, json_object,
        json_array, json_integer, json_double, json_string, json_boolean,
        json_null);

  size_t ndims;
  size_t* dimens = js_dimensions(js, &ndims);

  printf("dtype: %d\n", (int)js_datatype(js));
  double** mycoords = js_coord_arrays(js, dimens, ndims);
  assert(mycoords);

  for(size_t i=0; i < ndims; ++i) { free(mycoords[i]); }
  free(mycoords);
  free(dimens);
  free(err);
  json_value_free(js);
  return 0;
}
Beispiel #3
0
bool MJsonValue::ParseJson(const wchar_t* buffer)
{
	if (mp_data)
	{
		FreeData();
	}

	json_settings setting = {};
	setting.settings = json_enable_comments;
	char errMsg[json_error_max] = "";

	json_value* p = json_parse_ex(&setting, buffer, wcslen(buffer), errMsg);
	if (p == NULL)
	{
		SafeFree(ms_Error);
		size_t eLen = strlen(errMsg);
		if (eLen)
		{
			ms_Error = (wchar_t*)malloc((eLen+1)*sizeof(*ms_Error));
			if (ms_Error)
				MultiByteToWideChar(CP_ACP, 0, errMsg, -1, ms_Error, eLen+1);
		}
		return false;
	}

	mb_Root = true;
	mp_data = p;
	return true;
}
TESTCASE(allow_trailing_comma, object_one_element) {
  const char payload[] = "{\"foo\" : true, }";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_trailing_comma, 0, 0, 0);
  struct json_object_s* object = 0;

  ASSERT_TRUE(value);
  ASSERT_EQ(json_type_object, value->type);

  object = (struct json_object_s* )value->payload;

  ASSERT_TRUE(object->start);
  ASSERT_EQ(1, object->length);

  ASSERT_TRUE(object->start->name->string);
  ASSERT_STREQ("foo", (char* )object->start->name->string);
  ASSERT_EQ(strlen("foo"), object->start->name->string_size);
  ASSERT_EQ(strlen((char* )object->start->name->string), object->start->name->string_size);

  ASSERT_TRUE(object->start->value);
  ASSERT_FALSE(object->start->value->payload);
  ASSERT_EQ(json_type_true, object->start->value->type);

  ASSERT_FALSE(object->start->next);

  free(value);
}
TESTCASE(allow_trailing_comma, array_two_elements) {
  const char payload[] = "[ true, false, ]";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_trailing_comma, 0, 0, 0);
  struct json_array_s* object = 0;
  struct json_array_element_s* element = 0;

  ASSERT_TRUE(value);
  ASSERT_EQ(json_type_array, value->type);

  object = (struct json_array_s* )value->payload;

  ASSERT_TRUE(object->start);
  ASSERT_EQ(2, object->length);

  element = object->start;

  ASSERT_TRUE(element->value);
  ASSERT_FALSE(element->value->payload);
  ASSERT_EQ(json_type_true, element->value->type);

  element = element->next;

  ASSERT_TRUE(element->value);
  ASSERT_FALSE(element->value->payload);
  ASSERT_EQ(json_type_false, element->value->type);

  ASSERT_FALSE(element->next);

  free(value);
}
Beispiel #6
0
static int parse_traffic(char *buf, int len, char *port, uint64_t *traffic)
{
    char *data = get_data(buf, len);
    char error_buf[512];
    json_settings settings = { 0 };

    if (data == NULL) {
        LOGE("No data found");
        return -1;
    }

    json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);
    if (obj == NULL) {
        LOGE("%s", error_buf);
        return -1;
    }

    if (obj->type == json_object) {
        int i = 0;
        for (i = 0; i < obj->u.object.length; i++) {
            char *name        = obj->u.object.values[i].name;
            json_value *value = obj->u.object.values[i].value;
            if (value->type == json_integer) {
                strncpy(port, name, 8);
                *traffic = value->u.integer;
            }
        }
    }

    json_value_free(obj);
    return 0;
}
TESTCASE(allow_string_simplification, solidus) {
  const char payload[] = "[ \"\\/\" ]";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_string_simplification, 0, 0, 0);
  struct json_array_s* array = 0;
  struct json_value_s* value2 = 0;
  struct json_string_s* string = 0;

  ASSERT_TRUE(value);
  ASSERT_TRUE(value->payload);
  ASSERT_EQ(json_type_array, value->type);

  array = (struct json_array_s* )value->payload;

  ASSERT_TRUE(array->start);
  ASSERT_EQ(1, array->length);

  ASSERT_TRUE(array->start->value);
  ASSERT_FALSE(array->start->next); // we have only one element

  value2 = array->start->value;

  ASSERT_TRUE(value2->payload);
  ASSERT_EQ(json_type_string, value2->type);

  string = (struct json_string_s* )value2->payload;

  ASSERT_TRUE(string->string);
  ASSERT_STREQ("/", string->string);
  ASSERT_EQ(strlen("/"), string->string_size);
  ASSERT_EQ(strlen(string->string), string->string_size);

  free(value);
}
Beispiel #8
0
cx_json_tree cx_json_tree_create (const char *data, cxu32 size)
{
  CX_ASSERT (data);
  
  cx_json_tree_internal *tree = NULL;
  
  json_settings settings;
  
  memset (&settings, 0, sizeof(settings));
  
  char errorBuffer [512];
  
  json_value *root = json_parse_ex (&settings, data, size, errorBuffer, 512);
  
  if (root)
  {
    tree = cx_malloc (sizeof (cx_json_tree_internal));
    
    tree->root = root;
  }
  
  CX_LOG_CONSOLE (CX_JSON_DEBUG_LOG_ENABLED && (root == NULL), errorBuffer);
  
  return tree;
}
Beispiel #9
0
json_value * sut_json_load (const char * filename)
{
   char * json;

   if (!sut_load_file (filename, &json, 0))
   {
      fprintf (stderr, "Error loading JSON file: %s\n", filename);
      return 0;
   }

   json_settings settings = {};
   char json_error [128];

   json_value * value;

   if (! (value = json_parse_ex (&settings, json, json_error)))
   {
      fprintf (stderr, "Error parsing JSON: %s\n", json_error);
      free (json);

      return 0;
   }

   free (json);

   return value;
}
Beispiel #10
0
static bool ParseJson( vlc_object_t *p_obj, char *psz_buffer, acoustid_results_t *p_results )
{
    json_settings settings;
    char psz_error[128];
    memset (&settings, 0, sizeof (json_settings));
    json_value *root = json_parse_ex( &settings, psz_buffer, psz_error );
    if ( root == NULL )
    {
        msg_Warn( p_obj, "Can't parse json data: %s", psz_error );
        goto error;
    }
    if ( root->type != json_object )
    {
        msg_Warn( p_obj, "wrong json root node" );
        goto error;
    }
    json_value *node = jsongetbyname( root, "status" );
    if ( !node || node->type != json_string )
    {
        msg_Warn( p_obj, "status node not found or invalid" );
        goto error;
    }
    if ( strcmp( node->u.string.ptr, "ok" ) != 0 )
    {
        msg_Warn( p_obj, "Bad request status" );
        goto error;
    }
    node = jsongetbyname( root, "results" );
    if ( !node || node->type != json_array )
    {
        msg_Warn( p_obj, "Bad results array or no results" );
        goto error;
    }
    p_results->p_results = calloc( node->u.array.length, sizeof(acoustid_result_t) );
    if ( ! p_results->p_results ) goto error;
    p_results->count = node->u.array.length;
    for( unsigned int i=0; i<node->u.array.length; i++ )
    {
        json_value *resultnode = node->u.array.values[i];
        if ( resultnode && resultnode->type == json_object )
        {
            acoustid_result_t *p_result = & p_results->p_results[i];
            json_value *value = jsongetbyname( resultnode, "score" );
            if ( value && value->type == json_double )
                p_result->d_score = value->u.dbl;
            value = jsongetbyname( resultnode, "id" );
            if ( value && value->type == json_string )
                p_result->psz_id = strdup( value->u.string.ptr );
            parse_recordings( p_obj, jsongetbyname( resultnode, "recordings" ), p_result );
        }
    }
    json_value_free( root );
    return true;

error:
    if ( root ) json_value_free( root );
    return false;
}
Beispiel #11
0
json_value &readFileToJSON(string filename) {
  char *raw_text = readFileToCString(filename);
  json_settings settings;
  memset (&settings, 0, sizeof (json_settings));
  char err[512];
  json_value *json = json_parse_ex(&settings, raw_text, err);
  if (json == NULL) {
    error("Error parsing JSON in file %s.\n%s", filename.c_str(), err);
  }
  delete raw_text;
  return *json;
}
TESTCASE(allow_trailing_comma, object_no_element) {
  const char payload[] = "{,}";
  struct json_parse_result_s result;
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_trailing_comma, 0, 0, &result);

  ASSERT_FALSE(value);

  ASSERT_EQ(json_parse_error_invalid_string, result.error);
  ASSERT_EQ(1, result.error_offset);
  ASSERT_EQ(1, result.error_line_no);
  ASSERT_EQ(1, result.error_row_no);
}
Beispiel #13
0
bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)
{
    // empty string means unload
    if(pFilename[0] == 0)
    {
        m_Strings.clear();
        m_CurrentVersion = 0;
        return true;
    }

    // read file data into buffer
    IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
    if(!File)
        return false;
    int FileSize = (int)io_length(File);
    char *pFileData = (char *)mem_alloc(FileSize+1, 1);
    io_read(File, pFileData, FileSize);
    pFileData[FileSize] = 0;
    io_close(File);

    // init
    char aBuf[64];
    str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename);
    pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
    m_Strings.clear();

    // parse json data
    json_settings JsonSettings;
    mem_zero(&JsonSettings, sizeof(JsonSettings));
    char aError[256];
    json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);
    if(pJsonData == 0)
    {
        pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError);
        mem_free(pFileData);
        return false;
    }

    // extract data
    const json_value &rStart = (*pJsonData)["translated strings"];
    if(rStart.type == json_array)
    {
        for(unsigned i = 0; i < rStart.u.array.length; ++i)
            AddString((const char *)rStart[i]["or"], (const char *)rStart[i]["tr"]);
    }

    // clean up
    json_value_free(pJsonData);
    mem_free(pFileData);
    m_CurrentVersion = ++m_VersionCounter;
    return true;
}
Beispiel #14
0
	bool Parse(const std::string& json, uint16_t& msgid, uint16_t& type) {
		json_settings settings;
		memset(&settings, 0, sizeof(json_settings));
		char error_buf[512];

		json_value* object = json_parse_ex(&settings, json.c_str(), error_buf);

		if(object == NULL) {
			std::cerr << error_buf << std::endl;
			return false;
		}

		// check if its a valid object
		if(object->type != json_object) {
			json_value_free(object);
			return false;
		}

		// get packet array
		json_value packet = (*object)["packet"];

		// set msgid (if available)
		json_value id = (*object)["msgid"];

		if(id.type != json_none) {
			msgid = (long)id;
		}

		// set type (if available)
		json_value t = (*object)["type"];

		if(t.type != json_none) {
			type = (long)t;
		}

		// iterate through array
		for(int i = 0; ; i++) {
			json_value o = packet[i];

			if(o.type != json_object) {
				break;
			}

			OnPacketData(o);
		}

		json_value_free(object);
		return true;
	}
Beispiel #15
0
static struct server *get_server(char *buf, int len)
{
    char *data = get_data(buf, len);
    char error_buf[512];
    struct server *server = (struct server *)malloc(sizeof(struct server));

    if (data == NULL) {
        LOGE("No data found");
        return NULL;
    }

    memset(server, 0, sizeof(struct server));
    json_settings settings = { 0 };
    json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);

    if (obj == NULL) {
        LOGE("%s", error_buf);
        return NULL;
    }

    if (obj->type == json_object) {
        int i = 0;
        for (i = 0; i < obj->u.object.length; i++) {
            char *name = obj->u.object.values[i].name;
            json_value *value = obj->u.object.values[i].value;
            if (strcmp(name, "server_port") == 0) {
                if (value->type == json_string) {
                    strncpy(server->port, value->u.string.ptr, 8);
                } else if (value->type == json_integer) {
                    snprintf(server->port, 8, "%" PRIu64 "", value->u.integer);
                }
            } else if (strcmp(name, "password") == 0) {
                if (value->type == json_string) {
                    strncpy(server->password, value->u.string.ptr, 128);
                }
            } else {
                LOGE("invalid data: %s", data);
                json_value_free(obj);
                return NULL;
            }
        }
    }

    json_value_free(obj);
    return server;
}
Beispiel #16
0
/**
 * Creates a new #json_value from JSON data. The returned #json_value
 * should be freed with #json_value_free() when no longer needed.
 *
 * @param data   The JSON data.
 * @param length The length of the JSON data.
 * @param err    The return location for a GError or NULL.
 *
 * @return The #json_value or NULL on error.
 **/
json_value *steam_json_new(const gchar *data, gsize length, GError **err)
{
    json_value    *json;
    json_settings  js;
    gchar         *estr;

    memset(&js, 0, sizeof js);
    estr = g_new0(gchar, json_error_max);
    json = json_parse_ex(&js, data, length, estr);

    if ((json != NULL) && (strlen(estr) < 1)) {
        g_free(estr);
        return json;
    }

    g_set_error(err, STEAM_JSON_ERROR, STEAM_JSON_ERROR_PARSER,
                "Parser: %s", estr);

    g_free(estr);
    return NULL;
}
TESTCASE(allow_equals_in_object, number) {
  const char payload[] = "{\"foo\" = -0.123e-42}";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_equals_in_object, 0);
  struct json_object_s* object = 0;
  struct json_value_s* value2 = 0;
  struct json_number_s* number = 0;

  ASSERT_TRUE(value);
  ASSERT_TRUE(value->payload);
  ASSERT_EQ(json_type_object, value->type);

  object = (struct json_object_s* )value->payload;

  ASSERT_TRUE(object->start);
  ASSERT_EQ(1, object->length);

  ASSERT_TRUE(object->start->name);
  ASSERT_TRUE(object->start->value);
  ASSERT_FALSE(object->start->next); // we have only one element

  ASSERT_TRUE(object->start->name->string);
  ASSERT_STREQ("foo", object->start->name->string);
  ASSERT_EQ(strlen("foo"), object->start->name->string_size);
  ASSERT_EQ(strlen(object->start->name->string), object->start->name->string_size);

  value2 = object->start->value;

  ASSERT_TRUE(value2->payload);
  ASSERT_EQ(json_type_number, value2->type);

  number = (struct json_number_s* )value2->payload;

  ASSERT_TRUE(number->number);
  ASSERT_STREQ("-0.123e-42", number->number);
  ASSERT_EQ(strlen("-0.123e-42"), number->number_size);
  ASSERT_EQ(strlen(number->number), number->number_size);

  free(value);
}
TESTCASE(allow_equals_in_object, string) {
  const char payload[] = "{\"foo\" = \"Heyo, gaia?\"}";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_equals_in_object, 0);
  struct json_object_s* object = 0;
  struct json_value_s* value2 = 0;
  struct json_string_s* string = 0;

  ASSERT_TRUE(value);
  ASSERT_TRUE(value->payload);
  ASSERT_EQ(json_type_object, value->type);

  object = (struct json_object_s* )value->payload;

  ASSERT_TRUE(object->start);
  ASSERT_EQ(1, object->length);

  ASSERT_TRUE(object->start->name);
  ASSERT_TRUE(object->start->value);
  ASSERT_FALSE(object->start->next); // we have only one element

  ASSERT_TRUE(object->start->name->string);
  ASSERT_STREQ("foo", object->start->name->string);
  ASSERT_EQ(strlen("foo"), object->start->name->string_size);
  ASSERT_EQ(strlen(object->start->name->string), object->start->name->string_size);

  value2 = object->start->value;

  ASSERT_TRUE(value2->payload);
  ASSERT_EQ(json_type_string, value2->type);

  string = (struct json_string_s* )value2->payload;

  ASSERT_TRUE(string->string);
  ASSERT_STREQ("Heyo, gaia?", string->string);
  ASSERT_EQ(strlen("Heyo, gaia?"), string->string_size);
  ASSERT_EQ(strlen(string->string), string->string_size);

  free(value);
}
void testcheckIfErrorOccured()
{

    int errorCode = 0;
    char *jsonFullPath = getFullFileName("tests/jsons/googleOauth2Access_invalidGrand.json");
    char *fileContent = getFileContent(jsonFullPath, &errorCode);
    CU_ASSERT_EQUAL_FATAL(errorCode, 0);
    CU_ASSERT_PTR_NOT_NULL_FATAL(fileContent);

    json_settings settings;
    memset(&settings, 0, sizeof (json_settings));
    char error[256];

    json_value *value = json_parse_ex(&settings, fileContent, error);
    CU_ASSERT_PTR_NOT_NULL_FATAL(value);
    
    int return_value = checkIfErrorOccured(value);
    CU_ASSERT_NOT_EQUAL(return_value, 0);
    CU_ASSERT_EQUAL(return_value, INVALID_GRAND);

    json_value_free(value); 
    
}
Beispiel #20
0
bool load_config (strat_ctx ctx)
{
   char * config_json;

   if (!sut_load_file ("config.json", &config_json, 0))
   {
      fprintf (stderr, "Error loading configuration file\n");
      return false;
   }

   json_settings settings = {};
   char json_error [128];

   if (! (ctx->config = json_parse_ex (&settings, config_json, json_error)))
   {
      fprintf (stderr, "Error parsing configuration file: %s\n", json_error);
      free (config_json);

      return false;
   }

   return true;
}
void testProcessIncomingAccessTokenResponse()
{
    int errorCode = 0;
    char *jsonFullPath = getFullFileName("tests/jsons/googleOauth2AccessTokenResponse_valid.json");
    char *fileContent = getFileContent(jsonFullPath, &errorCode);
    CU_ASSERT_EQUAL_FATAL(errorCode, 0);
    CU_ASSERT_PTR_NOT_NULL_FATAL(fileContent);

    json_settings settings;
    memset(&settings, 0, sizeof (json_settings));
    char error[256];
    json_value *value = json_parse_ex(&settings, fileContent, error);
    TokenResponse* result = processIncomingAccessTokenResponse(value);
    
    CU_ASSERT_PTR_NOT_NULL_FATAL(result);
    CU_ASSERT_STRING_EQUAL(result->access_token, "access_token_string");
    CU_ASSERT_STRING_EQUAL(result->error_code, NO_ERROR);
    CU_ASSERT_STRING_EQUAL(result->refresh_token, "refresh_token_string");
    CU_ASSERT_STRING_EQUAL(result->token_type, "Bearer");
    CU_ASSERT_EQUAL(result->expires_in, 3920);
    
    json_value_free(value);   

}
Beispiel #22
0
bstring get_signer_pubkey(bstring url)
{
    CURL *curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, url->data);

    bstring result = bfromcstr("");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, save_incoming_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, result);

    bstring error = bfromcstralloc(CURL_ERROR_SIZE, "");
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bdata(error));
    CURLcode rc = curl_easy_perform(curl);
    if (rc != CURLE_OK)
    {
	fprintf(stderr, "Error obtaining token: %s\n", bdata(error));
	exit(1);
    }

    long response_code;
    rc = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
    if (rc != CURLE_OK)
    {
	fprintf(stderr, "Error obtaining response code\n");
	return 0;
    }
    if (response_code == 403)
    {
	fprintf(stderr, "Permission denied.\n");
	return 0;
    }
    if (response_code >= 300)
    {
	fprintf(stderr, "Invalid response code %ld from server\n", response_code);
	return 0;
    }
    
    // printf("rc=%d '%s'\n", rc, result->data);
	 
    curl_easy_cleanup(curl);
    curl = 0;
    bdestroy(error);

    json_settings settings = { 0 } ;
    char json_error[json_error_max + 1];
    json_value *ret = json_parse_ex(&settings, bdata(result), blength(result), json_error);

    if (ret->type != json_object)
	return 0;
    
    int i;
    bstring pubkey = 0;
    for (i = 0; i < ret->u.object.length; i++)
    {
	if (strcmp(ret->u.object.values[i].name, "pubkey") == 0)
	{
	    json_value *t = ret->u.object.values[i].value;
	    pubkey = bfromcstr(t->u.string.ptr);
	}
    }

    json_value_free(ret);

    bdestroy(result);
    return pubkey;
}
Beispiel #23
0
int CMain::ReadConfig()
{
	// read and parse config
	IOHANDLE File = io_open(m_Config.m_aConfigFile, IOFLAG_READ);
	if(!File)
	{
		dbg_msg("main", "Couldn't open %s", m_Config.m_aConfigFile);
		return 1;
	}
	int FileSize = (int)io_length(File);
	char *pFileData = (char *)mem_alloc(FileSize + 1, 1);

	io_read(File, pFileData, FileSize);
	pFileData[FileSize] = 0;
	io_close(File);

	// parse json data
	json_settings JsonSettings;
	mem_zero(&JsonSettings, sizeof(JsonSettings));
	char aError[256];
	json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, strlen(pFileData), aError);
	if(!pJsonData)
	{
		dbg_msg("main", "JSON Error in file %s: %s", m_Config.m_aConfigFile, aError);
		mem_free(pFileData);
		return 1;
	}

	// reset clients
	for(int i = 0; i < NET_MAX_CLIENTS; i++)
	{
		if(!Client(i)->m_Active || !Client(i)->m_Connected)
			continue;

		m_Server.Network()->Drop(Client(i)->m_ClientNetID, "Server reloading...");
	}
	mem_zero(m_aClients, sizeof(m_aClients));
	for(int i = 0; i < NET_MAX_CLIENTS; i++)
		m_aClients[i].m_ClientNetID = -1;

	// extract data
	int ID = 0;
	const json_value &rStart = (*pJsonData)["servers"];
	if(rStart.type == json_array)
	{
		for(unsigned i = 0; i < rStart.u.array.length; i++)
		{
			if(ID < 0 || ID >= NET_MAX_CLIENTS)
				continue;

			Client(ID)->m_Active = true;
			Client(ID)->m_Disabled = rStart[i]["disabled"].u.boolean;
			str_copy(Client(ID)->m_aName, rStart[i]["name"].u.string.ptr, sizeof(Client(ID)->m_aName));
			str_copy(Client(ID)->m_aUsername, rStart[i]["username"].u.string.ptr, sizeof(Client(ID)->m_aUsername));
			str_copy(Client(ID)->m_aType, rStart[i]["type"].u.string.ptr, sizeof(Client(ID)->m_aType));
			str_copy(Client(ID)->m_aHost, rStart[i]["host"].u.string.ptr, sizeof(Client(ID)->m_aHost));
			str_copy(Client(ID)->m_aLocation, rStart[i]["location"].u.string.ptr, sizeof(Client(ID)->m_aLocation));
			str_copy(Client(ID)->m_aPassword, rStart[i]["password"].u.string.ptr, sizeof(Client(ID)->m_aPassword));

			if(m_Config.m_Verbose)
			{
				if(Client(ID)->m_Disabled)
					dbg_msg("main", "[#%d: Name: \"%s\", Username: \"%s\", Type: \"%s\", Host: \"%s\", Location: \"%s\", Password: \"%s\"]",
						ID, Client(ID)->m_aName, Client(ID)->m_aUsername, Client(ID)->m_aType, Client(ID)->m_aHost, Client(ID)->m_aLocation, Client(ID)->m_aPassword);
				else
					dbg_msg("main", "#%d: Name: \"%s\", Username: \"%s\", Type: \"%s\", Host: \"%s\", Location: \"%s\", Password: \"%s\"",
						ID, Client(ID)->m_aName, Client(ID)->m_aUsername, Client(ID)->m_aType, Client(ID)->m_aHost, Client(ID)->m_aLocation, Client(ID)->m_aPassword);

			}
			ID++;
		}
	}

	// clean up
	json_value_free(pJsonData);
	mem_free(pFileData);

	// tell clients to reload the page
	m_JSONUpdateThreadData.m_ReloadRequired = 2;

	return 0;
}
Beispiel #24
0
struct json_value_s *json_parse(const void *src, size_t src_size) {
  return json_parse_ex(src, src_size, json_parse_flags_default, NULL);
}
Beispiel #25
0
jconf_t *read_jconf(const char * file)
{

    static jconf_t conf;
    memset(&conf, 0, sizeof(conf));

    char *buf;
    json_value *obj;

    FILE *f = fopen(file, "rb");
    if (f == NULL) {
        FATAL("Invalid config path.");
    }

    fseek(f, 0, SEEK_END);
    long pos = ftell(f);
    fseek(f, 0, SEEK_SET);

    if (pos >= MAX_CONF_SIZE) {
        FATAL("Too large config file.");
    }

    buf = malloc(pos + 1);
    if (buf == NULL) {
        FATAL("No enough memory.");
    }

    int nread = fread(buf, pos, 1, f);
    if (!nread) {
        FATAL("Failed to read the config file.");
    }
    fclose(f);

    buf[pos] = '\0'; // end of string

    json_settings settings = { 0 };
    char error_buf[512];
    obj = json_parse_ex(&settings, buf, pos, error_buf);

    if (obj == NULL) {
        FATAL(error_buf);
    }

    if (obj->type == json_object) {
        int i, j;
        for (i = 0; i < obj->u.object.length; i++) {
            char *name = obj->u.object.values[i].name;
            json_value *value = obj->u.object.values[i].value;
            if (strcmp(name, "server") == 0) {
                if (value->type == json_array) {
                    for (j = 0; j < value->u.array.length; j++) {
                        if (j >= MAX_REMOTE_NUM) {
                            break;
                        }
                        json_value *v = value->u.array.values[j];
                        parse_addr(to_string(v), conf.remote_addr + j);
                        conf.remote_num = j + 1;
                    }
                } else if (value->type == json_string) {
                    conf.remote_addr[0].host = to_string(value);
                    conf.remote_addr[0].port = NULL;
                    conf.remote_num = 1;
                }
            } else if (strcmp(name, "server_port") == 0) {
                conf.remote_port = to_string(value);
            } else if (strcmp(name, "local_address") == 0) {
                conf.local_addr = to_string(value);
            } else if (strcmp(name, "local_port") == 0) {
                conf.local_port = to_string(value);
            } else if (strcmp(name, "password") == 0) {
                conf.password = to_string(value);
            } else if (strcmp(name, "method") == 0) {
                conf.method = to_string(value);
            } else if (strcmp(name, "timeout") == 0) {
                conf.timeout = to_string(value);
            } else if (strcmp(name, "fast_open") == 0) {
                conf.fast_open = value->u.boolean;
            } else if (strcmp(name, "nofile") == 0) {
                conf.nofile = value->u.integer;
            } else if (strcmp(name, "nameserver") == 0) {
                conf.nameserver = to_string(value);
#ifdef USE_CRYPTO_OPENSSL
            } else if (strcmp(name, "bitcoin_address") == 0) {
                conf.bitcoin_address = to_string(value);
            } else if (strcmp(name, "bitcoin_privkey") == 0) {
                conf.bitcoin_privkey = to_string(value);
            } else if (strcmp(name, "bitcoin_list") == 0) {
                conf.bitcoin_list = to_string(value);
#endif
            }
        }
    } else {
        FATAL("Invalid config file");
    }

    free(buf);
    json_value_free(obj);
    return &conf;

}
Beispiel #26
0
jconf_t *read_jconf(const char* file)
{

    static jconf_t conf;

    char *buf;
    json_value *obj;

    FILE *f = fopen(file, "r");
    if (f == NULL) FATAL("Invalid config path.");

    fseek(f, 0, SEEK_END);
    long pos = ftell(f);
    fseek(f, 0, SEEK_SET);

    if (pos >= MAX_CONF_SIZE) FATAL("Too large config file.");

    buf = malloc(pos + 1);
    if (buf == NULL) FATAL("No enough memory.");

    fread(buf, pos, 1, f);
    fclose(f);

    buf[pos] = '\0'; // end of string

    json_settings settings = { 0 };
    char error_buf[512];
    obj = json_parse_ex(&settings, buf, pos, error_buf);

    if (obj == NULL)
    {
        FATAL(error_buf);
    }

    if (obj->type == json_object)
    {
        int i;
        for (i = 0; i < obj->u.object.length; i++)
        {
            char *name = obj->u.object.values[i].name;
            json_value *value = obj->u.object.values[i].value;
            if (strcmp(name, "whitelist") == 0)
            {
                conf.whitelist = to_string(value);
            }
            else if (strcmp(name, "TwitterID") == 0)
            {
                conf.TwitterID = to_string(value);
            }
            else if (strcmp(name, "CONSUMER_KEY") == 0)
            {
                conf.CONSUMER_KEY = to_string(value);
            }
            else if (strcmp(name, "CONSUMER_SECRET") == 0)
            {
                conf.CONSUMER_SECRET = to_string(value);
            }
            else if (strcmp(name, "OAUTH_TOKEN") == 0)
            {
                conf.OAUTH_TOKEN = to_string(value);
            }
            else if (strcmp(name, "OAUTH_TOKEN_SECRET") == 0)
            {
                conf.OAUTH_TOKEN_SECRET = to_string(value);
            }
        }
    }
    else
    {
        FATAL("Invalid config file");
    }

    free(buf);
    json_value_free(obj);
    return &conf;

}
Beispiel #27
0
void CUpdater::CheckUpdates(CMenus *pMenus)
{
	dbg_msg("autoupdate", "Checking for updates...");
	if (!CHttpDownloader::GetToFile("http://" UPDATES_HOST UPDATES_BASE_PATH UPDATES_MANIFEST_FILE, UPDATES_MANIFEST_FILE))
	{
		dbg_msg("autoupdate", "Error downloading updates manifest :/");
		return;
	}

    Reset();

    IOHANDLE fileAutoUpdate = io_open(UPDATES_MANIFEST_FILE, IOFLAG_READ);
    io_seek(fileAutoUpdate, 0, IOSEEK_END);
    std::streamsize size = io_tell(fileAutoUpdate);
    io_seek(fileAutoUpdate, 0, IOSEEK_START);

    std::vector<char> buffer(size);
    if (io_read(fileAutoUpdate, buffer.data(), size))
    {
        bool needUpdate = false;

        json_settings JsonSettings;
        mem_zero(&JsonSettings, sizeof(JsonSettings));
        char aError[256];
        json_value *pJsonNodeMain = json_parse_ex(&JsonSettings, buffer.data(), size, aError);
        if (pJsonNodeMain == 0)
        {
            dbg_msg("autoupdate", "Error: %s", aError);
            return;
        }

        int verCode = -1;
        for(int j=pJsonNodeMain->u.object.length-1; j>=0; j--) // Ascendent Search: Manifest has descendant order
        {
            sscanf((const char *)pJsonNodeMain->u.object.values[j].name, "%d", &verCode);
            json_value *pNodeCode = pJsonNodeMain->u.object.values[j].value;

            if (verCode <= HCLIENT_VERSION_CODE)
                continue;

            needUpdate = true;

            const json_value &rVersion = (*pNodeCode)["version"];
            str_copy(m_NewVersion, (const char *)rVersion, sizeof(m_NewVersion));

            // Need update client?
            const json_value &rClient = (*pNodeCode)["client"];
            m_NeedUpdateClient = (rClient.u.boolean);

            // Need update server?
            const json_value &rServer = (*pNodeCode)["server"];
            m_NeedUpdateServer = (rServer.u.boolean);

            // Get files to download
            const json_value &rDownload = (*pNodeCode)["download"];
            for(unsigned k = 0; k < rDownload.u.array.length; k++)
                AddFileToDownload((const char *)rDownload[k]);
            // Get files to remove
            const json_value &rRemove = (*pNodeCode)["remove"];
            for(unsigned k = 0; k < rRemove.u.array.length; k++)
                AddFileToRemove((const char *)rRemove[k]);
        }

        if (needUpdate) pMenus->SetPopup(CMenus::POPUP_UPDATER);
        else m_Updated = true;
    }

    io_close(fileAutoUpdate);
    fs_remove(UPDATES_MANIFEST_FILE);
}
Beispiel #28
0
IGeoIP::GeoInfo CGeoIP::GetInfo(std::string ip)
{
    dbg_msg("GeoIP", "Searching geolocation of '%s'...", ip.c_str());

    NETADDR bindAddr;
    mem_zero(&bindAddr, sizeof(bindAddr));
    char aNetBuff[1024];
    std::string jsonData;
    IGeoIP::GeoInfo rInfo;

    //Connect
    bindAddr.type = NETTYPE_IPV4;
    m_Socket = net_tcp_create(bindAddr);
    net_set_non_blocking(m_Socket);
    if(net_tcp_connect(m_Socket, &m_HostAddress) < 0)
    {
    	if (net_errno() != EINPROGRESS)
    	{
    		dbg_msg("GeoIP","ERROR: Can't connect.");
    		net_tcp_close(m_Socket);
    		return rInfo;
    	}
    }

    net_socket_read_wait(m_Socket, 1);
    net_set_blocking(m_Socket);

    //Send request
    str_format(aNetBuff, sizeof(aNetBuff), "GET /geoip/%s HTTP/1.0\r\nHost: www.telize.com\r\n\r\n", ip.c_str());
    net_tcp_send(m_Socket, aNetBuff, strlen(aNetBuff));

    //read data
    bool errors = true;
    std::string NetData;
    int TotalRecv = 0;
    int TotalBytes = 0;
    int CurrentRecv = 0;
    bool isHead = true;
    int enterCtrl = 0;
    while ((CurrentRecv = net_tcp_recv(m_Socket, aNetBuff, sizeof(aNetBuff))) > 0)
    {
        for (int i=0; i<CurrentRecv ; i++)
        {
            if (isHead)
            {
                if (aNetBuff[i]=='\n')
                {
                    enterCtrl++;
                    if (enterCtrl == 2)
                    {
                        isHead = false;
                        NetData.clear();
                        continue;
                    }

                    std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower);
					if (NetData.find("content-length:") != std::string::npos)
                    {
                        sscanf(NetData.c_str(), "content-length:%d", &TotalBytes);
                        if (TotalBytes == 0)
                            sscanf(NetData.c_str(), "content-length: %d", &TotalBytes);
                    }

                    NetData.clear();
                    continue;
                }
                else if (aNetBuff[i]!='\r')
                    enterCtrl=0;

                NetData+=aNetBuff[i];
            }
            else
            {
                if (TotalBytes == 0)
                {
                    net_tcp_close(m_Socket);
                    dbg_msg("GeoIP","ERROR: Error with size received data.");
                    break;
                }

                jsonData += aNetBuff[i];

                TotalRecv++;
                if (TotalRecv == TotalBytes)
                {
                	errors = false;
                    break;
                }
            }
        }
    }

    //Finish
    net_tcp_close(m_Socket);

    if (!errors)
    {
		// parse json data
		json_settings JsonSettings;
		mem_zero(&JsonSettings, sizeof(JsonSettings));
		char aError[256];
		json_value *pJsonData = json_parse_ex(&JsonSettings, jsonData.c_str(), jsonData.length(), aError);
		if (pJsonData == 0)
		{
			dbg_msg("GeoIP", "Error: %s", aError);
			return rInfo;
		}

		// generate configurations
		const json_value &countryCode = (*pJsonData)["country_code"];
		if (countryCode.type == json_string) str_copy(rInfo.m_aCountryCode, (const char *)countryCode, sizeof(rInfo.m_aCountryCode));
		const json_value &countryName = (*pJsonData)["country"];
		if (countryName.type == json_string) str_copy(rInfo.m_aCountryName, (const char *)countryName, sizeof(rInfo.m_aCountryName));
		//const json_value &isp = (*pJsonData)["isp"];
		//if (isp.type == json_string) geoInfo->m_Isp = (const char *)isp;
    }

	return rInfo;
}
Beispiel #29
0
int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser)
{
	int l = str_length(pName);
	if(l < 5 || IsDir || str_comp(pName+l-5, ".json") != 0)
		return 0;

	CSkins *pSelf = (CSkins *)pUser;

	// read file data into buffer
	char aBuf[512];
	str_format(aBuf, sizeof(aBuf), "skins/%s", pName);
	IOHANDLE File = pSelf->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!File)
		return 0;
	int FileSize = (int)io_length(File);
	char *pFileData = (char *)mem_alloc(FileSize, 1);
	io_read(File, pFileData, FileSize);
	io_close(File);

	// init
	CSkin Skin = pSelf->m_DummySkin;
	str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-4));
	if(pSelf->Find(Skin.m_aName, true) != -1)
		return 0;
	bool SpecialSkin = pName[0] == 'x' && pName[1] == '_';

	// parse json data
	json_settings JsonSettings;
	mem_zero(&JsonSettings, sizeof(JsonSettings));
	char aError[256];
	json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, FileSize, aError);
	mem_free(pFileData);

	if(pJsonData == 0)
	{
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError);
		return 0;
	}

	// extract data
	const json_value &rStart = (*pJsonData)["skin"];
	if(rStart.type == json_object)
	{
		for(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex)
		{
			const json_value &rPart = rStart[(const char *)ms_apSkinPartNames[PartIndex]];
			if(rPart.type != json_object)
				continue;

			// filename
			const json_value &rFilename = rPart["filename"];
			if(rFilename.type == json_string)
			{
				int SkinPart = pSelf->FindSkinPart(PartIndex, (const char *)rFilename, SpecialSkin);
				if(SkinPart > -1)
					Skin.m_apParts[PartIndex] = pSelf->GetSkinPart(PartIndex, SkinPart);
			}

			// use custom colors
			bool UseCustomColors = false;
			const json_value &rColour = rPart["custom_colors"];
			if(rColour.type == json_string)
			{
				UseCustomColors = str_comp((const char *)rColour, "true") == 0;
			}
			Skin.m_aUseCustomColors[PartIndex] = UseCustomColors;

			// color components
			if(!UseCustomColors)
				continue;

			for(int i = 0; i < NUM_COLOR_COMPONENTS; i++)
			{
				if(PartIndex != SKINPART_MARKING && i == 3)
					continue;

				const json_value &rComponent = rPart[(const char *)ms_apColorComponents[i]];
				if(rComponent.type == json_integer)
				{
					switch(i)
					{
					case 0: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFF00FFFF) | (rComponent.u.integer << 16); break;
					case 1:	Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFF00FF) | (rComponent.u.integer << 8); break;
					case 2: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFFFF00) | rComponent.u.integer; break;
					case 3: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0x00FFFFFF) | (rComponent.u.integer << 24); break;
					}
				}
			}
		}
	}

	// clean up
	json_value_free(pJsonData);

	// set skin data
	Skin.m_Flags = SpecialSkin ? SKINFLAG_SPECIAL : 0;
	if(DirType != IStorage::TYPE_SAVE)
		Skin.m_Flags |= SKINFLAG_STANDARD;
	if(g_Config.m_Debug)
	{
		str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName);
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "skins", aBuf);
	}
	pSelf->m_aSkins.add(Skin);

	return 0;
}
  value2 = object->start->value;

  ASSERT_TRUE(value2->payload);
  ASSERT_EQ(json_type_array, value2->type);

  array = (struct json_array_s* )value2->payload;

  ASSERT_FALSE(array->start);
  ASSERT_EQ(0, array->length);

  free(value);
}

TESTCASE(allow_equals_in_object, true) {
  const char payload[] = "{\"foo\" = true}";
  struct json_value_s* value = json_parse_ex(payload, strlen(payload), json_parse_flags_allow_equals_in_object, 0);
  struct json_object_s* object = 0;
  struct json_value_s* value2 = 0;

  ASSERT_TRUE(value);
  ASSERT_TRUE(value->payload);
  ASSERT_EQ(json_type_object, value->type);

  object = (struct json_object_s* )value->payload;

  ASSERT_TRUE(object->start);
  ASSERT_EQ(1, object->length);

  ASSERT_TRUE(object->start->name);
  ASSERT_TRUE(object->start->value);
  ASSERT_FALSE(object->start->next); // we have only one element