Esempio n. 1
0
File: config.c Progetto: indutny/bud
bud_error_t bud_config_load_frontend(JSON_Object* obj,
                                     bud_config_frontend_t* frontend) {
  JSON_Value* val;

  bud_config_load_addr(obj, (bud_config_addr_t*) frontend);

  frontend->max_send_fragment = -1;
  frontend->allow_half_open = -1;
  frontend->reneg_limit = -1;
  if (obj == NULL)
    return bud_ok();

  frontend->security = json_object_get_string(obj, "security");
  frontend->reneg_window = json_object_get_number(obj, "reneg_window");
  val = json_object_get_value(obj, "reneg_limit");
  if (val != NULL)
    frontend->reneg_limit = json_value_get_number(val);

  val = json_object_get_value(obj, "max_send_fragment");
  if (val != NULL)
    frontend->max_send_fragment = json_value_get_number(val);
  val = json_object_get_value(obj, "allow_half_open");
  if (val != NULL)
    frontend->allow_half_open = json_value_get_boolean(val);

  return bud_config_load_frontend_ifaces(obj, &frontend->interface);
}
Esempio n. 2
0
static EJSBool
json_value_to_ejsval(JSON_Value *v, ejsval *rv)
{
    switch (json_value_get_type (v)) {
    case JSONNull:
        *rv = _ejs_null;
        return EJS_TRUE;

    case JSONString:
        *rv = _ejs_string_new_utf8 (json_value_get_string(v));
        return EJS_TRUE;

    case JSONNumber:
        *rv = NUMBER_TO_EJSVAL(json_value_get_number(v));
        return EJS_TRUE;

    case JSONObject: {
        JSON_Object *obj = json_value_get_object (v);
        *rv = _ejs_object_create (_ejs_null);

        int count = json_object_get_count (obj);
        for (int i = 0; i < count; i ++) {
            const char *propkey = json_object_get_name (obj, i);
            ejsval propval;
            if (!json_value_to_ejsval (json_object_get_value (obj, propkey), &propval))
                return EJS_FALSE;
            _ejs_object_setprop_utf8 (*rv, propkey, propval);
        }

        return EJS_TRUE;
    }
        
    case JSONArray: {
        JSON_Array *arr = json_value_get_array (v);
        int count = json_array_get_count (arr);

        *rv = _ejs_array_new (count, EJS_FALSE);

        for (int i = 0; i < count; i ++) {
            ejsval propkey = _ejs_number_new (i);
            ejsval propval;
            if (!json_value_to_ejsval (json_array_get_value (arr, i), &propval))
                return EJS_FALSE;
            _ejs_object_setprop (*rv, propkey, propval);
        }

        return EJS_TRUE;
    }
    case JSONBoolean:
        *rv = BOOLEAN_TO_EJSVAL(json_value_get_boolean(v));
        return EJS_TRUE;


    case JSONError:
        EJS_NOT_IMPLEMENTED();
        return EJS_FALSE;
    }
}
Esempio n. 3
0
char *json(UDF_INIT *initid, UDF_ARGS *args,
      char *result, unsigned long *length,
      char *is_null, char *error)
{
    JSON_Value *jv = json_parse_string(args->args[0]);
    JSON_Value_Type json_type = json_value_get_type(jv);
    if(json_type==JSONError){
        *length=0;
        *is_null=1;
        *error=1;
        json_value_free(jv);
        return NULL;
    }else{
        if(json_type == JSONObject){
            JSON_Object *o = json_value_get_object(jv);
            JSON_Value *value = json_object_dotget_value(o,args->args[1]);
            if(value==NULL){
                *length = 0;
                *is_null = 0;
                return NULL;
            }else{
                *is_null = 0;
                switch(json_value_get_type(value)){
                    case JSONArray:
                        *is_null = 1;
                        break;
                    case JSONError:
                    case JSONObject:
                        *is_null = 1;
                        *error = 1;
                        break;
                    case JSONString:
                        strcpy(initid->ptr,((char*)json_value_get_string(value)));
                        break;
                    case JSONNumber:
                        sprintf(initid->ptr,"%f",json_value_get_number(value));
                        break;
                    case JSONNull:
                        *is_null = 1;
                        break;
                    case JSONBoolean:
                        sprintf(initid->ptr,"%d",json_value_get_boolean(value));
                        break;
                }
                *length = initid->ptr == NULL ? 0 : strlen(initid->ptr); 
            }
        }else{
            *is_null = 1;
        }
        json_value_free(jv);
        return initid->ptr; 
    }
}
Esempio n. 4
0
void bud_config_load_addr(JSON_Object* obj, bud_config_addr_t* addr) {
  JSON_Value* val;

  /* Backend configuration */
  addr->keepalive = -1;
  if (obj == NULL)
    return;

  addr->port = (uint16_t) json_object_get_number(obj, "port");
  addr->host = json_object_get_string(obj, "host");
  val = json_object_get_value(obj, "keepalive");
  if (val != NULL)
    addr->keepalive = json_value_get_number(val);
}
Esempio n. 5
0
static mrb_value
json_value_to_mrb_value(mrb_state* mrb, JSON_Value* value) {
  ARENA_SAVE;
  switch (json_value_get_type(value)) {
  case JSONError:
  case JSONNull:
    return mrb_nil_value();
  case JSONString:
    return mrb_str_new_cstr(mrb, json_value_get_string(value));
  case JSONNumber:
    return mrb_float_value(json_value_get_number(value));
  case JSONObject:
    {
      mrb_value hash = mrb_hash_new(mrb);
      JSON_Object* object = json_value_get_object(value);
      size_t count = json_object_get_count(object);
      int n;
      for (n = 0; n < count; n++) {
        const char* name = json_object_get_name(object, n);
        mrb_hash_set(mrb, hash, mrb_str_new_cstr(mrb, name),
          json_value_to_mrb_value(mrb, json_object_get_value(object, name)));
      }
      return hash;
    }
  case JSONArray:
    {
      mrb_value ary;
      ary = mrb_ary_new(mrb);
      JSON_Array* array = json_value_get_array(value);
      size_t count = json_array_get_count(array);
      int n;
      for (n = 0; n < count; n++) {
        JSON_Value* elem = json_array_get_value(array, n);
        mrb_ary_push(mrb, ary, json_value_to_mrb_value(mrb, elem));
      }
      return ary;
    }
  case JSONBoolean:
    if (json_value_get_boolean(value)) {
      return mrb_true_value();
    }
    return mrb_false_value();
  default:
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument");
  }
  return mrb_nil_value();
}
Esempio n. 6
0
bud_error_t bud_config_load_frontend(JSON_Object* obj,
                                     bud_config_frontend_t* frontend) {
  bud_error_t err;
  JSON_Value* val;

  bud_config_load_addr(obj, (bud_config_addr_t*) frontend);

  frontend->server_preference = -1;
  frontend->ssl3 = -1;
  frontend->max_send_fragment = -1;
  frontend->allow_half_open = -1;
  if (obj == NULL)
    return bud_ok();

  frontend->security = json_object_get_string(obj, "security");
  frontend->ciphers = json_object_get_string(obj, "ciphers");
  frontend->ecdh = json_object_get_string(obj, "ecdh");
  frontend->cert_file = json_object_get_string(obj, "cert");
  frontend->key_file = json_object_get_string(obj, "key");
  frontend->reneg_window = json_object_get_number(obj, "reneg_window");
  frontend->reneg_limit = json_object_get_number(obj, "reneg_limit");
  frontend->ticket_key = json_object_get_string(obj, "ticket_key");

  /* Get and verify NPN */
  frontend->npn = json_object_get_array(obj, "npn");
  err = bud_config_verify_npn(frontend->npn);
  if (!bud_is_ok(err))
    goto fatal;

  val = json_object_get_value(obj, "server_preference");
  if (val != NULL)
    frontend->server_preference = json_value_get_boolean(val);
  val = json_object_get_value(obj, "ssl3");
  if (val != NULL)
    frontend->ssl3 = json_value_get_boolean(val);
  val = json_object_get_value(obj, "max_send_fragment");
  if (val != NULL)
    frontend->max_send_fragment = json_value_get_number(val);
  val = json_object_get_value(obj, "allow_half_open");
  if (val != NULL)
    frontend->allow_half_open = json_value_get_boolean(val);

fatal:
  return err;
}
Esempio n. 7
0
static corto_int16 json_deserNumber(void* o, corto_primitive t, JSON_Value *v)
{

    if (json_value_get_type(v) != JSONNumber) {
        corto_seterr("expected number, got %s", json_valueTypeToString(v));
        goto error;
    }

    corto_float64 number = json_value_get_number(v);
    corto_convert(
        corto_primitive(corto_float64_o),
        &number,
        t,
        o);

    return 0;
error:
    return -1;
}
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;
}
Esempio n. 9
0
File: config.c Progetto: indutny/bud
bud_error_t bud_config_load(bud_config_t* config) {
  int i;
  bud_error_t err;
  JSON_Value* json;
  JSON_Value* val;
  JSON_Object* frontend;
  JSON_Object* obj;
  JSON_Object* log;
  JSON_Object* avail;
  JSON_Array* contexts;

  if (config->piped) {
    char* content;

    ASSERT(config->loop != NULL, "Loop should be present");
    err = bud_read_file_by_fd(config->loop, 0, &content);
    if (!bud_is_ok(err))
      goto end;

    err = bud_hashmap_insert(&config->files.hashmap,
                             kPipedConfigPath,
                             strlen(kPipedConfigPath),
                             content);
    if (!bud_is_ok(err)) {
      free(content);
      goto end;
    }

    json = json_parse_string(content);
  } else if (config->inlined) {
    json = json_parse_string(config->path);
  } else {
    const char* contents;

    err = bud_config_load_file(config, config->path, &contents);
    if (!bud_is_ok(err))
      goto end;
    json = json_parse_string(contents);
  }

  if (json == NULL) {
    err = bud_error_dstr(kBudErrJSONParse, config->path);
    goto end;
  }

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

  err = bud_config_load_tracing(&config->trace,
                                json_object_get_object(obj, "tracing"));
  if (!bud_is_ok(err))
    goto failed_alloc_path;

  /* Allocate contexts and backends */
  contexts = json_object_get_array(obj, "contexts");
  config->context_count = contexts == NULL ? 0 : json_array_get_count(contexts);
  config->contexts = calloc(config->context_count + 1,
                            sizeof(*config->contexts));
  if (config->contexts == NULL) {
    err = bud_error_str(kBudErrNoMem, "bud_context_t");
    goto failed_alloc_contexts;
  }

  config->json = json;

  /* Workers configuration */
  config->worker_count = -1;
  config->restart_timeout = -1;
  config->master_ipc = -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);
  val = json_object_get_value(obj, "master_ipc");
  if (val != NULL)
    config->master_ipc = json_value_get_boolean(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 */
  frontend = json_object_get_object(obj, "frontend");
  err = bud_config_load_frontend(frontend, &config->frontend);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* Load frontend's context */
  err = bud_context_load(frontend, &config->contexts[0]);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* Backend configuration */
  config->balance = json_object_get_string(obj, "balance");
  err = bud_config_load_backend_list(config,
                                      obj,
                                      &config->contexts[0].backend);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* User and group configuration */
  config->user = json_object_get_string(obj, "user");
  config->group = json_object_get_string(obj, "group");

  /* 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++) {
    bud_context_t* ctx;

    /* 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_load_context;
    }

    err = bud_context_load(obj, ctx);
    if (!bud_is_ok(err))
      goto failed_load_context;

    err = bud_config_load_backend_list(config, obj, &ctx->backend);
    if (!bud_is_ok(err))
      goto failed_load_context;
  }

  bud_config_set_defaults(config);

  return bud_config_init(config);

failed_load_context:
  /* Deinitalize contexts */
  for (i++; i >= 0; i--) {
    bud_context_t* ctx;

    ctx = &config->contexts[i];
    free(ctx->backend.list);
    ctx->backend.list = NULL;
  }

failed_alloc_contexts:
  free(config->contexts);
  config->contexts = NULL;
  free(config->trace.dso);
  config->trace.dso = NULL;

failed_alloc_path:
  json_value_free(json);
  config->json = NULL;

end:
  return err;
}
Esempio n. 10
0
bud_config_t* bud_config_load(uv_loop_t* loop,
                              const char* path,
                              bud_error_t* err) {
  int i;
  int context_count;
  JSON_Value* json;
  JSON_Value* val;
  JSON_Object* obj;
  JSON_Object* log;
  JSON_Object* frontend;
  JSON_Object* backend;
  JSON_Array* contexts;
  bud_config_t* config;
  bud_context_t* ctx;

  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;
  }
  contexts = json_object_get_array(obj, "contexts");
  context_count = contexts == NULL ? 0 : json_array_get_count(contexts);

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

  config->loop = loop;
  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);
  }

  /* Frontend configuration */

  frontend = json_object_get_object(obj, "frontend");
  config->frontend.proxyline = -1;
  config->frontend.keepalive = -1;
  config->frontend.server_preference = -1;
  config->frontend.ssl3 = -1;
  if (frontend != NULL) {
    config->frontend.port = (uint16_t) json_object_get_number(frontend, "port");
    config->frontend.host = json_object_get_string(frontend, "host");
    config->frontend.security = json_object_get_string(frontend, "security");
    config->frontend.npn = json_object_get_array(frontend, "npn");
    config->frontend.ciphers = json_object_get_string(frontend, "ciphers");
    config->frontend.cert_file = json_object_get_string(frontend, "cert");
    config->frontend.key_file = json_object_get_string(frontend, "key");
    config->frontend.reneg_window = json_object_get_number(frontend,
                                                           "reneg_window");
    config->frontend.reneg_limit = json_object_get_number(frontend,
                                                          "reneg_limit");

    *err = bud_config_verify_npn(config->frontend.npn);
    if (!bud_is_ok(*err))
      goto failed_get_index;

    val = json_object_get_value(frontend, "proxyline");
    if (val != NULL)
      config->frontend.proxyline = json_value_get_boolean(val);
    val = json_object_get_value(frontend, "keepalive");
    if (val != NULL)
      config->frontend.keepalive = json_value_get_number(val);
    val = json_object_get_value(frontend, "server_preference");
    if (val != NULL)
      config->frontend.server_preference = json_value_get_boolean(val);
    val = json_object_get_value(frontend, "ssl3");
    if (val != NULL)
      config->frontend.ssl3 = json_value_get_boolean(val);
  }

  /* Backend configuration */
  backend = json_object_get_object(obj, "backend");
  config->backend.keepalive = -1;
  if (backend != NULL) {
    config->backend.port = (uint16_t) json_object_get_number(backend, "port");
    config->backend.host = json_object_get_string(backend, "host");
    val = json_object_get_value(backend, "keepalive");
    if (val != NULL)
      config->backend.keepalive = json_value_get_number(val);
  }

  /* 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 < 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");

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

  bud_config_set_defaults(config);

  *err = bud_ok();
  return config;

failed_get_index:
  free(config);

failed_get_object:
  json_value_free(json);

end:
  return NULL;
}
static IOTHUB_DEVICE_METHOD_RESULT parseResponseJson(BUFFER_HANDLE responseJson, int* responseStatus, unsigned char** responsePayload, size_t* responsePayloadSize)
{
    IOTHUB_DEVICE_METHOD_RESULT result;
    JSON_Value* root_value;
    JSON_Object* json_object;
    JSON_Value* statusJsonValue;
    JSON_Value* payloadJsonValue;
    char* payload;
    STRING_HANDLE jsonStringHandle;
    const char* jsonStr;
    unsigned char* bufferStr;
    
    if ((bufferStr = BUFFER_u_char(responseJson)) == NULL)
    {
        LogError("BUFFER_u_char failed");
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((jsonStringHandle = STRING_from_byte_array(bufferStr, BUFFER_length(responseJson))) == NULL)
    {
        LogError("STRING_construct_n failed");
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((jsonStr = STRING_c_str(jsonStringHandle)) == NULL)
    {
        LogError("STRING_c_str failed");
        STRING_delete(jsonStringHandle);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((root_value = json_parse_string(jsonStr)) == NULL)
    {
        LogError("json_parse_string failed");
        STRING_delete(jsonStringHandle);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((json_object = json_value_get_object(root_value)) == NULL)
    {
        LogError("json_value_get_object failed");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((statusJsonValue = json_object_get_value(json_object, "status")) == NULL)
    {
        LogError("json_object_get_value failed for status");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((payloadJsonValue = json_object_get_value(json_object, "payload")) == NULL)
    {
        LogError("json_object_get_value failed for payload");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((payload = json_serialize_to_string(payloadJsonValue)) == NULL)
    {
        LogError("json_serialize_to_string failed for payload");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else
    {
        *responseStatus = (int)json_value_get_number(statusJsonValue);
        *responsePayload = (unsigned char *)payload;
        *responsePayloadSize = strlen(payload);

        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_OK;
    }

    return result;
}
Esempio n. 12
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;
                    }
                }
            }
        }
    }
}
Esempio n. 13
0
// parses a JSON object containing zones and calculates the zone that fits the given latitude and longitude best, bestDistance is used internally and contains the distance from the midpoint of the selected zone
static void ParseZones(char **bestZone, double *bestDistance, JSON_Object *zonesJson, double latitude, double longitude)
{
    *bestDistance = -1.0;

    if (zonesJson != NULL)
    {
        size_t zoneCount = json_object_get_count(zonesJson);

        for (int i = 0; i < zoneCount; i++)
        {
            const char *zoneName = json_object_get_name(zonesJson, i);
            JSON_Value *valueJson = json_object_get_value(zonesJson, zoneName);

            if (valueJson != NULL && valueJson->type == JSONObject)
            {
                JSON_Object *zoneJson = json_value_get_object(valueJson);
                double topLeftX = 0.0, topLeftY = 0.0, bottomRightX = 0.0, bottomRightY = 0.0;
                JSON_Object *subzonesJson = NULL;

                size_t propertyCount = json_object_get_count(zoneJson);
                for (int j = 0; j < propertyCount; j++)
                {
                    const char *propertyName = json_object_get_name(zoneJson, j);
                    JSON_Value *propertyJson = json_object_get_value(zoneJson, propertyName);

                    if (propertyJson != NULL)
                    {
                        if (propertyJson->type == JSONNumber)
                        {
                            double number = json_value_get_number(propertyJson);

                            if (strcmp(propertyName, "tl_x") == 0)
                                topLeftX = number;
                            else if (strcmp(propertyName, "tl_y") == 0)
                                topLeftY = number;
                            else if (strcmp(propertyName, "br_x") == 0)
                                bottomRightX = number;
                            else if (strcmp(propertyName, "br_y") == 0)
                                bottomRightY = number;
                        }
                        else if (propertyJson->type == JSONObject && (strcmp(propertyName, "subzones") == 0))
                            subzonesJson = json_value_get_object(propertyJson);
                    }
                }

                if (topLeftX != 0.0 && topLeftY != 0.0 && bottomRightX != 0.0 && bottomRightY != 0.0 && longitude > topLeftX && latitude < topLeftY && longitude < bottomRightX && latitude > bottomRightY)
                {
                    double latitudeMidpoint = 0.0, longitudeMidpoint = 0.0;
                    GetMidpoint(&latitudeMidpoint, &longitudeMidpoint, topLeftY, topLeftX, bottomRightY, bottomRightX);
                    double distance = GetDistance(latitudeMidpoint, longitudeMidpoint, latitude, longitude);
//                    printf("Distance from %s = %f\n", zoneName, distance);
                    if (*bestDistance == -1.0 || distance < *bestDistance)
                    {
                        if (*bestZone != NULL)
                        {
                            free(*bestZone);
                            *bestZone = NULL;
                        }

                        if (subzonesJson != NULL)
                        {
                            char *bestSubzone = NULL;
                            double subzoneDistance = -1.0;
                            ParseZones(&bestSubzone, &subzoneDistance, subzonesJson, latitude, longitude);

                            if (bestSubzone != NULL && subzoneDistance != -1.0)
                            {
                                *bestDistance = subzoneDistance;
                                *bestZone = bestSubzone;
                            }
                        }

                        if (*bestZone == NULL)
                        {
                            *bestDistance = distance;
                            *bestZone = (char*) malloc(strlen(zoneName) + 1);
                            if (*bestZone != NULL)
                                strcpy(*bestZone, zoneName);
                        }
                    }
                }
            }
        }
    }
}
Esempio n. 14
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;
}
Esempio n. 15
0
static mrb_value
json_value_to_mrb_value(mrb_state* mrb, JSON_Value* value) {
  mrb_value ret;
  switch (json_value_get_type(value)) {
  case JSONError:
  case JSONNull:
    ret = mrb_nil_value();
    break;
  case JSONString:
    ret = mrb_str_new_cstr(mrb, json_value_get_string(value));
    break;
  case JSONNumber:
    {
      double d = json_value_get_number(value);
      if (floor(d) == d) {
        ret = mrb_fixnum_value(d);
      }
      else {
        ret = mrb_float_value(mrb, d);
      }
    }
    break;
  case JSONObject:
    {
      mrb_value hash = mrb_hash_new(mrb);
      JSON_Object* object = json_value_get_object(value);
      size_t count = json_object_get_count(object);
      size_t n;
      for (n = 0; n < count; n++) {
        int ai = mrb_gc_arena_save(mrb);
        const char* name = json_object_get_name(object, n);
        mrb_hash_set(mrb, hash, mrb_str_new_cstr(mrb, name),
          json_value_to_mrb_value(mrb, json_object_get_value(object, name)));
        mrb_gc_arena_restore(mrb, ai);
      }
      ret = hash;
    }
    break;
  case JSONArray:
    {
      mrb_value ary;
      JSON_Array* array;
      size_t n, count;
      ary = mrb_ary_new(mrb);
      array = json_value_get_array(value);
      count = json_array_get_count(array);
      for (n = 0; n < count; n++) {
        int ai = mrb_gc_arena_save(mrb);
        JSON_Value* elem = json_array_get_value(array, n);
        mrb_ary_push(mrb, ary, json_value_to_mrb_value(mrb, elem));
        mrb_gc_arena_restore(mrb, ai);
      }
      ret = ary;
    }
    break;
  case JSONBoolean:
    if (json_value_get_boolean(value))
      ret = mrb_true_value();
    else
      ret = mrb_false_value();
    break;
  default:
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument");
  }
  return ret;
}
Esempio n. 16
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;
}