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
corto_int16 json_deserReference(void* p, corto_type t, JSON_Value* v)
{
    switch(json_value_get_type(v)) {
    case JSONString: {
        const char* reference = json_value_get_string(v);
        corto_object o = corto_resolve(NULL, (corto_string)reference);
        if (!o) {
            corto_error("unresolved reference \"%s\"", reference);
            goto error;
        }

        if (!corto_instanceof(t, o)) {
            corto_error("%s is not an instance of %s", reference, corto_idof(t));
        }

        corto_setref(p, o);
        corto_release(o);
        break;
    }
    case JSONObject: {
        JSON_Object* obj = json_value_get_object(v);

        JSON_Value* type = json_object_get_value(obj, "type");
        if (json_value_get_type(type) != JSONString) {
            corto_seterr("type parameter of anonymous object must be a string");
            goto error;
        }
        corto_type cortoType = corto_resolve(NULL, (char*)json_value_get_string(type));
        if (!cortoType) {
            corto_seterr("type '%s' not found for anonymous object", json_value_get_string(type));
            goto error;
        }

        corto_object cortoObj = *(corto_object*)p;
        if (!cortoObj || (corto_typeof(cortoObj) != cortoType)) {
            cortoObj = corto_create(cortoType);
            corto_setref(p, cortoObj);
            corto_release(cortoObj);
        }
        corto_release(cortoType);

        JSON_Value* value = json_object_get_value(obj, "value");
        if (json_deserType(cortoObj, cortoType, value)) {
            goto error;
        }
        break;
    }
    case JSONNull:
        corto_setref(p, NULL);
        break;
    default:
        corto_seterr("expected string, null or object (reference), got %s", json_valueTypeToString(v));
        break;
    }

    return 0;
error:
    return -1;
}
Esempio n. 3
0
File: config.c Progetto: indutny/bud
bud_error_t bud_config_load_backend(bud_config_t* config,
                                    JSON_Object* obj,
                                    bud_config_backend_t* backend,
                                    bud_hashmap_t* map,
                                    unsigned int* ext_count) {
  bud_error_t err;
  JSON_Value* val;
  const char* external;
  int r;

  bud_config_load_addr(obj, (bud_config_addr_t*) backend);
  backend->config = config;
  backend->xforward = -1;

  val = json_object_get_value(obj, "proxyline");
  if (json_value_get_type(val) == JSONString) {
    const char* pline;

    pline = json_value_get_string(val);
    if (strcmp(pline, "haproxy") == 0)
      backend->proxyline = kBudProxylineHAProxy;
    else if (strcmp(pline, "json") == 0)
      backend->proxyline = kBudProxylineJSON;
    else
      return bud_error_dstr(kBudErrProxyline, pline);
  } else {
    backend->proxyline = val != NULL && json_value_get_boolean(val) ?
        kBudProxylineHAProxy :
        kBudProxylineNone;
  }

  val = json_object_get_value(obj, "x-forward");
  if (val != NULL)
    backend->xforward = json_value_get_boolean(val);

  /* Set defaults here to use them in sni.c */
  bud_config_set_backend_defaults(backend);

  r = bud_config_str_to_addr(backend->host, backend->port, &backend->addr);
  if (r != 0)
    return bud_error_num(kBudErrPton, r);

  external = json_object_get_string(obj, "external");
  if (external == NULL)
    return bud_ok();

  /* Insert backend into a hashmap */
  err = bud_hashmap_insert(map, external, strlen(external), backend);
  if (!bud_is_ok(err))
    return err;

  (*ext_count)++;

  return bud_ok();
}
Esempio n. 4
0
File: parson.c Progetto: EQ4/faudio
static int json_object_add(JSON_Object *object, const char *name, JSON_Value *value)
{
    size_t index;

    if (object->count >= object->capacity) {
        size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);

        if (new_capacity > OBJECT_MAX_CAPACITY) {
            return ERROR;
        }

        if (json_object_resize(object, new_capacity) == ERROR) {
            return ERROR;
        }
    }

    if (json_object_get_value(object, name) != NULL) {
        return ERROR;
    }

    index = object->count;
    object->names[index] = parson_strndup(name, strlen(name));

    if (!object->names[index]) {
        return ERROR;
    }

    object->values[index] = value;
    object->count++;
    return SUCCESS;
}
Esempio n. 5
0
int json_object_set(json_t *json, const char *key, json_t *value)
{
    json_object_value_t *ov = NULL;

    if ( ! json_is_object(json))
        return 1;

    ov = json_object_get_value((json_object_t *)json, key);
    if (ov) {
        ov->value = value;
    } else {
        ov = (json_object_value_t *)malloc(sizeof(json_object_value_t));
        if ( ! ov)
            return 1;

        ov->key = strdup(key);
        ov->value = value;

        if (((json_object_t *)json)->first) {
            ov->prev = ((json_object_t *)json)->last;
            ov->next = NULL;
            ((json_object_t *)json)->last->next = ov;
            ((json_object_t *)json)->last = ov;
            ((json_object_t *)json)->size++;
        } else {
            ov->prev = ov->next = NULL;
            ((json_object_t *)json)->first =
                ((json_object_t *)json)->last = ov;
            ((json_object_t *)json)->size = 1;
        }
    }

    return 0;
}
Esempio n. 6
0
/* Testing correctness of parsed values */
void test_suite_2(void) {
    JSON_Value *root_value;
    JSON_Object *object;
    JSON_Array *array;
    int i;
    const char *filename = "tests/test_2.txt";
    printf("Testing %s:\n", filename);
    root_value = json_parse_file(filename);
    TEST(root_value);
    TEST(json_value_get_type(root_value) == JSONObject);
    object = json_value_get_object(root_value);
    TEST(STREQ(json_object_get_string(object, "string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(object, "utf string"), "lorem ipsum"));
    TEST(json_object_get_number(object, "positive one") == 1.0);
    TEST(json_object_get_number(object, "negative one") == -1.0);
    TEST(json_object_get_number(object, "hard to parse number") == -0.000314);
    TEST(json_object_get_boolean(object, "boolean true") == 1);
    TEST(json_object_get_boolean(object, "boolean false") == 0);
    TEST(json_value_get_type(json_object_get_value(object, "null")) == JSONNull);
    
    array = json_object_get_array(object, "string array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    
    array = json_object_get_array(object, "x^2 array");
    if (array != NULL) {
        for (i = 0; i < json_array_get_count(array); i++) {
            TEST(json_array_get_number(array, i) == (i * i));
        }
    } else {
        tests_failed++;
    }
    
    TEST(json_object_get_array(object, "non existent array") == NULL);
    TEST(STREQ(json_object_dotget_string(object, "object.nested string"), "str"));
    TEST(json_object_dotget_boolean(object, "object.nested true") == 1);
    TEST(json_object_dotget_boolean(object, "object.nested false") == 0);
    TEST(json_object_dotget_value(object, "object.nested null") != NULL);
    TEST(json_object_dotget_number(object, "object.nested number") == 123);
    
    TEST(json_object_dotget_value(object, "should.be.null") == NULL);
    TEST(json_object_dotget_value(object, "should.be.null.") == NULL);
    TEST(json_object_dotget_value(object, ".") == NULL);
    TEST(json_object_dotget_value(object, "") == NULL);
    
    array = json_object_dotget_array(object, "object.nested array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    TEST(json_object_dotget_boolean(object, "nested true"));    
    json_value_free(root_value);
}
Esempio n. 7
0
/* Testing correctness of parsed values */
void test_suite_2(JSON_Value *root_value) {
    JSON_Object *root_object;
    JSON_Array *array;
    size_t i;
    TEST(root_value);
    TEST(json_value_get_type(root_value) == JSONObject);
    root_object = json_value_get_object(root_value);
    TEST(STREQ(json_object_get_string(root_object, "string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(root_object, "utf string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(root_object, "utf-8 string"), "あいうえお"));
    TEST(STREQ(json_object_get_string(root_object, "surrogate string"), "lorem𝄞ipsum𝍧lorem"));
    TEST(json_object_get_number(root_object, "positive one") == 1.0);
    TEST(json_object_get_number(root_object, "negative one") == -1.0);
    TEST(json_object_get_number(root_object, "hard to parse number") == -0.000314);
    TEST(json_object_get_boolean(root_object, "boolean true") == 1);
    TEST(json_object_get_boolean(root_object, "boolean false") == 0);
    TEST(json_value_get_type(json_object_get_value(root_object, "null")) == JSONNull);
    
    array = json_object_get_array(root_object, "string array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    
    array = json_object_get_array(root_object, "x^2 array");
    if (array != NULL) {
        for (i = 0; i < json_array_get_count(array); i++) {
            TEST(json_array_get_number(array, i) == (i * i));
        }
    } else {
        tests_failed++;
    }
    
    TEST(json_object_get_array(root_object, "non existent array") == NULL);
    TEST(STREQ(json_object_dotget_string(root_object, "object.nested string"), "str"));
    TEST(json_object_dotget_boolean(root_object, "object.nested true") == 1);
    TEST(json_object_dotget_boolean(root_object, "object.nested false") == 0);
    TEST(json_object_dotget_value(root_object, "object.nested null") != NULL);
    TEST(json_object_dotget_number(root_object, "object.nested number") == 123);
    
    TEST(json_object_dotget_value(root_object, "should.be.null") == NULL);
    TEST(json_object_dotget_value(root_object, "should.be.null.") == NULL);
    TEST(json_object_dotget_value(root_object, ".") == NULL);
    TEST(json_object_dotget_value(root_object, "") == NULL);
    
    array = json_object_dotget_array(root_object, "object.nested array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    TEST(json_object_dotget_boolean(root_object, "nested true"));
    
    TEST(STREQ(json_object_get_string(root_object, "/**/"), "comment"));
    TEST(STREQ(json_object_get_string(root_object, "//"), "comment"));
}
Esempio n. 8
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. 9
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. 10
0
// retrieves the balancer url with the lowest load, if there are several balancers with the same load one of these is randomly selected
static char *GetBalancerUrl(void)
{
    char *bestUrl = NULL;

    char *balance = GetUrl(URL_BALANCE);
    if (balance != NULL)
    {
        JSON_Value *rootJson = json_parse_string(balance);
        free(balance);
        balance = NULL;

        if (rootJson != NULL && rootJson->type == JSONObject)
        {
            JSON_Object *serversJson = json_value_get_object(rootJson);

            if (serversJson != NULL)
            {
                size_t serverCount = json_object_get_count(serversJson);
                int bestLoad = 0;

                for (int i = 0; i < serverCount; i++)
                {
                    const char *url = json_object_get_name(serversJson, i);

                    JSON_Value *value = json_object_get_value(serversJson, url);

                    if (value != NULL && value->type == JSONNumber)
                    {
                        int load = (int) json_object_get_number(serversJson, url);

                        if (load != 0 && (bestUrl == NULL || load <= bestLoad/* || (load == bestLoad && rand() % 2)*/))
                        {
                            if (bestUrl != NULL)
                            {
                                free(bestUrl);
                                bestUrl = NULL;
                            }

                            bestUrl = (char*) malloc(strlen(url) + 1);
                            if (bestUrl != NULL)
                                strcpy(bestUrl, url);

                            bestLoad = load;
                        }
                    }
                }
            }

            json_value_free(rootJson);
            rootJson = NULL;
        }
    }

    return bestUrl;
}
Esempio n. 11
0
json_t *json_object_get(json_t *json, const char *key)
{
    struct json_object_value_t *ov;

    ov = json_object_get_value((json_object_t *)json, key);
    if (ov) {
        return ov->value;
    }

    return NULL;
}
static int parse_loader(JSON_Object* loader_json, GATEWAY_MODULE_LOADER_INFO* loader_info)
{
    int result;

    // get loader name; we assume it is "native" if the JSON doesn't have a name
    /*Codes_SRS_NATIVEMODULEHOST_17_013: [ NativeModuleHost_Create shall get "name" string from the "outprocess.loader" object. ]*/
    const char* loader_name = json_object_get_string(loader_json, LOADER_NAME_KEY);
    if (loader_name == NULL)
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_014: [ If the loader name string is not present, then NativeModuleHost_Create shall assume the loader is the native dynamic library loader name. ]*/
        loader_name = DYNAMIC_LOADER_NAME;
    }

    // locate the loader
    /*Codes_SRS_NATIVEMODULEHOST_17_015: [ NativeModuleHost_Create shall find the module loader by name. ]*/
    const MODULE_LOADER* loader = ModuleLoader_FindByName(loader_name);
    if (loader == NULL)
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
        LogError("Loader JSON has a non-existent loader 'name' specified - %s.", loader_name);
        result = __LINE__;
    }
    else
    {
        loader_info->loader = loader;

        // get entrypoint
        /*Codes_SRS_NATIVEMODULEHOST_17_016: [ NativeModuleHost_Create shall get "entrypoint" string from the "outprocess.loader" object. ]*/
        JSON_Value* entrypoint_json = json_object_get_value(loader_json, LOADER_ENTRYPOINT_KEY);
        if (entrypoint_json == NULL)
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
            LogError("An error occurred when getting the entrypoint for loader - %s.", loader_name);
            result = __LINE__;
        }
        else
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_017: [ NativeModuleHost_Create shall parse the entrypoint string. ]*/
            loader_info->entrypoint = loader->api->ParseEntrypointFromJson(loader, entrypoint_json);
            if (loader_info->entrypoint == NULL)
            {
                /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                LogError("An error occurred when parsing the entrypoint for loader - %s.", loader_name);
                result = __LINE__;
            }
            else
            {
                result = 0;
            }
        }
    }
    return result;
}
Esempio n. 13
0
corto_int16 json_deserialize(corto_value *v, corto_string s)
{
    corto_assert(v != NULL, "NULL passed to json_deserialize");

    char *json = s;
    if ((json[0] != '{') && (json[1] != '[') && (json[0] != '[')) {
        corto_asprintf(&json, "{\"value\": %s}", json);
    }

    JSON_Value *jsonValue = json_parse_string(json);
    if (!jsonValue) {
        corto_seterr("invalid JSON '%s'", json);
        goto error;
    }

    corto_type type = corto_value_getType(v);

    if (type->kind == CORTO_PRIMITIVE) {
        JSON_Object* jsonObj = json_value_get_object(jsonValue);
        if (!jsonObj) {
            corto_seterr("json: invalid JSON for primitive value '%s'", json);
            goto error;
        }

        JSON_Value *jsonValue = json_object_get_value(jsonObj, "value");
        if (!jsonValue) {
            corto_seterr("json: missing 'value' field for primitive value '%s'", json);
            goto error;
        }
    }

    if (json_deserialize_from_JSON_Value(v, jsonValue)) {
        goto error;
    }

    if (json != s) {
        corto_dealloc(json);
    }

    return 0;
error:
    if (json != s) {
        corto_dealloc(json);
    }

    if (jsonValue) {
        json_value_free(jsonValue);
    }
    return -1;
}
Esempio n. 14
0
static void GenStat(Stat* s, JSON_Value* v) {
    switch (json_value_get_type(v)) {
    case JSONObject:
        {
            JSON_Object* o = json_value_get_object(v);
            size_t count = json_object_get_count(o);

            for (size_t i = 0; i < count; i++) {
                const char* name = json_object_get_name(o, i);
                GenStat(s, json_object_get_value(o, name));
                s->stringLength += strlen(name);
            }
            s->objectCount++;
            s->memberCount += count;
            s->stringCount += count;
        }
        break;

    case JSONArray:
        {
            JSON_Array* a = json_value_get_array(v);
            size_t count = json_array_get_count(a);
            for (int i = 0; i < count; i++)
                GenStat(s, json_array_get_value(a, i));
            s->arrayCount++;
            s->elementCount += count;
        }
        break;

    case JSONString:
        s->stringCount++;
        s->stringLength += strlen(json_value_get_string(v));
        break;

    case JSONNumber:
        s->numberCount++;
        break;

    case JSONBoolean:
        if (json_value_get_boolean(v))
            s->trueCount++;
        else
            s->falseCount++;
        break;

    case JSONNull:
        s->nullCount++;
        break;
    }
}
Esempio n. 15
0
bud_error_t bud_config_load_backend(bud_config_t* config,
                                    JSON_Object* obj,
                                    bud_config_backend_t* backend) {
  JSON_Value* val;

  bud_config_load_addr(obj, (bud_config_addr_t*) backend);
  backend->config = config;
  backend->proxyline = -1;
  backend->xforward = -1;

  val = json_object_get_value(obj, "proxyline");
  if (val != NULL)
    backend->proxyline = json_value_get_boolean(val);

  val = json_object_get_value(obj, "x-forward");
  if (val != NULL)
    backend->xforward = json_value_get_boolean(val);

  /* Set defaults here to use them in sni.c */
  bud_config_set_backend_defaults(backend);

  return bud_ok();
}
Esempio n. 16
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. 17
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. 18
0
static int json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
    size_t index;
    void *reallocated_ptr;
    if (object->count >= object->capacity) {
        size_t new_capacity = object->capacity * 2;
        if (new_capacity > MAX_CAPACITY) { return 0; }
        reallocated_ptr = parson_realloc((void*)object->names, new_capacity * sizeof(char*));
        if (!reallocated_ptr) { return 0;}
        object->names = (const char**)reallocated_ptr;
        reallocated_ptr = parson_realloc(object->values, new_capacity * sizeof(JSON_Value*));
        if (!reallocated_ptr) { return 0;}
        object->values = (JSON_Value**)reallocated_ptr;
        object->capacity = new_capacity;
    }
    if (json_object_get_value(object, name) != NULL) { return 0; }
    index = object->count;
    object->names[index] = parson_strdup(name);
    if (!object->names[index]) { return 0; }
    object->values[index] = value;
    object->count++;
    return 1;
}
Esempio n. 19
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. 20
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;
}
static MODULE_HANDLE NativeModuleHost_Create(BROKER_HANDLE broker, const void* configuration)
{
    MODULE_HOST * result;
    if (broker == NULL || configuration == NULL)
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_008: [ NativeModuleHost_Create shall return NULL if broker is NULL. ]*/
        /*Codes_SRS_NATIVEMODULEHOST_17_009: [ NativeModuleHost_Create shall return NULL if configuration does not contain valid JSON. ]*/
        LogError("broker [%p] or configuration [%p] is NULL, both are required", broker, configuration);
        result = NULL;
    }
    else
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_010: [ NativeModuleHost_Create shall intialize the Module_Loader. ]*/
        if (ModuleLoader_Initialize() != MODULE_LOADER_SUCCESS)
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
            LogError("ModuleLoader_Initialize failed");
            result = NULL;
        }
        else
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_011: [ NativeModuleHost_Create shall parse the configuration JSON. ]*/
            char * outprocess_module_args = (char *)configuration;
            JSON_Value *root_value = json_parse_string(outprocess_module_args);
            JSON_Object * module_host_args;
            if ((root_value == NULL) ||
                ((module_host_args = json_value_get_object(root_value)) == NULL))
            {
                if (root_value != NULL)
                {
                    json_value_free(root_value);
                }
                LogError("NativeModuleHost_Create could not parse arguments as JSON");
                result = NULL;
            }
            else
            {
                /*Codes_SRS_NATIVEMODULEHOST_17_035: [ If the "outprocess.loaders" array exists in the configuration JSON, NativeModuleHost_Create shall initialize the Module_Loader from this array. ]*/
                JSON_Value * loaders_array = json_object_get_value(module_host_args, OOP_MODULE_LOADERS_ARRAY_KEY);
                if ((loaders_array != NULL) &&
                    (ModuleLoader_InitializeFromJson(loaders_array) != MODULE_LOADER_SUCCESS))
                {
                    LogError("NativeModuleHost_Create could not extract loaders array from module arguments.");
                    result = NULL;
                }
                else
                {
                    /*Codes_SRS_NATIVEMODULEHOST_17_012: [ NativeModuleHost_Create shall get the "outprocess.loader" object from the configuration JSON. ]*/
                    JSON_Object * loader_args = json_object_get_object(module_host_args, OOP_MODULE_LOADER_KEY);
                    if (loader_args == NULL)
                    {
                        LogError("NativeModuleHost_Create could not get loader arguments.");
                        result = NULL;
                    }
                    else
                    {
                        GATEWAY_MODULE_LOADER_INFO loader_info;
                        if (parse_loader(loader_args, &loader_info) != 0)
                        {
                            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                            LogError("NativeModuleHost_Create could not extract loader information from loader arguments.");
                            result = NULL;
                        }
                        else
                        {
                            // Have loader and entrypoint now, get module.
                            result = (MODULE_HOST*)malloc(sizeof(MODULE_HOST));
							if (result == NULL)
							{
								LogError("NativeModuleHost_Create could not allocate module.");
								result = NULL;
							}
							else
							{
								/*Codes_SRS_NATIVEMODULEHOST_17_018: [ NativeModuleHost_Create shall get the "module.args" object from the configuration JSON. ]*/
								JSON_Value * module_args = json_object_get_value(module_host_args, OOP_MODULE_ARGS_KEY);
								char * module_args_string = json_serialize_to_string(module_args);
								if (module_create(result, broker, &loader_info, module_args_string) != 0)
								{
									/*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
									LogError("NativeModuleHost_Create could not load module.");
									free(result);
									result = NULL;
								}
								/*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
								json_free_serialized_string(module_args_string);
							}
                            loader_info.loader->api->FreeEntrypoint(loader_info.loader, loader_info.entrypoint);
                        }
                    }
                }
                /*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
                json_value_free(root_value);
            }
            if (result == NULL)
            {
                // failed to create a module, give up entirely.
                /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                ModuleLoader_Destroy();
            }
        }
    }
    return result;
}
Esempio n. 22
0
bud_error_t bud_sni_from_json(bud_config_t* config,
                              struct json_value_t* json,
                              bud_context_t* ctx) {
  JSON_Object* obj;
  JSON_Value* val;
  const char* cert_str;
  const char* key_str;
  const char* pass_str;
  JSON_Array* cert_strs;
  JSON_Array* key_strs;
  JSON_Array* pass_strs;
  bud_error_t err;

  cert_str = NULL;
  key_str = NULL;
  pass_str = NULL;
  cert_strs = NULL;
  key_strs = NULL;
  pass_strs = NULL;

  obj = json_value_get_object(json);
  val = json_object_get_value(obj, "cert");
  if (json_value_get_type(val) == JSONString)
    cert_str = json_value_get_string(val);
  else
    cert_strs = json_value_get_array(val);
  val = json_object_get_value(obj, "key");
  if (json_value_get_type(val) == JSONString)
    key_str = json_value_get_string(val);
  else
    key_strs = json_value_get_array(val);
  val = json_object_get_value(obj, "passphrase");
  if (json_value_get_type(val) == JSONString)
    pass_str = json_value_get_string(val);
  else
    pass_strs = json_value_get_array(val);

  if (obj == NULL ||
      !((cert_str != NULL && key_str != NULL) ||
        (cert_strs != NULL && key_strs != NULL))) {
    err = bud_error_str(kBudErrJSONParse, "<SNI Response>");
    goto fatal;
  }

  /* Load NPN from response */
  memset(ctx, 0, sizeof(*ctx));
  ctx->cert_file = cert_str;
  ctx->key_file = key_str;
  ctx->key_pass = pass_str;
  ctx->cert_files = cert_strs;
  ctx->key_files = key_strs;
  ctx->key_passes = pass_strs;
  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");
  ctx->npn = json_object_get_array(obj, "npn");
  ctx->ca_array = json_object_get_array(obj, "ca");
  val = json_object_get_value(obj, "request_cert");
  if (val != NULL)
    ctx->request_cert = json_value_get_boolean(val);
  err = bud_config_load_backend_list(config, obj, &ctx->backend);
  if (!bud_is_ok(err))
    goto fatal;

  err = bud_context_init(config, ctx);

  /* Make sure that deallocated values won't be used */
  ctx->cert_file = NULL;
  ctx->key_file = NULL;
  ctx->key_pass = NULL;
  ctx->cert_files = NULL;
  ctx->key_files = NULL;
  ctx->key_passes = NULL;
  if (!bud_is_ok(err))
    goto fatal;

  return bud_ok();

fatal:
  if (!bud_is_ok(err)) {
    SSL_CTX_free(ctx->ctx);
    ctx->ctx = NULL;
  }
  free(ctx->backend.list);
  ctx->backend.list = NULL;
  return err;
}
Esempio n. 23
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;
}
static MODULE_LOADER_RESULT add_loader_from_json(const JSON_Value* loader, size_t index)
{
    MODULE_LOADER_RESULT result;

    if (json_value_get_type(loader) != JSONObject)
    {
        LogError("loader %zu is not a JSON object", index);

        /*Codes_SRS_MODULE_LOADER_13_065: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an entry in the loaders array is not a JSON object. ]*/
        result = MODULE_LOADER_ERROR;
    }
    else
    {
        JSON_Object* loader_object = json_value_get_object(loader);
        if (loader_object == NULL)
        {
            LogError("json_value_get_object failed for loader %zu", index);

            /*Codes_SRS_MODULE_LOADER_13_064: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/
            result = MODULE_LOADER_ERROR;
        }
        else
        {
            const char* type = json_object_get_string(loader_object, "type");
            const char* loader_name = json_object_get_string(loader_object, "name");
            if ((type == NULL || loader_name == NULL) ||
                (strlen(type) == 0 || strlen(loader_name) == 0))
            {
                LogError(
                    "invalid type and/or name for loader %zu. "
                    "type = %s, name = %s",
                    index, type, loader_name
                );

                /*Codes_SRS_MODULE_LOADER_13_066: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if a loader entry's name or type fields are NULL or are empty strings. ]*/
                result = MODULE_LOADER_ERROR;
            }
            else
            {
                MODULE_LOADER_TYPE loader_type = ModuleLoader_ParseType(type);
                if (loader_type == UNKNOWN)
                {
                    LogError("loader type %s for loader %zu is invalid", type, index);

                    /*Codes_SRS_MODULE_LOADER_13_067: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if a loader entry's type field has an unknown value. ]*/
                    result = MODULE_LOADER_ERROR;
                }
                else
                {
                    // get the default loader for the given type
                    MODULE_LOADER* default_loader = ModuleLoader_GetDefaultLoaderForType(loader_type);
                    if (default_loader == NULL)
                    {
                        LogError(
                            "no default module loader for type %s was "
                            "found for loader entry %zu",
                            type, index
                        );

                        /*Codes_SRS_MODULE_LOADER_13_068: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if no default loader could be located for a loader entry. ]*/
                        result = MODULE_LOADER_ERROR;
                    }
                    else
                    {
                        JSON_Value* configuration = json_object_get_value(loader_object, "configuration");
                        MODULE_LOADER_BASE_CONFIGURATION* loader_configuration;
                        if (configuration != NULL)
                        {
                            /*Codes_SRS_MODULE_LOADER_13_069: [ ModuleLoader_InitializeFromJson shall invoke ParseConfigurationFromJson to parse the loader entry's configuration JSON. ]*/
                            loader_configuration = default_loader->api->ParseConfigurationFromJson(default_loader, configuration);
                        }
                        else
                        {
                            loader_configuration = NULL;
                        }

                        // now we have all the information we need to construct/replace a MODULE_LOADER
                        bool is_default_loader = ModuleLoader_IsDefaultLoader(loader_name);
                        MODULE_LOADER* new_loader = is_default_loader ? default_loader :
                                                        (MODULE_LOADER*)malloc(sizeof(MODULE_LOADER));
                        if (new_loader == NULL)
                        {
                            LogError("malloc failed for MODULE_LOADER struct for loader %zu", index);

                            /*Codes_SRS_MODULE_LOADER_13_064: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/
                            result = MODULE_LOADER_ERROR;
                        }
                        else
                        {
                            if (!is_default_loader)
                            {
                                new_loader->name = malloc(strlen(loader_name) + 1);
                                if (new_loader->name == NULL)
                                {
                                    LogError("malloc failed for loader name string for loader %zu", index);
                                    if (loader_configuration != NULL)
                                    {
                                        default_loader->api->FreeConfiguration(default_loader, loader_configuration);
                                    }
                                    free(new_loader);

                                    /*Codes_SRS_MODULE_LOADER_13_064: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/
                                    result = MODULE_LOADER_ERROR;
                                }
                                else
                                {
                                    strcpy((char *)new_loader->name, loader_name);
                                    new_loader->type = loader_type;
                                    new_loader->configuration = loader_configuration;
                                    new_loader->api = default_loader->api;

                                    /*Codes_SRS_MODULE_LOADER_13_070: [ ModuleLoader_InitializeFromJson shall allocate a MODULE_LOADER and add the loader to the gateway by calling ModuleLoader_Add if the loader entry is not for a default loader. ]*/

                                    // add this module to the loaders list
                                    result = ModuleLoader_Add(new_loader);
                                    if (result != MODULE_LOADER_SUCCESS)
                                    {
                                        /*Codes_SRS_MODULE_LOADER_13_071: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if ModuleLoader_Add fails. ]*/
                                        LogError("ModuleLoader_Add failed");
                                        if (loader_configuration != NULL)
                                        {
                                            default_loader->api->FreeConfiguration(default_loader, loader_configuration);
                                        }
                                        free((void *)new_loader->name);
                                        free(new_loader);
                                    }
                                }
                            }
                            else
                            {
                                /*Codes_SRS_MODULE_LOADER_13_072: [ ModuleLoader_InitializeFromJson shall update the configuration on the default loader if the entry is for a default loader by calling ModuleLoader_UpdateConfiguration. ]*/

                                // since we are updating the configuration on an existing loader, we only
                                // replace the configuration field
                                result = ModuleLoader_UpdateConfiguration(new_loader, loader_configuration);
                            }
                        }
                    }
                }
            }
        }
    }

    return result;
}
Esempio n. 26
0
static corto_int16 json_deserComposite(void* p, corto_type t, JSON_Value *v)
{
    corto_assert(t->kind == CORTO_COMPOSITE, "not deserializing composite");

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

    JSON_Object* o = json_value_get_object(v);
    size_t count = json_object_get_count(o);
    size_t i;
    corto_bool isUnion = corto_interface(t)->kind == CORTO_UNION;
    corto_int32 discriminator = 0;
    corto_member unionMember = NULL;

    for (i = 0; i < count; i++) {
        const char* memberName = json_object_get_name(o, i);
        corto_member member_o;

        if (!strcmp(memberName, "super")) {
            JSON_Value* value = json_object_get_value(o, memberName);
            if (json_deserItem(p, corto_type(corto_interface(t)->base), value)) {
                goto error;
            }
        } else if (!strcmp(memberName, "_d") && isUnion) {
            JSON_Value* value = json_object_get_value(o, memberName);
            if (json_deserPrimitive(&discriminator, corto_union(t)->discriminator, value)) {
                goto error;
            }
            unionMember = corto_union_findCase(t, discriminator);
            if (!unionMember) {
                corto_seterr("discriminator '%d' invalid for union '%s'",
                    discriminator, corto_fullpath(NULL, t));
            }
        } else {
            member_o = corto_interface_resolveMember(t, (char*)memberName);

            /* Ensure that we're not resolving members from a base type */
            if (!member_o || (corto_parentof(member_o) != t)) {
                corto_seterr(
                    "cannot find member '%s' in type '%s'",
                    memberName,
                    corto_fullpath(NULL, t));
                goto error;
            }

            if (isUnion && (unionMember != member_o)) {
                corto_seterr(
                    "member '%s' does not match discriminator '%d' (expected member '%s')",
                    memberName,
                    discriminator,
                    corto_idof(unionMember));
                goto error;
            } else if (isUnion) {
                corto_int32 prev = *(corto_int32*)p;
                if (prev != discriminator) {
                    corto_member prevMember = corto_union_findCase(t, prev);
                    corto_deinitp(CORTO_OFFSET(p, prevMember->offset), prevMember->type);
                    memset(CORTO_OFFSET(p, member_o->offset), 0, member_o->type->size);
                }
                *(corto_int32*)p = discriminator;
            }

            if (!json_deserMustSkip(member_o, p)) {
                JSON_Value* value = json_object_get_value(o, memberName);
                void *offset = CORTO_OFFSET(p, member_o->offset);
                if (member_o->modifiers & CORTO_OBSERVABLE) {
                    offset = *(void**)offset;
                    if (json_deserType(offset, member_o->type, value)) {
                        goto error;
                    }
                } else {
                    if (member_o->modifiers & CORTO_OPTIONAL) {
                        if (*(void**)offset) {
                            corto_deinitp(*(void**)offset, member_o->type);
                            memset(*(void**)offset, 0, member_o->type->size);
                        } else {
                            *(void**)offset = corto_calloc(member_o->type->size);
                        }
                        offset = *(void**)offset;
                    }
                    if (json_deserItem(offset, member_o->type, value)) {
                        goto error;
                    }
                }
            }
        }
    }

    return 0;
error:
    return -1;
}
Esempio n. 27
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. 28
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. 29
0
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. 30
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);
                        }
                    }
                }
            }
        }
    }
}