static json_t* decode_text(const char *text)
{
	json_t *root = NULL;
	json_error_t err;

	if (!text)
		goto exit;

	root = json_loads(text, 0, &err);
	if (!root) {
		printf("json_loads() failed: %s\n", err.text);
		goto exit;
	}

	if (!json_is_array(root)) {
		printf("json_is_array() failed\n");
		json_decref(root);
		root = NULL;
	}

exit:
	return root;
}
Exemplo n.º 2
0
static size_t
write_compact_objects(json_t* objects, json_t* header, stream_t* stream)
{
    size_t bytes = 0;
    size_t obj_bytes = 1;
    size_t objs_bytes = 0;
    int i;

    assert(json_is_array(objects));
    size_t array_length = json_array_size(objects);

    for (i = 0; i < array_length && obj_bytes > 0; ++i) {
        json_t* obj = json_array_get(objects, i);

        obj_bytes = write_compact_object(obj, header, stream);
        objs_bytes += obj_bytes;
    }

    if (i == array_length) {
        bytes = objs_bytes;
    }
    return bytes;
}
Exemplo n.º 3
0
static void parse_memcached(const json_t *obj)
{
	json_t *servers;

	if (!json_is_object(obj)) {
		/* No memcached config so don't use it. */
		memcached_free(srv.mc);
		srv.mc = NULL;
		return;
	}

	servers = json_object_get(obj, "servers");
	if (json_is_array(servers)) {
		unsigned int i, size = json_array_size(servers);

		for (i = 0; i < size; i++) {
			json_t *server_obj;

			server_obj = json_array_get(servers, i);
			parse_memcached_server(server_obj);
		}
	}
}
Exemplo n.º 4
0
static w_query_expr *parse_list(w_query *query, json_t *term, bool allof)
{
    struct w_expr_list *list;
    size_t i;

    /* don't allow "allof" on its own */
    if (!json_is_array(term) || json_array_size(term) < 2) {
        query->errmsg = strdup("must use [\"allof\", expr...]");
        return NULL;
    }

    list = calloc(1, sizeof(*list));
    if (!list) {
        query->errmsg = strdup("out of memory");
        return NULL;
    }

    list->allof = allof;
    list->num = json_array_size(term) - 1;
    list->exprs = calloc(list->num, sizeof(list->exprs[0]));

    for (i = 0; i < list->num; i++) {
        w_query_expr *parsed;
        json_t *exp = json_array_get(term, i + 1);

        parsed = w_query_expr_parse(query, exp);
        if (!parsed) {
            // other expression parser sets errmsg
            dispose_list(list);
            return NULL;
        }

        list->exprs[i] = parsed;
    }

    return w_query_expr_new(eval_list, dispose_list, list);
}
Exemplo n.º 5
0
int load_cfg_svr(json_t *root, const char *key, nw_svr_cfg *cfg)
{
    json_t *node = json_object_get(root, key);
    if (!node || !json_is_object(node))
        return -__LINE__;

    json_t *bind = json_object_get(node, "bind");
    if (!bind)
        return -__LINE__;
    if (json_is_string(bind)) {
        cfg->bind_count = 1;
        cfg->bind_arr = malloc(sizeof(nw_svr_bind));
        if (nw_sock_cfg_parse(json_string_value(bind), &cfg->bind_arr[0].addr, &cfg->bind_arr[0].sock_type) < 0)
            return -__LINE__;
    } else if (json_is_array(bind)) {
        cfg->bind_count = json_array_size(bind);
        if (cfg->bind_count == 0)
            return -__LINE__;
        cfg->bind_arr = malloc(sizeof(nw_svr_bind) * cfg->bind_count);
        for (uint32_t i = 0; i < cfg->bind_count; ++i) {
            json_t *row = json_array_get(bind, i);
            if (!json_is_string(row))
                return -__LINE__;
            if (nw_sock_cfg_parse(json_string_value(row), &cfg->bind_arr[i].addr, &cfg->bind_arr[i].sock_type) < 0)
                return -__LINE__;
        }
    } else {
        return -__LINE__;
    }

    ERR_RET(read_cfg_uint32(node, "max_pkg_size", &cfg->max_pkg_size, true, 0));
    ERR_RET(read_cfg_uint32(node, "buf_limit", &cfg->buf_limit, false, 0));
    ERR_RET(read_cfg_uint32(node, "read_mem", &cfg->read_mem, false, 0));
    ERR_RET(read_cfg_uint32(node, "write_mem", &cfg->write_mem, false, 0));

    return 0;
}
Exemplo n.º 6
0
Frame* CreateFramesFromJSON(json_t* root)
{
	if (!json_is_array(root))
	{
		SDL_LogError(
				SDL_LOG_CATEGORY_APPLICATION,
				"Frames is not JSON array"
				);
		return NULL;
	}

	Frame* frames = NULL;
	Frame** frameIter = &frames;
	uint32_t i = 0;

	for (i = 0; i < json_array_size(root); i++)
	{
		json_t* frameNode;

		frameNode = json_array_get(root, i);
		if (!json_is_object(frameNode))
		{
			SDL_LogWarn(
				SDL_LOG_CATEGORY_APPLICATION,
				"Frame is invalid JSON type. Expected object.\n"
			);
			continue;
		}

		while (*frameIter != NULL)
			frameIter = &((*frameIter)->next);

		*frameIter = CreateFrameFromJSON(frameNode);
	}

	return frames;
}
Exemplo n.º 7
0
int broker_msg_handle_subscribe(RemoteDSLink *link, json_t *req) {
    broker_utils_send_closed_resp(link, req, NULL);

    json_t *paths = json_object_get(req, "paths");
    if (!json_is_array(paths)) {
        return 1;
    }


    json_t *maxPermitJson = json_object_get(req, "permit");
    PermissionLevel maxPermit = PERMISSION_CONFIG;
    if (json_is_string(maxPermitJson)) {
        maxPermit = permission_str_level(json_string_value(maxPermitJson));
    }

    if (maxPermit < PERMISSION_READ) {
        return 0;
    }

    size_t index;
    json_t *obj;
    json_array_foreach(paths, index, obj) {
        handle_subscribe(link, obj);
    }
Exemplo n.º 8
0
static TR_RP_REALM *tr_cfg_parse_comm_rps (TR_CFG *trc, json_t *jrps, TR_CFG_RC *rc)
{
  TR_RP_REALM *rp = NULL;
  TR_RP_REALM *temp_rp = NULL;
  int i = 0;

  if ((!trc) ||
      (!jrps) ||
      (!json_is_array(jrps))) {
    if (rc)
      *rc = TR_CFG_BAD_PARAMS;
    return NULL;
  }

  for (i = (json_array_size(jrps)-1); i >= 0; i--) {
    if (NULL == (temp_rp = talloc(trc, TR_RP_REALM))) {
      tr_debug("tr_cfg_parse_comm_rps: Can't allocate memory for RP Realm.");
      if (rc)
	*rc = TR_CFG_NOMEM;
      return NULL;
    }
    memset (temp_rp, 0, sizeof(TR_RP_REALM));

    if (NULL == (temp_rp->realm_name = tr_new_name((char *)json_string_value(json_array_get(jrps, i))))) {
      tr_debug("tr_cfg_parse_comm_rps: No memory for RP Realm Name.");
      if (rc)
	*rc = TR_CFG_NOMEM;
      return NULL;
    }

    temp_rp->next = rp;
    rp = temp_rp;
  }

  return rp;
}
Exemplo n.º 9
0
// QUESTION: Should -3 be returned for !array, etc. ?
int_t portal_parse_sections(json_t *array, uint32_t *sections) {

	uint64_t count;
	chr_t *current;
	int_t result = 1;

	if (!array || !json_is_array(array) || !sections) {
		return -1;
	}

	// Clear the output just in case something goes wrong.
	*sections = 0;

	if (!(count = json_array_size_d(array))) {
		return 0;
	}

	for (uint64_t i = 0; i < count && result == 1; i++) {

		if (!json_is_string(json_array_get_d(array, i)) || !(current = (chr_t *)json_string_value_d(json_array_get_d(array, i)))) {
			return -1;
		}

		if (!st_cmp_ci_eq(NULLER(current), PLACER("meta", 4))) *sections |= PORTAL_ENDPOINT_MESSAGE_META;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("source", 6))) *sections |= PORTAL_ENDPOINT_MESSAGE_SOURCE;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("security", 8))) *sections |= PORTAL_ENDPOINT_MESSAGE_SECURITY;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("server", 6))) *sections |= PORTAL_ENDPOINT_MESSAGE_SERVER;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("header", 6))) *sections |= PORTAL_ENDPOINT_MESSAGE_HEADER;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("body", 4))) *sections |= PORTAL_ENDPOINT_MESSAGE_BODY;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("attachments", 11))) *sections |= PORTAL_ENDPOINT_MESSAGE_ATTACHMENTS;
		else if (!st_cmp_ci_eq(NULLER(current), PLACER("info",4))) *sections |= PORTAL_ENDPOINT_MESSAGE_INFO;
		else if (result == 1) result = -2;
	}

	return result;
}
Exemplo n.º 10
0
int json_array_append_new(json_t *json, json_t *value)
{
    json_array_t *array;

    if(!value)
        return -1;

    if(!json_is_array(json) || json == value)
    {
        json_decref(value);
        return -1;
    }
    array = json_to_array(json);

    if(!json_array_grow(array, 1, 1)) {
        json_decref(value);
        return -1;
    }

    array->table[array->entries] = value;
    array->entries++;

    return 0;
}
Exemplo n.º 11
0
static int
avro_schema_from_json_t(json_t *json, avro_schema_t *schema,
			st_table *named_schemas)
{
#ifdef _WIN32
 #pragma message("#warning: Bug: '0' is not of type avro_type_t.")
#else
 #warning "Bug: '0' is not of type avro_type_t."
#endif
  /* We should really have an "AVRO_INVALID" type in
   * avro_type_t. Suppress warning below in which we set type to 0.
   */
	avro_type_t type = (avro_type_t) 0;
	unsigned int i;
	avro_schema_t named_type = NULL;

	if (avro_type_from_json_t(json, &type, named_schemas, &named_type)) {
		return EINVAL;
	}

	switch (type) {
	case AVRO_LINK:
		*schema = avro_schema_link(named_type);
		break;

	case AVRO_STRING:
		*schema = avro_schema_string();
		break;

	case AVRO_BYTES:
		*schema = avro_schema_bytes();
		break;

	case AVRO_INT32:
		*schema = avro_schema_int();
		break;

	case AVRO_INT64:
		*schema = avro_schema_long();
		break;

	case AVRO_FLOAT:
		*schema = avro_schema_float();
		break;

	case AVRO_DOUBLE:
		*schema = avro_schema_double();
		break;

	case AVRO_BOOLEAN:
		*schema = avro_schema_boolean();
		break;

	case AVRO_NULL:
		*schema = avro_schema_null();
		break;

	case AVRO_RECORD:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_namespace =
			    json_object_get(json, "namespace");
			json_t *json_fields = json_object_get(json, "fields");
			unsigned int num_fields;
			const char *record_name;
			const char *record_namespace;

			if (!json_is_string(json_name)) {
				avro_set_error("Record type must have a \"name\"");
				return EINVAL;
			}
			if (!json_is_array(json_fields)) {
				avro_set_error("Record type must have \"fields\"");
				return EINVAL;
			}
			num_fields = json_array_size(json_fields);
			if (num_fields == 0) {
				avro_set_error("Record type must have at least one field");
				return EINVAL;
			}
			record_name = json_string_value(json_name);
			if (!record_name) {
				avro_set_error("Record type must have a \"name\"");
				return EINVAL;
			}
			if (json_is_string(json_namespace)) {
				record_namespace =
				    json_string_value(json_namespace);
			} else {
				record_namespace = NULL;
			}
			*schema =
			    avro_schema_record(record_name, record_namespace);
			if (save_named_schemas(record_name, *schema, named_schemas)) {
				avro_set_error("Cannot save record schema");
				return ENOMEM;
			}
			for (i = 0; i < num_fields; i++) {
				json_t *json_field =
				    json_array_get(json_fields, i);
				json_t *json_field_name;
				json_t *json_field_type;
				json_t *json_default_value;
				avro_schema_t json_field_type_schema;
				int field_rval;

				if (!json_is_object(json_field)) {
					avro_set_error("Record field %d must be an array", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_name =
				    json_object_get(json_field, "name");
				if (!json_field_name) {
					avro_set_error("Record field %d must have a \"name\"", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				json_field_type =
				    json_object_get(json_field, "type");
				if (!json_field_type) {
					avro_set_error("Record field %d must have a \"type\"", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				field_rval =
				    avro_schema_from_json_t(json_field_type,
							    &json_field_type_schema,
							    named_schemas);
				if (field_rval) {
					avro_schema_decref(*schema);
					return field_rval;
				}
				json_default_value =
						json_object_get(json_field, "default");
				avro_datum_t default_value = NULL;
				if (json_default_value) {
					avro_schema_t default_schema = json_field_type_schema;
					if (json_field_type_schema->type == AVRO_UNION) {
						// From the spec: "Default values for union fields correspond
						// to the first schema in the union."
						default_schema =
								avro_schema_union_branch(json_field_type_schema, 0);
					}
					default_value =
							json_t_to_avro_value(default_schema, json_default_value);
					if (default_value == NULL) {
						avro_schema_decref(*schema);
						return EINVAL;
					}
				}
				field_rval =
				    avro_schema_record_field_append(*schema,
								    json_string_value
								    (json_field_name),
										json_field_type_schema,
										default_value);
				avro_schema_decref(json_field_type_schema);
				if (field_rval != 0) {
					avro_schema_decref(*schema);
					return field_rval;
				}
			}
		}
		break;

	case AVRO_ENUM:
		{
			json_t *json_name = json_object_get(json, "name");
			json_t *json_symbols = json_object_get(json, "symbols");
			const char *name;
			unsigned int num_symbols;

			if (!json_is_string(json_name)) {
				avro_set_error("Enum type must have a \"name\"");
				return EINVAL;
			}
			if (!json_is_array(json_symbols)) {
				avro_set_error("Enum type must have \"symbols\"");
				return EINVAL;
			}

			name = json_string_value(json_name);
			if (!name) {
				avro_set_error("Enum type must have a \"name\"");
				return EINVAL;
			}
			num_symbols = json_array_size(json_symbols);
			if (num_symbols == 0) {
				avro_set_error("Enum type must have at least one symbol");
				return EINVAL;
			}
			*schema = avro_schema_enum(name);
			if (save_named_schemas(name, *schema, named_schemas)) {
				avro_set_error("Cannot save enum schema");
				return ENOMEM;
			}
			for (i = 0; i < num_symbols; i++) {
				int enum_rval;
				json_t *json_symbol =
				    json_array_get(json_symbols, i);
				const char *symbol;
				if (!json_is_string(json_symbol)) {
					avro_set_error("Enum symbol %d must be a string", i);
					avro_schema_decref(*schema);
					return EINVAL;
				}
				symbol = json_string_value(json_symbol);
				enum_rval =
				    avro_schema_enum_symbol_append(*schema,
								   symbol);
				if (enum_rval != 0) {
					avro_schema_decref(*schema);
					return enum_rval;
				}
			}
		}
		break;

	case AVRO_ARRAY:
		{
			int items_rval;
			json_t *json_items = json_object_get(json, "items");
			avro_schema_t items_schema;
			if (!json_items) {
				avro_set_error("Array type must have \"items\"");
				return EINVAL;
			}
			items_rval =
			    avro_schema_from_json_t(json_items, &items_schema,
						    named_schemas);
			if (items_rval) {
				return items_rval;
			}
			*schema = avro_schema_array(items_schema);
			avro_schema_decref(items_schema);
		}
		break;

	case AVRO_MAP:
		{
			int values_rval;
			json_t *json_values = json_object_get(json, "values");
			avro_schema_t values_schema;

			if (!json_values) {
				avro_set_error("Map type must have \"values\"");
				return EINVAL;
			}
			values_rval =
			    avro_schema_from_json_t(json_values, &values_schema,
						    named_schemas);
			if (values_rval) {
				return values_rval;
			}
			*schema = avro_schema_map(values_schema);
			avro_schema_decref(values_schema);
		}
		break;

	case AVRO_UNION:
		{
			unsigned int num_schemas = json_array_size(json);
			avro_schema_t s;
			if (num_schemas == 0) {
				avro_set_error("Union type must have at least one branch");
				return EINVAL;
			}
			*schema = avro_schema_union();
			for (i = 0; i < num_schemas; i++) {
				int schema_rval;
				json_t *schema_json = json_array_get(json, i);
				if (!schema_json) {
					avro_set_error("Cannot retrieve branch JSON");
					return EINVAL;
				}
				schema_rval =
				    avro_schema_from_json_t(schema_json, &s,
							    named_schemas);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
				schema_rval =
				    avro_schema_union_append(*schema, s);
				avro_schema_decref(s);
				if (schema_rval != 0) {
					avro_schema_decref(*schema);
					return schema_rval;
				}
			}
		}
		break;

	case AVRO_FIXED:
		{
			json_t *json_size = json_object_get(json, "size");
			json_t *json_name = json_object_get(json, "name");
			json_int_t size;
			const char *name;
			if (!json_is_integer(json_size)) {
				avro_set_error("Fixed type must have a \"size\"");
				return EINVAL;
			}
			if (!json_is_string(json_name)) {
				avro_set_error("Fixed type must have a \"name\"");
				return EINVAL;
			}
			size = json_integer_value(json_size);
			name = json_string_value(json_name);
			*schema = avro_schema_fixed(name, (int64_t) size);
			if (save_named_schemas(name, *schema, named_schemas)) {
				avro_set_error("Cannot save fixed schema");
				return ENOMEM;
			}
		}
		break;

	default:
		avro_set_error("Unknown schema type");
		return EINVAL;
	}
	return 0;
}
Exemplo n.º 12
0
static int
avro_type_from_json_t(json_t *json, avro_type_t *type,
		      st_table *named_schemas, avro_schema_t *named_type)
{
	json_t *json_type;
	const char *type_str;

	if (json_is_array(json)) {
		*type = AVRO_UNION;
		return 0;
	} else if (json_is_object(json)) {
		json_type = json_object_get(json, "type");
	} else {
		json_type = json;
	}
	if (!json_is_string(json_type)) {
		avro_set_error("\"type\" field must be a string");
		return EINVAL;
	}
	type_str = json_string_value(json_type);
	if (!type_str) {
		avro_set_error("\"type\" field must be a string");
		return EINVAL;
	}
	/*
	 * TODO: gperf/re2c this 
	 */
	if (strcmp(type_str, "string") == 0) {
		*type = AVRO_STRING;
	} else if (strcmp(type_str, "bytes") == 0) {
		*type = AVRO_BYTES;
	} else if (strcmp(type_str, "int") == 0) {
		*type = AVRO_INT32;
	} else if (strcmp(type_str, "long") == 0) {
		*type = AVRO_INT64;
	} else if (strcmp(type_str, "float") == 0) {
		*type = AVRO_FLOAT;
	} else if (strcmp(type_str, "double") == 0) {
		*type = AVRO_DOUBLE;
	} else if (strcmp(type_str, "boolean") == 0) {
		*type = AVRO_BOOLEAN;
	} else if (strcmp(type_str, "null") == 0) {
		*type = AVRO_NULL;
	} else if (strcmp(type_str, "record") == 0) {
		*type = AVRO_RECORD;
	} else if (strcmp(type_str, "enum") == 0) {
		*type = AVRO_ENUM;
	} else if (strcmp(type_str, "array") == 0) {
		*type = AVRO_ARRAY;
	} else if (strcmp(type_str, "map") == 0) {
		*type = AVRO_MAP;
	} else if (strcmp(type_str, "fixed") == 0) {
		*type = AVRO_FIXED;
	} else if ((*named_type = find_named_schemas(type_str, named_schemas))) {
		*type = AVRO_LINK;
	} else {
		avro_set_error("Unknown Avro \"type\": %s", type_str);
		return EINVAL;
	}
	return 0;
}
Exemplo n.º 13
0
void pilot::JSONFileHandler::endArrayWrite() {
	Assertion(json_is_array(_currentEl), "Array ended while not in an array!");

	_elementStack.pop_back();
	_currentEl = _elementStack.back();
}
Exemplo n.º 14
0
/*====================================================================
 * 函数名    : vGenCONNSRVCONNMsg
 * 功能      : 终端与某服务器连上时上报消息
 * 算法实现  : 
 * 参数说明  : vpd 要上报的设备
 * 返回值说明: 成功 生成的消息
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/26       v1.0        YLI                          创建
 * ====================================================================*/
json_t * vGenCONNSRVCONNMsg(VPD vpd)
{
	json_t *root;
	json_t *conn_srv_state_info;
	json_t *jt;
	json_t *jp;
	char saCfgPath[L_PATH_MAX_LEN];
	int n,m;
	root = json_object();
	memset(saCfgPath,0x00,sizeof saCfgPath);
	//eventid
	if (json_object_set(root,"eventid",
		json_string("EV_CONNSRV_CONN_MSG")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	conn_srv_state_info = json_array();
	if(getenv("APP_PROFILE_PATH") == NULL)
	{
		json_decref(root);
		vLogErr("devtypes config file path error,please check evn value!!!");
		return NULL;
	}
	strcpy(saCfgPath,getenv("APP_PROFILE_PATH"));
	strcat(saCfgPath,"/devtypes.json");

	/*conn_srv_state_info*/
	jt = tPflGetJsonObj(saCfgPath,K_LOGICTYPE_KEY);
	if(jt == NULL)
	{
		json_decref(root);
		return NULL;
	}
	srand((unsigned)time(NULL));
	if (json_is_array(jt))
	{
		int it;
		m = json_array_size(jt);
		n = rand()%m;
		jp = json_pack("{s:s,s:s}",
			"type",json_string_value(json_array_get(jt,n)),
			"ip",_gstrpShm->rc.nSrvIP);

		if ((jp ==NULL) || (json_array_insert(conn_srv_state_info,0,
		jp)) == FAILUER)
		{
			json_decref(root);
			vLogErr("devtype set error!!!");
			return NULL;
		}	
		it = rand()%m;
		while(it == n) it = rand()%m;
		n = it;
		jp = json_pack("{s:s,s:s}",
			"type",json_string_value(json_array_get(jt,n)),
			"ip",_gstrpShm->rc.nSrvIP);
		if (json_array_insert(conn_srv_state_info,1,
		json_array_get(jt,n)) == FAILUER)
		{
			json_decref(root);
			vLogErr("devtype set error!!!");
			return NULL;
		}	
	}
	json_decref(jt);
	json_decref(jp);
	json_decref(conn_srv_state_info);
	json_object_set(root,"conn_srv_state_info",conn_srv_state_info);
	return root;
}
Exemplo n.º 15
0
// Parse pools array in json config
bool parse_pool_array(json_t *obj)
{
	size_t idx;
	json_t *p, *val;

	if (!json_is_array(obj))
		return false;

	// array of objects [ {}, {} ]
	json_array_foreach(obj, idx, p)
	{
		if (!json_is_object(p))
			continue;

		for (int i = 0; i < ARRAY_SIZE(cfg_array_keys); i++)
		{
			int opt = -1;
			char *s = NULL;
			if (cfg_array_keys[i].cat != CFG_POOL)
				continue;

			val = json_object_get(p, cfg_array_keys[i].name);
			if (!val)
				continue;

			for (int k = 0; k < options_count(); k++)
			{
				const char *alias = cfg_array_keys[i].longname;
				if (alias && !strcasecmp(options[k].name, alias)) {
					opt = k;
					break;
				}
				if (!alias && !strcasecmp(options[k].name, cfg_array_keys[i].name)) {
					opt = k;
					break;
				}
			}
			if (opt == -1)
				continue;

			if (json_is_string(val)) {
				s = strdup(json_string_value(val));
				if (!s)
					continue;

				// applog(LOG_DEBUG, "pool key %s '%s'", options[opt].name, s);
				parse_arg(options[opt].val, s);
				free(s);
			} else {
				// numeric or bool
				char buf[32] = { 0 };
				double d = 0.;
				if (json_is_true(val)) d = 1.;
				else if (json_is_integer(val))
					d = 1.0 * json_integer_value(val);
				else if (json_is_real(val))
					d = json_real_value(val);
				snprintf(buf, sizeof(buf)-1, "%f", d);
				// applog(LOG_DEBUG, "pool key %s '%f'", options[opt].name, d);
				parse_arg(options[opt].val, buf);
			}
		}
	}
	return true;
}
Exemplo n.º 16
0
// ["dirname", "foo"] -> ["dirname", "foo", ["depth", "ge", 0]]
static w_query_expr *dirname_parser_inner(w_query *query, json_t *term,
        bool caseless)
{
    const char *which = caseless ? "idirname" : "dirname";
    struct dirname_data *data;
    json_t *name;
    struct w_query_int_compare depth_comp;

    if (!json_is_array(term)) {
        ignore_result(asprintf(&query->errmsg, "Expected array for '%s' term",
                               which));
        return NULL;
    }

    if (json_array_size(term) < 2) {
        ignore_result(asprintf(&query->errmsg,
                               "Invalid number of arguments for '%s' term",
                               which));
        return NULL;
    }

    if (json_array_size(term) > 3) {
        ignore_result(asprintf(&query->errmsg,
                               "Invalid number of arguments for '%s' term",
                               which));
        return NULL;
    }

    name = json_array_get(term, 1);
    if (!json_is_string(name)) {
        ignore_result(asprintf(&query->errmsg,
                               "Argument 2 to '%s' must be a string", which));
        return NULL;
    }

    if (json_array_size(term) == 3) {
        json_t *depth;

        depth = json_array_get(term, 2);
        if (!json_is_array(depth)) {
            ignore_result(asprintf(&query->errmsg,
                                   "Invalid number of arguments for '%s' term",
                                   which));
            return NULL;
        }

        if (!parse_int_compare(depth, &depth_comp, &query->errmsg)) {
            return NULL;
        }

        if (strcmp("depth", json_string_value(json_array_get(depth, 0)))) {
            ignore_result(asprintf(&query->errmsg,
                                   "Third parameter to '%s' should be a relational depth term",
                                   which));
            return NULL;
        }
    } else {
        depth_comp.operand = 0;
        depth_comp.op = W_QUERY_ICMP_GE;
    }

    data = calloc(1, sizeof(*data));
    if (!data) {
        ignore_result(asprintf(&query->errmsg, "out of memory"));
        return NULL;
    }
    data->dirname = w_string_new(json_string_value(name));
    data->startswith =
        caseless ?  w_string_startswith_caseless : w_string_startswith;
    data->depth = depth_comp;

    return w_query_expr_new(eval_dirname, dispose_dirname, data);
}
Exemplo n.º 17
0
/*
 * validate the "aud" and "azp" claims in the id_token payload
 */
static apr_byte_t oidc_proto_validate_aud_and_azp(request_rec *r, oidc_cfg *cfg,
		oidc_provider_t *provider, apr_jwt_payload_t *id_token_payload) {

	char *azp = NULL;
	apr_jwt_get_string(r->pool, &id_token_payload->value, "azp", &azp);

	/*
	 * the "azp" claim is only needed when the id_token has a single audience value and that audience
	 * is different than the authorized party; it MAY be included even when the authorized party is
	 * the same as the sole audience.
	 */
	if ((azp != NULL) && (apr_strnatcmp(azp, provider->client_id) != 0)) {
		oidc_error(r,
				"the \"azp\" claim (%s) is present in the id_token, but is not equal to the configured client_id (%s)",
				azp, provider->client_id);
		return FALSE;
	}

	/* get the "aud" value from the JSON payload */
	json_t *aud = json_object_get(id_token_payload->value.json, "aud");
	if (aud != NULL) {

		/* check if it is a single-value */
		if (json_is_string(aud)) {

			/* a single-valued audience must be equal to our client_id */
			if (apr_strnatcmp(json_string_value(aud), provider->client_id)
					!= 0) {
				oidc_error(r,
						"the configured client_id (%s) did not match the \"aud\" claim value (%s) in the id_token",
						provider->client_id, json_string_value(aud));
				return FALSE;
			}

			/* check if this is a multi-valued audience */
		} else if (json_is_array(aud)) {

			if ((json_array_size(aud) > 1) && (azp == NULL)) {
				oidc_debug(r,
						"the \"aud\" claim value in the id_token is an array with more than 1 element, but \"azp\" claim is not present (a SHOULD in the spec...)");
			}

			if (oidc_util_json_array_has_value(r, aud,
					provider->client_id) == FALSE) {
				oidc_error(r,
						"our configured client_id (%s) could not be found in the array of values for \"aud\" claim",
						provider->client_id);
				return FALSE;
			}
		} else {
			oidc_error(r,
					"id_token JSON payload \"aud\" claim is not a string nor an array");
			return FALSE;
		}

	} else {
		oidc_error(r, "id_token JSON payload did not contain an \"aud\" claim");
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 18
0
void read_ff_json(const char *json_file, struct atomgrp *ag)
{
	json_error_t json_file_error;
	json_t *base = json_load_file(json_file, 0, &json_file_error);

	if (!base) {
		fprintf(stderr,
			"error reading json file %s on line %d column %d: %s\n",
			json_file, json_file_error.line, json_file_error.column,
			json_file_error.text);
	}

	if (!json_is_object(base)) {
		fprintf(stderr, "json file not an object %s\n", json_file);
	}

	json_t *atoms, *bonds, *angles, *torsions, *impropers;
	atoms = json_object_get(base, "atoms");
	if (!json_is_array(atoms)) {
		fprintf(stderr, "json atoms are not an array %s\n", json_file);
	}
	size_t natoms = json_array_size(atoms);
	if (natoms != (size_t) ag->natoms) {
		fprintf(stderr,
			"json file has a different number of atoms %zd vs. %d : %s\n",
			natoms, ag->natoms, json_file);
	}

	ag->num_atom_types = 0;
	for (size_t i = 0; i < natoms; i++) {
		json_t *atom = json_array_get(atoms, i);
		if (!json_is_object(atom)) {
			fprintf(stderr,
				"Atom %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *ace_volume, *ftype_index, *ftype_name, *eps03;
		json_t *name, *radius03, *eps;
		json_t *charge, *radius, *element;

		ace_volume = json_object_get(atom, "ace_volume");
		if (!json_is_real(ace_volume)) {
			fprintf(stderr,
				"json ace volume is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].acevolume = json_real_value(ace_volume);

		ftype_index = json_object_get(atom, "ftype_index");
		if (!json_is_integer(ftype_index)) {
			fprintf(stderr,
				"json ftype index is not integer for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].atom_ftypen = json_integer_value(ftype_index);
		if (ag->atoms[i].atom_ftypen > ag->num_atom_types) {
			ag->num_atom_types = ag->atoms[i].atom_ftypen;
		}

		ftype_name = json_object_get(atom, "ftype_name");
		if (!json_is_string(ftype_name)) {
			fprintf(stderr,
				"json ftype name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].ftype_name = strdup(json_string_value(ftype_name));

		element = json_object_get(atom, "element");
		if (!json_is_string(element)) {
			fprintf(stderr,
				"json element name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].element = strdup(json_string_value(element));

		eps = json_object_get(atom, "eps");
		if (!json_is_real(eps)) {
			fprintf(stderr,
				"json eps is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].eps = sqrt(-json_real_value(eps));

		eps03 = json_object_get(atom, "eps03");
		if (!json_is_real(eps03)) {
			fprintf(stderr,
				"json eps03 is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].eps03 = sqrt(-json_real_value(eps03));

		radius = json_object_get(atom, "radius");
		if (!json_is_real(radius)) {
			fprintf(stderr,
				"json radius is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].rminh = json_real_value(radius);

		radius03 = json_object_get(atom, "radius03");
		if (!json_is_real(radius03)) {
			fprintf(stderr,
				"json radius03 is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].rminh03 = json_real_value(radius03);

		charge = json_object_get(atom, "charge");
		if (!json_is_real(radius03)) {
			fprintf(stderr,
				"json charge is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].chrg = json_real_value(charge);

		name = json_object_get(atom, "name");
		if (!json_is_string(name)) {
			fprintf(stderr,
				"json name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].name = strdup(json_string_value(name));

		ag->atoms[i].nbonds = 0;
		ag->atoms[i].nangs = 0;
		ag->atoms[i].ntors = 0;
		ag->atoms[i].nimps = 0;
		ag->atoms[i].fixed = 0;
	}

	bonds = json_object_get(base, "bonds");
	if (!json_is_array(bonds)) {
		fprintf(stderr, "json bonds are not an array %s\n", json_file);
	}
	size_t nbonds = json_array_size(bonds);
	ag->nbonds = nbonds;
	ag->bonds = _mol_calloc(nbonds, sizeof(struct atombond));
	for (size_t i = 0; i < nbonds; i++) {
		json_t *bond = json_array_get(bonds, i);
		if (!json_is_object(bond)) {
			fprintf(stderr,
				"Bond %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *length, *atom1, *atom2, *spring_constant, *sdf_type;

		atom1 = json_object_get(bond, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for bond %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->bonds[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nbonds)++;

		atom2 = json_object_get(bond, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for bond %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->bonds[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nbonds)++;

		length = json_object_get(bond, "length");
		if (!json_is_real(length)) {
			fprintf(stderr,
				"json length is not floating point for bond %zd in json_file %s\n",
				i, json_file);
		}
		ag->bonds[i].l0 = json_real_value(length);

		spring_constant = json_object_get(bond, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for bond %zd in json_file %s\n",
				i, json_file);
		}
		ag->bonds[i].k = json_real_value(spring_constant);

		sdf_type = json_object_get(bond, "sdf_type");
		if (!json_is_integer(sdf_type)) {
			fprintf(stderr,
				"json sdf_type is not integer for bond %zd in json_file %s\n",
				i, json_file);
		}
		ag->bonds[i].sdf_type = json_integer_value(sdf_type);
	}

	angles = json_object_get(base, "angles");
	if (!json_is_array(angles)) {
		fprintf(stderr, "json angles are not an array %s\n", json_file);
	}
	size_t nangles = json_array_size(angles);
	ag->nangs = nangles;
	ag->angs = _mol_calloc(nangles, sizeof(struct atomangle));
	for (size_t i = 0; i < nangles; i++) {
		json_t *angle = json_array_get(angles, i);
		if (!json_is_object(angle)) {
			fprintf(stderr,
				"Angle %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *theta, *atom1, *atom2, *atom3, *spring_constant;

		atom1 = json_object_get(angle, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->angs[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nangs)++;

		atom2 = json_object_get(angle, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->angs[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nangs)++;

		atom3 = json_object_get(angle, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->angs[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].nangs)++;

		theta = json_object_get(angle, "theta");
		if (!json_is_real(theta)) {
			fprintf(stderr,
				"json theta is not floating point for angle %zd in json_file %s\n",
				i, json_file);
		}
		ag->angs[i].th0 = json_real_value(theta);

		spring_constant = json_object_get(angle, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for angle %zd in json_file %s\n",
				i, json_file);
		}
		ag->angs[i].k = json_real_value(spring_constant);
	}

	torsions = json_object_get(base, "torsions");
	if (!json_is_array(torsions)) {
		fprintf(stderr, "json torsions are not an array %s\n",
			json_file);
	}
	size_t ntorsions = json_array_size(torsions);
	ag->ntors = ntorsions;
	ag->tors = _mol_calloc(ntorsions, sizeof(struct atomtorsion));
	for (size_t i = 0; i < ntorsions; i++) {
		json_t *torsion = json_array_get(torsions, i);
		if (!json_is_object(torsion)) {
			fprintf(stderr,
				"Torsion %zd not an object in json file %s\n",
				i, json_file);
		}
		json_t *atom1, *atom2, *atom3, *atom4, *minima, *delta_constant,
		    *spring_constant;

		atom1 = json_object_get(torsion, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->tors[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].ntors)++;

		atom2 = json_object_get(torsion, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->tors[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].ntors)++;

		atom3 = json_object_get(torsion, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->tors[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].ntors)++;

		atom4 = json_object_get(torsion, "atom4");
		if (!json_is_integer(atom4)) {
			fprintf(stderr,
				"json atom4 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i4 = json_integer_value(atom4) - 1;
		ag->tors[i].a3 = &(ag->atoms[i4]);
		(ag->atoms[i4].ntors)++;

		minima = json_object_get(torsion, "minima");
		if (!json_is_integer(minima)) {
			fprintf(stderr,
				"json minima is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].n = json_integer_value(minima);

		delta_constant = json_object_get(torsion, "delta_constant");
		if (!json_is_real(delta_constant)) {
			fprintf(stderr,
				"json delta_constant is not floating point for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].d = json_real_value(delta_constant);

		spring_constant = json_object_get(torsion, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].k = json_real_value(spring_constant);
	}

	impropers = json_object_get(base, "impropers");
	if (!json_is_array(impropers)) {
		fprintf(stderr, "json impropers are not an array %s\n",
			json_file);
	}
	size_t nimpropers = json_array_size(impropers);
	ag->nimps = nimpropers;
	ag->imps = _mol_calloc(nimpropers, sizeof(struct atomimproper));
	for (size_t i = 0; i < nimpropers; i++) {
		json_t *improper = json_array_get(impropers, i);
		if (!json_is_object(improper)) {
			fprintf(stderr,
				"Improper %zd not an object in json file %s\n",
				i, json_file);
		}
		json_t *atom1, *atom2, *atom3, *atom4, *phi, *spring_constant;

		atom1 = json_object_get(improper, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->imps[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nimps)++;

		atom2 = json_object_get(improper, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->imps[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nimps)++;

		atom3 = json_object_get(improper, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->imps[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].nimps)++;

		atom4 = json_object_get(improper, "atom4");
		if (!json_is_integer(atom4)) {
			fprintf(stderr,
				"json atom4 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i4 = json_integer_value(atom4) - 1;
		ag->imps[i].a3 = &(ag->atoms[i4]);
		(ag->atoms[i4].nimps)++;

		phi = json_object_get(improper, "phi");
		if (!json_is_real(phi)) {
			fprintf(stderr,
				"json phi is not floating point for improper %zd in json_file %s\n",
				i, json_file);
		}
		ag->imps[i].psi0 = json_real_value(phi);

		spring_constant = json_object_get(improper, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for improper %zd in json_file %s\n",
				i, json_file);
		}
		ag->imps[i].k = json_real_value(spring_constant);
	}

	json_decref(base);

//allocate atom arrays of pointers to parameters
	for (size_t i = 0; i < natoms; i++) {
		int i1 = ag->atoms[i].nbonds;
		ag->atoms[i].bonds = _mol_calloc(i1, sizeof(struct atombond *));
		ag->atoms[i].nbonds = 0;
		i1 = ag->atoms[i].nangs;
		ag->atoms[i].angs = _mol_calloc(i1, sizeof(struct atomangle *));
		ag->atoms[i].nangs = 0;
		i1 = ag->atoms[i].ntors;
		ag->atoms[i].tors =
		    _mol_calloc(i1, sizeof(struct atomtorsion *));
		ag->atoms[i].ntors = 0;
		i1 = ag->atoms[i].nimps;
		ag->atoms[i].imps =
		    _mol_calloc(i1, sizeof(struct atomimproper *));
		ag->atoms[i].nimps = 0;
	}
	struct atom *atm;
//fill bonds
	for (int i = 0; i < ag->nbonds; i++) {
		atm = ag->bonds[i].a0;
		atm->bonds[(atm->nbonds)++] = &(ag->bonds[i]);
		atm = ag->bonds[i].a1;
		atm->bonds[(atm->nbonds)++] = &(ag->bonds[i]);
	}
//fill angles
	for (int i = 0; i < ag->nangs; i++) {
		atm = ag->angs[i].a0;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
		atm = ag->angs[i].a1;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
		atm = ag->angs[i].a2;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
	}
//fill torsions
	for (int i = 0; i < ag->ntors; i++) {
		atm = ag->tors[i].a0;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a1;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a2;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a3;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
	}
//fill impropers
	for (int i = 0; i < ag->nimps; i++) {
		atm = ag->imps[i].a0;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a1;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a2;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a3;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
	}
//atom indices in the group
	fill_ingrp(ag);

	ag->is_psf_read = true;

	// copy vals from deprecated to new data structures
	int atomsi;
	for (atomsi = 0; atomsi < ag->natoms; atomsi++) {
		_mol_atom_create_bond_indices(&ag->atoms[atomsi],
					      ag->atoms[atomsi].nbonds);
	}
	_mol_atom_group_copy_from_deprecated(ag);
}
Exemplo n.º 19
0
static void task_populate_titledb_thread(void* arg) {
    populate_titledb_data* data = (populate_titledb_data*) arg;

    Result res = 0;

    linked_list titles;
    linked_list_init(&titles);

    json_t* root = NULL;
    if(R_SUCCEEDED(res = http_download_json("https://api.titledb.com/v1/entry?nested=true"
                                                    "&only=id&only=name&only=author&only=headline&only=category"
                                                    "&only=cia.id&only=cia.mtime&only=cia.version&only=cia.size&only=cia.titleid"
                                                    "&only=tdsx.id&only=tdsx.mtime&only=tdsx.version&only=tdsx.size&only=tdsx.smdh.id",
                                            &root, 1024 * 1024))) {
        if(json_is_array(root)) {
            for(u32 i = 0; i < json_array_size(root) && R_SUCCEEDED(res); i++) {
                svcWaitSynchronization(task_get_pause_event(), U64_MAX);
                if(task_is_quit_all() || svcWaitSynchronization(data->cancelEvent, 0) == 0) {
                    break;
                }

                json_t* entry = json_array_get(root, i);
                if(json_is_object(entry)) {
                    list_item* item = (list_item*) calloc(1, sizeof(list_item));
                    if(item != NULL) {
                        titledb_info* titledbInfo = (titledb_info*) calloc(1, sizeof(titledb_info));
                        if(titledbInfo != NULL) {
                            titledbInfo->id = (u32) json_object_get_integer(entry, "id", 0);
                            string_copy(titledbInfo->category, json_object_get_string(entry, "category", "Unknown"), sizeof(titledbInfo->category));
                            string_copy(titledbInfo->meta.shortDescription, json_object_get_string(entry, "name", ""), sizeof(titledbInfo->meta.shortDescription));
                            string_copy(titledbInfo->meta.publisher, json_object_get_string(entry, "author", ""), sizeof(titledbInfo->meta.publisher));

                            json_t* headline = json_object_get(entry, "headline");
                            if(json_is_string(headline)) {
                                const char* val = json_string_value(headline);

                                if(json_string_length(headline) > sizeof(titledbInfo->headline) - 1) {
                                    snprintf(titledbInfo->headline, sizeof(titledbInfo->headline), "%.508s...", val);
                                } else {
                                    string_copy(titledbInfo->headline, val, sizeof(titledbInfo->headline));
                                }
                            } else {
                                titledbInfo->headline[0] = '\0';
                            }

                            json_t* cias = json_object_get(entry, "cia");
                            if(json_is_array(cias)) {
                                for(u32 j = 0; j < json_array_size(cias); j++) {
                                    json_t* cia = json_array_get(cias, j);
                                    if(json_is_object(cia)) {
                                        const char* mtime = json_object_get_string(cia, "mtime", "Unknown");
                                        if(!titledbInfo->cia.exists || task_populate_titledb_compare_dates(mtime, titledbInfo->cia.mtime, sizeof(titledbInfo->cia.mtime)) >= 0) {
                                            titledbInfo->cia.exists = true;

                                            titledbInfo->cia.id = (u32) json_object_get_integer(cia, "id", 0);
                                            string_copy(titledbInfo->cia.mtime, mtime, sizeof(titledbInfo->cia.mtime));
                                            string_copy(titledbInfo->cia.version, json_object_get_string(cia, "version", "Unknown"), sizeof(titledbInfo->cia.version));
                                            titledbInfo->cia.size = (u32) json_object_get_integer(cia, "size", 0);
                                            titledbInfo->cia.titleId = strtoull(json_object_get_string(cia, "titleid", "0"), NULL, 16);
                                        }
                                    }
                                }
                            }

                            json_t* tdsxs = json_object_get(entry, "tdsx");
                            if(json_is_array(tdsxs)) {
                                for(u32 j = 0; j < json_array_size(tdsxs); j++) {
                                    json_t* tdsx = json_array_get(tdsxs, j);
                                    if(json_is_object(tdsx)) {
                                        const char* mtime = json_object_get_string(tdsx, "mtime", "Unknown");
                                        if(!titledbInfo->tdsx.exists || task_populate_titledb_compare_dates(mtime, titledbInfo->tdsx.mtime, sizeof(titledbInfo->tdsx.mtime)) >= 0) {
                                            titledbInfo->tdsx.exists = true;

                                            titledbInfo->tdsx.id = (u32) json_object_get_integer(tdsx, "id", 0);
                                            string_copy(titledbInfo->tdsx.mtime, mtime, sizeof(titledbInfo->tdsx.mtime));
                                            string_copy(titledbInfo->tdsx.version, json_object_get_string(tdsx, "version", "Unknown"), sizeof(titledbInfo->tdsx.version));
                                            titledbInfo->tdsx.size = (u32) json_object_get_integer(tdsx, "size", 0);

                                            json_t* smdh = json_object_get(tdsx, "smdh");
                                            if(json_is_object(smdh)) {
                                                titledbInfo->tdsx.smdh.exists = true;

                                                titledbInfo->tdsx.smdh.id = (u32) json_object_get_integer(smdh, "id", 0);
                                            }
                                        }
                                    }
                                }
                            }

                            char* latestTime = "Unknown";
                            if(titledbInfo->cia.exists && titledbInfo->tdsx.exists) {
                                if(task_populate_titledb_compare_dates(titledbInfo->cia.mtime, titledbInfo->tdsx.mtime, sizeof(titledbInfo->cia.mtime)) >= 0) {
                                    latestTime = titledbInfo->cia.mtime;
                                } else {
                                    latestTime = titledbInfo->tdsx.mtime;
                                }
                            } else if(titledbInfo->cia.exists) {
                                latestTime = titledbInfo->cia.mtime;
                            } else if(titledbInfo->tdsx.exists) {
                                latestTime = titledbInfo->tdsx.mtime;
                            }

                            string_copy(titledbInfo->mtime, latestTime, sizeof(titledbInfo->mtime));

                            if((titledbInfo->cia.exists || titledbInfo->tdsx.exists) && (data->filter == NULL || data->filter(data->userData, titledbInfo))) {
                                string_copy(item->name, titledbInfo->meta.shortDescription, LIST_ITEM_NAME_MAX);
                                item->data = titledbInfo;

                                task_populate_titledb_update_status(item);

                                linked_list_add_sorted(&titles, item, data->userData, data->compare);
                            } else {
                                free(titledbInfo);
                                free(item);
                            }
                        } else {
                            free(item);

                            res = R_APP_OUT_OF_MEMORY;
                        }
                    } else {
                        res = R_APP_OUT_OF_MEMORY;
                    }
                }
            }

            linked_list_iter iter;
            linked_list_iterate(&titles, &iter);

            while(linked_list_iter_has_next(&iter)) {
                list_item* item = linked_list_iter_next(&iter);

                if(R_SUCCEEDED(res)) {
                    linked_list_add(data->items, item);
                } else {
                    task_free_titledb(item);
                    linked_list_iter_remove(&iter);
                }
            }
        } else {
            res = R_APP_BAD_DATA;
        }

        json_decref(root);
    }

    data->itemsListed = true;

    if(R_SUCCEEDED(res)) {
        linked_list_iter iter;
        linked_list_iterate(&titles, &iter);

        while(linked_list_iter_has_next(&iter)) {
            svcWaitSynchronization(task_get_pause_event(), U64_MAX);

            Handle events[2] = {data->resumeEvent, data->cancelEvent};
            s32 index = 0;
            svcWaitSynchronizationN(&index, events, 2, false, U64_MAX);

            if(task_is_quit_all() || svcWaitSynchronization(data->cancelEvent, 0) == 0) {
                break;
            }

            list_item* item = (list_item*) linked_list_iter_next(&iter);
            titledb_info* titledbInfo = (titledb_info*) item->data;

            char url[128];
            if(titledbInfo->cia.exists) {
                snprintf(url, sizeof(url), "https://3ds.titledb.com/v1/cia/%lu/icon_l.bin", titledbInfo->cia.id);
            } else if(titledbInfo->tdsx.exists && titledbInfo->tdsx.smdh.exists) {
                snprintf(url, sizeof(url), "https://3ds.titledb.com/v1/smdh/%lu/icon_l.bin", titledbInfo->tdsx.smdh.id);
            } else {
                continue;
            }

            u8 icon[0x1200];
            u32 iconSize = 0;
            if(R_SUCCEEDED(http_download(url, &iconSize, &icon, sizeof(icon))) && iconSize == sizeof(icon)) {
                titledbInfo->meta.texture = screen_allocate_free_texture();
                screen_load_texture_tiled(titledbInfo->meta.texture, icon, sizeof(icon), 48, 48, GPU_RGB565, false);
            }
        }
    }

    linked_list_destroy(&titles);

    svcCloseHandle(data->resumeEvent);
    svcCloseHandle(data->cancelEvent);

    data->result = res;
    data->finished = true;
}
Exemplo n.º 20
0
struct atomgrp *read_json_ag(const char *json_file)
{
	struct atomgrp *ag =
	    (struct atomgrp *)_mol_calloc(1, sizeof(struct atomgrp));
	json_error_t json_file_error;
	json_t *base = json_load_file(json_file, 0, &json_file_error);

	if (!base) {
		fprintf(stderr,
			"error reading json file %s on line %d column %d: %s\n",
			json_file, json_file_error.line, json_file_error.column,
			json_file_error.text);
	}

	if (!json_is_object(base)) {
		fprintf(stderr, "json file not an object %s\n", json_file);
	}

	json_t *atoms, *bonds, *angles, *torsions, *impropers;
	atoms = json_object_get(base, "atoms");
	if (!json_is_array(atoms)) {
		fprintf(stderr, "json atoms are not an array %s\n", json_file);
	}
	size_t natoms = json_array_size(atoms);
	ag->natoms = natoms;
	ag->atoms = (struct atom *)_mol_calloc(ag->natoms, sizeof(struct atom));

	ag->num_atom_types = 0;

	char *prev_segment = _mol_calloc(1, sizeof(char));
	char *prev_residue = _mol_calloc(1, sizeof(char));
	int prev_residue_seq = -107;
	ag->nres = 0;
	int alloc_res = 250;
	ag->iares = _mol_malloc(alloc_res*sizeof(int));
	for (size_t i = 0; i < natoms; i++) {
		json_t *atom = json_array_get(atoms, i);
		if (!json_is_object(atom)) {
			fprintf(stderr,
				"Atom %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *ace_volume, *ftype_index, *ftype_name, *eps03;
		json_t *name, *radius03, *eps, *acp_type, *residue_name;
		json_t *charge, *radius, *element;
		json_t *x, *y, *z;
		json_t *yeti_type, *sybyl_type;
		json_t *backbone, *hb_acceptor, *hb_donor, *hb_weight;
		json_t *segment, *residue;


		segment = json_object_get(atom, "segment");
		residue = json_object_get(atom, "residue");
		if ((segment != NULL) && (residue != NULL)) {
			if (!json_is_string(segment)) {
				fprintf(stderr,
					"json segment is not string for atom %zd in json_file %s\n",
					i, json_file);
			}
			if (!json_is_string(residue)) {
				fprintf(stderr,
					"json residue is not string for atom %zd in json_file %s\n",
					i, json_file);
			}

			const char *cur_segment = json_string_value(segment);
			const char *cur_residue = json_string_value(residue);

			if (strcmp(cur_segment, prev_segment) != 0) {
				prev_residue_seq += 100;
				free(prev_segment);
				prev_segment = strdup(cur_segment);
			}
			if (strcmp(cur_residue, prev_residue) != 0) {
				int cur_residue_int = atoi(cur_residue);
				int prev_residue_int = atoi(prev_residue);
				if ((cur_residue_int - prev_residue_int) > 1) {
					prev_residue_seq +=
					    (cur_residue_int -
					     prev_residue_int);
				} else {
					prev_residue_seq += 1;
				}
				free(prev_residue);
				prev_residue = strdup(cur_residue);

				if (ag->nres +1 == alloc_res) {
					alloc_res *= 2;
					ag->iares = _mol_realloc(ag->iares, alloc_res * i);
				}
				ag->iares[ag->nres] = i;
				ag->nres++;
			}


			ag->atoms[i].comb_res_seq = prev_residue_seq;
		} else {
			ag->atoms[i].comb_res_seq = prev_residue_seq;
		}

		ace_volume = json_object_get(atom, "ace_volume");
		if (!json_is_real(ace_volume)) {
			fprintf(stderr,
				"json ace volume is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].acevolume = json_real_value(ace_volume);

		ftype_index = json_object_get(atom, "ftype_index");
		if (!json_is_integer(ftype_index)) {
			fprintf(stderr,
				"json ftype index is not integer for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].atom_ftypen = json_integer_value(ftype_index);
		if (ag->atoms[i].atom_ftypen > ag->num_atom_types) {
			ag->num_atom_types = ag->atoms[i].atom_ftypen;
		}

		ftype_name = json_object_get(atom, "ftype_name");
		if (!json_is_string(ftype_name)) {
			fprintf(stderr,
				"json ftype name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].ftype_name = strdup(json_string_value(ftype_name));

		element = json_object_get(atom, "element");
		if (!json_is_string(element)) {
			fprintf(stderr,
				"json element name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].element = strdup(json_string_value(element));

		eps = json_object_get(atom, "eps");
		if (!json_is_real(eps)) {
			fprintf(stderr,
				"json eps is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].eps = sqrt(-json_real_value(eps));

		eps03 = json_object_get(atom, "eps03");
		if (!json_is_real(eps03)) {
			fprintf(stderr,
				"json eps03 is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].eps03 = sqrt(-json_real_value(eps03));

		radius = json_object_get(atom, "radius");
		if (!json_is_real(radius)) {
			fprintf(stderr,
				"json radius is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].rminh = json_real_value(radius);

		radius03 = json_object_get(atom, "radius03");
		if (!json_is_real(radius03)) {
			fprintf(stderr,
				"json radius03 is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].rminh03 = json_real_value(radius03);

		charge = json_object_get(atom, "charge");
		if (!json_is_real(radius03)) {
			fprintf(stderr,
				"json charge is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].chrg = json_real_value(charge);

		name = json_object_get(atom, "name");
		if (!json_is_string(name)) {
			fprintf(stderr,
				"json name is not string for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].name = strdup(json_string_value(name));

		residue_name = json_object_get(atom, "residue_name");
		if (residue_name != NULL) {
			if (!json_is_string(residue_name)) {
				fprintf(stderr,
					"json residue_name is not string for atom %zd in json_file %s\n",
					i, json_file);
			}
			ag->atoms[i].residue_name =
			    strdup(json_string_value(residue_name));
		} else {
			ag->atoms[i].residue_name = NULL;
		}

		x = json_object_get(atom, "x");
		if (!json_is_real(x)) {
			fprintf(stderr,
				"json coordinate x is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].X = json_real_value(x);

		y = json_object_get(atom, "y");
		if (!json_is_real(y)) {
			fprintf(stderr,
				"json coordinate y is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].Y = json_real_value(y);

		z = json_object_get(atom, "z");
		if (!json_is_real(z)) {
			fprintf(stderr,
				"json coordinate z is not floating point for atom %zd in json_file %s\n",
				i, json_file);
		}
		ag->atoms[i].Z = json_real_value(z);

		acp_type = json_object_get(atom, "acp_type");
		if (acp_type != NULL) {
			if (!json_is_integer(acp_type)) {
				fprintf(stderr,
					"json acp_type index is not integer for atom %zd in json_file %s\n",
					i, json_file);
			}
			ag->atoms[i].acp_type = json_integer_value(acp_type);
		} else {
			ag->atoms[i].acp_type = -1;
		}

		yeti_type = json_object_get(atom, "yeti_type");
		if (yeti_type != NULL) {
			const char *yeti_type_string;
			if (!json_is_string(yeti_type)) {
				fprintf(stderr,
					"json yeti_type is not string for atom %zd in json_file %s\n",
					i, json_file);
			}
			yeti_type_string = json_string_value(yeti_type);
			if (strcmp("carbonyl", yeti_type_string) == 0) {
				ag->atoms[i].yeti_type = MOL_YETI_CARBONYL;
			} else if (strcmp("hydroxyl", yeti_type_string) == 0) {
				ag->atoms[i].yeti_type = MOL_YETI_HYDROXYL;
			} else if (strcmp("sulfonamide", yeti_type_string) == 0) {
				ag->atoms[i].yeti_type = MOL_YETI_SULFONAMIDE;
			} else if (strcmp("N5_aromatic", yeti_type_string) == 0) {
				ag->atoms[i].yeti_type = MOL_YETI_N5_AROMATIC;
			} else if (strcmp("N6_aromatic", yeti_type_string) == 0) {
				ag->atoms[i].yeti_type = MOL_YETI_N6_AROMATIC;
			} else {
				fprintf(stderr,
					"unknown json yeti_type %s for atom %zd in json_file %s\n",
					yeti_type_string, i, json_file);
				ag->atoms[i].yeti_type = MOL_YETI_NONE;
			}
		} else {
			ag->atoms[i].yeti_type = MOL_YETI_NONE;
		}

		sybyl_type = json_object_get(atom, "sybyl_type");
		if (sybyl_type != NULL) {
			const char *sybyl_type_string;
			if (!json_is_string(sybyl_type)) {
				fprintf(stderr,
					"json sybyl_type is not string for atom %zd in json_file %s\n",
					i, json_file);
			}
			sybyl_type_string = json_string_value(sybyl_type);
			ag->atoms[i].hybridization =
			    mol_hydridization_from_sybyl(sybyl_type_string);
		} else {
			ag->atoms[i].hybridization = UNKNOWN_HYBRID;
		}

		backbone = json_object_get(atom, "backbone");
		if (backbone != NULL) {
			if (!json_is_boolean(backbone)) {
				fprintf(stderr,
					"json backbone is not boolean for atom %zd in json_file %s\n",
					i, json_file);
			}
			ag->atoms[i].backbone = json_is_true(backbone);
		} else {
			ag->atoms[i].backbone = false;
		}

		ag->atoms[i].hprop = 0;
		hb_acceptor = json_object_get(atom, "hb_acceptor");
		if (hb_acceptor != NULL) {
			if (!json_is_boolean(hb_acceptor)) {
				fprintf(stderr,
					"json hb_acceptor is not boolean for atom %zd in json_file %s\n",
					i, json_file);
			}
			if (json_is_true(hb_acceptor)) {
				ag->atoms[i].hprop |= HBOND_ACCEPTOR;
			}
		}
		hb_donor = json_object_get(atom, "hb_donor");
		if (hb_donor != NULL) {
			if (!json_is_boolean(hb_donor)) {
				fprintf(stderr,
					"json hb_donor is not boolean for atom %zd in json_file %s\n",
					i, json_file);
			}
			if (json_is_true(hb_donor)) {
				ag->atoms[i].hprop |= DONATABLE_HYDROGEN;
			}
		}
		ag->atoms[i].hbond_weight = 1.0;
		hb_weight = json_object_get(atom, "hb_weight");
		if (hb_weight != NULL) {
			if (!json_is_real(hb_weight)) {
				fprintf(stderr,
					"json hb_weight is not floating point for atom %zd in json_file %s\n",
					i, json_file);
			}
			ag->atoms[i].hbond_weight = json_real_value(hb_weight);
		}

		ag->atoms[i].nbonds = 0;
		ag->atoms[i].nangs = 0;
		ag->atoms[i].ntors = 0;
		ag->atoms[i].nimps = 0;
		ag->atoms[i].fixed = 0;
		ag->atoms[i].sa = -1;
		ag->atoms[i].base = -1;
		ag->atoms[i].base2 = -1;
	}
	ag->iares[ag->nres] = ag->natoms;
	ag->iares = _mol_realloc(ag->iares, (ag->nres+1) * sizeof(int));
	free(prev_segment);
	free(prev_residue);

	bonds = json_object_get(base, "bonds");
	if (!json_is_array(bonds)) {
		fprintf(stderr, "json bonds are not an array %s\n", json_file);
	}
	size_t nbonds = json_array_size(bonds);
	ag->nbonds = nbonds;
	ag->bonds = _mol_calloc(nbonds, sizeof(struct atombond));
	for (size_t i = 0; i < nbonds; i++) {
		json_t *bond = json_array_get(bonds, i);
		if (!json_is_object(bond)) {
			fprintf(stderr,
				"Bond %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *length, *atom1, *atom2, *spring_constant, *sdf_type;

		atom1 = json_object_get(bond, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for bond %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->bonds[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nbonds)++;

		atom2 = json_object_get(bond, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for bond %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->bonds[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nbonds)++;

		length = json_object_get(bond, "length");
		if (!json_is_real(length)) {
			fprintf(stderr,
				"json length is not floating point for bond %zd in json_file %s\n",
				i, json_file);
		}
		ag->bonds[i].l0 = json_real_value(length);

		spring_constant = json_object_get(bond, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for bond %zd in json_file %s\n",
				i, json_file);
		}
		ag->bonds[i].k = json_real_value(spring_constant);

		sdf_type = json_object_get(bond, "sdf_type");
		if (sdf_type != NULL) {
			if (!json_is_integer(sdf_type)) {
				fprintf(stderr,
					"json sdf_type is not integer for bond %zd in json_file %s\n",
					i, json_file);
			}
			ag->bonds[i].sdf_type = json_integer_value(sdf_type);
		} else {
			ag->bonds[i].sdf_type = 0;
		}
	}

	angles = json_object_get(base, "angles");
	if (!json_is_array(angles)) {
		fprintf(stderr, "json angles are not an array %s\n", json_file);
	}
	size_t nangles = json_array_size(angles);
	ag->nangs = nangles;
	ag->angs = _mol_calloc(nangles, sizeof(struct atomangle));
	for (size_t i = 0; i < nangles; i++) {
		json_t *angle = json_array_get(angles, i);
		if (!json_is_object(angle)) {
			fprintf(stderr,
				"Angle %zd not an object in json file %s\n", i,
				json_file);
		}
		json_t *theta, *atom1, *atom2, *atom3, *spring_constant;

		atom1 = json_object_get(angle, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->angs[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nangs)++;

		atom2 = json_object_get(angle, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->angs[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nangs)++;

		atom3 = json_object_get(angle, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for angle %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->angs[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].nangs)++;

		theta = json_object_get(angle, "theta");
		if (!json_is_real(theta)) {
			fprintf(stderr,
				"json theta is not floating point for angle %zd in json_file %s\n",
				i, json_file);
		}
		ag->angs[i].th0 = json_real_value(theta);

		spring_constant = json_object_get(angle, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for angle %zd in json_file %s\n",
				i, json_file);
		}
		ag->angs[i].k = json_real_value(spring_constant);
	}

	torsions = json_object_get(base, "torsions");
	if (!json_is_array(torsions)) {
		fprintf(stderr, "json torsions are not an array %s\n",
			json_file);
	}
	size_t ntorsions = json_array_size(torsions);
	ag->ntors = ntorsions;
	ag->tors = _mol_calloc(ntorsions, sizeof(struct atomtorsion));
	for (size_t i = 0; i < ntorsions; i++) {
		json_t *torsion = json_array_get(torsions, i);
		if (!json_is_object(torsion)) {
			fprintf(stderr,
				"Torsion %zd not an object in json file %s\n",
				i, json_file);
		}
		json_t *atom1, *atom2, *atom3, *atom4, *minima, *delta_constant,
		    *spring_constant;

		atom1 = json_object_get(torsion, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->tors[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].ntors)++;

		atom2 = json_object_get(torsion, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->tors[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].ntors)++;

		atom3 = json_object_get(torsion, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->tors[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].ntors)++;

		atom4 = json_object_get(torsion, "atom4");
		if (!json_is_integer(atom4)) {
			fprintf(stderr,
				"json atom4 is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		int i4 = json_integer_value(atom4) - 1;
		ag->tors[i].a3 = &(ag->atoms[i4]);
		(ag->atoms[i4].ntors)++;

		minima = json_object_get(torsion, "minima");
		if (!json_is_integer(minima)) {
			fprintf(stderr,
				"json minima is not integer for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].n = json_integer_value(minima);

		delta_constant = json_object_get(torsion, "delta_constant");
		if (!json_is_real(delta_constant)) {
			fprintf(stderr,
				"json delta_constant is not floating point for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].d = json_real_value(delta_constant);

		spring_constant = json_object_get(torsion, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for torsion %zd in json_file %s\n",
				i, json_file);
		}
		ag->tors[i].k = json_real_value(spring_constant);
	}

	impropers = json_object_get(base, "impropers");
	if (!json_is_array(impropers)) {
		fprintf(stderr, "json impropers are not an array %s\n",
			json_file);
	}
	size_t nimpropers = json_array_size(impropers);
	ag->nimps = nimpropers;
	ag->imps = _mol_calloc(nimpropers, sizeof(struct atomimproper));
	for (size_t i = 0; i < nimpropers; i++) {
		json_t *improper = json_array_get(impropers, i);
		if (!json_is_object(improper)) {
			fprintf(stderr,
				"Improper %zd not an object in json file %s\n",
				i, json_file);
		}
		json_t *atom1, *atom2, *atom3, *atom4, *phi, *spring_constant;

		atom1 = json_object_get(improper, "atom1");
		if (!json_is_integer(atom1)) {
			fprintf(stderr,
				"json atom1 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i1 = json_integer_value(atom1) - 1;
		ag->imps[i].a0 = &(ag->atoms[i1]);
		(ag->atoms[i1].nimps)++;

		atom2 = json_object_get(improper, "atom2");
		if (!json_is_integer(atom2)) {
			fprintf(stderr,
				"json atom2 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i2 = json_integer_value(atom2) - 1;
		ag->imps[i].a1 = &(ag->atoms[i2]);
		(ag->atoms[i2].nimps)++;

		atom3 = json_object_get(improper, "atom3");
		if (!json_is_integer(atom3)) {
			fprintf(stderr,
				"json atom3 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i3 = json_integer_value(atom3) - 1;
		ag->imps[i].a2 = &(ag->atoms[i3]);
		(ag->atoms[i3].nimps)++;

		atom4 = json_object_get(improper, "atom4");
		if (!json_is_integer(atom4)) {
			fprintf(stderr,
				"json atom4 is not integer for improper %zd in json_file %s\n",
				i, json_file);
		}
		int i4 = json_integer_value(atom4) - 1;
		ag->imps[i].a3 = &(ag->atoms[i4]);
		(ag->atoms[i4].nimps)++;

		phi = json_object_get(improper, "phi");
		if (!json_is_real(phi)) {
			fprintf(stderr,
				"json phi is not floating point for improper %zd in json_file %s\n",
				i, json_file);
		}
		ag->imps[i].psi0 = json_real_value(phi);

		spring_constant = json_object_get(improper, "spring_constant");
		if (!json_is_real(spring_constant)) {
			fprintf(stderr,
				"json spring_constant is not floating point for improper %zd in json_file %s\n",
				i, json_file);
		}
		ag->imps[i].k = json_real_value(spring_constant);
	}

	json_decref(base);

//allocate atom arrays of pointers to parameters
	for (size_t i = 0; i < natoms; i++) {
		int i1 = ag->atoms[i].nbonds;
		ag->atoms[i].bonds = _mol_calloc(i1, sizeof(struct atombond *));
		ag->atoms[i].nbonds = 0;
		i1 = ag->atoms[i].nangs;
		ag->atoms[i].angs = _mol_calloc(i1, sizeof(struct atomangle *));
		ag->atoms[i].nangs = 0;
		i1 = ag->atoms[i].ntors;
		ag->atoms[i].tors =
		    _mol_calloc(i1, sizeof(struct atomtorsion *));
		ag->atoms[i].ntors = 0;
		i1 = ag->atoms[i].nimps;
		ag->atoms[i].imps =
		    _mol_calloc(i1, sizeof(struct atomimproper *));
		ag->atoms[i].nimps = 0;
	}
	struct atom *atm;
//fill bonds
	for (int i = 0; i < ag->nbonds; i++) {
		atm = ag->bonds[i].a0;
		atm->bonds[(atm->nbonds)++] = &(ag->bonds[i]);
		atm = ag->bonds[i].a1;
		atm->bonds[(atm->nbonds)++] = &(ag->bonds[i]);
	}
//fill angles
	for (int i = 0; i < ag->nangs; i++) {
		atm = ag->angs[i].a0;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
		atm = ag->angs[i].a1;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
		atm = ag->angs[i].a2;
		atm->angs[(atm->nangs)++] = &(ag->angs[i]);
	}
//fill torsions
	for (int i = 0; i < ag->ntors; i++) {
		atm = ag->tors[i].a0;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a1;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a2;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
		atm = ag->tors[i].a3;
		atm->tors[(atm->ntors)++] = &(ag->tors[i]);
	}
//fill impropers
	for (int i = 0; i < ag->nimps; i++) {
		atm = ag->imps[i].a0;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a1;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a2;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
		atm = ag->imps[i].a3;
		atm->imps[(atm->nimps)++] = &(ag->imps[i]);
	}
//atom indices in the group
	fill_ingrp(ag);

	ag->is_psf_read = true;

	// copy vals from deprecated to new data structures
	int atomsi;
	for (atomsi = 0; atomsi < ag->natoms; atomsi++) {
		_mol_atom_create_bond_indices(&ag->atoms[atomsi],
					      ag->atoms[atomsi].nbonds);
	}
	_mol_atom_group_copy_from_deprecated(ag);
	return ag;
}
Exemplo n.º 21
0
int VtFile_clusters(struct VtFile *file_scan, const char *cluster_date,
                    void (*cb)(json_t *cluster_json, void *data), void *user_data) {
  CURL *curl;
  CURLcode res;
  int ret = 0;
  json_t *resp_json = NULL;
  long http_response_code = 0;
  char url[1024];

  if (!cluster_date || !cluster_date[0]) {
    VT_ERROR("search cluster_date can not be empty\n");
    return -1;
  }

  VtApiPage_resetBuffer((struct VtApiPage *) file_scan);
  curl = curl_easy_init();
  if (!curl) {
    VT_ERROR("init curl\n");
    goto cleanup;
  }

  snprintf(url, sizeof(url) - 1 , VT_API_BASE_URL "file/clusters?apikey=%s&date=%s",
           file_scan->api_key, cluster_date);
// 	DBG(1, "URL=%s \n", url);
  curl_easy_setopt(curl, CURLOPT_URL, url);

  set_std_curl_data(file_scan, curl);

  /* Perform the request, res will get the return code */
  res = curl_easy_perform(curl);
  DBG(1, "Perform done\n");
  /* Check for errors */
  if(res != CURLE_OK) {
    VT_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    ret = res;
    goto cleanup;
  } else {
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);
    if (http_response_code != 200) {
      VT_ERROR("HTTP Response code: %ld\n", http_response_code);
      ret = http_response_code;
      goto cleanup;
    }
  }

  DBG(1, "Page:\n%s\n",file_scan->buffer);

  if (file_scan->response)
    VtResponse_put(&file_scan->response);
  file_scan->response = VtResponse_new();
  ret = VtResponse_fromJSONstr(file_scan->response, file_scan->buffer);
  if (ret) {
    VT_ERROR("Parsing JSON\n");
    goto cleanup;
  }

  resp_json =  VtResponse_getJanssonObj(file_scan->response);

  if (resp_json) {
    json_t *offset_json = json_object_get(resp_json, "offset");
    if (json_is_string(offset_json)) {
      VtFile_setOffset(file_scan, json_string_value(offset_json));
    }
  }

  if (cb && resp_json) {
    json_t *clusters_json = json_object_get(resp_json, "clusters");
    unsigned int index;
    json_t *cl_json = NULL;


    if (!clusters_json || !json_is_array(clusters_json)) {
      goto cleanup;
    }

    json_array_foreach(clusters_json, index, cl_json) {
      if (!json_is_object(cl_json)) {
        VT_ERROR("not valid object\n");
        continue;
      }
      cb(cl_json, user_data);
    }
  }
Exemplo n.º 22
0
int VtFile_search(struct VtFile *file_scan, const char *query,
                  void (*cb)(const char *resource, void *data),
                  void *user_data) {
  CURL *curl;
  CURLcode res;
  int ret = 0;
  json_t *resp_json = NULL;
  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  static const char header_buf[] = "Expect:";
  long http_response_code = 0;

  if (!query || !query[0]) {
    VT_ERROR("search query can not be empty\n");
    return -1;
  }

  VtApiPage_resetBuffer((struct VtApiPage *) file_scan);
  curl = curl_easy_init();
  if (!curl) {
    VT_ERROR("init curl\n");
    goto cleanup;
  }
  // initialize custom header list (stating that Expect: 100-continue is not wanted
  headerlist = curl_slist_append(headerlist, header_buf);

  DBG(1, "Api Key =  '%s'\n", file_scan->api_key);

  ret = curl_formadd(&formpost,
                     &lastptr,
                     CURLFORM_COPYNAME, "query",
                     CURLFORM_COPYCONTENTS,  query,
                     CURLFORM_END);
  if (ret)
    VT_ERROR("Adding qury %s\n", query);

  ret = curl_formadd(&formpost,
                     &lastptr,
                     CURLFORM_COPYNAME, "apikey",
                     CURLFORM_COPYCONTENTS, file_scan->api_key,
                     CURLFORM_END);
  if (ret)
    VT_ERROR("Adding key\n");



  if (file_scan->offset) {
    ret = curl_formadd(&formpost,
                       &lastptr,
                       CURLFORM_COPYNAME, "offset",
                       CURLFORM_COPYCONTENTS, file_scan->offset,
                       CURLFORM_END);
    if (ret)
      VT_ERROR("Adding offset\n");

  }

// 	DBG(1, "URL=%s \n", url);
  curl_easy_setopt(curl, CURLOPT_URL, VT_API_BASE_URL "file/search");

  set_std_curl_data(file_scan, curl);

  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); // set form

  /* Perform the request, res will get the return code */
  res = curl_easy_perform(curl);
  DBG(1, "Perform done\n");
  /* Check for errors */
  if(res != CURLE_OK) {
    VT_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    ret = res;
    goto cleanup;
  } else {
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);
    if (http_response_code != 200) {
      VT_ERROR("HTTP Response code: %ld\n", http_response_code);
      ret = http_response_code;
      goto cleanup;
    }
  }

  DBG(1, "Page:\n%s\n",file_scan->buffer);

  if (file_scan->response)
    VtResponse_put(&file_scan->response);
  file_scan->response = VtResponse_new();
  ret = VtResponse_fromJSONstr(file_scan->response, file_scan->buffer);
  if (ret) {
    VT_ERROR("Parsing JSON\n");
    goto cleanup;
  }
  resp_json =  VtResponse_getJanssonObj(file_scan->response);

  if (resp_json) {
    json_t *offset_json = json_object_get(resp_json, "offset");
    if (json_is_string(offset_json)) {
      VtFile_setOffset(file_scan, json_string_value(offset_json));
    }
  }

  if (cb && resp_json) {
    json_t *hashes_json = json_object_get(resp_json, "hashes");
    unsigned int index;
    json_t *hash_obj;
    json_t *offset_json = json_object_get(resp_json, "offset");

    if (offset_json && json_is_string(offset_json)
        && json_string_value(offset_json) && json_string_value(offset_json)[0]) {
      VtFile_setOffset(file_scan, json_string_value(offset_json));
    }

    if (!hashes_json || !json_is_array(hashes_json)) {
      VT_ERROR("Parse error: hashes\n");
      goto cleanup;
    }

    json_array_foreach(hashes_json, index, hash_obj) {
      if (!json_is_string(hash_obj)) {
        VT_ERROR("hash is not string\n");
        continue;
      }
      cb(json_string_value(hash_obj), user_data);
    }
  }
Exemplo n.º 23
0
/*====================================================================
 * 函数名    : vGenRegSrvMsg
 * 功能      : 生成服务器注册消息
 * 算法实现  : 
 * 参数说明  : nFlag 标志物理或逻辑服务器
 *			   nIdx  base索引
 * 返回值说明: 
 *			  成功 生成的注册消息
 *			  失败  NULL              
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/14       v1.0        YLI                          创建
 * ====================================================================*/
json_t *vGenRegSrvMsg(int nFlag,int nIdx)
{
	json_t *root;
	json_t *jt;
	json_t *srv_info;
	char saBuf[100];
	char saCfgPath[L_PATH_MAX_LEN];
	int n,m;
	memset(saBuf,0x00,sizeof saBuf);
	memset(saCfgPath,0x00,sizeof saCfgPath);
	srand((unsigned)time(NULL));
	root = json_object();
	//devid
	if (nFlag == F_PHY_FLAG)  //phy srv
	{
		sprintf(saBuf,"11%d",_gstrpPid[nIdx].nPhyCount);
	}
	else if (nFlag == F_LOGIC_FLAG) //logic srv
	{
		memset(saBuf,0x00,sizeof saBuf);
		//vLogNM(EL_DEBUG,"phy.log","phy count [%d] [%d]",_gstrpShm->rc.nPhyNum,_gstrpPid[nIdx].nPhyCount);
		vLogNM(EL_ERR,"phy.log","phy count [%d] [%d]",_gstrpShm->rc.nPhyNum,_gstrpPid[nIdx].nPhyCount);
		if (_gstrpPid[nIdx].nPhyCount == 0)
		{
			json_decref(root);
			vLogErr("phy server is not exist !!!!");
			return NULL;
		}
		n = rand() % _gstrpPid[nIdx].nPhyCount;
		//m = rand() % (_gstrpPid[nIdx].nLogicCount + 1);
		sprintf(saBuf,"11%d%d",n,_gstrpPid[nIdx].nLogicCount);
	}
	else
	{
		json_decref(root);
		vLogErr("devid generate error!!!");
		return NULL;
	}
	if (json_object_set(root,"devid",
		json_string(saBuf)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devid set error!!!");
		return NULL;
	}
	//devtype
	if(getenv("APP_PROFILE_PATH") == NULL)
	{
		json_decref(root);
		vLogErr("devtypes config file path error,please check evn value!!!");
		return NULL;
	}
	strcpy(saCfgPath,getenv("APP_PROFILE_PATH"));
	strcat(saCfgPath,"/devtypes.json");

	if (nFlag == F_PHY_FLAG)
	{
		jt = tPflGetJsonObj(saCfgPath,K_PHYTYPE_KEY);
	}
	else
	{
		jt = tPflGetJsonObj(saCfgPath,K_LOGICTYPE_KEY);
	}
	if (jt == NULL)
	{
		json_decref(root);
		vLogErr("devtypes file open error,please check devtypes.json is exist!!!");
		return NULL;
	}
	if (json_is_array(jt))
	{
		m = json_array_size(jt);
		n = rand()%m;
		if (json_object_set(root,"devtype",
		json_array_get(jt,n)) == FAILUER)
		{
			json_decref(root);
			vLogErr("devtype set error!!!");
			return NULL;
		}	
	}
	json_decref(jt);
	//eventid
	if (json_object_set(root,"eventid",
		json_string("EV_REG_REQ")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	/*srv_info*/
	srv_info = json_object();
	//devip
	json_object_set(srv_info,"devip",
		json_string(_gstrpShm->rc.nSrvIP));
	//devver
	if (json_object_set(srv_info,"devver",
		json_string("123")) == FAILUER)
	{
		json_decref(root);
		vLogErr("devadpver set error!!!");
		return NULL;
	}
	//devadpver
	json_object_set(srv_info,"devadpver",json_string("123"));
	//devname
	json_object_set(srv_info,"devname",json_string("truelink"));
	json_object_set(root,"srv_info",srv_info);
	json_decref(srv_info);
	return root;
}
Exemplo n.º 24
0
/*
 * get the key from the JWKs that corresponds with the key specified in the header
 */
static apr_byte_t oidc_proto_get_key_from_jwks(request_rec *r,
		apr_jwt_header_t *jwt_hdr, json_t *j_jwks, const char *type,
		apr_jwk_t **result) {

	char *x5t = NULL;
	apr_jwt_get_string(r->pool, &jwt_hdr->value, "x5t", &x5t);

	oidc_debug(r, "search for kid \"%s\" or thumbprint x5t \"%s\"",
			jwt_hdr->kid, x5t);

	/* get the "keys" JSON array from the JWKs object */
	json_t *keys = json_object_get(j_jwks, "keys");
	if ((keys == NULL) || !(json_is_array(keys))) {
		oidc_error(r, "\"keys\" array element is not a JSON array");
		return FALSE;
	}

	int i;
	for (i = 0; i < json_array_size(keys); i++) {

		/* get the next element in the array */
		json_t *elem = json_array_get(keys, i);

		/* check that it is a JSON object */
		if (!json_is_object(elem)) {
			oidc_warn(r,
					"\"keys\" array element is not a JSON object, skipping");
			continue;
		}

		/* get the key type and see if it is the RSA type that we are looking for */
		json_t *kty = json_object_get(elem, "kty");
		if ((!json_is_string(kty))
				|| (strcmp(json_string_value(kty), type) != 0))
			continue;

		/* see if we were looking for a specific kid, if not we'll return the first one found */
		if ((jwt_hdr->kid == NULL) && (x5t == NULL)) {
			oidc_debug(r, "no kid/x5t to match, return first key found");

			apr_jwk_parse_json(r->pool, elem, NULL, result);
			break;
		}

		/* we are looking for a specific kid, get the kid from the current element */
		json_t *ekid = json_object_get(elem, "kid");
		if ((ekid != NULL) && json_is_string(ekid) && (jwt_hdr->kid != NULL)) {
			/* compare the requested kid against the current element */
			if (apr_strnatcmp(jwt_hdr->kid, json_string_value(ekid)) == 0) {
				oidc_debug(r, "found matching kid: \"%s\"", jwt_hdr->kid);

				apr_jwk_parse_json(r->pool, elem, NULL, result);
				break;
			}
		}

		/* we are looking for a specific x5t, get the x5t from the current element */
		json_t *ex5t = json_object_get(elem, "kid");
		if ((ex5t != NULL) && json_is_string(ex5t) && (x5t != NULL)) {
			/* compare the requested kid against the current element */
			if (apr_strnatcmp(x5t, json_string_value(ex5t)) == 0) {
				oidc_debug(r, "found matching x5t: \"%s\"", x5t);

				apr_jwk_parse_json(r->pool, elem, NULL, result);
				break;
			}
		}

	}

	return TRUE;
}
Exemplo n.º 25
0
/* Call the simple functions not covered by other tests of the public API */
int main()
{
    json_t *value;

    value = json_integer(1);
    if(json_typeof(value) != JSON_INTEGER)
        fail("json_typeof failed");

    if(json_is_object(value))
        fail("json_is_object failed");

    if(json_is_array(value))
        fail("json_is_array failed");

    if(json_is_string(value))
        fail("json_is_string failed");

    if(!json_is_integer(value))
        fail("json_is_integer failed");

    if(json_is_real(value))
        fail("json_is_real failed");

    if(!json_is_number(value))
        fail("json_is_number failed");

    if(json_is_true(value))
        fail("json_is_true failed");

    if(json_is_false(value))
        fail("json_is_false failed");

    if(json_is_boolean(value))
        fail("json_is_boolean failed");

    if(json_is_null(value))
        fail("json_is_null failed");

    json_decref(value);


    value = json_string("foo");
    if(!value)
        fail("json_string failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");

    if(json_string_set(value, "bar"))
        fail("json_string_set failed");
    if(strcmp(json_string_value(value), "bar"))
        fail("invalid string value");

    json_decref(value);

    value = json_string(NULL);
    if(value)
        fail("json_string(NULL) failed");

    /* invalid UTF-8  */
    value = json_string("a\xefz");
    if(value)
        fail("json_string(<invalid utf-8>) failed");

    value = json_string_nocheck("foo");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");

    if(json_string_set_nocheck(value, "bar"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "bar"))
        fail("invalid string value");

    json_decref(value);

    /* invalid UTF-8 */
    value = json_string_nocheck("qu\xff");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "qu\xff"))
        fail("invalid string value");

    if(json_string_set_nocheck(value, "\xfd\xfe\xff"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "\xfd\xfe\xff"))
        fail("invalid string value");

    json_decref(value);


    value = json_integer(123);
    if(!value)
        fail("json_integer failed");
    if(json_integer_value(value) != 123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.0)
        fail("invalid number value");

    if(json_integer_set(value, 321))
        fail("json_integer_set failed");
    if(json_integer_value(value) != 321)
        fail("invalid integer value");
    if(json_number_value(value) != 321.0)
        fail("invalid number value");

    json_decref(value);

    value = json_real(123.123);
    if(!value)
        fail("json_real failed");
    if(json_real_value(value) != 123.123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.123)
        fail("invalid number value");

    if(json_real_set(value, 321.321))
        fail("json_real_set failed");
    if(json_real_value(value) != 321.321)
        fail("invalid real value");
    if(json_number_value(value) != 321.321)
        fail("invalid number value");

    json_decref(value);

    value = json_true();
    if(!value)
        fail("json_true failed");
    json_decref(value);

    value = json_false();
    if(!value)
        fail("json_false failed");
    json_decref(value);

    value = json_null();
    if(!value)
        fail("json_null failed");
    json_decref(value);

    /* Test reference counting on singletons (true, false, null) */
    value = json_true();
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");

    value = json_false();
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");

    value = json_null();
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");

    return 0;
}
Exemplo n.º 26
0
/*
 * based on an account name, perform OpenID Connect Provider Issuer Discovery to find out the issuer and obtain and store its metadata
 */
apr_byte_t oidc_proto_account_based_discovery(request_rec *r, oidc_cfg *cfg,
		const char *acct, char **issuer) {

	// TODO: maybe show intermediate/progress screen "discovering..."

	oidc_debug(r, "enter, acct=%s", acct);

	const char *resource = apr_psprintf(r->pool, "acct:%s", acct);
	const char *domain = strrchr(acct, '@');
	if (domain == NULL) {
		oidc_error(r, "invalid account name");
		return FALSE;
	}
	domain++;
	const char *url = apr_psprintf(r->pool, "https://%s/.well-known/webfinger",
			domain);

	apr_table_t *params = apr_table_make(r->pool, 1);
	apr_table_addn(params, "resource", resource);
	apr_table_addn(params, "rel", "http://openid.net/specs/connect/1.0/issuer");

	const char *response = NULL;
	if (oidc_util_http_get(r, url, params, NULL, NULL,
			cfg->provider.ssl_validate_server, &response,
			cfg->http_timeout_short, cfg->outgoing_proxy) == FALSE) {
		/* errors will have been logged by now */
		return FALSE;
	}

	/* decode and see if it is not an error response somehow */
	json_t *j_response = NULL;
	if (oidc_util_decode_json_and_check_error(r, response, &j_response) == FALSE)
		return FALSE;

	/* get the links parameter */
	json_t *j_links = json_object_get(j_response, "links");
	if ((j_links == NULL) || (!json_is_array(j_links))) {
		oidc_error(r, "response JSON object did not contain a \"links\" array");
		json_decref(j_response);
		return FALSE;
	}

	/* get the one-and-only object in the "links" array */
	json_t *j_object = json_array_get(j_links, 0);
	if ((j_object == NULL) || (!json_is_object(j_object))) {
		oidc_error(r,
				"response JSON object did not contain a JSON object as the first element in the \"links\" array");
		json_decref(j_response);
		return FALSE;
	}

	/* get the href from that object, which is the issuer value */
	json_t *j_href = json_object_get(j_object, "href");
	if ((j_href == NULL) || (!json_is_string(j_href))) {
		oidc_error(r,
				"response JSON object did not contain a \"href\" element in the first \"links\" array object");
		json_decref(j_response);
		return FALSE;
	}

	*issuer = apr_pstrdup(r->pool, json_string_value(j_href));

	oidc_debug(r,
			"returning issuer \"%s\" for account \"%s\" after doing successful webfinger-based discovery",
			*issuer, acct);

	json_decref(j_response);

	return TRUE;
}
Exemplo n.º 27
0
/*
 * check to see if JSON provider metadata is valid
 */
static apr_byte_t oidc_metadata_provider_is_valid(request_rec *r,
		json_t *j_provider, const char *issuer) {

	/* get the "issuer" from the provider metadata and double-check that it matches what we looked for */
	json_t *j_issuer = json_object_get(j_provider, "issuer");
	if ((j_issuer == NULL) || (!json_is_string(j_issuer))) {
		oidc_error(r,
				"provider (%s) JSON metadata did not contain an \"issuer\" string",
				issuer);
		return FALSE;
	}

	/* check that the issuer matches */
	if (issuer != NULL) {
		if (oidc_util_issuer_match(issuer, json_string_value(j_issuer)) == FALSE) {
			oidc_warn(r,
					"requested issuer (%s) does not match the \"issuer\" value in the provider metadata file: %s",
					issuer, json_string_value(j_issuer));
			//return FALSE;
		}
	}

	/* verify that the provider supports the a flow that we implement */
	json_t *j_response_types_supported = json_object_get(j_provider,
			"response_types_supported");
	if ((j_response_types_supported != NULL)
			&& (json_is_array(j_response_types_supported))) {
		int i = 0;
		for (i = 0; i < json_array_size(j_response_types_supported); i++) {
			json_t *elem = json_array_get(j_response_types_supported, i);
			if (!json_is_string(elem)) {
				oidc_error(r,
						"unhandled in-array JSON non-string object type [%d]",
						elem->type);
				continue;
			}
			if (oidc_proto_flow_is_supported(r->pool, json_string_value(elem)))
				break;
		}
		if (i == json_array_size(j_response_types_supported)) {
			oidc_warn(r,
					"could not find a supported response type in provider metadata (%s) for entry \"response_types_supported\"; assuming that \"code\" flow is supported...",
					issuer);
			//return FALSE;
		}
	} else {
		oidc_warn(r,
				"provider (%s) JSON metadata did not contain a \"response_types_supported\" array; assuming that \"code\" flow is supported...",
				issuer);
		// TODO: hey, this is required-by-spec stuff right?
	}

	/* verify that the provider supports a response_mode that we implement */
	json_t *response_modes_supported = json_object_get(j_provider,
			"response_modes_supported");
	if ((response_modes_supported != NULL)
			&& (json_is_array(response_modes_supported))) {
		int i = 0;
		for (i = 0; i < json_array_size(response_modes_supported); i++) {
			json_t *elem = json_array_get(response_modes_supported, i);
			if (!json_is_string(elem)) {
				oidc_error(r,
						"unhandled in-array JSON non-string object type [%d]",
						elem->type);
				continue;
			}
			if ((apr_strnatcmp(json_string_value(elem), "fragment") == 0)
					|| (apr_strnatcmp(json_string_value(elem), "query") == 0)
					|| (apr_strnatcmp(json_string_value(elem), "form_post") == 0))
				break;
		}
		if (i == json_array_size(response_modes_supported)) {
			oidc_warn(r,
					"could not find a supported response mode in provider metadata (%s) for entry \"response_modes_supported\"",
					issuer);
			return FALSE;
		}
	} else {
		oidc_debug(r,
				"provider (%s) JSON metadata did not contain a \"response_modes_supported\" array; assuming that \"fragment\" and \"query\" are supported",
				issuer);
	}

	/* check the required authorization endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"authorization_endpoint", TRUE) == FALSE)
		return FALSE;

	/* check the optional token endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"token_endpoint", FALSE) == FALSE)
		return FALSE;

	/* check the optional user info endpoint */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"userinfo_endpoint", FALSE) == FALSE)
		return FALSE;

	/* check the optional JWKs URI */
	if (oidc_metadata_is_valid_uri(r, "provider", issuer, j_provider,
			"jwks_uri", FALSE) == FALSE)
		return FALSE;

	/* find out what type of authentication the token endpoint supports (we only support post or basic) */
	json_t *j_token_endpoint_auth_methods_supported = json_object_get(
			j_provider, "token_endpoint_auth_methods_supported");
	if ((j_token_endpoint_auth_methods_supported == NULL)
			|| (!json_is_array(j_token_endpoint_auth_methods_supported))) {
		oidc_debug(r,
				"provider (%s) JSON metadata did not contain a \"token_endpoint_auth_methods_supported\" array, assuming \"client_secret_basic\" is supported",
				issuer);
	} else {
		int i;
		for (i = 0;
				i < json_array_size(j_token_endpoint_auth_methods_supported);
				i++) {
			json_t *elem = json_array_get(
					j_token_endpoint_auth_methods_supported, i);
			if (!json_is_string(elem)) {
				oidc_warn(r,
						"unhandled in-array JSON object type [%d] in provider (%s) metadata for entry \"token_endpoint_auth_methods_supported\"",
						elem->type, issuer);
				continue;
			}
			if (strcmp(json_string_value(elem), "client_secret_post") == 0) {
				break;
			}
			if (strcmp(json_string_value(elem), "client_secret_basic") == 0) {
				break;
			}
		}
		if (i == json_array_size(j_token_endpoint_auth_methods_supported)) {
			oidc_error(r,
					"could not find a supported value [client_secret_post|client_secret_basic] in provider (%s) metadata for entry \"token_endpoint_auth_methods_supported\"",
					issuer);
			return FALSE;
		}
	}

	return TRUE;
}
Exemplo n.º 28
0
bool Json::isArray() const { 
   return json_is_array(m_json) > 0;
}
Exemplo n.º 29
0
static void
ccmd_set_option(json_t * params)
{
    const char *optname, *optstr, *pattern;
    json_t *jmsg, *joval, *jopt;
    int isstr, i, ret;
    const struct nh_option_desc *gameopt, *birthopt, *option;
    union nh_optvalue value;
    struct nh_autopickup_rules ar = { NULL, 0 };
    struct nh_autopickup_rule *r;

    if (json_unpack
        (params, "{ss,so,si*}", "name", &optname, "value", &joval, "isstr",
         &isstr) == -1)
        exit_client("Bad parameters for set_option");

    /* find the option_desc for the options that should be set; the option type
       is required in order to decode the option value. */
    gameopt = nh_get_options(GAME_OPTIONS);
    birthopt =
        nh_get_options(gameid ? ACTIVE_BIRTH_OPTIONS : CURRENT_BIRTH_OPTIONS);
    option = find_option(optname, gameopt, birthopt);
    if (!option) {
        jmsg = json_pack("{si,so}", "return", FALSE, "option", json_object());
        client_msg("set_option", jmsg);
        return;
    }

    /* decode the option value depending on the option type */
    if (isstr || option->type == OPTTYPE_STRING) {
        if (!json_is_string(joval))
            exit_client("could not decode option string");
        value.s = (char *)json_string_value(joval);

    } else if (option->type == OPTTYPE_INT || option->type == OPTTYPE_ENUM ||
               option->type == OPTTYPE_BOOL) {
        if (!json_is_integer(joval))
            exit_client("could not decode option value");
        value.i = json_integer_value(joval);

    } else if (option->type == OPTTYPE_AUTOPICKUP_RULES) {
        if (!json_is_array(joval))
            exit_client("could not decode option");

        ar.num_rules = json_array_size(joval);
        ar.rules = malloc(sizeof (struct nh_autopickup_rule) * ar.num_rules);
        if (ar.num_rules) {
            value.ar = &ar;
            for (i = 0; i < ar.num_rules; i++) {
                r = &ar.rules[i];
                if (json_unpack
                    (json_array_get(joval, i), "{ss,si,si,si}", "pattern",
                     &pattern, "oclass", &r->oclass, "buc", &r->buc, "action",
                     &r->action) == -1)
                    exit_client("Error unpacking autopickup rule");
                strncpy(r->pattern, pattern, sizeof (r->pattern) - 1);
            }
        } else
            value.ar = NULL;
    }

    ret = nh_set_option(optname, value, isstr);

    if (option->type == OPTTYPE_AUTOPICKUP_RULES)
        free(ar.rules);

    gameopt = nh_get_options(GAME_OPTIONS);
    birthopt =
        nh_get_options(gameid ? ACTIVE_BIRTH_OPTIONS : CURRENT_BIRTH_OPTIONS);
    option = find_option(optname, gameopt, birthopt);

    jopt = json_option(option);
    optstr = nh_get_option_string(option);

    if (ret == TRUE)
        db_set_option(user_info.uid, optname, option->type, optstr);
    /* return the altered option struct and the string representation to the
       client. The intent is to save some network round trips and make a
       separate get_option_string message unneccessary */
    jmsg = json_pack("{si,so}", "return", ret, "option", jopt);
    client_msg("set_option", jmsg);
}
Exemplo n.º 30
0
/*====================================================================
 * 函数名    : vGenRegTermMsg
 * 功能      : 生成终端注册消息
 * 算法实现  : 
 * 参数说明  : 
 *				nIdx 标识是哪个的base
 * 返回值说明: 成功 生成的json字符串
 *			   失败 NULL             
 * ----------------------------------------------------------------------
 * 修改记录:
 * 日  期        版本        修改人        走读人        修改记录
 * 2015/1/13       v1.0        YLI                          创建
 * ====================================================================*/
json_t *vGenRegTermMsg(int nIdx)
{
	json_t *root;
	json_t *mt_info;
	json_t *netinfo;
	json_t *aps_addr;
	json_t *jt;
	const char *key;
	json_t *value;
	int n,size;
	char saCfgPath[L_PATH_MAX_LEN];
	char tmp[100];
	root = json_object();
	memset(tmp,0x00,sizeof tmp);
	memset(saCfgPath,0x00,sizeof saCfgPath);
	
	srand((unsigned)time(NULL));

	//set eventid
	if (json_object_set(root,"eventid",
		json_string("EV_REG_REQ")) == FAILUER)
	{
		json_decref(root);
		vLogErr("eventid set error!!!");
		return NULL;
	}
	//devid
	n = rand() % (S_RAND_RANG + _gstrpPid[nIdx].nTermCount);
	sprintf(tmp,"1.2.%02d",n);
	if (json_object_set(root,"devid",
		json_string(tmp)) == FAILUER)
	{
		json_decref(root);
		vLogErr("devid set error!!!");
		return NULL;
	}
	//devtype
	if(getenv("APP_PROFILE_PATH") == NULL)
	{
		json_decref(root);
		vLogErr("devtypes config file path error,please check evn value!!!");
		return NULL;
	}
	strcpy(saCfgPath,getenv("APP_PROFILE_PATH"));
	strcat(saCfgPath,"/devtypes.json");
	jt = tPflGetJsonObj(saCfgPath,K_DEVTYPE_KEY);
	if (jt == NULL)
	{
		json_decref(root);
		vLogErr("devtypes file open error,please check devtypes.json is exist!!!");
		return NULL;
	}
	
	
	if (json_is_array(jt))
	{
		size = json_array_size(jt);
		n = rand()%size;
		if (json_object_set(root,"devtype",
		json_array_get(jt,n)) == FAILUER)
		{
			json_decref(root);
			vLogErr("devtype set error!!!");
			return NULL;
		}	
	}

	/*mt_info*/
	mt_info = json_object();
	//devver
	if (json_object_set(mt_info,"devver",
		json_string("123")) == FAILUER)
	{
		json_decref(root);
		vLogErr("devver set error!!!");
		return NULL;
	}
	//devname
	json_object_set(mt_info,"devname",json_string("truelink"));
	//netinfo
	netinfo = json_object();
	json_object_set(netinfo,"ip",
		json_string(_gstrpShm->rc.nSrvIP));
	json_object_set(netinfo,"dns",
		json_string("172.16.0.65"));
	json_object_set(mt_info,"netinfo",netinfo);

	//aps_addr
	aps_addr = json_object();
	json_object_set(aps_addr,"domain",
		json_string("fdaf"));
	json_object_set(aps_addr,"ip",
		json_string(_gstrpShm->rc.nSrvIP));
	json_object_set(mt_info,"aps_addr",aps_addr);

	//oem
	json_object_set(mt_info,"oem",json_string("dfd"));
	//os
	json_object_set(mt_info,"os",json_string("Centos 6.4"));
	//cpu_num
	json_object_set(mt_info,"cpu_num",json_integer(4));
	//cpu_type
	//cpu_freq
	json_decref(jt);
	jt = GetCpuInfo();
	json_object_foreach(jt,key,value)
	{
		if(strncmp(key,"cpuMHz",6) == 0)
		{
			json_object_set(mt_info,"cpu_freq",value);
		}
		if (strncmp(key,"modelname",9) == 0)
		{
			json_object_set(mt_info,"cpu_type",value);
		}
	}
	json_decref(jt);
	jt = GetMemInfo();
	//memory
	json_object_foreach(jt,key,value)
	{
		if(strncmp(key,"MemTotal",8) == 0)
		{
			json_object_set(mt_info,"memory",value);
		}
	}
	json_object_set(root,"mt_info",mt_info);
	json_decref(mt_info);
	return root;
}