char* bud_config_encode_npn(bud_config_t* config, const JSON_Array* npn, size_t* len, bud_error_t* err) { int i; char* npn_line; size_t npn_line_len; unsigned int offset; int npn_count; const char* npn_item; int npn_item_len; /* Try global defaults */ if (npn == NULL) npn = config->frontend.npn; if (npn == NULL) { *err = bud_ok(); *len = 0; return NULL; } /* Calculate storage requirements */ npn_count = json_array_get_count(npn); npn_line_len = 0; for (i = 0; i < npn_count; i++) { npn_line_len += 1 + strlen(json_array_get_string(npn, i)); } npn_line = malloc(npn_line_len); if (npn_line == NULL) { *err = bud_error_str(kBudErrNoMem, "NPN copy"); return NULL; } /* Fill npn line */ for (i = 0, offset = 0; i < npn_count; i++) { npn_item = json_array_get_string(npn, i); npn_item_len = strlen(npn_item); npn_line[offset++] = npn_item_len; memcpy(npn_line + offset, npn_item, npn_item_len); offset += npn_item_len; } ASSERT(offset == npn_line_len, "NPN Line overflow"); *len = npn_line_len; *err = bud_ok(); return npn_line; }
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; } }
int main() { m2x_context *ctx = NULL; JSON_Value *val = NULL; JSON_Array *feeds = NULL; size_t i; ctx = m2x_open(M2X_KEY); if (m2x_json_feed_list(ctx, "", &val) == 0) { feeds = json_object_get_array(json_value_get_object(val), "feeds"); for (i = 0; i < json_array_get_count(feeds); i++) { JSON_Object* feed = json_array_get_object(feeds, i); printf("Feed id: %s\n", json_object_get_string(feed, "id")); printf(" name: %s\n", json_object_get_string(feed, "name")); printf("Contains %ld streams\n\n", json_array_get_count(json_object_get_array(feed, "streams"))); } json_value_free(val); } m2x_close(ctx); return 0; }
gint jobdesc_encoders_count (gchar *job) { JSON_Value *val; JSON_Object *obj; JSON_Array *encoders; gint count; val = json_parse_string_with_comments (job); obj = json_value_get_object (val); encoders = json_object_dotget_array (obj, "encoders"); count = json_array_get_count (encoders); json_value_free (val); return count; }
bud_error_t bud_config_verify_npn(const JSON_Array* npn) { int i; int npn_count; if (npn == NULL) return bud_ok(); npn_count = json_array_get_count(npn); for (i = 0; i < npn_count; i++) { if (json_value_get_type(json_array_get_value(npn, i)) == JSONString) continue; return bud_error(kBudErrNPNNonString); } return bud_ok(); }
static PROVISIONING_QUERY_RESPONSE* queryResponse_fromJson(JSON_Array* root_array, PROVISIONING_QUERY_TYPE type) { PROVISIONING_QUERY_RESPONSE* new_query_resp = NULL; if (root_array == NULL) { LogError("No Query Response in JSON"); } else if ((new_query_resp = malloc(sizeof(PROVISIONING_QUERY_RESPONSE))) == NULL) { LogError("Allocation of Query Response failed"); } else { memset(new_query_resp, 0, sizeof(PROVISIONING_QUERY_RESPONSE)); new_query_resp->response_arr_type = type; new_query_resp->response_arr_size = json_array_get_count(root_array); void*** generic_response_arr_ptr; FROM_JSON_FUNCTION fromJson; if (queryResponse_get_type_specific_deserialization_info(new_query_resp, &generic_response_arr_ptr, &fromJson) != 0) { LogError("Unable to deserialize that array type"); queryResponse_free(new_query_resp); new_query_resp = NULL; } else { if (new_query_resp->response_arr_size <= 0) { *generic_response_arr_ptr = NULL; } else { if ((*generic_response_arr_ptr = struct_array_fromJson(root_array, new_query_resp->response_arr_size, fromJson)) == NULL) { LogError("Failed to deserialize array of query results"); queryResponse_free(new_query_resp); new_query_resp = NULL; } } } } return new_query_resp; }
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(); }
bud_error_t bud_config_verify_all_strings(const JSON_Array* arr, const char* name) { int i; int count; if (arr == NULL) return bud_ok(); count = json_array_get_count(arr); for (i = 0; i < count; i++) { if (json_value_get_type(json_array_get_value(arr, i)) == JSONString) continue; return bud_error_dstr(kBudErrNonString, name); } return bud_ok(); }
bud_error_t bud_config_load_ca_arr(X509_STORE** store, const JSON_Array* ca) { int i; int count; bud_error_t err; err = bud_config_verify_all_strings(ca, "ca"); if (!bud_is_ok(err)) return err; *store = X509_STORE_new(); if (*store == NULL) return bud_error_str(kBudErrNoMem, "CA store"); count = json_array_get_count(ca); for (i = 0; i < count; i++) { const char* cert; BIO* b; X509* x509; cert = json_array_get_string(ca, i); b = BIO_new_mem_buf((void*) cert, -1); if (b == NULL) return bud_error_str(kBudErrNoMem, "BIO_new_mem_buf:CA store bio"); while ((x509 = PEM_read_bio_X509(b, NULL, NULL, NULL)) != NULL) { if (x509 == NULL) { err = bud_error_dstr(kBudErrParseCert, cert); break; } if (X509_STORE_add_cert(*store, x509) != 1) { err = bud_error(kBudErrAddCert); break; } X509_free(x509); x509 = NULL; } BIO_free_all(b); if (x509 != NULL) X509_free(x509); } return err; }
bud_error_t bud_config_load_frontend_ifaces( JSON_Object* obj, bud_config_frontend_interface_t* interface) { JSON_Array* arr; int i; arr = json_object_get_array(obj, "interfaces"); interface->count = arr == NULL ? 0 : json_array_get_count(arr); if (interface->count == 0) return bud_ok(); interface->list = calloc(interface->count, sizeof(*interface->list)); if (interface->list == NULL) return bud_error_str(kBudErrNoMem, "bud_frontend_interface_t"); for (i = 0; i < interface->count; i++) bud_config_load_addr(json_array_get_object(arr, i), &interface->list[i]); return bud_ok(); }
void print_commits_info(const char *username, const char *repo) { JSON_Value *root_value; JSON_Array *commits; JSON_Object *commit; size_t i; char curl_command[512]; char cleanup_command[256]; char output_filename[] = "commits.json"; /* it ain't pretty, but it's not a libcurl tutorial */ sprintf(curl_command, "curl -s \"https://api.github.com/repos/%s/%s/commits\" > %s", username, repo, output_filename); sprintf(cleanup_command, "rm -f %s", output_filename); system(curl_command); /* parsing json and validating output */ root_value = json_parse_file(output_filename); if (json_value_get_type(root_value) != JSONArray) { system(cleanup_command); return; } /* getting array from root value and printing commit info */ commits = json_value_get_array(root_value); printf("%-10.10s %-10.10s %s\n", "Date", "SHA", "Author"); for (i = 0; i < json_array_get_count(commits); i++) { commit = json_array_get_object(commits, i); printf("%.10s %.10s %s\n", json_object_dotget_string(commit, "commit.author.date"), json_object_get_string(commit, "sha"), json_object_dotget_string(commit, "commit.author.name")); } /* cleanup code */ json_value_free(root_value); system(cleanup_command); }
ACVP_RESULT acvp_kdf135_ikev1_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) { unsigned int tc_id; JSON_Value *groupval; JSON_Object *groupobj = NULL; JSON_Value *testval; JSON_Object *testobj = NULL; JSON_Array *groups; JSON_Array *tests; JSON_Value *reg_arry_val = NULL; JSON_Object *reg_obj = NULL; JSON_Array *reg_arry = NULL; int i, g_cnt; int j, t_cnt; JSON_Value *r_vs_val = NULL; JSON_Object *r_vs = NULL; JSON_Array *r_tarr = NULL, *r_garr = NULL; /* Response testarray, grouparray */ JSON_Value *r_tval = NULL, *r_gval = NULL; /* Response testval, groupval */ JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */ ACVP_CAPS_LIST *cap; ACVP_KDF135_IKEV1_TC stc; ACVP_TEST_CASE tc; ACVP_RESULT rv; const char *alg_str = json_object_get_string(obj, "algorithm"); const char *mode_str = NULL; ACVP_CIPHER alg_id; char *json_result; ACVP_HASH_ALG hash_alg = 0; ACVP_KDF135_IKEV1_AUTH_METHOD auth_method = 0; const char *hash_alg_str = NULL, *auth_method_str = NULL; char *init_ckey = NULL, *resp_ckey = NULL, *gxy = NULL, *psk = NULL, *init_nonce = NULL, *resp_nonce = NULL; int init_nonce_len = 0, resp_nonce_len = 0, dh_secret_len = 0, psk_len = 0; if (!ctx) { ACVP_LOG_ERR("No ctx for handler operation"); return ACVP_NO_CTX; } if (!alg_str) { ACVP_LOG_ERR("unable to parse 'algorithm' from JSON."); return ACVP_MALFORMED_JSON; } mode_str = json_object_get_string(obj, "mode"); if (!mode_str) { ACVP_LOG_ERR("unable to parse 'mode' from JSON."); return ACVP_MALFORMED_JSON; } alg_id = acvp_lookup_cipher_w_mode_index(alg_str, mode_str); if (alg_id != ACVP_KDF135_IKEV1) { ACVP_LOG_ERR("Server JSON invalid 'algorithm' or 'mode'"); return ACVP_INVALID_ARG; } /* * Get a reference to the abstracted test case */ tc.tc.kdf135_ikev1 = &stc; stc.cipher = alg_id; cap = acvp_locate_cap_entry(ctx, alg_id); if (!cap) { ACVP_LOG_ERR("ACVP server requesting unsupported capability %s : %d.", alg_str, alg_id); return ACVP_UNSUPPORTED_OP; } /* * Create ACVP array for response */ rv = acvp_create_array(®_obj, ®_arry_val, ®_arry); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to create JSON response struct. "); return rv; } /* * Start to build the JSON response */ rv = acvp_setup_json_rsp_group(&ctx, ®_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to setup json response"); return rv; } groups = json_object_get_array(obj, "testGroups"); g_cnt = json_array_get_count(groups); for (i = 0; i < g_cnt; i++) { int tgId = 0; groupval = json_array_get_value(groups, i); groupobj = json_value_get_object(groupval); /* * Create a new group in the response with the tgid * and an array of tests */ r_gval = json_value_init_object(); r_gobj = json_value_get_object(r_gval); tgId = json_object_get_number(groupobj, "tgId"); if (!tgId) { ACVP_LOG_ERR("Missing tgid from server JSON groub obj"); rv = ACVP_MALFORMED_JSON; goto err; } json_object_set_number(r_gobj, "tgId", tgId); json_object_set_value(r_gobj, "tests", json_value_init_array()); r_tarr = json_object_get_array(r_gobj, "tests"); hash_alg_str = json_object_get_string(groupobj, "hashAlg"); if (!hash_alg_str) { ACVP_LOG_ERR("Failed to include hashAlg"); rv = ACVP_MISSING_ARG; goto err; } hash_alg = acvp_lookup_hash_alg(hash_alg_str); if (hash_alg != ACVP_SHA1 && hash_alg != ACVP_SHA224 && hash_alg != ACVP_SHA256 && hash_alg != ACVP_SHA384 && hash_alg != ACVP_SHA512) { ACVP_LOG_ERR("ACVP server requesting invalid hashAlg"); rv = ACVP_INVALID_ARG; goto err; } auth_method_str = json_object_get_string(groupobj, "authenticationMethod"); if (!auth_method_str) { ACVP_LOG_ERR("Failed to include authenticationMethod"); rv = ACVP_MISSING_ARG; goto err; } auth_method = read_auth_method(auth_method_str); if (!auth_method) { ACVP_LOG_ERR("ACVP server requesting invalid authenticationMethod"); rv = ACVP_INVALID_ARG; goto err; } init_nonce_len = json_object_get_number(groupobj, "nInitLength"); if (!(init_nonce_len >= ACVP_KDF135_IKEV1_INIT_NONCE_BIT_MIN && init_nonce_len <= ACVP_KDF135_IKEV1_INIT_NONCE_BIT_MAX)) { ACVP_LOG_ERR("nInitLength incorrect, %d", init_nonce_len); rv = ACVP_INVALID_ARG; goto err; } resp_nonce_len = json_object_get_number(groupobj, "nRespLength"); if (!(resp_nonce_len >= ACVP_KDF135_IKEV1_RESP_NONCE_BIT_MIN && resp_nonce_len <= ACVP_KDF135_IKEV1_RESP_NONCE_BIT_MAX)) { ACVP_LOG_ERR("nRespLength incorrect, %d", resp_nonce_len); rv = ACVP_INVALID_ARG; goto err; } dh_secret_len = json_object_get_number(groupobj, "dhLength"); if (!(dh_secret_len >= ACVP_KDF135_IKEV1_DH_SHARED_SECRET_BIT_MIN && dh_secret_len <= ACVP_KDF135_IKEV1_DH_SHARED_SECRET_BIT_MAX)) { ACVP_LOG_ERR("dhLength incorrect, %d", dh_secret_len); rv = ACVP_INVALID_ARG; goto err; } if (auth_method == ACVP_KDF135_IKEV1_AMETH_PSK) { /* Only for PSK authentication method */ psk_len = json_object_get_number(groupobj, "preSharedKeyLength"); if (!(psk_len >= ACVP_KDF135_IKEV1_PSK_BIT_MIN && psk_len <= ACVP_KDF135_IKEV1_PSK_BIT_MAX)) { ACVP_LOG_ERR("preSharedKeyLength incorrect, %d", psk_len); rv = ACVP_INVALID_ARG; goto err; } } ACVP_LOG_INFO("\n Test group: %d", i); ACVP_LOG_INFO(" hash alg: %s", hash_alg_str); ACVP_LOG_INFO(" auth method: %s", auth_method_str); ACVP_LOG_INFO(" init nonce len: %d", init_nonce_len); ACVP_LOG_INFO(" resp nonce len: %d", resp_nonce_len); ACVP_LOG_INFO(" dh secret len: %d", dh_secret_len); ACVP_LOG_INFO(" psk len: %d", psk_len); tests = json_object_get_array(groupobj, "tests"); t_cnt = json_array_get_count(tests); for (j = 0; j < t_cnt; j++) { ACVP_LOG_INFO("Found new KDF IKEv1 test vector..."); testval = json_array_get_value(tests, j); testobj = json_value_get_object(testval); tc_id = (unsigned int)json_object_get_number(testobj, "tcId"); init_nonce = (char *)json_object_get_string(testobj, "nInit"); if (!init_nonce) { ACVP_LOG_ERR("Failed to include nInit"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)init_nonce, ACVP_KDF135_IKEV1_INIT_NONCE_STR_MAX + 1) != ((init_nonce_len + 7) / 8) * 2) { ACVP_LOG_ERR("nInit length(%d) incorrect, expected(%d)", strnlen_s((char *)init_nonce, ACVP_KDF135_IKEV1_INIT_NONCE_STR_MAX + 1), ((init_nonce_len + 7) / 8) * 2); rv = ACVP_INVALID_ARG; goto err; } resp_nonce = (char *)json_object_get_string(testobj, "nResp"); if (!resp_nonce) { ACVP_LOG_ERR("Failed to include nResp"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)resp_nonce, ACVP_KDF135_IKEV1_RESP_NONCE_STR_MAX + 1) != ((resp_nonce_len + 7) / 8) * 2) { ACVP_LOG_ERR("nResp length(%d) incorrect, expected(%d)", strnlen_s((char *)resp_nonce, ACVP_KDF135_IKEV1_RESP_NONCE_STR_MAX + 1), ((resp_nonce_len + 7) / 8) * 2); rv = ACVP_INVALID_ARG; goto err; } init_ckey = (char *)json_object_get_string(testobj, "ckyInit"); if (!init_ckey) { ACVP_LOG_ERR("Failed to include ckyInit"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)init_ckey, ACVP_KDF135_IKEV1_COOKIE_STR_MAX + 1) > ACVP_KDF135_IKEV1_COOKIE_STR_MAX) { ACVP_LOG_ERR("ckyInit too long, max allowed=(%d)", ACVP_KDF135_IKEV1_COOKIE_STR_MAX); rv = ACVP_INVALID_ARG; goto err; } resp_ckey = (char *)json_object_get_string(testobj, "ckyResp"); if (!resp_ckey) { ACVP_LOG_ERR("Failed to include ckyResp"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)resp_ckey, ACVP_KDF135_IKEV1_COOKIE_STR_MAX + 1) > ACVP_KDF135_IKEV1_COOKIE_STR_MAX) { ACVP_LOG_ERR("ckyResp too long, max allowed=(%d)", ACVP_KDF135_IKEV1_COOKIE_STR_MAX); rv = ACVP_INVALID_ARG; goto err; } gxy = (char *)json_object_get_string(testobj, "gxy"); if (!gxy) { ACVP_LOG_ERR("Failed to include gxy"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)gxy, ACVP_KDF135_IKEV1_DH_SHARED_SECRET_STR_MAX + 1) > ACVP_KDF135_IKEV1_DH_SHARED_SECRET_STR_MAX) { ACVP_LOG_ERR("gxy too long, max allowed=(%d)", ACVP_KDF135_IKEV1_DH_SHARED_SECRET_STR_MAX); rv = ACVP_INVALID_ARG; goto err; } if (auth_method == ACVP_KDF135_IKEV1_AMETH_PSK) { /* Only for PSK authentication method */ psk = (char *)json_object_get_string(testobj, "preSharedKey"); if (!psk) { ACVP_LOG_ERR("Failed to include preSharedKey"); rv = ACVP_MISSING_ARG; goto err; } if (strnlen_s((char *)psk, ACVP_KDF135_IKEV1_PSK_STR_MAX + 1) > ACVP_KDF135_IKEV1_PSK_STR_MAX) { ACVP_LOG_ERR("preSharedKey too long, max allowed=(%d)", ACVP_KDF135_IKEV1_PSK_STR_MAX); rv = ACVP_INVALID_ARG; goto err; } } ACVP_LOG_INFO(" Test case: %d", j); ACVP_LOG_INFO(" tcId: %d", tc_id); /* * Create a new test case in the response */ r_tval = json_value_init_object(); r_tobj = json_value_get_object(r_tval); json_object_set_number(r_tobj, "tcId", tc_id); /* * Setup the test case data that will be passed down to * the crypto module2 */ rv = acvp_kdf135_ikev1_init_tc(ctx, &stc, tc_id, hash_alg, auth_method, init_nonce_len, resp_nonce_len, dh_secret_len, psk_len, init_nonce, resp_nonce, init_ckey, resp_ckey, gxy, psk); if (rv != ACVP_SUCCESS) { acvp_kdf135_ikev1_release_tc(&stc); json_value_free(r_tval); goto err; } /* Process the current test vector... */ if ((cap->crypto_handler)(&tc)) { ACVP_LOG_ERR("crypto module failed the KDF IKEv1 operation"); acvp_kdf135_ikev1_release_tc(&stc); rv = ACVP_CRYPTO_MODULE_FAIL; json_value_free(r_tval); goto err; } /* * Output the test case results using JSON */ rv = acvp_kdf135_ikev1_output_tc(ctx, &stc, r_tobj); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("JSON output failure in hash module"); acvp_kdf135_ikev1_release_tc(&stc); json_value_free(r_tval); goto err; } /* * Release all the memory associated with the test case */ acvp_kdf135_ikev1_release_tc(&stc); /* Append the test response value to array */ json_array_append_value(r_tarr, r_tval); } json_array_append_value(r_garr, r_gval); } json_array_append_value(reg_arry, r_vs_val); json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL); if (ctx->debug == ACVP_LOG_LVL_VERBOSE) { printf("\n\n%s\n\n", json_result); } else { ACVP_LOG_INFO("\n\n%s\n\n", json_result); } json_free_serialized_string(json_result); rv = ACVP_SUCCESS; err: if (rv != ACVP_SUCCESS) { acvp_release_json(r_vs_val, r_gval); } return rv; }
clib_package_t * clib_package_new(const char *json, int verbose) { if (!json) return NULL; clib_package_t *pkg = malloc(sizeof(clib_package_t)); if (!pkg) return NULL; JSON_Value *root = json_parse_string(json); if (!root) { clib_package_free(pkg); return NULL; } JSON_Object *json_object = json_value_get_object(root); if (!json_object) { if (verbose) clib_package_error("error", "unable to parse json"); json_value_free(root); clib_package_free(pkg); return NULL; } pkg->json = str_copy(json); pkg->name = json_object_get_string_safe(json_object, "name"); pkg->repo = NULL; pkg->repo = json_object_get_string_safe(json_object, "repo"); if (NULL != pkg->repo) { pkg->author = clib_package_parse_author(pkg->repo); // repo name may not be the package's name. for example: // stephenmathieson/str-replace.c -> str-replace pkg->repo_name = clib_package_parse_name(pkg->repo); // TODO support npm-style "repository"? } else { if (verbose) clib_package_warn("warning", "missing repo in package.json"); pkg->author = NULL; pkg->repo_name = NULL; } pkg->version = json_object_get_string_safe(json_object, "version"); pkg->license = json_object_get_string_safe(json_object, "license"); pkg->description = json_object_get_string_safe(json_object, "description"); pkg->install = json_object_get_string_safe(json_object, "install"); JSON_Array *src = json_object_get_array(json_object, "src"); if (src) { pkg->src = list_new(); if (!pkg->src) { json_value_free(root); clib_package_free(pkg); return NULL; } for (size_t i = 0; i < json_array_get_count(src); i++) { char *file = json_array_get_string_safe(src, i); if (!file) break; // TODO fail? list_node_t *node = list_node_new(file); list_rpush(pkg->src, node); } } else { pkg->src = NULL; } JSON_Object *deps = json_object_get_object(json_object, "dependencies"); pkg->dependencies = parse_package_deps(deps); JSON_Object *devs = json_object_get_object(json_object, "development"); pkg->development = parse_package_deps(devs); json_value_free(root); return pkg; }
/*------------------------------------------------------------------ - Config file format - simplify, don't need xml, but like the structure { "scalars" : { "nq" : 3, "lrgs" : 4, "print" : true "t" : 10.0, "dt" : 0.1 }, "coefficients" : { "alpha" : [0.112, 0.234, 0.253], "beta" : [0.453, 0.533, -0.732, 0.125, -0.653, 0.752], "delta" : [1.0, 1.0, 1.0] } } ------------------------------------------------------------------*/ int main( int argc, char **argv ){ double *hz, *hhxh; /* hamiltonian components */ double *al, *be, *de; fftw_complex *psi; /* State vector */ fftw_complex factor; double T = 10.0, dt = 0.1; uint64_t i, j, k, bcount; uint64_t nQ=3, N, L=4, dim; int *fft_dims, prnt=0; uint64_t testi, testj; int dzi, dzj; //TODO: consider using smaller vars for flags and these fftw_plan plan; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Parse configuration file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ //TODO: going to need logic to handle incomplete config files if( argc < 2 ){ fprintf( stderr, "Need a json configuration file. Terminating...\n" ); return 1; } /* Parse file and populate applicable data structures */ { JSON_Value *root_value = NULL; JSON_Object *root_object; JSON_Array *array; root_value = json_parse_file_with_comments( argv[1] ); root_object = json_value_get_object( root_value ); nQ = (uint64_t) json_object_dotget_number( root_object, "scalars.nq" ); prnt = json_object_dotget_boolean( root_object, "scalars.print" ); L = (uint64_t) json_object_dotget_number( root_object, "scalars.lrgs" ); T = json_object_dotget_number( root_object, "scalars.t" ); dt = json_object_dotget_number( root_object, "scalars.dt" ); al = (double *)malloc( nQ*sizeof(double) ); de = (double *)malloc( nQ*sizeof(double) ); be = (double *)malloc( (nQ*(nQ-1)/2)*sizeof(double) ); array = json_object_dotget_array( root_object, "coefficients.alpha" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ al[i] = -json_array_get_number( array, i ); } } array = json_object_dotget_array( root_object, "coefficients.beta" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ be[i] = -json_array_get_number( array, i ); } } array = json_object_dotget_array( root_object, "coefficients.delta" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ de[i] = -json_array_get_number( array, i ); } } json_value_free( root_value ); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Compute the Hamiltonian and state vector for the simulation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Create state vector and initialize to 1/sqrt(2^n)*(|00...0> + ... + |11...1>) TODO: keep track of local size and local base */ dim = 1 << nQ; factor = 1.0/sqrt( dim ); fft_dims = (int *)malloc( nQ*sizeof(int) ); psi = (fftw_complex *)malloc( (dim)*sizeof(fftw_complex) ); hz = (double *)calloc( (dim),sizeof(double) ); hhxh = (double *)calloc( (dim),sizeof(double) ); for( i = 0; i < nQ; i++ ){ fft_dims[i] = 2; } plan = fftw_plan_dft( nQ, fft_dims, psi, psi, FFTW_FORWARD, FFTW_MEASURE ); /* Assemble Hamiltonian and state vector */ for( k = 0; k < dim; k++ ){ //TODO: when parallelized, k in dzi test will be ~(k + base) bcount = 0; for( i = 0; i < nQ; i++ ){ testi = 1 << (nQ - i - 1); dzi = ((k/testi) % 2 == 0) ? 1 : -1; hz[k] += al[i] * dzi; hhxh[k] += de[i] * dzi; for( j = i; j < nQ; j++ ){ testj = 1 << (nQ - j - 1); dzj = ((k/testj) % 2 == 0) ? 1 : -1; hz[k] += be[bcount] * dzi * dzj; bcount++; } } psi[k] = factor; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Run the Simulation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ fftw_complex cz, cx; double t; N = (uint64_t)(T / dt); for( i = 0; i < N; i++ ){ t = i*dt; //t0 = (i-1)*dt; //Time-dependent coefficients cz = (-dt * I)*t/(2.0*T); cx = (-dt * I)*(1 - t/T); //Evolve system expMatTimesVec( psi, hz, cz, dim ); //apply Z part fftw_execute( plan ); expMatTimesVec( psi, hhxh, cx, dim ); //apply X part fftw_execute( plan ); expMatTimesVec( psi, hz, cz, dim ); //apply Z part /* TODO: can probably get some minor speedup by incorporating this into expMatTimesVec if needed */ scaleVec( psi, 1.0/dim, dim ); } fftw_destroy_plan( plan ); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Check solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ //TODO: locally, collect all local largests on one // node, find k largest from that subset if( prnt && nQ < 6 ){ for( i = 0; i < dim; i++ ){ printf( "psi[%d] = (%f, %f)\t%f\n", i, creal( psi[i] ), cimag( psi[i] ), cabs( psi[i]*psi[i] ) ); } } else { uint64_t *largest = (uint64_t *)calloc( L, sizeof(uint64_t) ); findLargest( largest, psi, dim, L ); for( i = 0; i < L; ++i ){ printf( "psi[%d] = (%f, %f)\t%f\n", i, creal( psi[largest[L-1-i]] ), cimag( psi[largest[L-1-i]] ), cabs( psi[largest[L-1-i]]*psi[largest[L-1-i]] ) ); } free( largest ); } /* Free work space. */ fftw_free( psi ); free( fft_dims ); free( hz ); free( hhxh ); return 0; }
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(fabs(json_object_get_number(root_object, "hard to parse number") - (-0.000314)) < EPSILON); 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"); TEST(array != NULL); TEST(json_array_get_count(array) > 1); 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")); } 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")); TEST(STREQ(json_object_get_string(root_object, "url"), "https://www.example.com/search?q=12345")); TEST(STREQ(json_object_get_string(root_object, "escaped chars"), "\" \\ /")); }
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; }
int main(){ int i, nQ, lrgs; double t, dt; double *al, *be, *de; JSON_Value *root_value = NULL; JSON_Object *root_object; //JSON_Object *scalar_object; //JSON_Object *coeff_object; JSON_Array *array; root_value = json_parse_file_with_comments( "config.json" ); root_object = json_value_get_object( root_value ); //scalar_object = json_value_get_object( root_object, ); //coeff_object = json_value_get_object( root_value ); nQ = (int)json_object_dotget_number( root_object, "scalars.NQ" ); lrgs = (int)json_object_dotget_number( root_object, "scalars.LRGS" ); t = json_object_dotget_number( root_object, "scalars.T" ); dt = json_object_dotget_number( root_object, "scalars.DT" ); al = (double *)malloc( nQ*sizeof(double) ); be = (double *)malloc( ((nQ*(nQ-1))/2)*sizeof(double) ); de = (double *)malloc( nQ*sizeof(double) ); array = json_object_dotget_array( root_object, "coefficients.ALPHA" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ al[i] = json_array_get_number( array, i ); } } array = json_object_dotget_array( root_object, "coefficients.BETA" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ be[i] = json_array_get_number( array, i ); } } array = json_object_dotget_array( root_object, "coefficients.DELTA" ); if( array != NULL ){ for( i = 0; i < json_array_get_count(array); i++ ){ de[i] = json_array_get_number( array, i ); } } json_value_free(root_value); printf("nQ = %d\n", nQ); printf("lrgs = %d\n", lrgs); printf("t = %f\n", t); printf("dt = %f\n\n", dt); for( i = 0; i < nQ; i++ ){ printf("al[%d] = %f ", i, al[i]); } printf("\n\n"); for( i = 0; i < (nQ*nQ-nQ)/2; i++ ){ printf("be[%d] = %f ", i, be[i]); } printf("\n\n"); for( i = 0; i < nQ; i++ ){ printf("de[%d] = %f ", i, de[i]); } printf("\n\n"); free(al); free(be); free(de); return 0; }
clib_package_t * clib_package_new(const char *json, int verbose) { clib_package_t *pkg = NULL; JSON_Value *root = NULL; JSON_Object *json_object = NULL; JSON_Array *src = NULL; JSON_Object *deps = NULL; JSON_Object *devs = NULL; int error = 1; if (!json) goto cleanup; if (!(root = json_parse_string(json))) { logger_error("error", "unable to parse json"); goto cleanup; } if (!(json_object = json_value_get_object(root))) { logger_error("error", "invalid package.json"); goto cleanup; } if (!(pkg = malloc(sizeof(clib_package_t)))) goto cleanup; memset(pkg, '\0', sizeof(clib_package_t)); pkg->json = str_copy(json); pkg->name = json_object_get_string_safe(json_object, "name"); pkg->repo = json_object_get_string_safe(json_object, "repo"); pkg->version = json_object_get_string_safe(json_object, "version"); pkg->license = json_object_get_string_safe(json_object, "license"); pkg->description = json_object_get_string_safe(json_object, "description"); pkg->install = json_object_get_string_safe(json_object, "install"); // TODO npm-style "repository" (thlorenz/gumbo-parser.c#1) if (pkg->repo) { pkg->author = parse_repo_owner(pkg->repo, DEFAULT_REPO_OWNER); // repo name may not be package name (thing.c -> thing) pkg->repo_name = parse_repo_name(pkg->repo); } else { if (verbose) logger_warn("warning", "missing repo in package.json"); pkg->author = NULL; pkg->repo_name = NULL; } if ((src = json_object_get_array(json_object, "src"))) { if (!(pkg->src = list_new())) goto cleanup; pkg->src->free = free; for (unsigned int i = 0; i < json_array_get_count(src); i++) { char *file = json_array_get_string_safe(src, i); if (!file) goto cleanup; if (!(list_rpush(pkg->src, list_node_new(file)))) goto cleanup; } } else { pkg->src = NULL; } if ((deps = json_object_get_object(json_object, "dependencies"))) { if (!(pkg->dependencies = parse_package_deps(deps))) { goto cleanup; } } else { pkg->dependencies = NULL; } if ((devs = json_object_get_object(json_object, "development"))) { if (!(pkg->development = parse_package_deps(devs))) { goto cleanup; } } else { pkg->development = NULL; } error = 0; cleanup: if (root) json_value_free(root); if (error && pkg) { clib_package_free(pkg); pkg = NULL; } return pkg; }
int config_parse(const char *file, config_t *config) { JSON_Value *jvroot; JSON_Object *joroot; JSON_Object *jomaccmd; JSON_Array *jarray; JSON_Value_Type jtype; const char *string; int ret; int i; if(file == NULL){ return -1; } /** Clear all flags */ config_free(config); printf("Start parsing configuration file....\n\n"); /* parsing json and validating output */ jvroot = json_parse_file_with_comments(file); jtype = json_value_get_type(jvroot); if (jtype != JSONObject) { return -1; } joroot = json_value_get_object(jvroot); string = json_object_get_string(joroot, "band"); if(string == NULL){ config->band = LW_BAND_EU868; }else{ for(i=0; i<LW_BAND_MAX_NUM; i++){ if(0 == strcmp(string, config_band_tab[i])){ config->band = (lw_band_t)i; break; } } if(i==LW_BAND_MAX_NUM){ config->band = LW_BAND_EU868; } } string = json_object_dotget_string(joroot, "key.nwkskey"); if(string != NULL){ if(str2hex(string, config->nwkskey, 16) == 16){ config->flag |= CFLAG_NWKSKEY; } } string = json_object_dotget_string(joroot, "key.appskey"); if(string != NULL){ if(str2hex(string, config->appskey, 16) == 16){ config->flag |= CFLAG_APPSKEY; } } string = json_object_dotget_string(joroot, "key.appkey"); if(string != NULL){ if(str2hex(string, config->appkey, 16) == 16){ config->flag |= CFLAG_APPKEY; } } ret = json_object_dotget_boolean(joroot, "join.key"); if(ret==0){ //printf("Join key false\n"); config->joinkey = false; }else if(ret==1){ //printf("Join key true\n"); config->joinkey = true; }else{ //printf("Unknown join key value\n"); config->joinkey = false; } string = json_object_dotget_string(joroot, "join.request"); if(string != NULL){ uint8_t tmp[255]; int len; len = str2hex(string, tmp, 255); if(len>0){ config->flag |= CFLAG_JOINR; config->joinr = malloc(len); if(config->joinr == NULL){ return -2; } config->joinr_size = len; memcpy(config->joinr, tmp, config->joinr_size); } } string = json_object_dotget_string(joroot, "join.accept"); if(string != NULL){ uint8_t tmp[255]; int len; len = str2hex(string, tmp, 255); if(len>0){ config->flag |= CFLAG_JOINA; config->joina = malloc(len); if(config->joina == NULL){ return -3; } config->joina_size = len; memcpy(config->joina, tmp, config->joina_size); } } jarray = json_object_get_array(joroot, "messages"); if(jarray != NULL){ uint8_t tmp[255]; for (i = 0; i < json_array_get_count(jarray); i++) { string = json_array_get_string(jarray, i); if(string!=NULL){ int len = str2hex(string, tmp, 255); if(len>0){ message_t *pl = malloc(sizeof(message_t)); memset(pl, 0, sizeof(message_t)); if(pl == NULL){ return -3; } pl->buf = malloc(len); if(pl->buf == NULL){ return -3; } pl->len = len; memcpy(pl->buf, tmp, pl->len); pl_insert(&config->message, pl); }else{ printf("Messages[%d] \"%s\" is not hex string\n", i, string); } }else{ printf("Messages item %d is not string\n", i); } } }else{ printf("Can't get payload array\n"); } jarray = json_object_get_array(joroot, "maccommands"); if(jarray != NULL){ uint8_t mhdr; int len; uint8_t tmp[255]; for (i = 0; i < json_array_get_count(jarray); i++) { jomaccmd = json_array_get_object(jarray, i); string = json_object_get_string(jomaccmd, "MHDR"); if(string != NULL){ len = str2hex(string, &mhdr, 1); if(len != 1){ printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string); continue; } }else{ string = json_object_get_string(jomaccmd, "direction"); if(string != NULL){ int j; len = strlen(string); if(len>200){ printf("\"maccommands\"[%d].direction \"%s\" too long\n", i, string); continue; } for(j=0; j<len; j++){ tmp[j] = tolower(string[j]); } tmp[j] = '\0'; if(0==strcmp((char *)tmp, "up")){ mhdr = 0x80; }else if(0==strcmp((char *)tmp, "down")){ mhdr = 0xA0; }else{ printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string); continue; } }else{ printf("Can't recognize maccommand direction\n"); continue; } } string = json_object_get_string(jomaccmd, "command"); if(string != NULL){ len = str2hex(string, tmp, 255); if(len <= 0){ printf("\"maccommands\"[%d].command \"%s\" is not hex string\n", i, string); continue; } }else{ printf("c\"maccommands\"[%d].command is not string\n", i); continue; } message_t *pl = malloc(sizeof(message_t)); memset(pl, 0, sizeof(message_t)); if(pl == NULL){ return -3; } pl->buf = malloc(len+1); if(pl->buf == NULL){ return -3; } pl->len = len+1; pl->buf[0] = mhdr; pl->next = 0; memcpy(pl->buf+1, tmp, pl->len-1); pl_insert(&config->maccmd, pl); } } print_spliter(); printf("%15s %s\n","BAND:\t", config_band_tab[LW_BAND_EU868]); printf("%15s","NWKSKEY:\t"); putlen(16); puthbuf(config->nwkskey, 16); printf("\n"); printf("%15s","APPSKEY:\t"); putlen(16); puthbuf(config->appskey, 16); printf("\n"); printf("%15s","APPKEY:\t"); putlen(16); puthbuf(config->appkey, 16); printf("\n"); printf("%15s","JOINR:\t"); putlen(config->joinr_size); puthbuf(config->joinr, config->joinr_size ); printf("\n"); printf("%15s","JOINA:\t"); putlen(config->joina_size); puthbuf(config->joina, config->joina_size ); printf("\n"); pl_print(config->message); maccmd_print(config->maccmd); json_value_free(jvroot); return 0; }
MODULE_LOADER_RESULT ModuleLoader_InitializeFromJson(const JSON_Value* loaders) { MODULE_LOADER_RESULT result; if (loaders == NULL) { LogError("loaders is NULL"); /*Codes_SRS_MODULE_LOADER_13_062: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if loaders is NULL. ]*/ result = MODULE_LOADER_ERROR; } else { if (json_value_get_type(loaders) != JSONArray) { LogError("loaders is not a JSON array"); /*Codes_SRS_MODULE_LOADER_13_063: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if loaders is not a JSON array. ]*/ result = MODULE_LOADER_ERROR; } else { JSON_Array* loaders_array = json_value_get_array(loaders); if (loaders_array == NULL) { LogError("json_value_get_array failed"); /*Codes_SRS_MODULE_LOADER_13_064: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/ result = MODULE_LOADER_ERROR; } else { size_t length = json_array_get_count(loaders_array); size_t i; for (i = 0; i < length; i++) { JSON_Value* loader = json_array_get_value(loaders_array, i); if (loader == NULL) { /*Codes_SRS_MODULE_LOADER_13_064: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/ LogError("json_array_get_value failed for loader %zu", i); break; } if (add_loader_from_json(loader, i) != MODULE_LOADER_SUCCESS) { LogError("add_loader_from_json failed for loader %zu", i); break; } } /*Codes_SRS_MODULE_LOADER_13_073: [ ModuleLoader_InitializeFromJson shall return MODULE_LOADER_SUCCESS if the the JSON has been processed successfully. ]*/ // if the loop terminated early then something went wrong result = (i < length) ? MODULE_LOADER_ERROR : MODULE_LOADER_SUCCESS; } } } return result; }
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; }
int parse_blueprint_json(JSON_Object *blueprint, blueprint_t *bp) { bstring Name, bp_name, name, game_version; uint32_t resource_cost[5]; bp->revision = json_object_get_number(blueprint, "blueprintVersion"); bp_name = bfromcstr(json_object_get_string(blueprint, "blueprintName")); name = bfromcstr(json_object_get_string(blueprint, "Name")); game_version = bfromcstr(json_object_get_string(blueprint, "GameVersion")); bstring param1 = bfromcstr(json_object_get_string(blueprint, "Parameter1")); bstring param2 = bfromcstr(json_object_get_string(blueprint, "Parameter2")); bstring lpos = bfromcstr(json_object_get_string(blueprint, "LocalPosition")); bstring lrot = bfromcstr(json_object_get_string(blueprint, "LocalRotation")); bp->name = name; bp->blueprint_name = bp_name; bp->Name = Name; bp->game_version = game_version; const char* cpos = json_object_get_string(blueprint, "LocalPosition"); bstring pos = bfromcstr(cpos); struct bstrList *pval = bsplit(pos, ','); for (int i = 0; i < 3; i++) { char *ptr; char *str = bstr2cstr(pval->entry[i], '0'); uint32_t n = strtol(str, &ptr, 10); } const char* crot = json_object_get_string(blueprint, "LocalRotation"); bstring rot = bfromcstr(crot); struct bstrList *rval = bsplit(rot, ','); for (int i = 0; i < 4; i++) { char *ptr; char *str = bstr2cstr(rval->entry[i], '0'); double dbl = strtod(str, &ptr); free(str); bp->local_rotation[i] = dbl; } bp->parameter1 = param1; bp->parameter2 = param2; bp->design_changed = json_object_get_boolean(blueprint, "designChanged"); bp->id = json_object_get_number(blueprint, "Id"); bp->force_id = json_object_get_number(blueprint, "ForceId"); bp->item_number = json_object_get_number(blueprint, "ItemNumber"); JSON_Array *jresource_cost = json_object_get_array(blueprint, "ResourceCost"); for (int i = 0; i < 5; i++) bp->resource_cost[i] = (uint32_t) json_array_get_number(jresource_cost, i); JSON_Array *min_coords = json_object_get_array(blueprint, "MinCords"); for (int i = 0; i < 3; i++) bp->min_coords[i] = (int32_t) json_array_get_number(min_coords, i); JSON_Array *max_coords = json_object_get_array(blueprint, "MaxCords"); for (int i = 0; i < 3; i++) bp->max_coords[i] = (int32_t) json_array_get_number(max_coords, i); JSON_Array *csi = json_object_get_array(blueprint, "CSI"); for (int i = 0; i < 40; i++) bp->constructable_special_info[i] = json_array_get_number(csi, i); bp->last_alive_block = (uint32_t) json_object_get_number(blueprint, "LastAliveBlock"); JSON_Array *palette = json_object_get_array(blueprint, "COL"); for(int i = 0; i < 32; i++) { uint32_t rbga = 0; const char* ccolor = json_array_get_string(palette, i); bstring color = bfromcstr(ccolor); // Create array of substrings struct bstrList *values = bsplit(color, ','); for (int n = 0; n < 4; n++) { char *ptr; char *str = bstr2cstr(values->entry[n], '0'); double dbl = strtod(str, &ptr); free(str); bp->color_palette[i].array[n] = round(dbl * 255.0); } bstrListDestroy(values); bdestroy(color); } JSON_Array *material = json_object_get_array(blueprint, "BlockIds"); JSON_Array *position = json_object_get_array(blueprint, "BLP"); JSON_Array *rotation = json_object_get_array(blueprint, "BLR"); JSON_Array *color = json_object_get_array(blueprint, "BCI"); JSON_Array *bp1 = json_object_get_array(blueprint, "BP1"); JSON_Array *bp2 = json_object_get_array(blueprint, "BP2"); JSON_Array *block_string_ids = json_object_get_array(blueprint, "BlockStringDataIds"); JSON_Array *block_data = json_object_get_array(blueprint, "BlockStringData"); bp->total_block_count = (uint32_t) json_object_get_number(blueprint, "TotalBlockCount"); bp->main_block_count = (uint32_t) json_object_get_number(blueprint, "BlockCount"); bp->blocks = calloc(bp->main_block_count, sizeof(block_t)); for (int i = 0; i < bp->main_block_count; i++) { block_t *act = &bp->blocks[i]; act->material = (uint32_t) json_array_get_number(material, i); act->rotation = (uint32_t) json_array_get_number(rotation, i); act->color = (uint32_t) json_array_get_number(color, i); bstring pos_string = bfromcstr(json_array_get_string(position, i)); struct bstrList *pos_list = bsplit(pos_string, ','); for (int n = 0; n < 3; n++) { char *ptr; char *str = bstr2cstr(pos_list->entry[n], '0'); double dbl = strtod(str, &ptr); uint32_t val = round(dbl); act->position.array[n] = val; free(str); } bstrListDestroy(pos_list); bdestroy(pos_string); bstring bp1_string = bfromcstr(json_array_get_string(bp1, i)); struct bstrList *bp1_values = bsplit(bp1_string, ','); for (int n = 0; n < 4; n++) { char *ptr; char *str = bstr2cstr(bp1_values->entry[n], '0'); double dbl = strtod(str, &ptr); act->bp1[n] = dbl; } bstring bp2_string = bfromcstr(json_array_get_string(bp2, i)); struct bstrList *bp2_values = bsplit(bp2_string, ','); for (int n = 0; n < 4; n++) { char *ptr; char *str = bstr2cstr(bp2_values->entry[n], '0'); double dbl = strtod(str, &ptr); uint32_t val = round(dbl); act->bp2[n] = val; } // Only used for lookup, not saved after that since it has no further semantic value const char *cb1 = json_array_get_string(bp1, i); if (act->bp1[3] != 0) { for (int n = 0; n < json_array_get_count(block_string_ids); n++) { uint32_t test_id = json_array_get_number(block_string_ids, n); if (test_id == 0) { break; } if (test_id == act->bp1[3]) { // BlockStringData at index n is the one we want act->string_data = bfromcstr(json_array_get_string(block_data, n)); } } } } JSON_Array *subconstructables = json_object_get_array(blueprint, "SCs"); bp->num_sc = json_array_get_count(subconstructables); bp->SCs = calloc(bp->num_sc, sizeof(blueprint_t)); for (int i = 0; i < bp->num_sc; i++) { JSON_Value *sc_json = json_array_get_value(subconstructables, i); JSON_Object *sc_obj = json_value_get_object(sc_json); int retval = parse_blueprint_json(sc_obj, &bp->SCs[i]); if (retval != 0) return retval; } return 0; }
ACVP_RESULT acvp_cmac_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) { unsigned int tc_id, msglen, keyLen = 0, keyingOption = 0, maclen, verify = 0; char *msg = NULL, *key1 = NULL, *key2 = NULL, *key3 = NULL, *mac = NULL; JSON_Value *groupval; JSON_Object *groupobj = NULL; JSON_Value *testval; JSON_Object *testobj = NULL; JSON_Array *groups; JSON_Array *tests; JSON_Value *reg_arry_val = NULL; JSON_Object *reg_obj = NULL; JSON_Array *reg_arry = NULL; int i, g_cnt; int j, t_cnt; JSON_Value *r_vs_val = NULL; JSON_Object *r_vs = NULL; JSON_Array *r_tarr = NULL, *r_garr = NULL; /* Response testarray, grouparray */ JSON_Value *r_tval = NULL, *r_gval = NULL; /* Response testval, groupval */ JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */ ACVP_CAPS_LIST *cap; ACVP_CMAC_TC stc; ACVP_TEST_CASE tc; ACVP_RESULT rv; const char *alg_str = json_object_get_string(obj, "algorithm"); ACVP_CIPHER alg_id; char *json_result, *direction = NULL; int key1_len, key2_len, key3_len, json_msglen; if (!ctx) { ACVP_LOG_ERR("No ctx for handler operation"); return ACVP_NO_CTX; } if (!obj) { ACVP_LOG_ERR("No obj for handler operation"); return ACVP_MALFORMED_JSON; } if (!alg_str) { ACVP_LOG_ERR("ERROR: unable to parse 'algorithm' from JSON"); return ACVP_MALFORMED_JSON; } /* * Get a reference to the abstracted test case */ tc.tc.cmac = &stc; /* * Get the crypto module handler for this hash algorithm */ alg_id = acvp_lookup_cipher_index(alg_str); if (alg_id < ACVP_CIPHER_START) { ACVP_LOG_ERR("ERROR: unsupported algorithm (%s)", alg_str); return ACVP_UNSUPPORTED_OP; } cap = acvp_locate_cap_entry(ctx, alg_id); if (!cap) { ACVP_LOG_ERR("ERROR: ACVP server requesting unsupported capability"); return ACVP_UNSUPPORTED_OP; } /* * Create ACVP array for response */ rv = acvp_create_array(®_obj, ®_arry_val, ®_arry); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("ERROR: Failed to create JSON response struct. "); return rv; } /* * Start to build the JSON response */ rv = acvp_setup_json_rsp_group(&ctx, ®_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to setup json response"); return rv; } groups = json_object_get_array(obj, "testGroups"); g_cnt = json_array_get_count(groups); for (i = 0; i < g_cnt; i++) { int tgId = 0; int diff = 0; groupval = json_array_get_value(groups, i); groupobj = json_value_get_object(groupval); /* * Create a new group in the response with the tgid * and an array of tests */ r_gval = json_value_init_object(); r_gobj = json_value_get_object(r_gval); tgId = json_object_get_number(groupobj, "tgId"); if (!tgId) { ACVP_LOG_ERR("Missing tgid from server JSON groub obj"); rv = ACVP_MALFORMED_JSON; goto err; } json_object_set_number(r_gobj, "tgId", tgId); json_object_set_value(r_gobj, "tests", json_value_init_array()); r_tarr = json_object_get_array(r_gobj, "tests"); if (alg_id == ACVP_CMAC_AES) { keyLen = (unsigned int)json_object_get_number(groupobj, "keyLen"); if (!keyLen) { ACVP_LOG_ERR("keylen missing from cmac aes json"); rv = ACVP_MISSING_ARG; goto err; } } else if (alg_id == ACVP_CMAC_TDES) { keyingOption = (unsigned int)json_object_get_number(groupobj, "keyingOption"); if (keyingOption <= ACVP_CMAC_TDES_KEYING_OPTION_MIN || keyingOption >= ACVP_CMAC_TDES_KEYING_OPTION_MAX) { ACVP_LOG_ERR("keyingOption missing or wrong from cmac tdes json"); rv = ACVP_INVALID_ARG; goto err; } } direction = (char *)json_object_get_string(groupobj, "direction"); if (!direction) { ACVP_LOG_ERR("Unable to parse 'direction' from JSON."); rv = ACVP_MALFORMED_JSON; goto err; } strcmp_s("ver", 3, direction, &diff); if (!diff) { verify = 1; } else { strcmp_s("gen", 3, direction, &diff); if (diff) { ACVP_LOG_ERR("'direction' should be 'gen' or 'ver'"); rv = ACVP_UNSUPPORTED_OP; goto err; } } msglen = (unsigned int)json_object_get_number(groupobj, "msgLen") / 8; maclen = (unsigned int)json_object_get_number(groupobj, "macLen") / 8; if (!maclen) { ACVP_LOG_ERR("Server JSON missing 'macLen'"); rv = ACVP_MISSING_ARG; goto err; } ACVP_LOG_INFO("\n\n Test group: %d", i); tests = json_object_get_array(groupobj, "tests"); t_cnt = json_array_get_count(tests); for (j = 0; j < t_cnt; j++) { ACVP_LOG_INFO("Found new cmac test vector..."); testval = json_array_get_value(tests, j); testobj = json_value_get_object(testval); tc_id = (unsigned int)json_object_get_number(testobj, "tcId"); msg = (char *)json_object_get_string(testobj, "message"); /* msg can be null if msglen is 0 */ if (msg) { json_msglen = strnlen_s(msg, ACVP_CMAC_MSGLEN_MAX_STR + 1); if (json_msglen > ACVP_CMAC_MSGLEN_MAX_STR) { ACVP_LOG_ERR("'msg' too long"); rv = ACVP_INVALID_ARG; goto err; } if (!msglen && json_msglen > 0) { ACVP_LOG_ERR("Server JSON missing 'msgLen'"); rv = ACVP_MISSING_ARG; goto err; } } else if (msglen) { ACVP_LOG_ERR("msglen is nonzero, expected 'msg' in json"); rv = ACVP_MISSING_ARG; goto err; } if (alg_id == ACVP_CMAC_AES) { key1 = (char *)json_object_get_string(testobj, "key"); if (!key1) { ACVP_LOG_ERR("Server JSON missing 'key'"); rv = ACVP_MISSING_ARG; goto err; } key1_len = strnlen_s(key1, ACVP_CMAC_KEY_MAX + 1); if (key1_len > ACVP_CMAC_KEY_MAX) { ACVP_LOG_ERR("Invalid length for 'key' attribute in CMAC-AES test"); rv = ACVP_INVALID_ARG; goto err; } } else if (alg_id == ACVP_CMAC_TDES) { key1 = (char *)json_object_get_string(testobj, "key1"); key2 = (char *)json_object_get_string(testobj, "key2"); key3 = (char *)json_object_get_string(testobj, "key3"); if (!key1 || !key2 || !key3) { ACVP_LOG_ERR("Server JSON missing 'key(1,2,3)' value"); rv = ACVP_MISSING_ARG; goto err; } key1_len = strnlen_s(key1, ACVP_CMAC_KEY_MAX + 1); key2_len = strnlen_s(key2, ACVP_CMAC_KEY_MAX + 1); key3_len = strnlen_s(key3, ACVP_CMAC_KEY_MAX + 1); if (key1_len > ACVP_CMAC_KEY_MAX || key2_len > ACVP_CMAC_KEY_MAX || key3_len > ACVP_CMAC_KEY_MAX) { ACVP_LOG_ERR("Invalid length for 'key(1|2|3)' attribute in CMAC-TDES test"); rv = ACVP_INVALID_ARG; goto err; } } if (verify) { mac = (char *)json_object_get_string(testobj, "mac"); if (!mac) { ACVP_LOG_ERR("Server JSON missing 'mac'"); rv = ACVP_MISSING_ARG; goto err; } } ACVP_LOG_INFO("\n Test case: %d", j); ACVP_LOG_INFO(" tcId: %d", tc_id); ACVP_LOG_INFO(" direction: %s", direction); ACVP_LOG_INFO(" msgLen: %d", msglen); ACVP_LOG_INFO(" msg: %s", msg); if (alg_id == ACVP_CMAC_AES) { ACVP_LOG_INFO(" keyLen: %d", keyLen); ACVP_LOG_INFO(" key: %s", key1); } else if (alg_id == ACVP_CMAC_TDES) { ACVP_LOG_INFO(" keyingOption: %d", keyingOption); ACVP_LOG_INFO(" key1: %s", key1); ACVP_LOG_INFO(" key2: %s", key2); ACVP_LOG_INFO(" key3: %s", key3); } if (verify) { ACVP_LOG_INFO(" mac: %s", mac); } /* * Create a new test case in the response */ r_tval = json_value_init_object(); r_tobj = json_value_get_object(r_tval); json_object_set_number(r_tobj, "tcId", tc_id); /* * Setup the test case data that will be passed down to * the crypto module. */ rv = acvp_cmac_init_tc(ctx, &stc, tc_id, msg, msglen, keyLen, key1, key2, key3, verify, mac, maclen, alg_id); if (rv != ACVP_SUCCESS) { acvp_cmac_release_tc(&stc); json_value_free(r_tval); goto err; } /* Process the current test vector... */ if ((cap->crypto_handler)(&tc)) { ACVP_LOG_ERR("ERROR: crypto module failed the operation"); acvp_cmac_release_tc(&stc); rv = ACVP_CRYPTO_MODULE_FAIL; json_value_free(r_tval); goto err; } /* * Output the test case results using JSON */ rv = acvp_cmac_output_tc(ctx, &stc, r_tobj); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("ERROR: JSON output failure in hash module"); acvp_cmac_release_tc(&stc); json_value_free(r_tval); goto err; } /* * Release all the memory associated with the test case */ acvp_cmac_release_tc(&stc); /* Append the test response value to array */ json_array_append_value(r_tarr, r_tval); } json_array_append_value(r_garr, r_gval); } json_array_append_value(reg_arry, r_vs_val); json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL); if (ctx->debug == ACVP_LOG_LVL_VERBOSE) { printf("\n\n%s\n\n", json_result); } else { ACVP_LOG_INFO("\n\n%s\n\n", json_result); } json_free_serialized_string(json_result); rv = ACVP_SUCCESS; err: if (rv != ACVP_SUCCESS) { acvp_release_json(r_vs_val, r_gval); } return rv; }
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; }
/******************************************************************************* ** ** Function initialize_setup ** ** Description Create streams and trigger ** Can be hardcoded ** to add reading from configuration file. ** ** Returns void ** *******************************************************************************/ static int create_streams(void) { FILE *streams_fp; char fname[10]; char key_from_file[100]; int stream_len=0; int device_present; int stream_present[MAX_STREAM]; int j; printf("Creating M2X Streams \n"); memset(stream_present, 0, MAX_STREAM); /* Get the list of streams from the M2X Server and validate that all the Streams are present */ response = m2x_device_streams(ctx, device_id); printf("Response code: %d\n", response.status); if (m2x_is_success(&response)) { JSON_Array *streams = json_object_get_array(json_value_get_object( response.json), "streams"); size_t i; for (i = 0; i < json_array_get_count(streams); i++) { JSON_Object *json_stream = json_array_get_object(streams, i); const char *stream_name = json_object_get_string(json_stream, "name"); for (j=0; j< MAX_STREAM; j++) { if (strncmp(stream_name, stream_name_list[j],strlen(stream_name))) { stream_present[j] = 1; /* Stream already present*/ } } printf("Name : %s\n", stream_name); printf("\n"); } } m2x_release_response(&response); /* Create a Stream */ for (i=0; i < MAX_STREAM; i++) { if (stream_present[i]) continue; printf("Creating %d M2X Stream :\"%s\" of size=%d \n", i, stream_name_list[i], sizeof(stream_name_list[i])); memset(&buf, 0, sizeof(buf)); stream_len= strlen(stream_name_list[i]); stream_len = (stream_len<MAX_STREAM_NAME)?stream_len:MAX_STREAM_NAME; memcpy(stream_name, stream_name_list[i], stream_len+1); /*stream_name[stream_len]='\n';*/ APPL_TRACE_INFO("\nBefore m2x_device_stream_create device_id: %s |\n", &device_id); APPL_TRACE_INFO("\nBefore m2x_device_stream_create stream_name: %s |\n", stream_name); switch(i) { case HUMIDITY: sprintf(buf, "{ \"unit\": { \"label\": \"percentage\", \"symbol\": \"%%\" }, \"type\": \"numeric\" }"); break; case TEMPERATURE: sprintf(buf, "{ \"unit\": { \"label\": \"celsius\", \"symbol\": \"C\" }, \"type\": \"numeric\" }"); break; case PRESSURE: sprintf(buf, "{ \"unit\": { \"label\": \"pascal\", \"symbol\": \"Pa\" }, \"type\": \"numeric\" }"); break; case GYRO: sprintf(buf, "{ \"unit\": { \"label\": \"point\", \"symbol\": \"p\" }, \"type\": \"numeric\" }"); break; case ACCL: sprintf(buf, "{ \"unit\": { \"label\": \"point\", \"symbol\": \"p\" }, \"type\": \"numeric\" }"); break; case MAGNETO_FLUX: sprintf(buf, "{ \"unit\": { \"label\": \"point\", \"symbol\": \"p\" }, \"type\": \"numeric\" }"); break; } response = m2x_device_stream_create(ctx, &device_id, stream_name, buf); if (m2x_is_success(&response) && response.raw) { APPL_TRACE_INFO("%s\n", response.raw); } /* Store the Device Id in the file */ sprintf(fname, "/tmp/m2x/stream_%s", stream_name); streams_fp = fopen (fname, "w+"); fprintf(streams_fp, "%s", stream_name); fclose(streams_fp); /* Release the response so that same struct is used for next response */ m2x_release_response(&response); /* Sleep for about a min, since it takes ~40 sec to create the device */ sleep(5); } }
static gchar * set_network_interfaces (RequestData *request_data) { gchar *interfaces, *result, *name, *path, *value; augeas *aug; JSON_Value *val; JSON_Array *array; JSON_Object *obj; gint if_count, i, ret; aug = aug_init (NULL, NULL, AUG_NONE | AUG_NO_ERR_CLOSE | AUG_NO_MODL_AUTOLOAD); aug_set (aug, "/augeas/load/Interfaces/lens", "Interfaces.lns"); aug_set (aug, "/augeas/load/Interfaces/incl", "/etc/network/interfaces"); aug_load (aug); interfaces = request_data->raw_request + request_data->header_size; val = json_parse_string (interfaces); if (val == NULL) { GST_ERROR ("parse json type interfaces failure"); result = g_strdup_printf ("{\n \"result\": \"failure\",\n \"reason\": \"invalid data\"\n}"); aug_close (aug); return result; } array = json_value_get_array (val); if (array == NULL) { GST_ERROR ("get interfaces array failure"); result = g_strdup_printf ("{\n \"result\": \"failure\",\n \"reason\": \"not array type interfaces\"\n}"); aug_close (aug); json_value_free (val); return result; } if_count = json_array_get_count (array); for (i = 0; i < if_count; i++) { obj = json_array_get_object (array, i); name = (gchar *)json_object_get_string (obj, "name"); value = (gchar *)json_object_get_string (obj, "method"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/method", name); aug_set (aug, path, value); g_free (path); } value = (gchar *)json_object_get_string (obj, "address"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/address", name); ret = aug_set (aug, path, value); g_free (path); } value = (gchar *)json_object_get_string (obj, "netmask"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/netmask", name); aug_set (aug, path, value); g_free (path); } value = (gchar *)json_object_get_string (obj, "network"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/network", name); aug_set (aug, path, value); g_free (path); } value = (gchar *)json_object_get_string (obj, "broadcast"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/broadcast", name); aug_set (aug, path, value); g_free (path); } value = (gchar *)json_object_get_string (obj, "gateway"); if (value != NULL) { path = g_strdup_printf ("//files/etc/network/interfaces/iface[.='%s']/gateway", name); aug_set (aug, path, value); g_free (path); } } if (aug_save (aug) == -1) { aug_get (aug, "/augeas//error", (const gchar **)&value); GST_ERROR ("set /etc/network/interface failure: %s", value); result = g_strdup_printf ("{\n \"result\": \"failure\",\n \"reason\": \"%s\"\n}", value); } else { result = g_strdup ("{\n \"result\": \"success\"\n}"); } json_value_free (val); aug_close (aug); return result; }
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; }
// 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; } } } } } }
ACVP_RESULT acvp_kdf135_ssh_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) { unsigned int tc_id; JSON_Value *groupval; JSON_Object *groupobj = NULL; JSON_Value *testval; JSON_Object *testobj = NULL; JSON_Array *groups; JSON_Array *tests; JSON_Value *reg_arry_val = NULL; JSON_Object *reg_obj = NULL; JSON_Array *reg_arry = NULL; int i, g_cnt; int j, t_cnt; JSON_Value *r_vs_val = NULL; JSON_Object *r_vs = NULL; JSON_Array *r_tarr = NULL, *r_garr = NULL; /* Response testarray, grouparray */ JSON_Value *r_tval = NULL, *r_gval = NULL; /* Response testval, groupval */ JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */ ACVP_CAPS_LIST *cap; ACVP_KDF135_SSH_TC stc; ACVP_TEST_CASE tc; ACVP_RESULT rv; ACVP_CIPHER alg_id; const char *alg_str = NULL; const char *mode_str = NULL; const char *cipher_str = NULL; const char *shared_secret_str = NULL; const char *session_id_str = NULL; const char *hash_str = NULL; char *json_result; if (!ctx) { ACVP_LOG_ERR("No ctx for handler operation"); return ACVP_NO_CTX; } if (!obj) { ACVP_LOG_ERR("No obj for handler operation"); return ACVP_MALFORMED_JSON; } alg_str = json_object_get_string(obj, "algorithm"); if (!alg_str) { ACVP_LOG_ERR("unable to parse 'algorithm' from JSON"); return ACVP_MALFORMED_JSON; } mode_str = json_object_get_string(obj, "mode"); if (!mode_str) { ACVP_LOG_ERR("unable to parse 'mode' from JSON"); return ACVP_MALFORMED_JSON; } alg_id = acvp_lookup_cipher_w_mode_index(alg_str, mode_str); if (alg_id != ACVP_KDF135_SSH) { ACVP_LOG_ERR("Server JSON invalid 'algorithm' or 'mode'"); return ACVP_INVALID_ARG; } /* * Get a reference to the abstracted test case */ tc.tc.kdf135_ssh = &stc; /* * Get the crypto module handler for this hash algorithm */ cap = acvp_locate_cap_entry(ctx, alg_id); if (!cap) { ACVP_LOG_ERR("ACVP server requesting unsupported capability %s : %d.", alg_str, alg_id); return ACVP_UNSUPPORTED_OP; } /* * Create ACVP array for response */ rv = acvp_create_array(®_obj, ®_arry_val, ®_arry); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to create JSON response struct. "); return rv; } /* * Start to build the JSON response */ rv = acvp_setup_json_rsp_group(&ctx, ®_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to setup json response"); return rv; } groups = json_object_get_array(obj, "testGroups"); if (!groups) { ACVP_LOG_ERR("Failed to include testGroups. "); rv = ACVP_MISSING_ARG; goto err; } g_cnt = json_array_get_count(groups); for (i = 0; i < g_cnt; i++) { int tgId = 0; int diff = 1; unsigned int e_key_len = 0, i_key_len = 0, hash_len = 0, iv_len = 0; ACVP_HASH_ALG sha_type = 0; const char *sha_str = NULL; groupval = json_array_get_value(groups, i); groupobj = json_value_get_object(groupval); /* * Create a new group in the response with the tgid * and an array of tests */ r_gval = json_value_init_object(); r_gobj = json_value_get_object(r_gval); tgId = json_object_get_number(groupobj, "tgId"); if (!tgId) { ACVP_LOG_ERR("Missing tgid from server JSON groub obj"); rv = ACVP_MALFORMED_JSON; goto err; } json_object_set_number(r_gobj, "tgId", tgId); json_object_set_value(r_gobj, "tests", json_value_init_array()); r_tarr = json_object_get_array(r_gobj, "tests"); // Get the expected (user will generate) key and iv lengths cipher_str = json_object_get_string(groupobj, "cipher"); if (!cipher_str) { ACVP_LOG_ERR("Failed to include cipher. "); rv = ACVP_MISSING_ARG; goto err; } sha_str = json_object_get_string(groupobj, "hashAlg"); if (!sha_str) { ACVP_LOG_ERR("Failed to include hashAlg. "); rv = ACVP_MISSING_ARG; goto err; } sha_type = acvp_lookup_hash_alg(sha_str); if (sha_type == ACVP_SHA1) { i_key_len = hash_len = ACVP_SHA1_BYTE_LEN; } else if (sha_type == ACVP_SHA224) { i_key_len = hash_len = ACVP_SHA224_BYTE_LEN; } else if (sha_type == ACVP_SHA256) { i_key_len = hash_len = ACVP_SHA256_BYTE_LEN; } else if (sha_type == ACVP_SHA384) { i_key_len = hash_len = ACVP_SHA384_BYTE_LEN; } else if (sha_type == ACVP_SHA512) { i_key_len = hash_len = ACVP_SHA512_BYTE_LEN; } else { ACVP_LOG_ERR("ACVP server requesting invalid hashAlg"); rv = ACVP_NO_CAP; goto err; } /* * Determine the encrypt key_len, inferred from cipher. */ strcmp_s(ACVP_MODE_TDES, 4, cipher_str, &diff); if (!diff) { e_key_len = ACVP_KEY_LEN_TDES; iv_len = ACVP_BLOCK_LEN_TDES; } strcmp_s(ACVP_MODE_AES_128, 7, cipher_str, &diff); if (!diff) { e_key_len = ACVP_KEY_LEN_AES128; iv_len = ACVP_BLOCK_LEN_AES128; } strcmp_s(ACVP_MODE_AES_192, 7, cipher_str, &diff); if (!diff) { e_key_len = ACVP_KEY_LEN_AES192; iv_len = ACVP_BLOCK_LEN_AES192; } strcmp_s(ACVP_MODE_AES_256, 7, cipher_str, &diff); if (!diff) { e_key_len = ACVP_KEY_LEN_AES256; iv_len = ACVP_BLOCK_LEN_AES256; } if (!e_key_len || !iv_len) { ACVP_LOG_ERR("Unsupported cipher type"); rv = ACVP_NO_CAP; goto err; } /* * Log Test Group information... */ ACVP_LOG_INFO(" Test group: %d", i); ACVP_LOG_INFO(" cipher: %s", cipher_str); ACVP_LOG_INFO(" hashAlg: %s", sha_str); tests = json_object_get_array(groupobj, "tests"); if (!tests) { ACVP_LOG_ERR("Failed to include tests. "); rv = ACVP_MISSING_ARG; goto err; } t_cnt = json_array_get_count(tests); if (!t_cnt) { ACVP_LOG_ERR("Failed to include tests in array. "); rv = ACVP_MISSING_ARG; goto err; } for (j = 0; j < t_cnt; j++) { ACVP_LOG_INFO("Found new KDF SSH test vector..."); testval = json_array_get_value(tests, j); testobj = json_value_get_object(testval); tc_id = (unsigned int)json_object_get_number(testobj, "tcId"); if (!tc_id) { ACVP_LOG_ERR("Failed to include tc_id. "); rv = ACVP_MISSING_ARG; goto err; } shared_secret_str = json_object_get_string(testobj, "k"); if (!shared_secret_str) { ACVP_LOG_ERR("Failed to include k. "); rv = ACVP_MISSING_ARG; goto err; } hash_str = json_object_get_string(testobj, "h"); if (!hash_str) { ACVP_LOG_ERR("Failed to include h. "); rv = ACVP_MISSING_ARG; goto err; } session_id_str = json_object_get_string(testobj, "sessionId"); if (!session_id_str) { ACVP_LOG_ERR("Failed to include sessionId. "); rv = ACVP_MISSING_ARG; goto err; } ACVP_LOG_INFO(" Test case: %d", j); ACVP_LOG_INFO(" tcId: %d", tc_id); ACVP_LOG_INFO(" k: %s", shared_secret_str); ACVP_LOG_INFO(" h: %s", hash_str); ACVP_LOG_INFO(" session_id: %s", session_id_str); /* * Create a new test case in the response */ r_tval = json_value_init_object(); r_tobj = json_value_get_object(r_tval); json_object_set_number(r_tobj, "tcId", tc_id); /* * Setup the test case data that will be passed down to * the crypto module. */ rv = acvp_kdf135_ssh_init_tc(ctx, &stc, tc_id, alg_id, sha_type, e_key_len, i_key_len, iv_len, hash_len, shared_secret_str, hash_str, session_id_str); if (rv != ACVP_SUCCESS) { acvp_kdf135_ssh_release_tc(&stc); json_value_free(r_tval); goto err; } /* Process the current test vector... */ if ((cap->crypto_handler)(&tc)) { ACVP_LOG_ERR("crypto module failed the KDF SSH operation"); acvp_kdf135_ssh_release_tc(&stc); rv = ACVP_CRYPTO_MODULE_FAIL; json_value_free(r_tval); goto err; } /* * Output the test case results using JSON */ rv = acvp_kdf135_ssh_output_tc(ctx, &stc, r_tobj); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("JSON output failure in hash module"); acvp_kdf135_ssh_release_tc(&stc); json_value_free(r_tval); goto err; } /* * Release all the memory associated with the test case */ acvp_kdf135_ssh_release_tc(&stc); /* Append the test response value to array */ json_array_append_value(r_tarr, r_tval); } json_array_append_value(r_garr, r_gval); } json_array_append_value(reg_arry, r_vs_val); json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL); if (ctx->debug == ACVP_LOG_LVL_VERBOSE) { printf("\n\n%s\n\n", json_result); } else { ACVP_LOG_INFO("\n\n%s\n\n", json_result); } json_free_serialized_string(json_result); rv = ACVP_SUCCESS; err: if (rv != ACVP_SUCCESS) { acvp_release_json(r_vs_val, r_gval); } return rv; }
ACVP_RESULT acvp_kdf135_srtp_kat_handler(ACVP_CTX *ctx, JSON_Object *obj) { unsigned int tc_id; JSON_Value *groupval; JSON_Object *groupobj = NULL; JSON_Value *testval; JSON_Object *testobj = NULL; JSON_Array *groups; JSON_Array *tests; JSON_Value *reg_arry_val = NULL; JSON_Object *reg_obj = NULL; JSON_Array *reg_arry = NULL; int i, g_cnt; int j, t_cnt; JSON_Value *r_vs_val = NULL; JSON_Object *r_vs = NULL; JSON_Array *r_tarr = NULL, *r_garr = NULL; /* Response testarray, grouparray */ JSON_Value *r_tval = NULL, *r_gval = NULL; /* Response testval, groupval */ JSON_Object *r_tobj = NULL, *r_gobj = NULL; /* Response testobj, groupobj */ ACVP_CAPS_LIST *cap; ACVP_KDF135_SRTP_TC stc; ACVP_TEST_CASE tc; ACVP_RESULT rv; const char *alg_str = json_object_get_string(obj, "algorithm"); const char *mode_str = NULL; ACVP_CIPHER alg_id; char *json_result; int aes_key_length; char *kdr = NULL, *master_key = NULL, *master_salt = NULL, *index = NULL, *srtcp_index = NULL; if (!ctx) { ACVP_LOG_ERR("No ctx for handler operation"); return ACVP_NO_CTX; } if (!alg_str) { ACVP_LOG_ERR("unable to parse 'algorithm' from JSON."); return ACVP_MALFORMED_JSON; } mode_str = json_object_get_string(obj, "mode"); if (!mode_str) { ACVP_LOG_ERR("unable to parse 'mode' from JSON."); return ACVP_MALFORMED_JSON; } alg_id = acvp_lookup_cipher_w_mode_index(alg_str, mode_str); if (alg_id != ACVP_KDF135_SRTP) { ACVP_LOG_ERR("Server JSON invalid 'algorithm' or 'mode'"); return ACVP_INVALID_ARG; } /* * Get a reference to the abstracted test case */ tc.tc.kdf135_srtp = &stc; stc.cipher = alg_id; cap = acvp_locate_cap_entry(ctx, alg_id); if (!cap) { ACVP_LOG_ERR("ACVP server requesting unsupported capability %s : %d.", alg_str, alg_id); return ACVP_UNSUPPORTED_OP; } /* * Create ACVP array for response */ rv = acvp_create_array(®_obj, ®_arry_val, ®_arry); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to create JSON response struct. "); return rv; } /* * Start to build the JSON response */ rv = acvp_setup_json_rsp_group(&ctx, ®_arry_val, &r_vs_val, &r_vs, alg_str, &r_garr); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("Failed to setup json response"); goto err; } groups = json_object_get_array(obj, "testGroups"); g_cnt = json_array_get_count(groups); for (i = 0; i < g_cnt; i++) { int tgId = 0; groupval = json_array_get_value(groups, i); groupobj = json_value_get_object(groupval); /* * Create a new group in the response with the tgid * and an array of tests */ r_gval = json_value_init_object(); r_gobj = json_value_get_object(r_gval); tgId = json_object_get_number(groupobj, "tgId"); if (!tgId) { ACVP_LOG_ERR("Missing tgid from server JSON groub obj"); rv = ACVP_MALFORMED_JSON; goto err; } json_object_set_number(r_gobj, "tgId", tgId); json_object_set_value(r_gobj, "tests", json_value_init_array()); r_tarr = json_object_get_array(r_gobj, "tests"); aes_key_length = (unsigned int)json_object_get_number(groupobj, "aesKeyLength"); if (!aes_key_length) { ACVP_LOG_ERR("aesKeyLength incorrect, %d", aes_key_length); rv = ACVP_INVALID_ARG; goto err; } kdr = (char *)json_object_get_string(groupobj, "kdr"); if (!kdr) { ACVP_LOG_ERR("Failed to include kdr"); rv = ACVP_MISSING_ARG; goto err; } ACVP_LOG_INFO("\n Test group: %d", i); ACVP_LOG_INFO(" kdr: %s", kdr); ACVP_LOG_INFO(" key length: %d", aes_key_length); tests = json_object_get_array(groupobj, "tests"); t_cnt = json_array_get_count(tests); for (j = 0; j < t_cnt; j++) { ACVP_LOG_INFO("Found new KDF SRTP test vector..."); testval = json_array_get_value(tests, j); testobj = json_value_get_object(testval); tc_id = (unsigned int)json_object_get_number(testobj, "tcId"); master_key = (char *)json_object_get_string(testobj, "masterKey"); if (!master_key) { ACVP_LOG_ERR("Failed to include JSON key:\"masterKey\""); rv = ACVP_MISSING_ARG; goto err; } master_salt = (char *)json_object_get_string(testobj, "masterSalt"); if (!master_salt) { ACVP_LOG_ERR("Failed to include JSON key:\"masterSalt\""); rv = ACVP_MISSING_ARG; goto err; } index = (char *)json_object_get_string(testobj, "index"); if (!index) { ACVP_LOG_ERR("Failed to include JSON key:\"index\""); rv = ACVP_MISSING_ARG; goto err; } srtcp_index = (char *)json_object_get_string(testobj, "srtcpIndex"); if (!srtcp_index) { ACVP_LOG_ERR("Failed to include JSON key:\"srtcpIndex\""); rv = ACVP_MISSING_ARG; goto err; } ACVP_LOG_INFO(" Test case: %d", j); ACVP_LOG_INFO(" tcId: %d", tc_id); ACVP_LOG_INFO(" masterKey: %s", master_key); ACVP_LOG_INFO(" masterSalt: %s", master_salt); ACVP_LOG_INFO(" index: %s", index); ACVP_LOG_INFO(" srtcpIndex: %s", srtcp_index); /* * Create a new test case in the response */ r_tval = json_value_init_object(); r_tobj = json_value_get_object(r_tval); json_object_set_number(r_tobj, "tcId", tc_id); /* * Setup the test case data that will be passed down to * the crypto module. */ rv = acvp_kdf135_srtp_init_tc(ctx, &stc, tc_id, aes_key_length, kdr, master_key, master_salt, index, srtcp_index); if (rv != ACVP_SUCCESS) { acvp_kdf135_srtp_release_tc(&stc); json_value_free(r_tval); goto err; } /* Process the current test vector... */ if ((cap->crypto_handler)(&tc)) { ACVP_LOG_ERR("crypto module failed"); acvp_kdf135_srtp_release_tc(&stc); rv = ACVP_CRYPTO_MODULE_FAIL; json_value_free(r_tval); goto err; } /* * Output the test case results using JSON */ rv = acvp_kdf135_srtp_output_tc(ctx, &stc, r_tobj); if (rv != ACVP_SUCCESS) { ACVP_LOG_ERR("JSON output failure"); acvp_kdf135_srtp_release_tc(&stc); json_value_free(r_tval); goto err; } /* * Release all the memory associated with the test case */ acvp_kdf135_srtp_release_tc(&stc); /* Append the test response value to array */ json_array_append_value(r_tarr, r_tval); } json_array_append_value(r_garr, r_gval); } json_array_append_value(reg_arry, r_vs_val); json_result = json_serialize_to_string_pretty(ctx->kat_resp, NULL); if (ctx->debug == ACVP_LOG_LVL_VERBOSE) { printf("\n\n%s\n\n", json_result); } else { ACVP_LOG_INFO("\n\n%s\n\n", json_result); } json_free_serialized_string(json_result); rv = ACVP_SUCCESS; err: if (rv != ACVP_SUCCESS) { acvp_release_json(r_vs_val, r_gval); } return rv; }