Example #1
0
void CServerBrowser::LoadDDNet()
{
	// reset servers / countries
	m_NumDDNetCountries = 0;
	m_NumDDNetTypes = 0;

	// load ddnet server list
	IStorage *pStorage = Kernel()->RequestInterface<IStorage>();
	IOHANDLE File = pStorage->OpenFile("ddnet-servers.json", IOFLAG_READ, IStorage::TYPE_ALL);

	if(File)
	{
		char aBuf[4096*4];
		mem_zero(aBuf, sizeof(aBuf));

		io_read(File, aBuf, sizeof(aBuf));
		io_close(File);


		// parse JSON
		json_value *pCountries = json_parse(aBuf);

		if (pCountries && pCountries->type == json_array)
		{
			for (int i = 0; i < json_array_length(pCountries) && m_NumDDNetCountries < MAX_DDNET_COUNTRIES; i++)
			{
				// pSrv - { name, flagId, servers }
				const json_value *pSrv = json_array_get(pCountries, i);
				const json_value *pTypes = json_object_get(pSrv, "servers");
				const json_value *pName = json_object_get(pSrv, "name");
				const json_value *pFlagID = json_object_get(pSrv, "flagId");

				if (pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer)
				{
					dbg_msg("client_srvbrowse", "invalid attributes");
					continue;
				}

				// build structure
				CDDNetCountry *pCntr = &m_aDDNetCountries[m_NumDDNetCountries];

				pCntr->Reset();

				str_copy(pCntr->m_aName, json_string_get(pName), sizeof(pCntr->m_aName));
				pCntr->m_FlagID = json_int_get(pFlagID);

				// add country
				for (unsigned int t = 0; t < pTypes->u.object.length; t++)
				{
					const char *pType = pTypes->u.object.values[t].name;
					const json_value *pAddrs = pTypes->u.object.values[t].value;

					// add type
					if(json_array_length(pAddrs) > 0 && m_NumDDNetTypes < MAX_DDNET_TYPES)
					{
						int pos;
						for(pos = 0; pos < m_NumDDNetTypes; pos++)
						{
							if(!str_comp(m_aDDNetTypes[pos], pType))
								break;
						}
						if(pos == m_NumDDNetTypes)
						{
							str_copy(m_aDDNetTypes[m_NumDDNetTypes], pType, sizeof(m_aDDNetTypes[m_NumDDNetTypes]));
							m_NumDDNetTypes++;
						}
					}

					// add addresses
					for (int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++)
					{
						const json_value *pAddr = json_array_get(pAddrs, g);
						const char* pStr = json_string_get(pAddr);
						net_addr_from_str(&pCntr->m_aServers[pCntr->m_NumServers], pStr);
						str_copy(pCntr->m_aTypes[pCntr->m_NumServers], pType, sizeof(pCntr->m_aTypes[pCntr->m_NumServers]));
					}
				}

				m_NumDDNetCountries++;
			}
		}

		if (pCountries)
			json_value_free(pCountries);
	}
}
Example #2
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;
}
Example #3
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;
}
Example #4
0
POOL_CONFIG* get_pool_config_from_json(char* json_data, int data_len)
{
	int i;
	json_value *root = NULL;
	json_value *value = NULL;
	POOL_CONFIG *config = palloc0(sizeof(POOL_CONFIG));
	config->backend_desc = palloc0(sizeof(BackendDesc));

	root = json_parse(json_data,data_len);
	/* The root node must be object */
	if (root == NULL || root->type != json_object)
		goto ERROR_EXIT;

	if (json_get_int_value_for_key(root, "num_init_children", &config->num_init_children))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "listen_backlog_multiplier", &config->listen_backlog_multiplier))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "child_life_time", &config->child_life_time))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "connection_life_time", &config->connection_life_time))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "child_max_connections", &config->child_max_connections))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "client_idle_limit", &config->client_idle_limit))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "max_pool", &config->max_pool))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replication_mode", &config->replication_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "enable_pool_hba", &config->enable_pool_hba))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "load_balance_mode", &config->load_balance_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replication_stop_on_mismatch", &config->replication_stop_on_mismatch))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "failover_if_affected_tuples_mismatch", &config->failover_if_affected_tuples_mismatch))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replicate_select", &config->replicate_select))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "master_slave_mode", &config->master_slave_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "connection_cache", &config->connection_cache))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_timeout", &config->health_check_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_period", &config->health_check_period))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_max_retries", &config->health_check_max_retries))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_retry_delay", &config->health_check_retry_delay))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "fail_over_on_backend_error", &config->fail_over_on_backend_error))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "recovery_timeout", &config->recovery_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "search_primary_node_timeout", &config->search_primary_node_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "client_idle_limit_in_recovery", &config->client_idle_limit_in_recovery))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "insert_lock", &config->insert_lock))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "memory_cache_enabled", &config->memory_cache_enabled))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "use_watchdog", &config->use_watchdog))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "clear_memqcache_on_escalation", &config->clear_memqcache_on_escalation))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "wd_port", &config->wd_port))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "wd_priority", &config->wd_priority))
		goto ERROR_EXIT;

	config->master_slave_sub_mode = json_get_string_value_for_key(root, "master_slave_sub_mode");
	if (config->master_slave_sub_mode == NULL)
		goto ERROR_EXIT;
	config->master_slave_sub_mode = pstrdup(config->master_slave_sub_mode);


	/* backend_desc array */
	value = json_get_value_for_key(root,"backend_desc");
	if (value == NULL || value->type != json_array)
		goto ERROR_EXIT;

	config->backend_desc->num_backends = value->u.array.length;
	for (i = 0; i < config->backend_desc->num_backends; i++)
	{
		json_value *arr_value = value->u.array.values[i];
		char *ptr;
		if (json_get_int_value_for_key(arr_value, "backend_port", &config->backend_desc->backend_info[i].backend_port))
			goto ERROR_EXIT;
		ptr = json_get_string_value_for_key(arr_value, "backend_hostname");
		if (ptr == NULL)
			goto ERROR_EXIT;
		strncpy(config->backend_desc->backend_info[i].backend_hostname, ptr,sizeof(config->backend_desc->backend_info[i].backend_hostname) -1);
	}

	/* wd_remote_nodes array */
	value = json_get_value_for_key(root,"wd_remote_nodes");
	if (value == NULL || value->type != json_array)
		goto ERROR_EXIT;
	
	config->wd_remote_nodes.num_wd = value->u.array.length;
	for (i = 0; i < config->wd_remote_nodes.num_wd; i++)
	{
		json_value *arr_value = value->u.array.values[i];
		char *ptr;
		if (json_get_int_value_for_key(arr_value, "wd_port", &config->wd_remote_nodes.wd_remote_node_info[i].wd_port))
			goto ERROR_EXIT;
		if (json_get_int_value_for_key(arr_value, "pgpool_port", &config->wd_remote_nodes.wd_remote_node_info[i].pgpool_port))
			goto ERROR_EXIT;
		ptr = json_get_string_value_for_key(arr_value, "hostname");
		if (ptr == NULL)
			goto ERROR_EXIT;
		strncpy(config->wd_remote_nodes.wd_remote_node_info[i].hostname, ptr,sizeof(config->wd_remote_nodes.wd_remote_node_info[i].hostname) -1);
	}

	json_value_free(root);
	return config;

ERROR_EXIT:
	if (root)
		json_value_free(root);
	if (config->backend_desc)
		pfree(config->backend_desc);
	if (config->master_slave_sub_mode)
		pfree(config->master_slave_sub_mode);
	pfree(config);
	return NULL;
}
Example #5
0
// updates the planes map, planes not seen for a defined intervall are removed from the map and only planes within a defined distance from the given latitude and longited
static void UpdatePlanes(char *balancerUrl, char *zoneName, double latitude, double longitude)
{
    time_t currentTime = time(NULL);

    if (currentTime != ((time_t) -1))
    {
        pthread_mutex_lock(&planesMutex);
        for (std::map<std::string, Plane*>::iterator p = planes.begin(); p != planes.end(); ++p)
        {
            Plane *plane = p->second;
            if (currentTime - plane->lastSeen > PLANE_TIMEOUT)
            {
                //printf("Removing: %s - CurrentTime = %d - LastSeen = %d\n", p->first.c_str(), (int) currentTime, (int) plane->lastSeen);
                free(plane);
                plane = NULL;
                planes.erase(p->first);
            }
        }
        pthread_mutex_unlock(&planesMutex);

        char url[strlen(balancerUrl) + strlen(URL_ZONE_INFIX) + strlen(zoneName) + strlen(URL_ZONE_SUFFIX)];
        sprintf(url, "%s%s%s%s", balancerUrl, URL_ZONE_INFIX, zoneName, URL_ZONE_SUFFIX);

        char *zone = GetUrl(url);
        if (zone != NULL)
        {
            int cmp = 1;
            if (lastZone != NULL)
                cmp = strcmp(zone, lastZone);

            if (cmp != 0)
            {
                JSON_Value *rootJson = json_parse_string(zone);
                lastZone = zone;

                if (rootJson != NULL)
                {
                    if (rootJson->type == JSONObject)
                    {
                        JSON_Object *aircraftJson = json_value_get_object(rootJson);
                        if (aircraftJson != NULL)
                        {
                            size_t aircraftCount = json_object_get_count(aircraftJson);
                            for (int i = 0; i < aircraftCount; i++)
                            {
                                const char *id = json_object_get_name(aircraftJson, i);
                                if (id != NULL)
                                {
                                    JSON_Value *value = json_object_get_value(aircraftJson, id);

                                    if (value != NULL && value->type == JSONArray)
                                    {
                                        JSON_Array *propertiesJson = json_value_get_array(value);

                                        if (propertiesJson != NULL)
                                        {
                                            const char *registration = NULL, *icaoId = NULL, *icaoType = NULL, *squawk = NULL;
                                            double latitudePlane = 0.0, longitudePlane = 0.0, altitude = 0.0;
                                            float heading = 0.0f;
                                            int speed = 0, verticalSpeed = 0;

                                            int propertyCount = json_array_get_count(propertiesJson);
                                            for (int k = 0; k < propertyCount; k++)
                                            {
                                                JSON_Value *valueJson = json_array_get_value(propertiesJson, k);

                                                if (valueJson != NULL)
                                                {
                                                    switch (k)
                                                    {
                                                    case ARRAY_INDEX_LATITUDE:
                                                        latitudePlane = json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_LONGITUDE:
                                                        longitudePlane = json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_ALTITUDE:
                                                        altitude = json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_HEADING:
                                                        heading = (float) json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_SPEED:
                                                        speed = (int) json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_SQUAWK:
                                                        squawk = json_value_get_string(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_ICAO_TYPE:
                                                        icaoType = json_value_get_string(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_REGISTRATION:
                                                        registration = json_value_get_string(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_VERTICAL_SPEED:
                                                        verticalSpeed = (int) json_value_get_number(valueJson);
                                                        break;
                                                    case ARRAY_INDEX_ICAO_ID:
                                                        icaoId = json_value_get_string(valueJson);
                                                        break;
                                                    }
                                                }
                                            }

                                            if (latitudePlane != 0.0 && longitudePlane != 0.0 && GetDistance(latitude, longitude, latitudePlane, longitudePlane) <= MAX_DISTANCE)
                                            {
                                                Plane *plane = NULL;

                                                pthread_mutex_lock(&planesMutex);
                                                std::map<std::string, Plane*>::iterator p = planes.find(id);
                                                if (p != planes.end())
                                                    plane = p->second;
                                                else
                                                {
                                                    plane = (Plane*) malloc(sizeof(*plane));
                                                    if (plane != NULL)
                                                        planes[std::string(id)] = plane;
                                                }

                                                if (plane != NULL)
                                                {
                                                    if (registration == NULL || strlen(registration) == 0)
                                                        registration = "Unknown";
                                                    if (icaoId == NULL || strlen(icaoId) == 0)
                                                        icaoId = "Unknown";
                                                    if (icaoType == NULL || strlen(icaoType) == 0)
                                                        icaoType = "UKN";
                                                    if (squawk == NULL || strlen(squawk) == 0)
                                                        squawk = "0000";
                                                    strncpy(plane->registration, registration, sizeof(plane->registration) / sizeof(char));
                                                    strncpy(plane->icaoId, icaoId, sizeof(plane->icaoId) / sizeof(char));
                                                    strncpy(plane->icaoType, icaoType, sizeof(plane->icaoType) / sizeof(char));
                                                    strncpy(plane->squawk, squawk, sizeof(plane->squawk) / sizeof(char));
                                                    if (plane->latitude != latitudePlane)
                                                    {
                                                        plane->latitude = latitudePlane;
                                                        plane->interpolatedLatitude = 0.0;
                                                    }
                                                    if (plane->longitude != longitudePlane)
                                                    {
                                                        plane->longitude = longitudePlane;
                                                        plane->interpolatedLongitude = 0.0;
                                                    }
                                                    if (plane->altitude != altitude)
                                                    {
                                                        plane->altitude = altitude;
                                                        plane->interpolatedAltitude = -1000.0;
                                                    }
                                                    plane->pitch = 0.0f;
                                                    plane->roll = 0.0f;
                                                    plane->heading = heading;
                                                    plane->speed = speed;
                                                    plane->verticalSpeed = verticalSpeed;
                                                    plane->lastSeen = currentTime;
                                                }
                                                pthread_mutex_unlock(&planesMutex);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        json_value_free(rootJson);
                        rootJson = NULL;
                    }
                }
            }
        }
    }
}
Example #6
0
bud_config_t* bud_config_load(const char* path, int inlined, bud_error_t* err) {
  int i;
  JSON_Value* json;
  JSON_Value* val;
  JSON_Object* obj;
  JSON_Object* tmp;
  JSON_Object* log;
  JSON_Object* avail;
  JSON_Array* contexts;
  JSON_Array* backend;
  bud_config_t* config;
  bud_context_t* ctx;

  if (inlined)
    json = json_parse_string(path);
  else
    json = json_parse_file(path);

  if (json == NULL) {
    *err = bud_error_str(kBudErrJSONParse, path);
    goto end;
  }

  obj = json_value_get_object(json);
  if (obj == NULL) {
    *err = bud_error(kBudErrJSONNonObjectRoot);
    goto failed_get_object;
  }

  config = calloc(1, sizeof(*config));
  if (config == NULL) {
    *err = bud_error_str(kBudErrNoMem, "bud_config_t");
    goto failed_get_object;
  }

  /* Copy path or inlined config value */
  config->path = strdup(path);
  if (config->path == NULL) {
    *err = bud_error_str(kBudErrNoMem, "bud_config_t strcpy(path)");
    goto failed_alloc_path;
  }

  config->inlined = inlined;

  /* Allocate contexts and backends */
  contexts = json_object_get_array(obj, "contexts");
  backend = json_object_get_array(obj, "backend");
  config->context_count = contexts == NULL ? 0 : json_array_get_count(contexts);
  config->backend_count = backend == NULL ? 0 : json_array_get_count(backend);
  config->contexts = calloc(config->context_count + 1,
                            sizeof(*config->contexts));
  config->backend = calloc(config->backend_count, sizeof(*config->backend));

  if (config->contexts == NULL || config->backend == NULL) {
    *err = bud_error_str(kBudErrNoMem, "bud_context_t");
    goto failed_get_index;
  }

  config->json = json;

  /* Workers configuration */
  config->worker_count = -1;
  config->restart_timeout = -1;
  val = json_object_get_value(obj, "workers");
  if (val != NULL)
    config->worker_count = json_value_get_number(val);
  val = json_object_get_value(obj, "restart_timeout");
  if (val != NULL)
    config->restart_timeout = json_value_get_number(val);

  /* Logger configuration */
  log = json_object_get_object(obj, "log");
  config->log.stdio = -1;
  config->log.syslog = -1;
  if (log != NULL) {
    config->log.level = json_object_get_string(log, "level");
    config->log.facility = json_object_get_string(log, "facility");

    val = json_object_get_value(log, "stdio");
    if (val != NULL)
      config->log.stdio = json_value_get_boolean(val);
    val = json_object_get_value(log, "syslog");
    if (val != NULL)
      config->log.syslog = json_value_get_boolean(val);
  }

  /* Availability configuration */
  avail = json_object_get_object(obj, "availability");
  config->availability.death_timeout = -1;
  config->availability.revive_interval = -1;
  config->availability.retry_interval = -1;
  config->availability.max_retries = -1;
  if (avail != NULL) {
    val = json_object_get_value(avail, "death_timeout");
    if (val != NULL)
      config->availability.death_timeout = json_value_get_number(val);
    val = json_object_get_value(avail, "revive_interval");
    if (val != NULL)
      config->availability.revive_interval = json_value_get_number(val);
    val = json_object_get_value(avail, "retry_interval");
    if (val != NULL)
      config->availability.retry_interval = json_value_get_number(val);
    val = json_object_get_value(avail, "max_retries");
    if (val != NULL)
      config->availability.max_retries = json_value_get_number(val);
  }

  /* Frontend configuration */
  *err = bud_config_load_frontend(json_object_get_object(obj, "frontend"),
                                  &config->frontend);
  if (!bud_is_ok(*err))
    goto failed_get_index;

  /* Backend configuration */
  config->balance = json_object_get_string(obj, "balance");
  for (i = 0; i < config->backend_count; i++) {
    bud_config_load_backend(config,
                            json_array_get_object(backend, i),
                            &config->backend[i]);
  }

  /* SNI configuration */
  bud_config_read_pool_conf(obj, "sni", &config->sni);

  /* OCSP Stapling configuration */
  bud_config_read_pool_conf(obj, "stapling", &config->stapling);

  /* SSL Contexts */

  /* TODO(indutny): sort them and do binary search */
  for (i = 0; i < config->context_count; i++) {
    /* NOTE: contexts[0] - is a default context */
    ctx = &config->contexts[i + 1];
    obj = json_array_get_object(contexts, i);
    if (obj == NULL) {
      *err = bud_error(kBudErrJSONNonObjectCtx);
      goto failed_get_index;
    }

    ctx->servername = json_object_get_string(obj, "servername");
    ctx->servername_len = ctx->servername == NULL ? 0 : strlen(ctx->servername);
    ctx->cert_file = json_object_get_string(obj, "cert");
    ctx->key_file = json_object_get_string(obj, "key");
    ctx->npn = json_object_get_array(obj, "npn");
    ctx->ciphers = json_object_get_string(obj, "ciphers");
    ctx->ecdh = json_object_get_string(obj, "ecdh");
    ctx->ticket_key = json_object_get_string(obj, "ticket_key");

    tmp = json_object_get_object(obj, "backend");
    if (tmp != NULL) {
      ctx->backend = &ctx->backend_st;
      bud_config_load_backend(config, tmp, ctx->backend);
    }

    *err = bud_config_verify_npn(ctx->npn);
    if (!bud_is_ok(*err))
      goto failed_get_index;
  }

  bud_config_set_defaults(config);

  *err = bud_ok();
  return config;

failed_get_index:
  free(config->contexts);
  config->contexts = NULL;
  free(config->backend);
  config->backend = NULL;
  free(config->path);
  config->path = NULL;

failed_alloc_path:
  free(config);

failed_get_object:
  json_value_free(json);

end:
  return NULL;
}
Example #7
0
//exit funtion
void saveData() {
	
	printf("Saving data @ %d...\n", currentMatchId);

	//make new arrays to hold the data
	json_value *outputArray = json_array_new(0);
	json_value **structures = malloc(1024);

	//TODO: Save brawler data into BRAWLER_DATA_FILE
	json_value *outputBrawlerArray = json_array_new(0);
	json_value *(brawlerStructs[4]);

	//for every champion that may or may not have had data stored for
	for (int i = 0; i < 1024; i++) {
		//if this champion had any data stored for it (at least one brawler has been bought on this champ)
		if (outputData[i].razorfinsBought    +
			outputData[i].ironbacksBought    +
			outputData[i].plundercrabsBought +
			outputData[i].ocklepodsBought > 0) {

			//make it a new array
			structures[i] = json_array_new(11);

			//push the appropriate data into it
			json_array_push(structures[i], json_integer_new(i));
			json_array_push(structures[i], json_integer_new(outputData[i].razorfinsBought));
			json_array_push(structures[i], json_integer_new(outputData[i].ironbacksBought));
			json_array_push(structures[i], json_integer_new(outputData[i].plundercrabsBought));
			json_array_push(structures[i], json_integer_new(outputData[i].ocklepodsBought));

			json_array_push(structures[i], json_integer_new(outputData[i].offensiveBuilds));
			json_array_push(structures[i], json_integer_new(outputData[i].defensiveBuilds));

			json_array_push(structures[i], json_integer_new(outputData[i].totalDamageTaken));
			json_array_push(structures[i], json_integer_new(outputData[i].totalDamageDealt));

			json_array_push(structures[i], json_integer_new(outputData[i].wins));
			json_array_push(structures[i], json_integer_new(outputData[i].picks));

			//add it to the output array
			json_array_push(outputArray, structures[i]);
		}
	}
	
	//for every brawler
	for (int i = 0; i < 4; i++) {
		//make it a new array
		brawlerStructs[i] = json_array_new(6);

		//push the appropriate data into it
		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].offensiveBuilds));
		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].defensiveBuilds));

		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].totalDamageTakenByBuyers));
		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].totalDamageDealtByBuyers));

		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].wins));
		json_array_push(brawlerStructs[i], json_integer_new(outputBrawlerData[i].picks));

		json_value *boughtObject = json_object_new(0);

		for (int j = 0; j < 8192; j++) {
			if (outputBrawlerData[i].itemsBought[j] < 1) continue;
			char itemName[63];
			snprintf(itemName, 62, "%d", j);

			json_object_push(boughtObject, itemName, json_integer_new(outputBrawlerData[i].itemsBought[j]));
		}

		json_array_push(brawlerStructs[i], boughtObject);

		//add it to the output array
		json_array_push(outputBrawlerArray, brawlerStructs[i]);
	}

	json_serialize_opts opts;
	opts.mode = json_serialize_mode_packed;

	int length = json_measure_ex(outputArray, opts);
	char *outputJSONString = malloc(length);

	json_serialize_ex(outputJSONString, outputArray, opts);

	fwrite(outputJSONString, sizeof(char), length, outputDataFileStream);


	length = json_measure_ex(outputBrawlerArray, opts);
	char *outputJSONString_brawlers = malloc(length);

	json_serialize_ex(outputJSONString_brawlers, outputBrawlerArray, opts);

	fwrite(outputJSONString_brawlers, sizeof(char), length, outputBrawlerDataFileStream);

	fcloseall();

	//json_builder_free(outputArray);
	//json_builder_free(outputBrawlerArray);
	json_value_free(matchIdArray);
	return;
}
Example #8
0
clib_package_t *
clib_package_new(const char *json, int verbose) {
  if (!json) return NULL;

  clib_package_t *pkg = malloc(sizeof(clib_package_t));
  if (!pkg) return NULL;

  JSON_Value *root = json_parse_string(json);
  if (!root) {
    clib_package_free(pkg);
    return NULL;
  }

  JSON_Object *json_object = json_value_get_object(root);
  if (!json_object) {
    if (verbose) clib_package_error("error", "unable to parse json");
    json_value_free(root);
    clib_package_free(pkg);
    return NULL;
  }

  pkg->json = str_copy(json);
  pkg->name = json_object_get_string_safe(json_object, "name");

  pkg->repo = NULL;
  pkg->repo = json_object_get_string_safe(json_object, "repo");
  if (NULL != pkg->repo) {
    pkg->author = clib_package_parse_author(pkg->repo);
    // repo name may not be the package's name.  for example:
    //   stephenmathieson/str-replace.c -> str-replace
    pkg->repo_name = clib_package_parse_name(pkg->repo);
    // TODO support npm-style "repository"?
  } else {
    if (verbose) clib_package_warn("warning", "missing repo in package.json");
    pkg->author = NULL;
    pkg->repo_name = NULL;
  }

  pkg->version = json_object_get_string_safe(json_object, "version");
  pkg->license = json_object_get_string_safe(json_object, "license");
  pkg->description = json_object_get_string_safe(json_object, "description");
  pkg->install = json_object_get_string_safe(json_object, "install");

  JSON_Array *src = json_object_get_array(json_object, "src");
  if (src) {
    pkg->src = list_new();
    if (!pkg->src) {
      json_value_free(root);
      clib_package_free(pkg);
      return NULL;
    }

    for (size_t i = 0; i < json_array_get_count(src); i++) {
      char *file = json_array_get_string_safe(src, i);
      if (!file) break; // TODO fail?
      list_node_t *node = list_node_new(file);
      list_rpush(pkg->src, node);
    }
  } else {
    pkg->src = NULL;
  }

  JSON_Object *deps = json_object_get_object(json_object, "dependencies");
  pkg->dependencies = parse_package_deps(deps);

  JSON_Object *devs = json_object_get_object(json_object, "development");
  pkg->development = parse_package_deps(devs);

  json_value_free(root);
  return pkg;
}
Example #9
0
jconf_t *
read_jconf(const char *file)
{
    static jconf_t conf;

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

    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 = ss_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 = { 0UL, 0, NULL, NULL, NULL };
    char error_buf[512];
    obj = json_parse_ex(&settings, buf, pos, error_buf);

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

    if (obj->type == json_object) {
        unsigned 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];
                        char *addr_str = to_string(v);
                        parse_addr(addr_str, conf.remote_addr + j);
                        ss_free(addr_str);
                        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, "timeout") == 0) {
                conf.timeout = to_string(value);
            } else if (strcmp(name, "user") == 0) {
                conf.user = to_string(value);
            } else if (strcmp(name, "obfs") == 0) {
                conf.obfs = to_string(value);
            } else if (strcmp(name, "obfs_host") == 0) {
                conf.obfs_host = to_string(value);
            } else if (strcmp(name, "obfs_uri") == 0) {
                conf.obfs_uri = to_string(value);
            } else if (strcmp(name, "http_method") == 0) {
                conf.http_method = to_string(value);
            } else if (strcmp(name, "failover") == 0) {
                conf.failover = to_string(value);
            } else if (strcmp(name, "fast_open") == 0) {
                check_json_value_type(value, json_boolean,
                        "invalid config file: option 'fast_open' must be a boolean");
                conf.fast_open = value->u.boolean;
            } else if (strcmp(name, "nofile") == 0) {
                check_json_value_type(value, json_integer,
                    "invalid config file: option 'nofile' must be an integer");
                conf.nofile = value->u.integer;
            } else if (strcmp(name, "nameserver") == 0) {
                conf.nameserver = to_string(value);
            } else if (strcmp(name, "dst_addr") == 0) {
                conf.dst_addr = to_string(value);
            } else if (strcmp(name, "mptcp") == 0) {
                check_json_value_type(value, json_boolean,
                    "invalid config file: option 'mptcp' must be a boolean");
                conf.mptcp = value->u.boolean;
            } else if (strcmp(name, "ipv6_first") == 0) {
                check_json_value_type(value, json_boolean,
                    "invalid config file: option 'ipv6_first' must be a boolean");
                conf.ipv6_first = value->u.boolean;
            } else if (strcmp(name, "reverse_proxy") == 0) {
                check_json_value_type(value, json_boolean,
                    "invalid config file: option 'reverse_proxy' must be a boolean");
                conf.reverse_proxy = value->u.boolean;
            }
        }
    } else {
        FATAL("Invalid config file");
    }

    ss_free(buf);
    json_value_free(obj);
    return &conf;
}
Example #10
0
void CCountryFlags::LoadCountryflagsIndexfile()
{
	// read file data into buffer
	const char *pFilename = "countryflags/index.json";
	IOHANDLE File = Storage()->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!File)
	{
		Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "couldn't open index file");
		return;
	}
	int FileSize = (int)io_length(File);
	char *pFileData = (char *)mem_alloc(FileSize, 1);
	io_read(File, pFileData, FileSize);
	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, FileSize, aError);
	mem_free(pFileData);

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

	// extract data
	const json_value &rInit = (*pJsonData)["country codes"];
	if(rInit.type == json_object)
	{
		enum
		{
			NUM_INDICES = 2,
		};
		const char *paIndices[NUM_INDICES] = {"custom", "ISO 3166-1"};
		for(int Index = 0; Index < NUM_INDICES; ++Index)
		{
			const json_value &rStart = rInit[(const char *)paIndices[Index]];
			if(rStart.type == json_array)
			{
				for(unsigned i = 0; i < rStart.u.array.length; ++i)
				{
					char aBuf[64];

					// validate country code
					int CountryCode = (json_int_t)rStart[i]["code"];
					if(CountryCode < CODE_LB || CountryCode > CODE_UB)
					{
						str_format(aBuf, sizeof(aBuf), "country code '%i' not within valid code range [%i..%i]", CountryCode, CODE_LB, CODE_UB);
						Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
						continue;
					}

					// add entry
					const char *pCountryName = rStart[i]["id"];
					CCountryFlag CountryFlag;
					CountryFlag.m_CountryCode = CountryCode;
					str_copy(CountryFlag.m_aCountryCodeString, pCountryName, sizeof(CountryFlag.m_aCountryCodeString));
					if(g_Config.m_ClLoadCountryFlags)
					{
						// load the graphic file
						CImageInfo Info;
						str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", pCountryName);
						if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))
						{
							char aMsg[64];
							str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf);
							Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg);
							continue;
						}
						CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
						mem_free(Info.m_pData);
					}
					m_aCountryFlags.add_unsorted(CountryFlag);

					// print message
					if(g_Config.m_Debug)
					{
						str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", pCountryName);
						Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
					}
				}
			}
		}
	}

	// clean up
	json_value_free(pJsonData);
	m_aCountryFlags.sort_range();

	// find index of default item
	int DefaultIndex = 0, Index = 0;
	for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index)
		if(r.front().m_CountryCode == -1)
		{
			DefaultIndex = Index;
			break;
		}

	// init LUT
	if(DefaultIndex != 0)
		for(int i = 0; i < CODE_RANGE; ++i)
			m_CodeIndexLUT[i] = DefaultIndex;
	else
		mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));
	for(int i = 0; i < m_aCountryFlags.size(); ++i)
		m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i;
}
Example #11
0
/**
 *
 * @property: (in): encoders.x.elements.element.property.name or source.elements.element.property.name
 */
gchar * jobdesc_element_property_value (gchar *job, gchar *property)
{
        JSON_Value *val;
        JSON_Object *obj;
        JSON_Array *array;
        JSON_Value_Type type;
        JSON_Value *value;
        gchar *p;
        gint64 i;
        gdouble n;
        gint index;

        val = json_parse_string_with_comments (job);
        obj = json_value_get_object (val);
        if (g_str_has_prefix (property, "encoder")) {
                array = json_object_dotget_array (obj, "encoders");
                sscanf (property, "encoder.%d", &index);
                obj = json_array_get_object (array, index);
                p = g_strrstr (property, "elements");
                value = json_object_dotget_value (obj, p);

        } else if (g_str_has_prefix (property, "source")) {
                value = json_object_dotget_value (obj, property);
        }
        if (value == NULL) {
                json_value_free (val);
                return NULL;
        }
        type = json_value_get_type (value);
        switch (type) {
        case JSONString:
                p = g_strdup (json_value_get_string (value));
                break;

        case JSONNumber:
                n = json_value_get_number (value);
                i = n;
                if (i == n) {
                        p = g_strdup_printf ("%ld", i);

                } else {
                        p = g_strdup_printf ("%f", n);
                }
                break;

        case JSONBoolean:
                if (json_value_get_boolean (value)) {
                        p = g_strdup ("TRUE");

                } else {
                        p = g_strdup ("FALSE");
                }
                break;

        default:
                GST_ERROR ("property value invalid.");
        }
        json_value_free (val);

        return p;
}
int parse_SX1301_configuration(const char * conf_file) {
	int i;
	const char conf_obj[] = "SX1301_conf";
	char param_name[32]; /* used to generate variable parameter names */
	const char *str; /* used to store string value from JSON object */
	struct lgw_conf_board_s boardconf;
	struct lgw_conf_rxrf_s rfconf;
	struct lgw_conf_rxif_s ifconf;
	JSON_Value *root_val;
	JSON_Object *root = NULL;
	JSON_Object *conf = NULL;
	JSON_Value *val;
	uint32_t sf, bw;
	
	/* try to parse JSON */
	root_val = json_parse_file_with_comments(conf_file);
	root = json_value_get_object(root_val);
	if (root == NULL) {
		MSG("ERROR: %s id not a valid JSON file\n", conf_file);
		exit(EXIT_FAILURE);
	}
	conf = json_object_get_object(root, conf_obj);
	if (conf == NULL) {
		MSG("INFO: %s does not contain a JSON object named %s\n", conf_file, conf_obj);
		return -1;
	} else {
		MSG("INFO: %s does contain a JSON object named %s, parsing SX1301 parameters\n", conf_file, conf_obj);
	}

	/* set board configuration */
	memset(&boardconf, 0, sizeof boardconf); /* initialize configuration structure */
	val = json_object_get_value(conf, "lorawan_public"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONBoolean) {
		boardconf.lorawan_public = (bool)json_value_get_boolean(val);
	} else {
		MSG("WARNING: Data type for lorawan_public seems wrong, please check\n");
		boardconf.lorawan_public = false;
	}
	val = json_object_get_value(conf, "clksrc"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONNumber) {
		boardconf.clksrc = (uint8_t)json_value_get_number(val);
	} else {
		MSG("WARNING: Data type for clksrc seems wrong, please check\n");
		boardconf.clksrc = 0;
	}
	MSG("INFO: lorawan_public %d, clksrc %d\n", boardconf.lorawan_public, boardconf.clksrc);
	/* all parameters parsed, submitting configuration to the HAL */
        if (lgw_board_setconf(boardconf) != LGW_HAL_SUCCESS) {
                MSG("WARNING: Failed to configure board\n");
	}

	/* set configuration for RF chains */
	for (i = 0; i < LGW_RF_CHAIN_NB; ++i) {
		memset(&rfconf, 0, sizeof(rfconf)); /* initialize configuration structure */
		sprintf(param_name, "radio_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for radio %i\n", i);
			continue;
		}
		/* there is an object to configure that radio, let's parse it */
		sprintf(param_name, "radio_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			rfconf.enable = (bool)json_value_get_boolean(val);
		} else {
			rfconf.enable = false;
		}
		if (rfconf.enable == false) { /* radio disabled, nothing else to parse */
			MSG("INFO: radio %i disabled\n", i);
		} else  { /* radio enabled, will parse the other parameters */
			snprintf(param_name, sizeof param_name, "radio_%i.freq", i);
			rfconf.freq_hz = (uint32_t)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.rssi_offset", i);
			rfconf.rssi_offset = (float)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.type", i);
			str = json_object_dotget_string(conf, param_name);
			if (!strncmp(str, "SX1255", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1255;
			} else if (!strncmp(str, "SX1257", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1257;
			} else {
				MSG("WARNING: invalid radio type: %s (should be SX1255 or SX1257)\n", str);
			}
			snprintf(param_name, sizeof param_name, "radio_%i.tx_enable", i);
			val = json_object_dotget_value(conf, param_name);
			if (json_value_get_type(val) == JSONBoolean) {
				rfconf.tx_enable = (bool)json_value_get_boolean(val);
			} else {
				rfconf.tx_enable = false;
			}
			MSG("INFO: radio %i enabled (type %s), center frequency %u, RSSI offset %f, tx enabled %d\n", i, str, rfconf.freq_hz, rfconf.rssi_offset, rfconf.tx_enable);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxrf_setconf(i, rfconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for radio %i\n", i);
		}
	}
	
	/* set configuration for LoRa multi-SF channels (bandwidth cannot be set) */
	for (i = 0; i < LGW_MULTI_NB; ++i) {
		memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
		sprintf(param_name, "chan_multiSF_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for LoRa multi-SF channel %i\n", i);
			continue;
		}
		/* there is an object to configure that LoRa multi-SF channel, let's parse it */
		sprintf(param_name, "chan_multiSF_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) { /* LoRa multi-SF channel disabled, nothing else to parse */
			MSG("INFO: LoRa multi-SF channel %i disabled\n", i);
		} else  { /* LoRa multi-SF channel enabled, will parse the other parameters */
			sprintf(param_name, "chan_multiSF_%i.radio", i);
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, param_name);
			sprintf(param_name, "chan_multiSF_%i.if", i);
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, param_name);
			// TODO: handle individual SF enabling and disabling (spread_factor)
			MSG("INFO: LoRa multi-SF channel %i enabled, radio %i selected, IF %i Hz, 125 kHz bandwidth, SF 7 to 12\n", i, ifconf.rf_chain, ifconf.freq_hz);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxif_setconf(i, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa multi-SF channel %i\n", i);
		}
	}
	
	/* set configuration for LoRa standard channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_Lora_std"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for LoRa standard channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_Lora_std.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: LoRa standard channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_Lora_std.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.bandwidth");
			switch(bw) {
				case 500000: ifconf.bandwidth = BW_500KHZ; break;
				case 250000: ifconf.bandwidth = BW_250KHZ; break;
				case 125000: ifconf.bandwidth = BW_125KHZ; break;
				default: ifconf.bandwidth = BW_UNDEFINED;
			}
			sf = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.spread_factor");
			switch(sf) {
				case  7: ifconf.datarate = DR_LORA_SF7;  break;
				case  8: ifconf.datarate = DR_LORA_SF8;  break;
				case  9: ifconf.datarate = DR_LORA_SF9;  break;
				case 10: ifconf.datarate = DR_LORA_SF10; break;
				case 11: ifconf.datarate = DR_LORA_SF11; break;
				case 12: ifconf.datarate = DR_LORA_SF12; break;
				default: ifconf.datarate = DR_UNDEFINED;
			}
			MSG("INFO: LoRa standard channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, SF %u\n", ifconf.rf_chain, ifconf.freq_hz, bw, sf);
		}
		if (lgw_rxif_setconf(8, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa standard channel\n");
		}
	}
	
	/* set configuration for FSK channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_FSK"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for FSK channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_FSK.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: FSK channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_FSK.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_FSK.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_FSK.bandwidth");
			if      (bw <= 7800)   ifconf.bandwidth = BW_7K8HZ;
			else if (bw <= 15600)  ifconf.bandwidth = BW_15K6HZ;
			else if (bw <= 31200)  ifconf.bandwidth = BW_31K2HZ;
			else if (bw <= 62500)  ifconf.bandwidth = BW_62K5HZ;
			else if (bw <= 125000) ifconf.bandwidth = BW_125KHZ;
			else if (bw <= 250000) ifconf.bandwidth = BW_250KHZ;
			else if (bw <= 500000) ifconf.bandwidth = BW_500KHZ;
			else ifconf.bandwidth = BW_UNDEFINED;
			ifconf.datarate = (uint32_t)json_object_dotget_number(conf, "chan_FSK.datarate");
			MSG("INFO: FSK channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, %u bps datarate\n", ifconf.rf_chain, ifconf.freq_hz, bw, ifconf.datarate);
		}
		if (lgw_rxif_setconf(9, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for FSK channel\n");
		}
	}
	json_value_free(root_val);
	return 0;
}
Example #13
0
static struct host
parseHost
(json_value *hostObj, int *ret)
{
  json_value *jName = json_find(hostObj, "name", json_string);
  json_value *jMac  = json_find(hostObj, "mac",  json_string);

  if ((NULL == jName) || (NULL == jMac))
    return (*ret = 1), (struct host) {0};

  struct host result = {
    .name       = utilStringDup(jName->u.string.ptr),
    .macAddress = utilStringDup(jMac->u.string.ptr)
  };

  return result;
}

static struct host *
parseHosts
(json_value *root, size_t *numHosts)
{
  json_value *jHosts = json_find(root, "hosts", json_array);
  if (NULL == jHosts)
    return NULL;

  const size_t numJHosts     = jHosts->u.array.length;
  struct host *result = calloc(numJHosts, sizeof(*result));

  for (size_t i=0; i<numJHosts; i++)
  {
    json_value *jHostObj = jHosts->u.array.values[i];

    int ret   = 0;
    result[i] = parseHost(jHostObj, &ret);
    
    if (ret)
    {
      free(result);
      return NULL;
    }
  }

  *numHosts = numJHosts;
  return result;
}

static struct resource
parseResource
(json_value *jResource, int *ret)
{
  json_value *jName = json_find(jResource, "name", json_string);
  json_value *jHost = json_find(jResource, "host", json_string);
  json_value *jVars = json_find(jResource, "vars", json_array);
  
  if ((NULL == jName) || (NULL == jHost) || (NULL == jVars))
    return (*ret = 1), (struct resource) {0};

  const size_t numVars = jVars->u.array.length;
  char **keyMap = calloc(numVars, sizeof(char *));
  char **valMap = calloc(numVars, sizeof(char *));

  for (size_t i=0; i<numVars; i++)
  {
    json_value *jVar = jVars->u.array.values[i];
    if (jVar->type != json_array)
      return (*ret = 1), (struct resource) {0};

    if (jVar->u.array.length != 2)
      return (*ret = 1), (struct resource) {0};

    json_value *jKey = jVar->u.array.values[0];
    json_value *jVal = jVar->u.array.values[1];

    if (jKey->type != json_string)
      return (*ret = 1), (struct resource) {0};

    if (jVal->type != json_string)
      return (*ret = 1), (struct resource) {0};

    keyMap[i] = utilStringDup(jKey->u.string.ptr);
    valMap[i] = utilStringDup(jVal->u.string.ptr);
  }

  struct resource result = {
    .name     = utilStringDup(jName->u.string.ptr),
    .host     = utilStringDup(jHost->u.string.ptr),
    .numVars  = numVars,
    .keyMap   = keyMap,
    .valMap   = valMap,
  };

  return result;
}

struct resource *
parseResources
(json_value *root, size_t *numResources)
{
  json_value *jResources = json_find(root, "resources", json_array);
  if (NULL == jResources)
    return NULL;

  const size_t numJResources  = jResources->u.array.length;
  struct resource *result     = calloc(numJResources, sizeof(*result));
  
  for (size_t i=0; i<numJResources; i++)
  {
    json_value *jResource = jResources->u.array.values[i];

    int ret       = 0;
    result[i]     = parseResource(jResource, &ret);
    result[i].id  = i;

    #if defined(CLUSTERD_BUILD)
      result[i].mutex = calloc(1, sizeof(pthread_mutex_t));
      result[i].inUse = calloc(1, sizeof(bool));
      pthread_mutex_init(result[i].mutex, NULL);
    #endif
  }

  *numResources = numJResources;
  return result;
}

configuration *
parseConfiguration
(void)
{
  char *jsonConfig = readFile(_configPath);
  if (NULL == jsonConfig)
  {
    fprintf(stderr, "Error: Unable to read configuration file\n");
    fprintf(stderr, "Does %s exist?\n", _configPath);
    return NULL;
  }

  json_value *root = json_parse(jsonConfig, strlen(jsonConfig));
  free(jsonConfig);
  if (NULL == root)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse json\n");
    return NULL;
  }

  configuration *result = calloc(1, sizeof(configuration));
  result->hosts = parseHosts(root, &result->numHosts);
  if (NULL == result->hosts)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse hosts\n");
    return NULL;
  }

  result->resources = parseResources(root, &result->numResources);
  if (NULL == result->hosts)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse resources\n");
    return NULL;
  }

  json_value *jMaster = json_find(root, "master", json_string);
  if (NULL == jMaster)
  {
    fprintf(stderr, "Error: No master hostname set\n");
    return NULL;
  }

  if (jMaster->type != json_string)
  {
    fprintf(stderr, "Error: Master feild is not a string\n");
    return NULL;
  }

  result->master = utilStringDup(jMaster->u.string.ptr);

  json_value_free(root);

  return result;
}
Example #14
0
static ACVP_RESULT execute_network_action(ACVP_CTX *ctx,
                                          ACVP_NET_ACTION action,
                                          char *url,
                                          char *data,
                                          int data_len,
                                          int *curl_code) {
    ACVP_RESULT result = 0;
    char *resp = NULL;
    char large_url[ACVP_ATTR_URL_MAX + 1] = {0};
    int large_submission = 0;
    int resp_len = 0;
    int rc = 0;

    switch(action) {
    case ACVP_NET_GET:
    case ACVP_NET_GET_VS:
    case ACVP_NET_GET_VS_RESULT:
    case ACVP_NET_GET_VS_SAMPLE:
        rc = acvp_curl_http_get(ctx, url);
        break;

    case ACVP_NET_POST:
    case ACVP_NET_POST_LOGIN:
    case ACVP_NET_POST_REG:
        rc = acvp_curl_http_post(ctx, url, data, data_len);
        break;

    case ACVP_NET_POST_VS_RESP:
        resp = json_serialize_to_string(ctx->kat_resp, &resp_len);
        if (!resp) {
            ACVP_LOG_ERR("Faled to serialize JSON to string");
            return ACVP_JSON_ERR;
        }
        json_value_free(ctx->kat_resp);
        ctx->kat_resp = NULL;

        if (ctx->post_size_constraint && resp_len > ctx->post_size_constraint) {
            /* Determine if this POST body goes over the "constraint" */
            large_submission = 1;
        }

        if (large_submission) {
            /*
             * Need to tell the server about this large submission.
             * The server will supply us with a one-time "large" URL;
             */
            result = acvp_notify_large(ctx, url, large_url, resp_len);
            if (result != ACVP_SUCCESS) goto end;

            rc = acvp_curl_http_post(ctx, large_url, resp, resp_len);
        } else {
            rc = acvp_curl_http_post(ctx, url, resp, resp_len);
        }

        break;

    default:
        ACVP_LOG_ERR("Unknown ACVP_NET_ACTION");
        return ACVP_INVALID_ARG;
    }

    /* Peek at the HTTP code */
    result = inspect_http_code(ctx, rc);

    if (result != ACVP_SUCCESS) {
        if (result == ACVP_JWT_EXPIRED &&
            action != ACVP_NET_POST_LOGIN) {
            /*
             * Expired JWT
             * We are going to refresh the session
             * and try to obtain a new JWT!
             * This should not ever happen during "login"...
             * and we need to avoid an infinite loop (via acvp_refesh).
             */
            ACVP_LOG_ERR("JWT authorization has timed out, curl rc=%d.\n"
                         "Refreshing session...", rc);

            result = acvp_refresh(ctx);
            if (result != ACVP_SUCCESS) {
                ACVP_LOG_ERR("JWT refresh failed.");
                goto end;
            }

            /* Try action again after the refresh */
            switch(action) {
            case ACVP_NET_GET:
            case ACVP_NET_GET_VS:
            case ACVP_NET_GET_VS_RESULT:
            case ACVP_NET_GET_VS_SAMPLE:
                rc = acvp_curl_http_get(ctx, url);
                break;

            case ACVP_NET_POST:
            case ACVP_NET_POST_REG:
                rc = acvp_curl_http_post(ctx, url, data, data_len);
                break;

            case ACVP_NET_POST_VS_RESP:
                if (large_submission) {
                    rc = acvp_curl_http_post(ctx, large_url, resp, resp_len);
                } else {
                    rc = acvp_curl_http_post(ctx, url, resp, resp_len);
                }
                break;

            case ACVP_NET_POST_LOGIN:
                ACVP_LOG_ERR("We should never be here!");
                break;
            }

            result = inspect_http_code(ctx, rc);
            if (result != ACVP_SUCCESS) {
                ACVP_LOG_ERR("Refreshed + retried, HTTP transport fails. curl rc=%d\n", rc);
                goto end;
            }
        } else if (result == ACVP_JWT_INVALID) {
            /*
             * Invalid JWT
             */
            ACVP_LOG_ERR("JWT invalid. curl rc=%d.\n", rc);
            goto end;
        }

        /* Generic error */
        goto end;
    }

    result = ACVP_SUCCESS;

end:
    if (resp) json_free_serialized_string(resp);

    *curl_code = rc;

    return result;
}
Example #15
0
File: pcp.c Project: pgpool/pgpool2
static void
process_watchdog_info_response(PCPConnInfo * pcpConn, char *buf, int len)
{
	char	   *json_data = NULL;
	PCPWDClusterInfo *wd_cluster_info = NULL;
	int			clusterDataSize = 0;

	if (strcmp(buf, "CommandComplete") == 0)
	{
		int			tempVal;
		char	   *ptr;

		json_data = (char *) memchr(buf, '\0', len);
		if (json_data == NULL)
			goto INVALID_RESPONSE;
		json_data += 1;

		json_value *root;
		json_value *value;
		int			i,
					nodeCount;

		root = json_parse(json_data, len);

		/* The root node must be object */
		if (root == NULL || root->type != json_object)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		if (json_get_int_value_for_key(root, "NodeCount", &nodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		/* find the WatchdogNodes array */
		value = json_get_value_for_key(root, "WatchdogNodes");
		if (value == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (value->type != json_array)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (nodeCount != value->u.array.length)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		/* create the cluster object */
		clusterDataSize = sizeof(PCPWDClusterInfo) + (sizeof(PCPWDNodeInfo) * nodeCount);
		wd_cluster_info = malloc(clusterDataSize);

		wd_cluster_info->nodeCount = nodeCount;

		if (json_get_int_value_for_key(root, "RemoteNodeCount", &wd_cluster_info->remoteNodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "QuorumStatus", &wd_cluster_info->quorumStatus))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "AliveNodeCount", &wd_cluster_info->aliveNodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "Escalated", &tempVal))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		wd_cluster_info->escalated = tempVal == 0 ? false : true;

		ptr = json_get_string_value_for_key(root, "MasterNodeName");
		if (ptr == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		strncpy(wd_cluster_info->masterNodeName, ptr, sizeof(wd_cluster_info->masterNodeName) - 1);

		ptr = json_get_string_value_for_key(root, "MasterHostName");
		if (ptr == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		strncpy(wd_cluster_info->masterHostName, ptr, sizeof(wd_cluster_info->masterHostName) - 1);

		/* Get watchdog nodes data */
		for (i = 0; i < nodeCount; i++)
		{
			char	   *ptr;
			json_value *nodeInfoValue = value->u.array.values[i];
			PCPWDNodeInfo *wdNodeInfo = &wd_cluster_info->nodeList[i];

			if (nodeInfoValue->type != json_object)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "ID", &wdNodeInfo->id))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			ptr = json_get_string_value_for_key(nodeInfoValue, "NodeName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->nodeName, ptr, sizeof(wdNodeInfo->nodeName) - 1);

			ptr = json_get_string_value_for_key(nodeInfoValue, "HostName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->hostName, ptr, sizeof(wdNodeInfo->hostName) - 1);

			ptr = json_get_string_value_for_key(nodeInfoValue, "DelegateIP");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->delegate_ip, ptr, sizeof(wdNodeInfo->delegate_ip) - 1);

			if (json_get_int_value_for_key(nodeInfoValue, "WdPort", &wdNodeInfo->wd_port))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "PgpoolPort", &wdNodeInfo->pgpool_port))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "State", &wdNodeInfo->state))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			ptr = json_get_string_value_for_key(nodeInfoValue, "StateName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->stateName, ptr, sizeof(wdNodeInfo->stateName) - 1);

			if (json_get_int_value_for_key(nodeInfoValue, "Priority", &wdNodeInfo->wd_priority))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

		}
		json_value_free(root);

		if (setNextResultBinaryData(pcpConn->pcpResInfo, (void *) wd_cluster_info, clusterDataSize, NULL) < 0)
			goto INVALID_RESPONSE;

		setCommandSuccessful(pcpConn);
	}
	else
	{
		pcp_internal_error(pcpConn,
						   "command failed with reason: \"%s\"\n", buf);
		setResultStatus(pcpConn, PCP_RES_BAD_RESPONSE);
	}
	return;

INVALID_RESPONSE:

	if (wd_cluster_info)
		pfree(wd_cluster_info);
	pcp_internal_error(pcpConn,
					   "command failed. invalid response\n");
	setResultStatus(pcpConn, PCP_RES_BAD_RESPONSE);
}
Example #16
0
static void json_array_free(JSON_Array *array) {
    size_t i;
    for (i = 0; i < array->count; i++) { json_value_free(array->items[i]); }
    parson_free(array->items);
    parson_free(array);
}
Example #17
0
int main (int argc, char *argv[])
{
    HTTPMgmt *httpmgmt;
    HTTPStreaming *httpstreaming;
    GMainLoop *loop;
    GOptionContext *ctx;
    GError *err = NULL;
    gint mode;
    struct rlimit rlim;
    GDateTime *datetime;
    gchar exe_path[512], *date;

    ctx = g_option_context_new (NULL);
    g_option_context_add_main_entries (ctx, options, NULL);
    g_option_context_add_group (ctx, gst_init_get_option_group ());
    if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
        g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
        exit (1);
    }
    g_option_context_free (ctx);
    GST_DEBUG_CATEGORY_INIT (GSTREAMILL, "gstreamill", 0, "gstreamill log");

    if (version) {
        print_version_info ();
        exit (0);
    }

    /* stop gstreamill. */
    if (stop) {
        gchar *pid_str;
        gint pid;

        g_file_get_contents (PID_FILE, &pid_str, NULL, NULL);
        if (pid_str == NULL) {
            g_print ("File %s not found, check if gstreamill is running.\n", PID_FILE);
            exit (1);
        }
        pid = atoi (pid_str);
        g_free (pid_str);
        g_print ("stoping gstreamill with pid %d ...\n", pid);
        kill (pid, SIGTERM);
        exit (0);
    }

    /* readlink exe path before setuid, on CentOS, readlink exe path after setgid/setuid failure on permission denied */
    memset (exe_path, '\0', sizeof (exe_path));
    if (readlink ("/proc/self/exe", exe_path, sizeof (exe_path)) == -1) {
        g_print ("Read /proc/self/exe error: %s", g_strerror (errno));
        exit (2);
    }

    if (prepare_gstreamill_run_dir () != 0) {
        g_print ("Can't create gstreamill run directory\n");
        exit (3);
    }
    /*
       if (set_user_and_group () != 0) {
       g_print ("set user and group failure\n");
       exit (4);
       }
     */

    mode = DAEMON_MODE;
    if (job_file != NULL) {
        /* gstreamill command with job, running in single job mode */
        mode = SINGLE_JOB_MODE;

    } else if (debug) {
        /* gstreamill command without job, run in background */
        mode = DEBUG_MODE;
    }

    if (gst_debug_get_default_threshold () < GST_LEVEL_WARNING) {
        gst_debug_set_default_threshold (GST_LEVEL_WARNING);
    }

    /* initialize ts segment static plugin */
    if (!gst_plugin_register_static (GST_VERSION_MAJOR,
                GST_VERSION_MINOR,
                "tssegment",
                "ts segment plugin",
                ts_segment_plugin_init,
                "0.1.0",
                "GPL",
                "GStreamer",
                "GStreamer",
                "http://gstreamer.net/")) {
        GST_ERROR ("registe tssegment error");
        exit (17);
    }

    /* subprocess, create_job_process */
    if (shm_name != NULL) {
        gint fd;
        gchar *job_desc, *p;
        Job *job;
        gchar *log_path, *name;
        gint ret;

        /* set subprocess maximum of core file */
        rlim.rlim_cur = 0;
        rlim.rlim_max = 0;
        if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
            GST_ERROR ("setrlimit error: %s", g_strerror (errno));
        }

        /* read job description from share memory */
        job_desc = NULL;
        fd = shm_open (shm_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        if (ftruncate (fd, shm_length) == -1) {
            exit (5);
        }
        p = mmap (NULL, shm_length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        job_desc = g_strndup (p, job_length);

        if ((job_desc != NULL) && (!jobdesc_is_valid (job_desc))) {
            exit (6);
        }

        /* initialize log */
        name = (gchar *)jobdesc_get_name (job_desc);
        if (!jobdesc_is_live (job_desc)) {
            gchar *path;

            path = jobdesc_get_log_path (job_desc);
            log_path = g_build_filename (path, "gstreamill.log", NULL);
            g_free (path);

        } else {
            log_path = g_build_filename (log_dir, name, "gstreamill.log", NULL);
        }
        ret = init_log (log_path);
        g_free (log_path);
        if (ret != 0) {
            exit (7);
        }

        /* launch a job. */
        datetime = g_date_time_new_now_local ();
        date = g_date_time_format (datetime, "%b %d %H:%M:%S");
        fprintf (_log->log_hd, "\n*** %s : job %s starting ***\n\n", date, name);
        g_date_time_unref (datetime);
        g_free (date);
        job = job_new ("name", name, "job", job_desc, NULL);
        job->is_live = jobdesc_is_live (job_desc);
        job->eos = FALSE;
        loop = g_main_loop_new (NULL, FALSE);

        GST_INFO ("Initializing job ...");
        if (job_initialize (job, TRUE, fd, p) != 0) {
            GST_ERROR ("initialize job failure, exit");
            exit (8);
        }
        GST_INFO ("Initializing job done");

        GST_INFO ("Initializing job's encoders output ...");
        if (job_encoders_output_initialize (job) != 0) {
            GST_ERROR ("initialize job encoders' output failure, exit");
            exit (8);
        }
        GST_INFO ("Initializing job's encoders output done");

        GST_INFO ("Starting job ...");
        if (job_start (job) != 0) {
            GST_WARNING ("start livejob failure, exit");
            exit (9);
        }
        datetime = g_date_time_new_now_local ();
        date = g_date_time_format (datetime, "%b %d %H:%M:%S");
        fprintf (_log->log_hd, "\n*** %s : job %s started ***\n\n", date, name);
        g_date_time_unref (datetime);
        g_free (date);
        g_free (name);
        g_free (job_desc);

        signal (SIGPIPE, SIG_IGN);
        signal (SIGUSR1, sighandler);
        signal (SIGTERM, stop_job);

        g_main_loop_run (loop);

    } else {
        /* set parent process maximum of core file */
        rlim.rlim_cur = RLIM_INFINITY;
        rlim.rlim_max = RLIM_INFINITY;
        if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
            GST_ERROR ("setrlimit error: %s", g_strerror (errno));
        }
    }

    /* run in background? */
    if (mode != SINGLE_JOB_MODE) {
        gchar *path;
        gint ret;
#if 0
        /* pid file exist? */
        if (g_file_test (PID_FILE, G_FILE_TEST_EXISTS)) {
            g_print ("file %s found, gstreamill already running !!!\n", PID_FILE);
            exit (10);
        }
#endif
        /* gstreamill is running? */
        if (isrunning_gstreamill()) {
            g_print ("gstreamill already running !!!\n");
            exit (10);
        }

        /* media directory */
        path = g_strdup_printf ("%s/dvr", MEDIA_LOCATION);
        if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
            g_printf ("Create DVR directory: %s", path);
            if (g_mkdir_with_parents (path, 0755) != 0) {
                g_printf ("Create DVR directory failure: %s", path);
            }
        }
        g_free (path);
        path = g_strdup_printf ("%s/transcode/in", MEDIA_LOCATION);
        if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
            g_printf ("Create transcode directory: %s", path);
            if (g_mkdir_with_parents (path, 0755) != 0) {
                g_printf ("Create transcode directory failure: %s", path);
            }
        }
        g_free (path);
        path = g_strdup_printf ("%s/transcode/out", MEDIA_LOCATION);
        if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
            g_printf ("Create transcode directory: %s", path);
            if (g_mkdir_with_parents (path, 0755) != 0) {
                g_printf ("Create transcode directory failure: %s", path);
            }
        }
        g_free (path);

        /* if DAEMON_MODE then daemonize */
        if ((mode == DAEMON_MODE) || (mode == DEBUG_MODE)) {
            /* log to file */
            path = g_build_filename (log_dir, "gstreamill.log", NULL);
            ret = init_log (path);
            g_free (path);
            if (ret != 0) {
                g_print ("Init log error, ret %d.\n", ret);
                exit (11);
            }
        }

        /* if DAEMON_MODE then daemonize */
        if (mode == DAEMON_MODE) {
            /* daemonize */
            if (daemon (0, 0) != 0) {
                fprintf (_log->log_hd, "Failed to daemonize");
                remove_pid_file ();
                exit (1);
            }

            /* create pid file */
            if (create_pid_file () != 0) {
                exit (1);
            }
        }

        /* customize signal */
        signal (SIGUSR1, sighandler);
        signal (SIGTERM, stop_gstreamill);

        datetime = g_date_time_new_now_local ();
        date = g_date_time_format (datetime, "%b %d %H:%M:%S");
        GST_WARNING ("\n*** %s : gstreamill started ***\n\n", date);
        g_free (date);
        g_date_time_unref (datetime);
    }

    /* ignore SIGPIPE */
    signal (SIGPIPE, SIG_IGN);

    loop = g_main_loop_new (NULL, FALSE);

    /* gstreamill */
    gstreamill = gstreamill_new ("mode", mode, "log_dir", log_dir, "exe_path", exe_path, NULL);
    if (gstreamill_start (gstreamill) != 0) {
        GST_ERROR ("start gstreamill error, exit.");
        remove_pid_file ();
        exit (12);
    }

    /* httpstreaming, pull */
    httpstreaming = httpstreaming_new ("gstreamill", gstreamill, "address", http_streaming, NULL);
    if (httpstreaming_start (httpstreaming, 10) != 0) {
        GST_ERROR ("start httpstreaming error, exit.");
        remove_pid_file ();
        exit (13);
    }

    if (mode != SINGLE_JOB_MODE) {
        /* run in background, management via http */
        httpmgmt = httpmgmt_new ("gstreamill", gstreamill, "address", http_mgmt, NULL);
        if (httpmgmt_start (httpmgmt) != 0) {
            GST_ERROR ("start http mangment error, exit.");
            remove_pid_file ();
            exit (14);
        }

    } else {
        /* run in foreground, start job */
        gchar *job, *p, *result;
        JSON_Value *val;
        JSON_Object *obj;

        /* ctrl-c, stop gstreamill */
        signal (SIGINT, stop_gstreamill);

        /* ctrl-\, stop gstreamill */
        signal (SIGQUIT, stop_gstreamill);

        if (!g_file_get_contents (job_file, &job, NULL, NULL)) {
            GST_ERROR ("Read job file %s error.", job_file);
            exit (15);
        }
        p = gstreamill_job_start (gstreamill, job);
        val = json_parse_string (p);
        obj = json_value_get_object (val);
        result = (gchar *)json_object_get_string (obj, "result");
        GST_INFO ("start job result: %s.", result);
        if (g_strcmp0 (result, "success") != 0) {
            exit (16);
        }
        json_value_free (val);
        g_free (p);
    }

    g_main_loop_run (loop);

    return 0;
}
void *GetStructureFromJSON( ULONG *descr, const char *jsondata )
{
	char tmpQuery[ 1024 ];
	void *firstObject = NULL;
	void *lastObject = NULL;
	
	DEBUG("[GetStructureFromJSON] Load\n");
	
	if( jsondata == NULL  )
	{
		ERROR("Cannot parse NULL!\n");
		return NULL;
	}
	
	if( descr == NULL  )
	{
		ERROR("Data description was not provided!\n");
		return NULL;
	}
	
	if( descr[ 0 ] != SQLT_TABNAME )
	{
		ERROR("SQLT_TABNAME was not provided!\n");
		return NULL;
	}
	
	INFO("Start\n");
	
	int j = 0;
	json_char* json;
	json_value* value;
	MinNode *node = NULL;
	
		//[{'ID'= '1' , 'Name'= 'testowa' , 'API'= '11' , 'Version'= '1' , 'Author'= 'stefanek' , 'Email'= '1' , 'Description'= '*****@*****.**' , 'PEGI'= '0' , 'DateCreated'= '18' , 'DateInstalled'= '2015' }]
	//json = (json_char*)"{ \"applications\" :  [  {\"ID\": \"1\" , \"Name\": \"testowa\" , \"API\": \"11\" , \"Version\": \"1\" , \"Author\": \"stefanek\" , \"Email\": \"1\" , \"Description\": \"[email protected]\" , \"PEGI\": \"0\" , \"DateCreated\": \"18\" , \"DateInstalled\": \"2015\" }] }";

	json = (json_char*)jsondata;
	
	//DEBUG("[GetStructureFromJSON] Before parse  -> '%s' \n", json );

	value = json_parse( json, strlen( json ) );

	if (value == NULL) 
	{
		ERROR("Cannot parse string to object\n");
		return NULL;
	}
	
	if( value->type == json_object || value->type == json_array )			// ''main object"
	{
		//DEBUG("OBJECT NAME = %s value array length %d\n", value->u.object.values[0].name, value->array.length );
		
		json_value* arrval;
		
		
		DEBUG("Parse arrval type %d value type %d \n", value->type, value->type );
		
		if( value->type == json_object )
		{
			void *data = calloc( 1, descr[ SQL_DATA_STRUCTURE_SIZE ] );
		
			UBYTE *strptr = (UBYTE *)data;	// pointer to structure to which will will insert data
			ULONG *dptr = &descr[ SQL_DATA_STRUCT_START ];		// first 2 entries inform about table and size, rest information provided is about columns
				
			unsigned int i;
			
			lastObject = data;
			
			for( i=0 ; i < value->u.object.length ; i++ )
			{
				//printf("------%d ---- %s\n", i, value->u.object.values[ i ].name );
			}
			
			//DEBUG("Found obejct\n");
			
			while( dptr[0] != SQLT_END )
			{
				switch( dptr[ 0 ] )
				{
					case SQLT_NODE:
					{
					}
					break;
					
					case SQLT_IDINT:	// primary key
					case SQLT_INT:
					{
						int retPos = -1;
						//DEBUG("FIND INT!\n");
						
						for( i = 0; i <  value->u.object.length; i++) 
						{
							//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
							if( strcmp( value->u.object.values[i].name, (char *) dptr[1] ) == 0 )
							{
								retPos = i;
							}
						}
						
						json_value*mval = NULL;
						if( retPos >= 0 )
						{
							mval = value->u.object.values[retPos].value;
						}
						
						if( retPos >= 0 && mval->type == json_integer )
						{
							//DEBUG("ENTRY FOUND %s  int val %d\n",(char *) dptr[ 1 ], mval->u.integer );
							memcpy( strptr + dptr[ 2 ], &(mval->u.integer), sizeof( int ) );
						}
					}
					break;
						
					case SQLT_STR:
					case SQLT_TIMESTAMP:
					{
						int retPos = -1;
						for( i = 0; i <  value->u.object.length; i++) 
						{
							//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, value->u.object.values[i].name);
							if( strcmp( value->u.object.values[i].name, (char *)dptr[1] ) == 0 )
							{
								retPos = i;
							}
						}
						
						json_value*mval = NULL;
						
						if( retPos >= 0 )
						{
							mval = value->u.object.values[retPos].value;
						}
						
						if( retPos >= 0  && mval->type == json_string && mval->u.string.ptr != NULL )
						{
							//DEBUG("STRENTRY FOUND %s data %s\n", (char *)dptr[ 1 ], mval->u.string.ptr );
							
							// this is date
							if( strlen( mval->u.string.ptr ) == 19 && mval->u.string.ptr[ 5 ] == '-' && mval->u.string.ptr[ 8 ] == '-' )
							{
								char *ptr = NULL;
								struct tm ltm;
							
								//DEBUG("TIMESTAMP load\n");
							
								//ptr = strptime( row[ i ], "%C%y-%m-%d %H:%M:%S", &ltm );
								if( ptr != NULL )
								{
									// REMEMBER, data fix
								
									ltm.tm_year += 1900;
									ltm.tm_mon ++;
								
									memcpy( strptr+ dptr[ 2 ], &ltm, sizeof( struct tm) );
								
									//DEBUG("Year %d  month %d  day %d\n", ltm.tm_year, ltm.tm_mon, ltm.tm_mday );
								}
							}
							else		// this is string
							{
								char *tmpval = StringDuplicate( mval->u.string.ptr );
								memcpy( strptr+ dptr[ 2 ], &tmpval, sizeof( char *) );
							}
						}
					}
					break;
				}
				i++;
				dptr += 3;
			}
		}
		else if( value->type == json_array )		// object contain our objects
		{
			arrval = value;
			
			int length = value->u.array.length;
			int x;
			for (x = 0; x < length; x++) // get object from array
			{
				json_value*locaval = value->u.array.values[x]; 
				
				void *data = calloc( 1, descr[ SQL_DATA_STRUCTURE_SIZE ] );
				if( firstObject == NULL )
				{
					firstObject = data;
				}
		
				UBYTE *strptr = (UBYTE *)data;	// pointer to structure to which will will insert data
				ULONG *dptr = &descr[ SQL_DATA_STRUCT_START ];		// first 2 entries inform about table and size, rest information provided is about columns
				
				int intlength = locaval->u.object.length;
				int i;
				
				while( dptr[0] != SQLT_END )
				{
					switch( dptr[ 0 ] )
					{
						case SQLT_NODE:
						{
							//DEBUG("Node found\n");
							MinNode *locnode = (MinNode *)(data + dptr[ 2 ]);
							locnode->mln_Succ = (MinNode *)lastObject;
							
							//DEBUG("\n\nlastObject %x currobject %x\n\n", lastObject, data );
						}
						break;
					
						case SQLT_IDINT:	// primary key
						case SQLT_INT:
						{
							int retPos = -1;
							for( i = 0; i < intlength; i++) 
							{
								//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
								if( strcmp( locaval->u.object.values[i].name, (char *) dptr[1] ) == 0 )
								{
									retPos = i;
								}
							}
							json_value*mval = locaval->u.object.values[retPos].value;
							
							if( retPos >= 0 && mval->type == json_integer )
							{
								//DEBUG("ENTRY FOUND %s  int val %d\n",(char *) dptr[ 1 ], mval->u.integer );
								memcpy( strptr + dptr[ 2 ], &(mval->u.integer), sizeof( int ) );
							}
						}
						break;
						
						case SQLT_STR:
						case SQLT_TIMESTAMP:
						{
							int retPos = -1;
							for( i = 0; i < intlength; i++) 
							{
								//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
								if( strcmp( locaval->u.object.values[i].name, (char *)dptr[1] ) == 0 )
								{
									retPos = i;
								}
							}
							
							json_value*mval = locaval->u.object.values[retPos].value;
							
							if( retPos >= 0  && mval->type == json_string && mval->u.string.ptr != NULL )
							{
								//DEBUG("STRENTRY FOUND %s data %s\n", (char *)dptr[ 1 ], mval->u.string.ptr );
								
								// this is date
								if( strlen( mval->u.string.ptr ) == 19 && mval->u.string.ptr[ 5 ] == '-' && mval->u.string.ptr[ 8 ] == '-' )
								{
									char *ptr = NULL;
									struct tm ltm;
							
									//DEBUG("TIMESTAMP load\n");
							
									//ptr = strptime( row[ i ], "%C%y-%m-%d %H:%M:%S", &ltm );
									if( ptr != NULL )
									{
										// REMEMBER, data fix
								
										ltm.tm_year += 1900;
										ltm.tm_mon ++;
								
										memcpy( strptr+ dptr[ 2 ], &ltm, sizeof( struct tm) );
								
										//DEBUG("Year %d  month %d  day %d\n", ltm.tm_year, ltm.tm_mon, ltm.tm_mday );
									}
								}
								else		// this is string
								{
									char *tmpval = StringDuplicate( mval->u.string.ptr );
									memcpy( strptr+ dptr[ 2 ], &tmpval, sizeof( char *) );
								}
							}
						}
						break;
					}
					i++;
					dptr += 3;
				}
				
				lastObject = data;
			}
		}
	}
	firstObject = lastObject;

	json_value_free( value );
	
	return firstObject;
}
Example #19
0
ACVP_RESULT acvp_cmac_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) {
    unsigned int tc_id, msglen, keyLen = 0, keyingOption = 0, maclen, verify = 0;
    char *msg = NULL, *key1 = NULL, *key2 = NULL, *key3 = NULL, *mac = NULL;
    JSON_Value *groupval;
    JSON_Object *groupobj = NULL;
    JSON_Value *testval;
    JSON_Object *testobj = NULL;
    JSON_Array *groups;
    JSON_Array *tests;

    JSON_Value *reg_arry_val = NULL;
    JSON_Object *reg_obj = NULL;
    JSON_Array *reg_arry = NULL;

    int i, g_cnt;
    int j, t_cnt;

    JSON_Value *r_vs_val = NULL;
    JSON_Object *r_vs = NULL;
    JSON_Array *r_tarr = NULL, *r_garr = NULL;  /* Response testarray, grouparray */
    JSON_Value *r_tval = NULL, *r_gval = NULL;  /* Response testval, groupval */
    JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */
    ACVP_CAPS_LIST *cap;
    ACVP_CMAC_TC stc;
    ACVP_TEST_CASE tc;
    ACVP_RESULT rv;
    const char *alg_str = json_object_get_string(obj, "algorithm");
    ACVP_CIPHER alg_id;
    char *json_result, *direction = NULL;
    int key1_len, key2_len, key3_len, json_msglen;

    if (!ctx) {
        ACVP_LOG_ERR("No ctx for handler operation");
        return ACVP_NO_CTX;
    }

    if (!obj) {
        ACVP_LOG_ERR("No obj for handler operation");
        return ACVP_MALFORMED_JSON;
    }

    if (!alg_str) {
        ACVP_LOG_ERR("ERROR: unable to parse 'algorithm' from JSON");
        return ACVP_MALFORMED_JSON;
    }

    /*
     * Get a reference to the abstracted test case
     */
    tc.tc.cmac = &stc;

    /*
     * Get the crypto module handler for this hash algorithm
     */
    alg_id = acvp_lookup_cipher_index(alg_str);
    if (alg_id < ACVP_CIPHER_START) {
        ACVP_LOG_ERR("ERROR: unsupported algorithm (%s)", alg_str);
        return ACVP_UNSUPPORTED_OP;
    }
    cap = acvp_locate_cap_entry(ctx, alg_id);
    if (!cap) {
        ACVP_LOG_ERR("ERROR: ACVP server requesting unsupported capability");
        return ACVP_UNSUPPORTED_OP;
    }

    /*
     * Create ACVP array for response
     */
    rv = acvp_create_array(&reg_obj, &reg_arry_val, &reg_arry);
    if (rv != ACVP_SUCCESS) {
        ACVP_LOG_ERR("ERROR: Failed to create JSON response struct. ");
        return rv;
    }

    /*
     * Start to build the JSON response
     */
    rv = acvp_setup_json_rsp_group(&ctx, &reg_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr);
    if (rv != ACVP_SUCCESS) {
        ACVP_LOG_ERR("Failed to setup json response");
        return rv;
    }

    groups = json_object_get_array(obj, "testGroups");
    g_cnt = json_array_get_count(groups);
    for (i = 0; i < g_cnt; i++) {
        int tgId = 0;
        int diff = 0;

        groupval = json_array_get_value(groups, i);
        groupobj = json_value_get_object(groupval);

        /*
         * Create a new group in the response with the tgid
         * and an array of tests
         */
        r_gval = json_value_init_object();
        r_gobj = json_value_get_object(r_gval);
        tgId = json_object_get_number(groupobj, "tgId");
        if (!tgId) {
            ACVP_LOG_ERR("Missing tgid from server JSON groub obj");
            rv = ACVP_MALFORMED_JSON;
            goto err;
        }
        json_object_set_number(r_gobj, "tgId", tgId);
        json_object_set_value(r_gobj, "tests", json_value_init_array());
        r_tarr = json_object_get_array(r_gobj, "tests");

        if (alg_id == ACVP_CMAC_AES) {
            keyLen = (unsigned int)json_object_get_number(groupobj, "keyLen");
            if (!keyLen) {
                ACVP_LOG_ERR("keylen missing from cmac aes json");
                rv = ACVP_MISSING_ARG;
                goto err;
            }
        } else if (alg_id == ACVP_CMAC_TDES) {
            keyingOption = (unsigned int)json_object_get_number(groupobj, "keyingOption");
            if (keyingOption <= ACVP_CMAC_TDES_KEYING_OPTION_MIN ||
                keyingOption >= ACVP_CMAC_TDES_KEYING_OPTION_MAX) {
                ACVP_LOG_ERR("keyingOption missing or wrong from cmac tdes json");
                rv = ACVP_INVALID_ARG;
                goto err;
            }
        }

        direction = (char *)json_object_get_string(groupobj, "direction");
        if (!direction) {
            ACVP_LOG_ERR("Unable to parse 'direction' from JSON.");
            rv = ACVP_MALFORMED_JSON;
            goto err;
        }

        strcmp_s("ver", 3, direction, &diff);
        if (!diff) {
            verify = 1;
        } else {
            strcmp_s("gen", 3, direction, &diff);
            if (diff) {
                ACVP_LOG_ERR("'direction' should be 'gen' or 'ver'");
                rv = ACVP_UNSUPPORTED_OP;
                goto err;
            }
        }

        msglen = (unsigned int)json_object_get_number(groupobj, "msgLen") / 8;

        maclen = (unsigned int)json_object_get_number(groupobj, "macLen") / 8;
        if (!maclen) {
            ACVP_LOG_ERR("Server JSON missing 'macLen'");
            rv = ACVP_MISSING_ARG;
            goto err;
        }

        ACVP_LOG_INFO("\n\n    Test group: %d", i);

        tests = json_object_get_array(groupobj, "tests");
        t_cnt = json_array_get_count(tests);
        for (j = 0; j < t_cnt; j++) {
            ACVP_LOG_INFO("Found new cmac test vector...");
            testval = json_array_get_value(tests, j);
            testobj = json_value_get_object(testval);

            tc_id = (unsigned int)json_object_get_number(testobj, "tcId");
            msg = (char *)json_object_get_string(testobj, "message");

            /* msg can be null if msglen is 0 */
            if (msg) {
                json_msglen = strnlen_s(msg, ACVP_CMAC_MSGLEN_MAX_STR + 1);
                if (json_msglen > ACVP_CMAC_MSGLEN_MAX_STR) {
                    ACVP_LOG_ERR("'msg' too long");
                    rv = ACVP_INVALID_ARG;
                    goto err;
                }
                if (!msglen && json_msglen > 0) {
                    ACVP_LOG_ERR("Server JSON missing 'msgLen'");
                    rv = ACVP_MISSING_ARG;
                    goto err;
                }
            } else if (msglen) {
                ACVP_LOG_ERR("msglen is nonzero, expected 'msg' in json");
                rv = ACVP_MISSING_ARG;
                goto err;
            }

            if (alg_id == ACVP_CMAC_AES) {
                key1 = (char *)json_object_get_string(testobj, "key");
                if (!key1) {
                    ACVP_LOG_ERR("Server JSON missing 'key'");
                    rv = ACVP_MISSING_ARG;
                    goto err;
                }
                key1_len = strnlen_s(key1, ACVP_CMAC_KEY_MAX + 1);
                if (key1_len > ACVP_CMAC_KEY_MAX) {
                    ACVP_LOG_ERR("Invalid length for 'key' attribute in CMAC-AES test");
                    rv = ACVP_INVALID_ARG;
                    goto err;
                }
            } else if (alg_id == ACVP_CMAC_TDES) {
                key1 = (char *)json_object_get_string(testobj, "key1");
                key2 = (char *)json_object_get_string(testobj, "key2");
                key3 = (char *)json_object_get_string(testobj, "key3");
                if (!key1 || !key2 || !key3) {
                    ACVP_LOG_ERR("Server JSON missing 'key(1,2,3)' value");
                    rv = ACVP_MISSING_ARG;
                    goto err;
                }
                key1_len = strnlen_s(key1, ACVP_CMAC_KEY_MAX + 1);
                key2_len = strnlen_s(key2, ACVP_CMAC_KEY_MAX + 1);
                key3_len = strnlen_s(key3, ACVP_CMAC_KEY_MAX + 1);
                if (key1_len > ACVP_CMAC_KEY_MAX ||
                    key2_len > ACVP_CMAC_KEY_MAX ||
                    key3_len > ACVP_CMAC_KEY_MAX) {
                    ACVP_LOG_ERR("Invalid length for 'key(1|2|3)' attribute in CMAC-TDES test");
                    rv = ACVP_INVALID_ARG;
                    goto err;
                }
            }

            if (verify) {
                mac = (char *)json_object_get_string(testobj, "mac");
                if (!mac) {
                    ACVP_LOG_ERR("Server JSON missing 'mac'");
                    rv = ACVP_MISSING_ARG;
                    goto err;
                }
            }

            ACVP_LOG_INFO("\n        Test case: %d", j);
            ACVP_LOG_INFO("             tcId: %d", tc_id);
            ACVP_LOG_INFO("        direction: %s", direction);

            ACVP_LOG_INFO("           msgLen: %d", msglen);
            ACVP_LOG_INFO("              msg: %s", msg);
            if (alg_id == ACVP_CMAC_AES) {
                ACVP_LOG_INFO("           keyLen: %d", keyLen);
                ACVP_LOG_INFO("              key: %s", key1);
            } else if (alg_id == ACVP_CMAC_TDES) {
                ACVP_LOG_INFO("     keyingOption: %d", keyingOption);
                ACVP_LOG_INFO("             key1: %s", key1);
                ACVP_LOG_INFO("             key2: %s", key2);
                ACVP_LOG_INFO("             key3: %s", key3);
            }

            if (verify) {
                ACVP_LOG_INFO("              mac: %s", mac);
            }

            /*
             * Create a new test case in the response
             */
            r_tval = json_value_init_object();
            r_tobj = json_value_get_object(r_tval);

            json_object_set_number(r_tobj, "tcId", tc_id);

            /*
             * Setup the test case data that will be passed down to
             * the crypto module.
             */
            rv = acvp_cmac_init_tc(ctx, &stc, tc_id, msg, msglen, keyLen, key1, key2, key3,
                                   verify, mac, maclen, alg_id);
            if (rv != ACVP_SUCCESS) {
                acvp_cmac_release_tc(&stc);
                json_value_free(r_tval);
                goto err;
            }

            /* Process the current test vector... */
            if ((cap->crypto_handler)(&tc)) {
                ACVP_LOG_ERR("ERROR: crypto module failed the operation");
                acvp_cmac_release_tc(&stc);
                rv = ACVP_CRYPTO_MODULE_FAIL;
                json_value_free(r_tval);
                goto err;
            }

            /*
             * Output the test case results using JSON
             */
            rv = acvp_cmac_output_tc(ctx, &stc, r_tobj);
            if (rv != ACVP_SUCCESS) {
                ACVP_LOG_ERR("ERROR: JSON output failure in hash module");
                acvp_cmac_release_tc(&stc);
                json_value_free(r_tval);
                goto err;
            }

            /*
             * Release all the memory associated with the test case
             */
            acvp_cmac_release_tc(&stc);

            /* Append the test response value to array */
            json_array_append_value(r_tarr, r_tval);
        }
        json_array_append_value(r_garr, r_gval);
    }

    json_array_append_value(reg_arry, r_vs_val);

    json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL);
    if (ctx->debug == ACVP_LOG_LVL_VERBOSE) {
        printf("\n\n%s\n\n", json_result);
    } else {
        ACVP_LOG_INFO("\n\n%s\n\n", json_result);
    }
    json_free_serialized_string(json_result);
    rv = ACVP_SUCCESS;

err:
    if (rv != ACVP_SUCCESS) {
        acvp_release_json(r_vs_val, r_gval);
    }
    return rv;
}
Example #20
0
int CMain::HandleMessage(int ClientNetID, char *pMessage)
{
	CClient *pClient = ClientNet(ClientNetID);
	if(!pClient)
		return true;

	if(str_comp_num(pMessage, "update", sizeof("update")-1) == 0)
	{
		char *pData = str_skip_whitespaces(&pMessage[sizeof("update")-1]);

		// parse json data
		json_settings JsonSettings;
		mem_zero(&JsonSettings, sizeof(JsonSettings));
		char aError[256];
		json_value *pJsonData = json_parse_ex(&JsonSettings, pData, strlen(pData), aError);
		if(!pJsonData)
		{
			dbg_msg("main", "JSON Error: %s", aError);
			if(pClient->m_Stats.m_Pong)
				m_Server.Network()->Send(ClientNetID, "1");
			return 1;
		}

		// extract data
		const json_value &rStart = (*pJsonData);
		if(rStart["uptime"].type)
			pClient->m_Stats.m_Uptime = rStart["uptime"].u.integer;
		if(rStart["load"].type)
			pClient->m_Stats.m_Load = rStart["load"].u.dbl;
		if(rStart["network_rx"].type)
			pClient->m_Stats.m_NetworkRx = rStart["network_rx"].u.integer;
		if(rStart["network_tx"].type)
			pClient->m_Stats.m_NetworkTx = rStart["network_tx"].u.integer;
		if(rStart["memory_total"].type)
			pClient->m_Stats.m_MemTotal = rStart["memory_total"].u.integer;
		if(rStart["memory_used"].type)
			pClient->m_Stats.m_MemUsed = rStart["memory_used"].u.integer;
		if(rStart["hdd_total"].type)
			pClient->m_Stats.m_HDDTotal = rStart["hdd_total"].u.integer;
		if(rStart["hdd_used"].type)
			pClient->m_Stats.m_HDDUsed = rStart["hdd_used"].u.integer;
		if(rStart["cpu"].type)
			pClient->m_Stats.m_CPU = rStart["cpu"].u.dbl;
		if(rStart["online4"].type && pClient->m_ClientNetType == NETTYPE_IPV6)
			pClient->m_Stats.m_Online4 = rStart["online4"].u.boolean;
		if(rStart["online6"].type && pClient->m_ClientNetType == NETTYPE_IPV4)
			pClient->m_Stats.m_Online6 = rStart["online6"].u.boolean;

		if(m_Config.m_Verbose)
		{
			if(rStart["online4"].type)
				dbg_msg("main", "Online4: %s\nUptime: %" PRId64 "\nLoad: %lf\nNetworkRx: %" PRId64 "\nNetworkTx: %" PRId64 "\nMemTotal: %" PRId64 "\nMemUsed: %" PRId64 "\nHDDTotal: %" PRId64 "\nHDDUsed: %" PRId64 "\nCPU: %lf\n",
					rStart["online4"].u.boolean ? "true" : "false",
					pClient->m_Stats.m_Uptime, pClient->m_Stats.m_Load, pClient->m_Stats.m_NetworkRx, pClient->m_Stats.m_NetworkTx, pClient->m_Stats.m_MemTotal, pClient->m_Stats.m_MemUsed, pClient->m_Stats.m_HDDTotal, pClient->m_Stats.m_HDDUsed, pClient->m_Stats.m_CPU);
			else if(rStart["online6"].type)
				dbg_msg("main", "Online6: %s\nUptime: %" PRId64 "\nLoad: %lf\nNetworkRx: %" PRId64 "\nNetworkTx: %" PRId64 "\nMemTotal: %" PRId64 "\nMemUsed: %" PRId64 "\nHDDTotal: %" PRId64 "\nHDDUsed: %" PRId64 "\nCPU: %lf\n",
					rStart["online6"].u.boolean ? "true" : "false",
					pClient->m_Stats.m_Uptime, pClient->m_Stats.m_Load, pClient->m_Stats.m_NetworkRx, pClient->m_Stats.m_NetworkTx, pClient->m_Stats.m_MemTotal, pClient->m_Stats.m_MemUsed, pClient->m_Stats.m_HDDTotal, pClient->m_Stats.m_HDDUsed, pClient->m_Stats.m_CPU);
			else
				dbg_msg("main", "Uptime: %" PRId64 "\nLoad: %lf\nNetworkRx: %" PRId64 "\nNetworkTx: %" PRId64 "\nMemTotal: %" PRId64 "\nMemUsed: %" PRId64 "\nHDDTotal: %" PRId64 "\nHDDUsed: %" PRId64 "\nCPU: %lf\n",
					pClient->m_Stats.m_Uptime, pClient->m_Stats.m_Load, pClient->m_Stats.m_NetworkRx, pClient->m_Stats.m_NetworkTx, pClient->m_Stats.m_MemTotal, pClient->m_Stats.m_MemUsed, pClient->m_Stats.m_HDDTotal, pClient->m_Stats.m_HDDUsed, pClient->m_Stats.m_CPU);
		}

		// clean up
		json_value_free(pJsonData);

		if(pClient->m_Stats.m_Pong)
			m_Server.Network()->Send(ClientNetID, "0");
		return 0;
	}
	else if(str_comp_num(pMessage, "pong", sizeof("pong")-1) == 0)
	{
		char *pData = str_skip_whitespaces(&pMessage[sizeof("pong")-1]);

		if(!str_comp(pData, "0") || !str_comp(pData, "off"))
			pClient->m_Stats.m_Pong = false;
		else if(!str_comp(pData, "1") || !str_comp(pData, "on"))
			pClient->m_Stats.m_Pong = true;

		return 0;
	}

	if(pClient->m_Stats.m_Pong)
		m_Server.Network()->Send(ClientNetID, "1");

	return 1;
}
Example #21
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.");

    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") == 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, "username") == 0)
            {
                conf.username = to_string(value);
            }
        }
    }
    else
    {
        FATAL("Invalid config file");
    }

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

}
Example #22
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;
}
Example #23
0
bool parse_wd_node_function_json(char* json_data, int data_len, char** func_name, int **node_id_set, int *count)
{
	json_value *root, *value;
	char* ptr;
	int node_count = 0;
	int i;

	*node_id_set = NULL;
	*func_name = NULL;
	*count = 0;

	root = json_parse(json_data,data_len);

	/* The root node must be object */
	if (root == NULL || root->type != json_object)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("watchdog is unable to parse node function json"),
				 errdetail("invalid json data \"%s\"",json_data)));
		return false;
	}
	ptr = json_get_string_value_for_key(root, "Function");
	if (ptr == NULL)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("watchdog is unable to parse node function json"),
				 errdetail("function node not found in json data \"%s\"",json_data)));
		return false;
	}
	*func_name = pstrdup(ptr);
	/* If it is a node function ?*/
	if (json_get_int_value_for_key(root, "NodeCount", &node_count))
	{
		/*node count not found, But we don't care much about this*/
		json_value_free(root);
		return true;
	}
	if (node_count <= 0)
	{
		json_value_free(root);
		return true;
	}
	*count = node_count;

	value = json_get_value_for_key(root,"NodeIdList");
	if (value == NULL)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("invalid json data"),
				 errdetail("unable to find NodeIdList node from data")));
		return false;
	}
	if (value->type != json_array)
	{
		json_value_free(root);
		ereport(WARNING,
				(errmsg("invalid json data"),
				 errdetail("NodeIdList node does not contains Array")));
		return false;
	}
	if (node_count != value->u.array.length)
	{
		json_value_free(root);
		ereport(WARNING,
				(errmsg("invalid json data"),
				 errdetail("NodeIdList array contains %d nodes while expecting %d",value->u.array.length, node_count)));
		return false;
	}

	*node_id_set = palloc(sizeof(int) * node_count);
	for (i = 0; i < node_count; i++)
	{
		*node_id_set[i] = value->u.array.values[i]->u.integer;
	}
	json_value_free(root);
	return true;
}
Example #24
0
static void json_array_free(JSON_Array *array) {
    while (array->count--) { json_value_free(array->items[array->count]); }
    parson_free(array->items);
    parson_free(array);
}
Example #25
0
/**
 * @brief Process a message received from the Chromecast
 * @param msg the CastMessage to process
 * @return 0 if the message has been successfuly processed else -1
 */
void intf_sys_t::processMessage(const castchannel::CastMessage &msg)
{
    const std::string & namespace_ = msg.namespace_();

#ifndef NDEBUG
    msg_Dbg(p_stream,"processMessage: %s->%s %s", namespace_.c_str(), msg.destination_id().c_str(), msg.payload_utf8().c_str());
#endif

    if (namespace_ == NAMESPACE_DEVICEAUTH)
    {
        castchannel::DeviceAuthMessage authMessage;
        authMessage.ParseFromString(msg.payload_binary());

        if (authMessage.has_error())
        {
            msg_Err(p_stream, "Authentification error: %d", authMessage.error().error_type());
        }
        else if (!authMessage.has_response())
        {
            msg_Err(p_stream, "Authentification message has no response field");
        }
        else
        {
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_AUTHENTICATED);
            msgConnect(DEFAULT_CHOMECAST_RECEIVER);
            msgReceiverLaunchApp();
        }
    }
    else if (namespace_ == NAMESPACE_HEARTBEAT)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "PING")
        {
            msg_Dbg(p_stream, "PING received from the Chromecast");
            msgPong();
        }
        else if (type == "PONG")
        {
            msg_Dbg(p_stream, "PONG received from the Chromecast");
        }
        else
        {
            msg_Warn(p_stream, "Heartbeat command not supported: %s", type.c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_RECEIVER)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "RECEIVER_STATUS")
        {
            json_value applications = (*p_data)["status"]["applications"];
            const json_value *p_app = NULL;

            vlc_mutex_locker locker(&lock);
            for (unsigned i = 0; i < applications.u.array.length; ++i)
            {
                std::string appId(applications[i]["appId"]);
                if (appId == APP_ID)
                {
                    const char *pz_transportId = applications[i]["transportId"];
                    if (pz_transportId != NULL)
                    {
                        appTransportId = std::string(pz_transportId);
                        p_app = &applications[i];
                    }
                    break;
                }
            }

            if ( p_app )
            {
                if (!appTransportId.empty()
                        && getConnectionStatus() == CHROMECAST_AUTHENTICATED)
                {
                    msgConnect(appTransportId);
                    setConnectionStatus(CHROMECAST_APP_STARTED);
                    msgPlayerLoad();
                    setConnectionStatus(CHROMECAST_MEDIA_LOAD_SENT);
                    vlc_cond_signal(&loadCommandCond);
                }
            }
            else
            {
                switch(getConnectionStatus())
                {
                /* If the app is no longer present */
                case CHROMECAST_APP_STARTED:
                case CHROMECAST_MEDIA_LOAD_SENT:
                    msg_Warn(p_stream, "app is no longer present. closing");
                    msgReceiverClose(appTransportId);
                    setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
                    break;

                case CHROMECAST_AUTHENTICATED:
                    msg_Dbg(p_stream, "Chromecast was running no app, launch media_app");
                    appTransportId = "";
                    msgReceiverLaunchApp();
                    break;

                default:
                    break;
                }

            }
        }
        else if (type == "LAUNCH_ERROR")
        {
            json_value reason = (*p_data)["reason"];
            msg_Err(p_stream, "Failed to start the MediaPlayer: %s",
                    (const char *)reason);
        }
        else
        {
            msg_Warn(p_stream, "Receiver command not supported: %s",
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_MEDIA)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "MEDIA_STATUS")
        {
            json_value status = (*p_data)["status"];
            msg_Dbg(p_stream, "Player state: %s sessionId:%d",
                    status[0]["playerState"].operator const char *(),
                    (int)(json_int_t) status[0]["mediaSessionId"]);
        }
        else if (type == "LOAD_FAILED")
        {
            msg_Err(p_stream, "Media load failed");
            msgReceiverClose(appTransportId);
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
        else if (type == "INVALID_REQUEST")
        {
            msg_Dbg(p_stream, "We sent an invalid request reason:%s", (*p_data)["reason"].operator const char *());
        }
        else
        {
            msg_Warn(p_stream, "Media command not supported: %s",
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_CONNECTION)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);
        json_value_free(p_data);

        if (type == "CLOSE")
        {
            msg_Warn(p_stream, "received close message");
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
        else
        {
            msg_Warn(p_stream, "Connection command not supported: %s",
                    type.c_str());
        }
    }
    else
    {
        msg_Err(p_stream, "Unknown namespace: %s", msg.namespace_().c_str());
    }
}
Example #26
0
File: cast.cpp Project: Adatan/vlc
/**
 * @brief Process a message received from the Chromecast
 * @param p_stream the sout_stream_t structure
 * @param msg the CastMessage to process
 * @return 0 if the message has been successfuly processed else -1
 */
static int processMessage(sout_stream_t *p_stream, const castchannel::CastMessage &msg)
{
    int i_ret = 0;
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    std::string namespace_ = msg.namespace_();

    if (namespace_ == "urn:x-cast:com.google.cast.tp.deviceauth")
    {
        castchannel::DeviceAuthMessage authMessage;
        authMessage.ParseFromString(msg.payload_binary());

        if (authMessage.has_error())
        {
            msg_Err(p_stream, "Authentification error: %d", authMessage.error().error_type());
            i_ret = -1;
        }
        else if (!authMessage.has_response())
        {
            msg_Err(p_stream, "Authentification message has no response field");
            i_ret = -1;
        }
        else
        {
            vlc_mutex_locker locker(&p_sys->lock);
            p_sys->i_status = CHROMECAST_AUTHENTICATED;
            msgConnect(p_stream, "receiver-0");
            msgLaunch(p_stream);
        }
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.tp.heartbeat")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "PING")
        {
            msg_Dbg(p_stream, "PING received from the Chromecast");
            msgPong(p_stream);
        }
        else if (type == "PONG")
        {
            msg_Dbg(p_stream, "PONG received from the Chromecast");
        }
        else
        {
            msg_Err(p_stream, "Heartbeat command not supported");
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.receiver")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "RECEIVER_STATUS")
        {
            json_value applications = (*p_data)["status"]["applications"];
            const json_value *p_app = NULL;
            for (unsigned i = 0; i < applications.u.array.length; ++i)
            {
                std::string appId(applications[i]["appId"]);
                if (appId == APP_ID)
                {
                    p_app = &applications[i];
                    vlc_mutex_lock(&p_sys->lock);
                    if (p_sys->appTransportId.empty())
                        p_sys->appTransportId = std::string(applications[i]["transportId"]);
                    vlc_mutex_unlock(&p_sys->lock);
                    break;
                }
            }

            vlc_mutex_lock(&p_sys->lock);
            if ( p_app )
            {
                if (!p_sys->appTransportId.empty()
                        && p_sys->i_status == CHROMECAST_AUTHENTICATED)
                {
                    p_sys->i_status = CHROMECAST_APP_STARTED;
                    msgConnect(p_stream, p_sys->appTransportId);
                    msgLoad(p_stream);
                    p_sys->i_status = CHROMECAST_MEDIA_LOAD_SENT;
                    vlc_cond_signal(&p_sys->loadCommandCond);
                }
            }
            else
            {
                switch(p_sys->i_status)
                {
                /* If the app is no longer present */
                case CHROMECAST_APP_STARTED:
                case CHROMECAST_MEDIA_LOAD_SENT:
                    msg_Warn(p_stream, "app is no longer present. closing");
                    msgClose(p_stream, p_sys->appTransportId);
                    p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
                    // ft
                default:
                    break;
                }

            }
            vlc_mutex_unlock(&p_sys->lock);
        }
        else
        {
            msg_Err(p_stream, "Receiver command not supported: %s",
                    msg.payload_utf8().c_str());
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.media")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "MEDIA_STATUS")
        {
            json_value status = (*p_data)["status"];
            msg_Dbg(p_stream, "Player state: %s",
                    status[0]["playerState"].operator const char *());
        }
        else if (type == "LOAD_FAILED")
        {
            msg_Err(p_stream, "Media load failed");
            atomic_store(&p_sys->ab_error, true);
            msgClose(p_stream, p_sys->appTransportId);
            vlc_mutex_lock(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            vlc_mutex_unlock(&p_sys->lock);
        }
        else
        {
            msg_Err(p_stream, "Media command not supported: %s",
                    msg.payload_utf8().c_str());
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.tp.connection")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);
        json_value_free(p_data);

        if (type == "CLOSE")
        {
            msg_Warn(p_stream, "received close message");
            vlc_mutex_lock(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            vlc_mutex_unlock(&p_sys->lock);
        }
    }
    else
    {
        msg_Err(p_stream, "Unknown namespace: %s", msg.namespace_().c_str());
        i_ret = -1;
    }

    return i_ret;
}
Example #27
0
ACVP_RESULT acvp_kdf135_srtp_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) {
    unsigned int tc_id;
    JSON_Value *groupval;
    JSON_Object *groupobj = NULL;
    JSON_Value *testval;
    JSON_Object *testobj = NULL;
    JSON_Array *groups;
    JSON_Array *tests;

    JSON_Value *reg_arry_val = NULL;
    JSON_Object *reg_obj = NULL;
    JSON_Array *reg_arry = NULL;

    int i, g_cnt;
    int j, t_cnt;

    JSON_Value *r_vs_val = NULL;
    JSON_Object *r_vs = NULL;
    JSON_Array *r_tarr = NULL, *r_garr = NULL;  /* Response testarray, grouparray */
    JSON_Value *r_tval = NULL, *r_gval = NULL;  /* Response testval, groupval */
    JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */
    ACVP_CAPS_LIST *cap;
    ACVP_KDF135_SRTP_TC stc;
    ACVP_TEST_CASE tc;
    ACVP_RESULT rv;
    const char *alg_str = json_object_get_string(obj, "algorithm");
    const char *mode_str = NULL;
    ACVP_CIPHER alg_id;
    char *json_result;

    int aes_key_length;
    char *kdr = NULL, *master_key = NULL, *master_salt = NULL, *index = NULL, *srtcp_index = NULL;

    if (!ctx) {
        ACVP_LOG_ERR("No ctx for handler operation");
        return ACVP_NO_CTX;
    }

    if (!alg_str) {
        ACVP_LOG_ERR("unable to parse 'algorithm' from JSON.");
        return ACVP_MALFORMED_JSON;
    }

    mode_str = json_object_get_string(obj, "mode");
    if (!mode_str) {
        ACVP_LOG_ERR("unable to parse 'mode' from JSON.");
        return ACVP_MALFORMED_JSON;
    }

    alg_id = acvp_lookup_cipher_w_mode_index(alg_str, mode_str);
    if (alg_id != ACVP_KDF135_SRTP) {
        ACVP_LOG_ERR("Server JSON invalid 'algorithm' or 'mode'");
        return ACVP_INVALID_ARG;
    }

    /*
     * Get a reference to the abstracted test case
     */
    tc.tc.kdf135_srtp = &stc;
    stc.cipher = alg_id;

    cap = acvp_locate_cap_entry(ctx, alg_id);
    if (!cap) {
        ACVP_LOG_ERR("ACVP server requesting unsupported capability %s : %d.", alg_str, alg_id);
        return ACVP_UNSUPPORTED_OP;
    }

    /*
     * Create ACVP array for response
     */
    rv = acvp_create_array(&reg_obj, &reg_arry_val, &reg_arry);
    if (rv != ACVP_SUCCESS) {
        ACVP_LOG_ERR("Failed to create JSON response struct. ");
        return rv;
    }

    /*
     * Start to build the JSON response
     */
    rv = acvp_setup_json_rsp_group(&ctx, &reg_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr);
    if (rv != ACVP_SUCCESS) {
        ACVP_LOG_ERR("Failed to setup json response");
        goto err;
    }

    groups = json_object_get_array(obj, "testGroups");
    g_cnt = json_array_get_count(groups);
    for (i = 0; i < g_cnt; i++) {
        int tgId = 0;
        groupval = json_array_get_value(groups, i);
        groupobj = json_value_get_object(groupval);

        /*
         * Create a new group in the response with the tgid
         * and an array of tests
         */
        r_gval = json_value_init_object();
        r_gobj = json_value_get_object(r_gval);
        tgId = json_object_get_number(groupobj, "tgId");
        if (!tgId) {
            ACVP_LOG_ERR("Missing tgid from server JSON groub obj");
            rv = ACVP_MALFORMED_JSON;
            goto err;
        }
        json_object_set_number(r_gobj, "tgId", tgId);
        json_object_set_value(r_gobj, "tests", json_value_init_array());
        r_tarr = json_object_get_array(r_gobj, "tests");

        aes_key_length = (unsigned int)json_object_get_number(groupobj, "aesKeyLength");
        if (!aes_key_length) {
            ACVP_LOG_ERR("aesKeyLength incorrect, %d", aes_key_length);
            rv = ACVP_INVALID_ARG;
            goto err;
        }

        kdr = (char *)json_object_get_string(groupobj, "kdr");
        if (!kdr) {
            ACVP_LOG_ERR("Failed to include kdr");
            rv = ACVP_MISSING_ARG;
            goto err;
        }

        ACVP_LOG_INFO("\n    Test group: %d", i);
        ACVP_LOG_INFO("           kdr: %s", kdr);
        ACVP_LOG_INFO("    key length: %d", aes_key_length);

        tests = json_object_get_array(groupobj, "tests");
        t_cnt = json_array_get_count(tests);

        for (j = 0; j < t_cnt; j++) {
            ACVP_LOG_INFO("Found new KDF SRTP test vector...");
            testval = json_array_get_value(tests, j);
            testobj = json_value_get_object(testval);

            tc_id = (unsigned int)json_object_get_number(testobj, "tcId");

            master_key = (char *)json_object_get_string(testobj, "masterKey");
            if (!master_key) {
                ACVP_LOG_ERR("Failed to include JSON key:\"masterKey\"");
                rv = ACVP_MISSING_ARG;
                goto err;
            }

            master_salt = (char *)json_object_get_string(testobj, "masterSalt");
            if (!master_salt) {
                ACVP_LOG_ERR("Failed to include JSON key:\"masterSalt\"");
                rv = ACVP_MISSING_ARG;
                goto err;
            }

            index = (char *)json_object_get_string(testobj, "index");
            if (!index) {
                ACVP_LOG_ERR("Failed to include JSON key:\"index\"");
                rv = ACVP_MISSING_ARG;
                goto err;
            }

            srtcp_index = (char *)json_object_get_string(testobj, "srtcpIndex");
            if (!srtcp_index) {
                ACVP_LOG_ERR("Failed to include JSON key:\"srtcpIndex\"");
                rv = ACVP_MISSING_ARG;
                goto err;
            }

            ACVP_LOG_INFO("        Test case: %d", j);
            ACVP_LOG_INFO("             tcId: %d", tc_id);
            ACVP_LOG_INFO("        masterKey: %s", master_key);
            ACVP_LOG_INFO("       masterSalt: %s", master_salt);
            ACVP_LOG_INFO("            index: %s", index);
            ACVP_LOG_INFO("       srtcpIndex: %s", srtcp_index);

            /*
             * Create a new test case in the response
             */
            r_tval = json_value_init_object();
            r_tobj = json_value_get_object(r_tval);

            json_object_set_number(r_tobj, "tcId", tc_id);

            /*
             * Setup the test case data that will be passed down to
             * the crypto module.
             */
            rv = acvp_kdf135_srtp_init_tc(ctx, &stc, tc_id, aes_key_length, kdr, master_key, master_salt, index, srtcp_index);
            if (rv != ACVP_SUCCESS) {
                acvp_kdf135_srtp_release_tc(&stc);
                json_value_free(r_tval);
                goto err;
            }

            /* Process the current test vector... */
            if ((cap->crypto_handler)(&tc)) {
                ACVP_LOG_ERR("crypto module failed");
                acvp_kdf135_srtp_release_tc(&stc);
                rv = ACVP_CRYPTO_MODULE_FAIL;
                json_value_free(r_tval);
                goto err;
            }

            /*
             * Output the test case results using JSON
             */
            rv = acvp_kdf135_srtp_output_tc(ctx, &stc, r_tobj);
            if (rv != ACVP_SUCCESS) {
                ACVP_LOG_ERR("JSON output failure");
                acvp_kdf135_srtp_release_tc(&stc);
                json_value_free(r_tval);
                goto err;
            }
            /*
             * Release all the memory associated with the test case
             */
            acvp_kdf135_srtp_release_tc(&stc);

            /* Append the test response value to array */
            json_array_append_value(r_tarr, r_tval);
        }
        json_array_append_value(r_garr, r_gval);
    }

    json_array_append_value(reg_arry, r_vs_val);

    json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL);
    if (ctx->debug == ACVP_LOG_LVL_VERBOSE) {
        printf("\n\n%s\n\n", json_result);
    } else {
        ACVP_LOG_INFO("\n\n%s\n\n", json_result);
    }
    json_free_serialized_string(json_result);
    rv = ACVP_SUCCESS;

err:
    if (rv != ACVP_SUCCESS) {
        acvp_release_json(r_vs_val, r_gval);
    }
    return rv;
}
Example #28
0
int config_parse(const char *file, config_t *config)
{
    JSON_Value *jvroot;
    JSON_Object *joroot;
    JSON_Object *jomaccmd;
    JSON_Array *jarray;
    JSON_Value_Type jtype;
    const char *string;
    int ret;
    int i;

    if(file == NULL){
        return -1;
    }

    /** Clear all flags */
    config_free(config);

    printf("Start parsing configuration file....\n\n");

    /* parsing json and validating output */
    jvroot = json_parse_file_with_comments(file);
    jtype = json_value_get_type(jvroot);
    if (jtype != JSONObject) {
        return -1;
    }
    joroot = json_value_get_object(jvroot);

    string = json_object_get_string(joroot, "band");
    if(string == NULL){
        config->band = LW_BAND_EU868;
    }else{
        for(i=0; i<LW_BAND_MAX_NUM; i++){
            if(0 == strcmp(string, config_band_tab[i])){
                config->band = (lw_band_t)i;
                break;
            }
        }
        if(i==LW_BAND_MAX_NUM){
            config->band = LW_BAND_EU868;
        }
    }

    string = json_object_dotget_string(joroot, "key.nwkskey");
    if(string != NULL){
        if(str2hex(string, config->nwkskey, 16) == 16){
            config->flag |= CFLAG_NWKSKEY;
        }
    }

    string = json_object_dotget_string(joroot, "key.appskey");
    if(string != NULL){
        if(str2hex(string, config->appskey, 16) == 16){
            config->flag |= CFLAG_APPSKEY;
        }
    }

    string = json_object_dotget_string(joroot, "key.appkey");
    if(string != NULL){
        if(str2hex(string, config->appkey, 16) == 16){
            config->flag |= CFLAG_APPKEY;
        }
    }

    ret = json_object_dotget_boolean(joroot, "join.key");
    if(ret==0){
        //printf("Join key false\n");
        config->joinkey = false;
    }else if(ret==1){
        //printf("Join key true\n");
        config->joinkey = true;
    }else{
        //printf("Unknown join key value\n");
        config->joinkey = false;
    }

    string = json_object_dotget_string(joroot, "join.request");
    if(string != NULL){
        uint8_t tmp[255];
        int len;
        len = str2hex(string, tmp, 255);
        if(len>0){
            config->flag |= CFLAG_JOINR;
            config->joinr = malloc(len);
            if(config->joinr == NULL){
                return -2;
            }
            config->joinr_size = len;
            memcpy(config->joinr, tmp, config->joinr_size);
        }
    }

    string = json_object_dotget_string(joroot, "join.accept");
    if(string != NULL){
        uint8_t tmp[255];
        int len;
        len = str2hex(string, tmp, 255);
        if(len>0){
            config->flag |= CFLAG_JOINA;
            config->joina = malloc(len);
            if(config->joina == NULL){
                return -3;
            }
            config->joina_size = len;
            memcpy(config->joina, tmp, config->joina_size);
        }
    }

    jarray = json_object_get_array(joroot, "messages");
    if(jarray != NULL){
        uint8_t tmp[255];
        for (i = 0; i < json_array_get_count(jarray); i++) {
            string = json_array_get_string(jarray, i);
            if(string!=NULL){
                int len = str2hex(string, tmp, 255);
                if(len>0){
                    message_t *pl = malloc(sizeof(message_t));
                    memset(pl, 0, sizeof(message_t));
                    if(pl == NULL){
                        return -3;
                    }
                    pl->buf = malloc(len);
                    if(pl->buf == NULL){
                        return -3;
                    }
                    pl->len = len;
                    memcpy(pl->buf, tmp, pl->len);
                    pl_insert(&config->message, pl);
                }else{
                    printf("Messages[%d] \"%s\" is not hex string\n", i, string);

                }
            }else{
                printf("Messages item %d is not string\n", i);
            }
        }
    }else{
        printf("Can't get payload array\n");
    }

    jarray = json_object_get_array(joroot, "maccommands");
    if(jarray != NULL){
        uint8_t mhdr;
        int len;
        uint8_t tmp[255];
        for (i = 0; i < json_array_get_count(jarray); i++) {
            jomaccmd = json_array_get_object(jarray, i);
            string = json_object_get_string(jomaccmd, "MHDR");
            if(string != NULL){
                len = str2hex(string, &mhdr, 1);
                if(len != 1){
                    printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string);
                    continue;
                }
            }else{
                string = json_object_get_string(jomaccmd, "direction");
                if(string != NULL){
                    int j;
                    len = strlen(string);
                    if(len>200){
                        printf("\"maccommands\"[%d].direction \"%s\" too long\n", i, string);
                        continue;
                    }
                    for(j=0; j<len; j++){
                        tmp[j] = tolower(string[j]);
                    }
                    tmp[j] = '\0';
                    if(0==strcmp((char *)tmp, "up")){
                        mhdr = 0x80;
                    }else if(0==strcmp((char *)tmp, "down")){
                        mhdr = 0xA0;
                    }else{
                        printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string);
                        continue;
                    }
                }else{
                    printf("Can't recognize maccommand direction\n");
                    continue;
                }
            }
            string = json_object_get_string(jomaccmd, "command");
            if(string != NULL){
                len = str2hex(string, tmp, 255);
                if(len <= 0){
                    printf("\"maccommands\"[%d].command \"%s\" is not hex string\n", i, string);
                    continue;
                }
            }else{
                printf("c\"maccommands\"[%d].command is not string\n", i);
                continue;
            }
            message_t *pl = malloc(sizeof(message_t));
            memset(pl, 0, sizeof(message_t));
            if(pl == NULL){
                return -3;
            }
            pl->buf = malloc(len+1);
            if(pl->buf == NULL){
                return -3;
            }
            pl->len = len+1;
            pl->buf[0] = mhdr;
            pl->next = 0;
            memcpy(pl->buf+1, tmp, pl->len-1);
            pl_insert(&config->maccmd, pl);
        }
    }

    print_spliter();
    printf("%15s %s\n","BAND:\t", config_band_tab[LW_BAND_EU868]);
    printf("%15s","NWKSKEY:\t");
    putlen(16);
    puthbuf(config->nwkskey, 16);
    printf("\n");
    printf("%15s","APPSKEY:\t");
    putlen(16);
    puthbuf(config->appskey, 16);
    printf("\n");
    printf("%15s","APPKEY:\t");
    putlen(16);
    puthbuf(config->appkey, 16);
    printf("\n");
    printf("%15s","JOINR:\t");
    putlen(config->joinr_size);
    puthbuf(config->joinr, config->joinr_size );
    printf("\n");
    printf("%15s","JOINA:\t");
    putlen(config->joina_size);
    puthbuf(config->joina, config->joina_size );
    printf("\n");
    pl_print(config->message);
    maccmd_print(config->maccmd);

    json_value_free(jvroot);
    return 0;
}
Example #29
0
int main(int argc, char** argv) {
    printf("haltestelle built <%s %s> version %s\n", __DATE__, __TIME__, VERSION);
    if(argc < 5) {
        fprintf(stderr, "usage: %s <designation> <busfarhn_host> <busfarhn_port> <serialport>\n", argv[0]);
        exit(-1);
    }

    /*global*/ designation   = argv[1];
    /*global*/ busfarhn_host = argv[2];
    /*global*/ busfarhn_port = atoi(argv[3]);
    char*      serialport    = argv[4];

    /*global*/ sockfd = start_socket();
    if(connect_to_busfarhn(designation) != 0) {
        fprintf(stderr, "[ERROR] connecting to %s:%d failed\n", busfarhn_host, busfarhn_port);
        return -1;
    }
#ifdef USE_SERIAL
    #ifdef SERIAL_IS_A_FILE
    printf("%s is a FILE\n", serialport);
    #elif defined SERIAL_IS_A_ATH0
    printf("%s is a SERIAL PORT (ATH style)\n", serialport);
    #else
    printf("%s is a SERIAL PORT\n", serialport);
    #endif
#else
    printf("WARNING: NOT USING THE SERIAL PORT\n");
#endif
    printf("[STARTUP] connected to %s:%i with designation %s\n", busfarhn_host, busfarhn_port, designation);

#ifdef USE_SERIAL
    #ifdef SERIAL_IS_A_FILE
    /*global*/ serialfd = fopen(serialport, "rw");
    #elif defined SERIAL_IS_A_ATH0
    /*global*/ serialfd = open(serialport, O_RDWR);
    #else
    /*global*/ serialfd = open(serialport, O_RDWR | O_NOCTTY | O_SYNC);
    #endif
    
    if (serialfd < 0) {
        fprintf(stderr, "error %d opening %s: %s", errno, serialport, strerror (errno));
        return;
    }

    #if !(defined SERIAL_IS_A_FILE || defined SERIAL_IS_A_ATH0)
    set_interface_attribs (serialfd, SERIAL_BAUDRATE, 0);  // set speed to 115,200 bps, 8n1 (no parity)
    set_blocking (serialfd, 0);                // set no blocking
    #endif
#endif

    hs_startup();

    char netbuf[MAXBUFLEN];
    unsigned int netbufpos = 0;

    struct sockaddr_storage their_addr;
    socklen_t addr_len;

#ifdef USE_SERIAL
    pthread_t pth;
    pthread_create(&pth, NULL, thread_read_serial, NULL);
#endif

    while(1) {
        // network
        int numbytes;
        addr_len = sizeof their_addr;
        if ((numbytes = recvfrom(sockfd, (netbuf + netbufpos), MAXBUFLEN - (netbufpos + 1), MSG_DONTWAIT, (struct sockaddr *)&their_addr, &addr_len)) > 0) {
            printf("[NET] received %i bytes\n", numbytes);

            int i = 0;
            for(i = 0; i < numbytes; i++) if(netbuf[netbufpos + i] == '\n') break;
            netbufpos += numbytes;

            if(i < numbytes) {
                // found breakline
                netbuf[netbufpos - 1] = '\0';
                netbufpos = 0;
                
                printf("CMD <%s>\n", netbuf);
                JSON_Value* json = json_parse_string(netbuf);

                if(json_value_get_type(json) == JSONObject) {
                    JSON_Object* obj = json_value_get_object(json);
                    const char* msgtype = json_object_dotget_string(obj, "type");
                    
                    if(strcmp(msgtype, "io.tcp.ping") == 0) do_ping();
                    else                                    do_network(json, netbuf);
                }

                json_value_free(json);
            }

            if(netbufpos + 1 == MAXBUFLEN) {
                printf("[NET] ERROR: received %i bytes and still no breakline. Discarding the message.\n", MAXBUFLEN);
                netbufpos = 0;
            }
        } else if(numbytes == 0) {
            break;
        }
        
    }

    hs_shutdown();

    close(sockfd);

    return 0;
}
Example #30
0
static gchar * set_network_interfaces (RequestData *request_data)
{
        gchar *interfaces, *result, *name, *path, *value;
        augeas *aug;
        JSON_Value *val;
        JSON_Array *array;
        JSON_Object *obj;
        gint if_count, i, ret;

        aug = aug_init (NULL, NULL, AUG_NONE | AUG_NO_ERR_CLOSE | AUG_NO_MODL_AUTOLOAD);
        aug_set (aug, "/augeas/load/Interfaces/lens", "Interfaces.lns");
        aug_set (aug, "/augeas/load/Interfaces/incl", "/etc/network/interfaces");
        aug_load (aug);
        interfaces = request_data->raw_request + request_data->header_size;
        val = json_parse_string (interfaces);
        if (val == NULL) {
                GST_ERROR ("parse json type interfaces failure");
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"invalid data\"\n}");
                aug_close (aug);
                return result;
        }
        array = json_value_get_array (val);
        if (array == NULL) {
                GST_ERROR ("get interfaces array failure");
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"not array type interfaces\"\n}");
                aug_close (aug);
                json_value_free (val);
                return result;
        }
        if_count = json_array_get_count (array);
        for (i = 0; i < if_count; i++) {
                obj = json_array_get_object (array, i);
                name = (gchar *)json_object_get_string (obj, "name");
                value = (gchar *)json_object_get_string (obj, "method");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/method", name);
                        aug_set (aug, path, value);
                        g_free (path);
                }
                value = (gchar *)json_object_get_string (obj, "address");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/address", name);
                        ret = aug_set (aug, path, value);
                        g_free (path);
                }
                value = (gchar *)json_object_get_string (obj, "netmask");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/netmask", name);
                        aug_set (aug, path, value);
                        g_free (path);
                }
                value = (gchar *)json_object_get_string (obj, "network");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/network", name);
                        aug_set (aug, path, value);
                        g_free (path);
                }
                value = (gchar *)json_object_get_string (obj, "broadcast");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/broadcast", name);
                        aug_set (aug, path, value);
                        g_free (path);
                }
                value = (gchar *)json_object_get_string (obj, "gateway");
                if (value != NULL) {
                        path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/gateway", name);
                        aug_set (aug, path, value);
                        g_free (path);
                }
        }
        if (aug_save (aug) == -1) {
                aug_get (aug, "/augeas//error", (const gchar **)&value);
                GST_ERROR ("set /etc/network/interface failure: %s", value);
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"%s\"\n}", value);

        } else {
                result = g_strdup ("{\n    \"result\": \"success\"\n}");
        }
        json_value_free (val);
        aug_close (aug);

        return result;
}