예제 #1
0
static struct json_object *serialize_sign_pub(
        const union command_args *args_u, uint16_t version){

    const struct sign_pub *sign_pub = &args_u->sign_pub;
    struct json_object *ret;

    if(version != 1)
        return NULL;
    bytes_t b = {.data=(void *)sign_pub->message,
                 .data_len=sign_pub->msg_len};

    const char *serialized_msg = tc_bytes_b64(&b);

    ret = json_object_new_object();

    json_object_object_add(ret, "signing_id",
                           json_object_new_string(sign_pub->signing_id));
    json_object_object_add(ret, "key_id",
                           json_object_new_string(sign_pub->key_id));
    json_object_object_add(ret, "message",
                           json_object_new_string(serialized_msg));

    free((void *)serialized_msg);
    return ret;
}

static union command_args *unserialize_sign_pub(
        struct json_object *in, uint16_t version) {

    struct json_object *temp;
    union command_args *ret_union =
        (union command_args *) malloc(sizeof(union command_args));
    struct sign_pub *ret = &ret_union->sign_pub;
    bytes_t *msg;

    if(version != 1)
        goto err_exit;

    if(!json_object_object_get_ex(in, "key_id", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"key_id\" does not exists.");
        goto err_exit;
    }
    ret->key_id = strdup(json_object_get_string(temp));

    if(!json_object_object_get_ex(in, "signing_id", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"signing_id\" does not exists.");
        free((void *)ret->key_id);
        goto err_exit;
    }
    ret->signing_id = strdup(json_object_get_string(temp));

    if(!json_object_object_get_ex(in, "message", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"message\" does not exists.");
        free((void *)ret->key_id);
        free((void *)ret->signing_id);
        goto err_exit;
    }

    msg = tc_b64_bytes(json_object_get_string(temp));
    ret->message = (uint8_t *)msg->data;
    ret->msg_len = msg->data_len;

    free(msg);

    return ret_union;

err_exit:
    free(ret);
    return NULL;
}

static int delete_sign_pub(union command_args *data){
    struct sign_pub *sign_pub = &data->sign_pub;
    free((void *)sign_pub->key_id);
    free((void *)sign_pub->signing_id);
    free((void *)sign_pub->message);
    free(data);
    return 0;
}

static struct json_object *serialize_sign_req(
        const union command_args *args_u, uint16_t version){

    const struct sign_req *sign_req = &args_u->sign_req;
    struct json_object *ret;
    const char *serialized_signature;

    if(version != 1)
        return NULL;

    ret = json_object_new_object();

    serialized_signature = tc_serialize_signature_share(sign_req->signature);
    if(!serialized_signature) {
        LOG(LOG_LVL_ERRO, "Failed serializing signature share");
        return NULL;
    }

    json_object_object_add(ret, "status_code",
                           json_object_new_int(sign_req->status_code));
    json_object_object_add(ret, "signing_id",
                           json_object_new_string(sign_req->signing_id));

    json_object_object_add(ret, "signature",
                           json_object_new_string(serialized_signature));
    free((void *)serialized_signature);
    return ret;
}

static union command_args *unserialize_sign_req(
        struct json_object *in, uint16_t version) {

    struct json_object *temp;
    union command_args *ret_union =
        (union command_args *) malloc(sizeof(union command_args));
    struct sign_req *ret = &ret_union->sign_req;

    if(version != 1)
        goto err_exit;

    if(!json_object_object_get_ex(in, "status_code", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"status_code\" does not exists.");
        goto err_exit;
    }
    ret->status_code = (uint8_t) json_object_get_int(temp);

    if(!json_object_object_get_ex(in, "signing_id", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"signing_id\" does not exists.");
        goto err_exit;
    }
    ret->signing_id = strdup(json_object_get_string(temp));

    if(!json_object_object_get_ex(in, "signature", &temp)) {
        LOG(LOG_LVL_CRIT, "Key \"signature\" does not exists.");
        free((void *)ret->signing_id);
        goto err_exit;
    }

    ret->signature = tc_deserialize_signature_share(
                                            json_object_get_string(temp));
    if(!ret->signature) {
        LOG(LOG_LVL_CRIT, "Unable to deserialize signature share");
        free((void *)ret->signing_id);
        goto err_exit;
    }
    return ret_union;

err_exit:
    free(ret);
    return NULL;
}

static int delete_sign_req(union command_args *data){
    struct sign_req *sign_req = &data->sign_req;
    free((void *)sign_req->signing_id);
    if(sign_req->signature)
        tc_clear_signature_share((signature_share_t *)sign_req->signature);
    free(data);
    return 0;
}

// *************************************************************
// ***********************Public API****************************
// *************************************************************

// Arrays with functions to do the serialization/unserialization and deletion.
static struct json_object *(
        *const serialize_funcs[OP_MAX])(const union command_args *data,
                                        uint16_t version) =
    {
        serialize_store_key_pub,
        serialize_store_key_req,
        serialize_store_key_res,
        serialize_store_key_ack,
        serialize_delete_key_share_pub,
        serialize_delete_key_share_req,
        serialize_sign_pub,
        serialize_sign_req
    };

static union command_args *(*const unserialize_funcs[OP_MAX])(
        struct json_object *in, uint16_t version) =
    {
        unserialize_store_key_pub,
        unserialize_store_key_req,
        unserialize_store_key_res,
        unserialize_store_key_ack,
        unserialize_delete_key_share_pub,
        unserialize_delete_key_share_req,
        unserialize_sign_pub,
        unserialize_sign_req
    };

static int (*delete_funcs[OP_MAX])(union command_args *data) =
    {
        delete_store_key_pub,
        delete_store_key_req,
        delete_store_key_res,
        delete_store_key_ack,
        delete_delete_key_share_pub,
        delete_delete_key_share_req,
        delete_sign_pub,
        delete_sign_req
    };

// *************************************************************
// ***********************Public API****************************
// *************************************************************

size_t serialize_op_req(const struct op_req *operation_request, char **output){
    struct json_object *temp;
    int operation = (int) operation_request->op;
    uint16_t version = operation_request->version;
    const char *temp_char_ptr;
    struct json_object *json_ret = json_object_new_object();
    size_t ret = 0;

    if(version != 1){
        LOG(LOG_LVL_CRIT, "Version %" PRIu16 " not supported.\n", version);
        goto err_exit;
    }
    if(operation >= OP_MAX) {
        LOG(LOG_LVL_CRIT, "Operation %d not supported.", operation);
        goto err_exit;
    }

    json_object_object_add(json_ret, "op",
                           json_object_new_int(operation_request->op));
    json_object_object_add(json_ret, "version",
                           json_object_new_int(operation_request->version));
    temp = (serialize_funcs[operation])(operation_request->args, version);
    if(!temp)
        goto err_exit;
    json_object_object_add(json_ret, "args", temp);

    // TODO pretty just for testing purposes
    temp_char_ptr =
        json_object_to_json_string_ext(json_ret, JSON_C_TO_STRING_PRETTY);

    // TODO(fmontoto) strdup?
    ret = strlen(temp_char_ptr);
    *output = (char *) malloc(ret * sizeof(char));
    memcpy(*output, temp_char_ptr, ret);
    json_object_put(json_ret);

    return ret;

err_exit:
    if(!json_object_put(json_ret))
        LOG(LOG_LVL_CRIT, "BUG(mem leak): JSON reference error, not freed.");
    return 0;

}

struct op_req *unserialize_op_req(const char *operation_request, size_t size){
    struct json_object *temp_json, *parsed_json;
    uint32_t temp_uint32;
    union command_args *temp_args;
    struct op_req *ret = (struct op_req *) malloc(sizeof(struct op_req));
    struct json_tokener *json_tok = json_tokener_new();

    parsed_json = json_tokener_parse_ex(json_tok, operation_request, size);
    json_tokener_free(json_tok);
    if(!parsed_json){
        LOG(LOG_LVL_CRIT, "unserialize_op_req: Invalid input.");
        goto err_exit;
    }

    if(!json_object_object_get_ex(parsed_json, "op", &temp_json)){
        LOG(LOG_LVL_CRIT, "Key \"op\" does not exists.");
        goto err_exit;
    }
    ret->op = (int) json_object_get_int(temp_json);

    if(!json_object_object_get_ex(parsed_json, "version", &temp_json)){
        LOG(LOG_LVL_CRIT, "Key \"version\" does not exists.");
        goto err_exit;
    }
    temp_uint32 = json_object_get_int(temp_json);
    if(temp_uint32 > UINT16_MAX) {
        LOG(LOG_LVL_CRIT, "Version (%" PRIu32 ") not valid.", temp_uint32);
        goto err_exit;
    }
    ret->version = (uint16_t) temp_uint32;

    // TODO refactor this into a method?
    if(ret->op >= OP_MAX) {
        LOG(LOG_LVL_CRIT, "Operation %d not supported.", ret->op);
        goto err_exit;
    }

    if(!json_object_object_get_ex(parsed_json, "args", &temp_json)){
        LOG(LOG_LVL_CRIT, "Key \"args\" does not exists.");
        goto err_exit;
    }
    temp_args = (unserialize_funcs[ret->op])(temp_json, ret->version);
    if(!temp_args)
        goto err_exit;
    ret->args = temp_args;

    json_object_put(parsed_json);

    return ret;

err_exit:
    free(ret);
    return NULL;
}

int delete_op_req(struct op_req *operation_request){
    int ret = 0;
    if(!operation_request)
        return 0;
    if(operation_request->version != 1){
        LOG(LOG_LVL_CRIT, "Version %" PRIu16 " not supported.",
            operation_request->version);
        return 1;
    }
    if(operation_request->op >= OP_MAX) {
        LOG(LOG_LVL_CRIT, "Operation %d not supported.",operation_request->op);
        return 1;
    }
    ret = (delete_funcs[operation_request->op])(operation_request->args);
    if(ret)
        return 1;
    free(operation_request);
    return 0;
}
예제 #2
0
bool OGRGMELayer::CreateTableIfNotCreated()
{
    if (!bCreateTablePending || (osTableId.size() != 0)) {
        CPLDebug("GME", "Not creating table since already created");
        CPLDebug("GME", "bCreateTablePending = %d osTableId ='%s'",
                 bCreateTablePending, osTableId.c_str());
        return true;
    }
    CPLDebug("GME", "Creating table...");

    json_object *pjoCreateDoc = json_object_new_object();
    json_object *pjoProjectId = json_object_new_string( osProjectId.c_str() );
    json_object_object_add( pjoCreateDoc, "projectId", pjoProjectId );
    json_object *pjoName = json_object_new_string( osTableName.c_str() );
    json_object_object_add( pjoCreateDoc, "name",  pjoName );
    json_object *pjoDraftACL = json_object_new_string( osDraftACL.c_str() );
    json_object_object_add( pjoCreateDoc, "draftAccessList", pjoDraftACL );
    json_object *pjoPublishedACL = json_object_new_string( osPublishedACL.c_str() );
    json_object_object_add( pjoCreateDoc, "publishedAccessList", pjoPublishedACL );
    json_object *pjoSchema = json_object_new_object();

    json_object *pjoColumns = json_object_new_array();

    poFeatureDefn->SetGeomType( eGTypeForCreation );

    json_object *pjoGeometryColumn = json_object_new_object();
    json_object *pjoGeometryName = json_object_new_string( "geometry" );
    json_object *pjoGeometryType;
    switch(eGTypeForCreation) {
    case wkbPoint:
    case wkbPoint25D:
    case wkbMultiPoint:
    case wkbMultiPoint25D:
        pjoGeometryType = json_object_new_string( "points" );
        break;
    case wkbLineString:
    case wkbLineString25D:
    case wkbMultiLineString:
    case wkbLinearRing:
    case wkbMultiLineString25D:
        pjoGeometryType = json_object_new_string( "lineStrings" );
        break;
    case wkbPolygon:
    case wkbPolygon25D:
    case wkbMultiPolygon:
    case wkbGeometryCollection:
    case wkbMultiPolygon25D:
        pjoGeometryType = json_object_new_string( "polygons" );
        break;
    case wkbGeometryCollection25D:
        pjoGeometryType = json_object_new_string( "mixedGeometry" );
        break;
    default:
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Unsupported Geometry type. Defaulting to Points");
        pjoGeometryType = json_object_new_string( "points" );
        poFeatureDefn->SetGeomType( wkbPoint );
    }
    json_object_object_add( pjoGeometryColumn, "name", pjoGeometryName );
    json_object_object_add( pjoGeometryColumn, "type", pjoGeometryType );
    json_object_array_add( pjoColumns, pjoGeometryColumn );

    for (int iOGRField = 0; iOGRField < poFeatureDefn->GetFieldCount(); iOGRField++ )
    {
        if ((iOGRField == iGxIdField) && (iGxIdField >= 0))
            continue; // don't create the gx_id field.
        const char *pszFieldName = poFeatureDefn->GetFieldDefn(iOGRField)->GetNameRef();
        if (EQUAL(pszFieldName, "gx_id")) {
            iGxIdField = iOGRField;
            continue;
        }
        json_object *pjoColumn = json_object_new_object();
        json_object *pjoFieldName =
            json_object_new_string( pszFieldName );
        json_object *pjoFieldType;

        switch(poFeatureDefn->GetFieldDefn(iOGRField)->GetType()) {
        case OFTInteger:
            pjoFieldType = json_object_new_string( "integer" );
            break;
        case OFTReal:
            pjoFieldType = json_object_new_string( "double" );
            break;
        default:
            pjoFieldType = json_object_new_string( "string" );
        }
        json_object_object_add( pjoColumn, "name", pjoFieldName );
        json_object_object_add( pjoColumn, "type", pjoFieldType );
        json_object_array_add( pjoColumns, pjoColumn );
    }

    json_object_object_add( pjoSchema, "columns", pjoColumns );
    json_object_object_add( pjoCreateDoc, "schema", pjoSchema );
    const char *body =
        json_object_to_json_string_ext(pjoCreateDoc,
                                       JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);

    CPLDebug("GME", "Create Table Doc:\n%s", body);

/* -------------------------------------------------------------------- */
/*      POST changes                                                    */
/* -------------------------------------------------------------------- */
    CPLString osRequest = "tables";
    CPLHTTPResult *poCreateResult = poDS->PostRequest(osRequest, body);
    if( poCreateResult == NULL || poCreateResult->pabyData == NULL )
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Table creation failed.");
        if( poCreateResult )
            CPLHTTPDestroyResult(poCreateResult);
        return false;
    }
    CPLDebug("GME", "CreateTable returned %d\n%s", poCreateResult->nStatus,
             poCreateResult->pabyData);

    json_object *pjoResponseDoc = OGRGMEParseJSON((const char *) poCreateResult->pabyData);

    osTableId = OGRGMEGetJSONString(pjoResponseDoc, "id", "");
    CPLHTTPDestroyResult(poCreateResult);
    if (osTableId.size() == 0) {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Table creation failed, or could not find table id.");
        return false;
    }

    /*
    OGRFieldDefn *poGxIdField = new OGRFieldDefn("gx_id", OFTString);

    poFeatureDefn->AddFieldDefn(poGxIdField);
    iGxIdField = poFeatureDefn->GetFieldCount() - 1;
    CPLDebug("GME", "create field %s(%d) of type %s",
             "gx_id", iGxIdField, OGRFieldDefn::GetFieldTypeName(OFTString));
    */
    bCreateTablePending = false;
    CPLDebug("GME", "sleeping 3s to give GME time to create the table...");
    CPLSleep( 3.0 );
    return true;
}
예제 #3
0
파일: export.c 프로젝트: Smattr/passwand
passwand_error_t passwand_export(const char *path, passwand_entry_t *entries, size_t entry_len) {

    assert(path != NULL);
    assert(entries != NULL || entry_len == 0);

    /* Create a new array as the top level JSON object in the export file. */
    json_object *j __attribute__((cleanup(disown))) = json_object_new_array();
    if (j == NULL)
        return PW_NO_MEM;

    for (size_t i = 0; i < entry_len; i++) {

        /* Encapsulate each entry in a JSON dictionary. */
        json_object *d = json_object_new_object();
        if (d == NULL)
            return PW_NO_MEM;

#define ADD(field) \
    do { \
        passwand_error_t err = add_to_dict(d, #field, entries[i].field, entries[i].field##_len); \
        if (err != PW_OK) { \
            json_object_put(d); \
            return err; \
        } \
    } while (0)

        ADD(space);
        ADD(key);
        ADD(value);
        ADD(hmac);
        ADD(hmac_salt);
        ADD(salt);
        ADD(iv);

#undef ADD

        json_object_array_add(j, d);
    }

    /* Now write out the array to the given file. */

    size_t path_len = strlen(path);
    if (SIZE_MAX - path_len < 2)
        return PW_OVERFLOW;
    char *tmp __attribute__((cleanup(autofree))) = malloc(strlen(path) + 2);
    if (tmp == NULL)
        return PW_NO_MEM;
    sprintf(tmp, "%s~", path);
    int fd = creat(tmp, 0600);
    if (fd == -1)
        return PW_IO;

    const char *json = json_object_to_json_string_ext(j, JSON_C_TO_STRING_PLAIN);
    size_t len = strlen(json);
    ssize_t written = write(fd, json, len);
    close(fd);
    if (written < 0 || (size_t)written != len) {
        unlink(tmp);
        return PW_IO;
    }

    if (rename(tmp, path) == -1) {
        unlink(tmp);
        return PW_IO;
    }

    return PW_OK;
}
예제 #4
0
파일: cpl_json.cpp 프로젝트: ksshannon/gdal
/**
 * Return the json document as a serialized string.
 * @return         serialized document.
 *
 * @since GDAL 2.3
 */
std::string CPLJSONDocument::SaveAsString()
{
    return json_object_to_json_string_ext(
                TO_JSONOBJ(m_poRootJsonObject), JSON_C_TO_STRING_PRETTY );
}
예제 #5
0
파일: main.c 프로젝트: sleep-walker/sway
int main(int argc, char **argv) {
	static int quiet = 0;
	static int raw = 0;
	char *socket_path = NULL;
	char *cmdtype = NULL;

	init_log(L_INFO);

	static struct option long_options[] = {
		{"help", no_argument, NULL, 'h'},
		{"quiet", no_argument, NULL, 'q'},
		{"raw", no_argument, NULL, 'r'},
		{"socket", required_argument, NULL, 's'},
		{"type", required_argument, NULL, 't'},
		{"version", no_argument, NULL, 'v'},
		{0, 0, 0, 0}
	};

	const char *usage =
		"Usage: swaymsg [options] [message]\n"
		"\n"
		"  -h, --help             Show help message and quit.\n"
		"  -q, --quiet            Be quiet.\n"
		"  -r, --raw              Use raw output even if using a tty\n"
		"  -s, --socket <socket>  Use the specified socket.\n"
		"  -t, --type <type>      Specify the message type.\n"
		"  -v, --version          Show the version number and quit.\n";

	raw = !isatty(STDOUT_FILENO);

	int c;
	while (1) {
		int option_index = 0;
		c = getopt_long(argc, argv, "hqrs:t:v", long_options, &option_index);
		if (c == -1) {
			break;
		}
		switch (c) {
		case 'q': // Quiet
			quiet = 1;
			break;
		case 'r': // Raw
			raw = 1;
			break;
		case 's': // Socket
			socket_path = strdup(optarg);
			break;
		case 't': // Type
			cmdtype = strdup(optarg);
			break;
		case 'v':
#if defined SWAY_GIT_VERSION && defined SWAY_GIT_BRANCH && defined SWAY_VERSION_DATE
			fprintf(stdout, "sway version %s (%s, branch \"%s\")\n", SWAY_GIT_VERSION, SWAY_VERSION_DATE, SWAY_GIT_BRANCH);
#else
			fprintf(stdout, "version not detected\n");
#endif
			exit(EXIT_SUCCESS);
			break;
		default:
			fprintf(stderr, "%s", usage);
			exit(EXIT_FAILURE);
		}
	}

	if (!cmdtype) {
		cmdtype = strdup("command");
	}
	if (!socket_path) {
		socket_path = get_socketpath();
		if (!socket_path) {
			sway_abort("Unable to retrieve socket path");
		}
	}

	uint32_t type = IPC_COMMAND;

	if (strcasecmp(cmdtype, "command") == 0) {
		type = IPC_COMMAND;
	} else if (strcasecmp(cmdtype, "get_workspaces") == 0) {
		type = IPC_GET_WORKSPACES;
	} else if (strcasecmp(cmdtype, "get_inputs") == 0) {
		type = IPC_GET_INPUTS;
	} else if (strcasecmp(cmdtype, "get_outputs") == 0) {
		type = IPC_GET_OUTPUTS;
	} else if (strcasecmp(cmdtype, "get_tree") == 0) {
		type = IPC_GET_TREE;
	} else if (strcasecmp(cmdtype, "get_marks") == 0) {
		type = IPC_GET_MARKS;
	} else if (strcasecmp(cmdtype, "get_bar_config") == 0) {
		type = IPC_GET_BAR_CONFIG;
	} else if (strcasecmp(cmdtype, "get_version") == 0) {
		type = IPC_GET_VERSION;
	} else {
		sway_abort("Unknown message type %s", cmdtype);
	}
	free(cmdtype);

	char *command = strdup("");
	if (optind < argc) {
		command = join_args(argv + optind, argc - optind);
	}

	int ret = 0;
	int socketfd = ipc_open_socket(socket_path);
	uint32_t len = strlen(command);
	char *resp = ipc_single_command(socketfd, type, command, &len);
	if (!quiet) {
		// pretty print the json
		json_object *obj = json_tokener_parse(resp);

		if (obj == NULL) {
			fprintf(stderr, "ERROR: Could not parse json response from ipc. This is a bug in sway.");
			printf("%s\n", resp);
			ret = 1;
		} else {
			if (raw) {
				printf("%s\n", json_object_to_json_string_ext(obj,
					JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED));
			} else {
				pretty_print(type, obj);
			}
			free(obj);
		}
	}
	close(socketfd);

	free(command);
	free(resp);
	free(socket_path);
	return ret;
}
예제 #6
0
파일: json.c 프로젝트: Goos/r3
const char * r3_node_to_json_pretty_string(const node * n) {
    json_object *obj = r3_node_to_json_object(n);
    return json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED);
}
예제 #7
0
파일: builtin-list.c 프로젝트: yuwgit/ndctl
int cmd_list(int argc, const char **argv)
{
	const struct option options[] = {
		OPT_STRING('b', "bus", &param.bus, "bus-id", "filter by bus"),
		OPT_STRING('r', "region", &param.region, "region-id",
				"filter by region"),
		OPT_STRING('d', "dimm", &param.dimm, "dimm-id",
				"filter by dimm"),
		OPT_STRING('t', "type", &param.type, "region-type",
				"filter by region-type"),
		OPT_BOOLEAN('B', "buses", &list.buses, "include bus info"),
		OPT_BOOLEAN('D', "dimms", &list.dimms, "include dimm info"),
		OPT_BOOLEAN('H', "health", &list.health, "include dimm health"),
		OPT_BOOLEAN('R', "regions", &list.regions,
				"include region info"),
		OPT_BOOLEAN('N', "namespaces", &list.namespaces,
				"include namespace info (default)"),
		OPT_BOOLEAN('i', "idle", &list.idle, "include idle devices"),
		OPT_END(),
	};
	const char * const u[] = {
		"ndctl list [<options>]",
		NULL
	};
	struct json_object *jnamespaces = NULL;
	struct json_object *jregions = NULL;
	struct json_object *jdimms = NULL;
	struct json_object *jbuses = NULL;
	struct ndctl_ctx *ctx;
	struct ndctl_bus *bus;
	unsigned int type = 0;
	int i, rc;

        argc = parse_options(argc, argv, options, u, 0);
	for (i = 0; i < argc; i++)
		error("unknown parameter \"%s\"\n", argv[i]);
	if (param.type && (strcmp(param.type, "pmem") != 0
				&& strcmp(param.type, "blk") != 0)) {
		error("unknown type \"%s\" must be \"pmem\" or \"blk\"\n",
				param.type);
		argc++;
	}

	if (argc)
		usage_with_options(u, options);

	if (num_list_flags() == 0) {
		list.buses = !!param.bus;
		list.regions = !!param.region;
		list.dimms = !!param.dimm;
	}

	if (num_list_flags() == 0)
		list.namespaces = true;

	if (param.type) {
		if (strcmp(param.type, "pmem") == 0)
			type = ND_DEVICE_REGION_PMEM;
		else
			type = ND_DEVICE_REGION_BLK;
	}

	rc = ndctl_new(&ctx);
	if (rc < 0)
		return rc;

	ndctl_bus_foreach(ctx, bus) {
		struct json_object *jbus = NULL;
		struct ndctl_region *region;
		struct ndctl_dimm *dimm;

		if (!util_bus_filter(bus, param.bus)
				|| !util_bus_filter_by_dimm(bus, param.dimm))
			continue;

		if (list.buses) {
			if (!jbuses) {
				jbuses = json_object_new_array();
				if (!jbuses) {
					fail("\n");
					continue;
				}
			}

			jbus = util_bus_to_json(bus);
			if (!jbus) {
				fail("\n");
				continue;
			}
			json_object_array_add(jbuses, jbus);
		}

		ndctl_dimm_foreach(bus, dimm) {
			struct json_object *jdimm;

			/* are we emitting dimms? */
			if (!list.dimms)
				break;

			if (!util_dimm_filter(dimm, param.dimm))
				continue;

			if (!list.idle && !ndctl_dimm_is_enabled(dimm))
				continue;

			if (!jdimms) {
				jdimms = json_object_new_array();
				if (!jdimms) {
					fail("\n");
					continue;
				}

				if (jbus)
					json_object_object_add(jbus, "dimms", jdimms);
			}

			jdimm = util_dimm_to_json(dimm);
			if (!jdimm) {
				fail("\n");
				continue;
			}

			if (list.health) {
				struct json_object *jhealth;

				jhealth = util_dimm_health_to_json(dimm);
				if (jhealth)
					json_object_object_add(jdimm, "health",
							jhealth);
				else if (ndctl_dimm_is_cmd_supported(dimm,
							ND_CMD_SMART)) {
					/*
					 * Failed to retrieve health data from
					 * a dimm that otherwise supports smart
					 * data retrieval commands.
					 */
					fail("\n");
					continue;
				}
			}

			/*
			 * Without a bus we are collecting dimms anonymously
			 * across the platform.
			 */
			json_object_array_add(jdimms, jdimm);
		}

		ndctl_region_foreach(bus, region) {
			struct json_object *jregion;

			if (!util_region_filter(region, param.region)
					|| !util_region_filter_by_dimm(region,
						param.dimm))
				continue;

			if (type && ndctl_region_get_type(region) != type)
				continue;

			if (!list.regions) {
				jnamespaces = list_namespaces(region, jbus,
						jnamespaces, true);
				continue;
			}

			if (!list.idle && !ndctl_region_is_enabled(region))
				continue;

			if (!jregions) {
				jregions = json_object_new_array();
				if (!jregions) {
					fail("\n");
					continue;
				}

				if (jbus)
					json_object_object_add(jbus, "regions",
							jregions);
			}

			jregion = region_to_json(region);
			if (!jregion) {
				fail("\n");
				continue;
			}

			/*
			 * Without a bus we are collecting regions anonymously
			 * across the platform.
			 */
			json_object_array_add(jregions, jregion);
		}

		if (jbuses) {
			jdimms = NULL;
			jregions = NULL;
			jnamespaces = NULL;
		}
	}

	if (jbuses)
		util_display_json_array(stdout, jbuses, jflag);
	else if ((!!jdimms + !!jregions + !!jnamespaces) > 1) {
		struct json_object *jplatform = json_object_new_object();

		if (!jplatform) {
			fail("\n");
			return -ENOMEM;
		}

		if (jdimms)
			json_object_object_add(jplatform, "dimms", jdimms);
		if (jregions)
			json_object_object_add(jplatform, "regions", jregions);
		if (jnamespaces)
			json_object_object_add(jplatform, "namespaces",
					jnamespaces);
		printf("%s\n", json_object_to_json_string_ext(jplatform,
					jflag));
		json_object_put(jplatform);
	} else if (jdimms)
		util_display_json_array(stdout, jdimms, jflag);
	else if (jregions)
		util_display_json_array(stdout, jregions, jflag);
	else if (jnamespaces)
		util_display_json_array(stdout, jnamespaces, jflag);

	if (did_fail)
		return -ENOMEM;
	return 0;
}
예제 #8
0
파일: macsio_main.c 프로젝트: LLNL/MACSio
static int
main_write(int argi, int argc, char **argv, json_object *main_obj)
{
    int rank = 0, dumpNum = 0, dumpCount = 0;
    unsigned long long problem_nbytes, dumpBytes = 0, summedBytes = 0;
    char nbytes_str[32], seconds_str[32], bandwidth_str[32], seconds_str2[32];
    double dumpTime = 0;
    double bandwidth, summedBandwidth;
    MACSIO_TIMING_GroupMask_t main_wr_grp = MACSIO_TIMING_GroupMask("main_write");
    double dump_loop_start, dump_loop_end;
    double min_dump_loop_start, max_dump_loop_end;
    int exercise_scr = JsonGetInt(main_obj, "clargs/exercise_scr");

    /* Sanity check args */

    /* Generate a static problem object to dump on each dump */
    json_object *problem_obj = MACSIO_DATA_GenerateTimeZeroDumpObject(main_obj,0);
    problem_nbytes = (unsigned long long) json_object_object_nbytes(problem_obj, JSON_C_FALSE);

#warning MAKE JSON OBJECT KEY CASE CONSISTENT
    json_object_object_add(main_obj, "problem", problem_obj);

    /* Just here for debugging for the moment */
    if (MACSIO_LOG_DebugLevel >= 2)
    {
        char outfName[256];
        FILE *outf;
        int json_c_print_flags = JSON_C_TO_STRING_PRETTY | JSON_C_TO_STRING_SPACED;

        if (MACSIO_LOG_DebugLevel < 3)
            json_c_print_flags |= JSON_C_TO_STRING_NO_EXTARR_VALS;

        snprintf(outfName, sizeof(outfName), "main_obj_write_%03d.json", MACSIO_MAIN_Rank);
        outf = fopen(outfName, "w");
        fprintf(outf, "\"%s\"\n", json_object_to_json_string_ext(main_obj, json_c_print_flags));
        fclose(outf);
    }

#warning WERE NOT GENERATING OR WRITING ANY METADATA STUFF

#warning MAKE THIS LOOP MORE LIKE A MAIN SIM LOOP WITH SIMPLE COMPUTE AND COMM STEP
    dump_loop_start = MT_Time();
    dumpTime = 0.0;
    for (dumpNum = 0; dumpNum < json_object_path_get_int(main_obj, "clargs/num_dumps"); dumpNum++)
    {
        double dt;
        int scr_need_checkpoint_flag = 1;
        MACSIO_TIMING_TimerId_t heavy_dump_tid;

#warning ADD OPTION TO UNLINK OLD FILE SETS

#ifdef HAVE_SCR
        if (exercise_scr)
            SCR_Need_checkpoint(&scr_need_checkpoint_flag);
#endif

        const MACSIO_IFACE_Handle_t *iface = MACSIO_IFACE_GetByName(
            json_object_path_get_string(main_obj, "clargs/interface"));

        /* log dump start */

        if (!exercise_scr || scr_need_checkpoint_flag)
        {
            int scr_valid = 0;

#ifdef HAVE_SCR
            if (exercise_scr)
                SCR_Start_checkpoint();
#endif

            /* Start dump timer */
            heavy_dump_tid = MT_StartTimer("heavy dump", main_wr_grp, dumpNum);

#warning REPLACE DUMPN AND DUMPT WITH A STATE TUPLE
#warning SHOULD HAVE PLUGIN RETURN FILENAMES SO MACSIO CAN STAT FOR TOTAL BYTES ON DISK
            /* do the dump */
            (*(iface->dumpFunc))(argi, argc, argv, main_obj, dumpNum, dumpTime);
#ifdef HAVE_MPI
            mpi_errno = 0;
#endif
            errno = 0;


            dt = MT_StopTimer(heavy_dump_tid);

#ifdef HAVE_SCR
            if (exercise_scr)
                SCR_Complete_checkpoint(scr_valid);
#endif
        }

        /* stop timer */
        dumpTime += dt;
        dumpBytes += problem_nbytes;
        dumpCount += 1;

        /* log dump timing */
        MACSIO_LOG_MSG(Info, ("Dump %02d BW: %s/%s = %s", dumpNum,
            MU_PrByts(problem_nbytes, 0, nbytes_str, sizeof(nbytes_str)),
            MU_PrSecs(dt, 0, seconds_str, sizeof(seconds_str)),
            MU_PrBW(problem_nbytes, dt, 0, bandwidth_str, sizeof(bandwidth_str))));
    }

    dump_loop_end = MT_Time();

    MACSIO_LOG_MSG(Info, ("Overall BW: %s/%s = %s",
        MU_PrByts(dumpBytes, 0, nbytes_str, sizeof(nbytes_str)),
        MU_PrSecs(dumpTime, 0, seconds_str, sizeof(seconds_str)),
        MU_PrBW(dumpBytes, dumpTime, 0, bandwidth_str, sizeof(bandwidth_str))));

    bandwidth = dumpBytes / dumpTime;
    summedBandwidth = bandwidth;
    min_dump_loop_start = dump_loop_start;
    max_dump_loop_end = dump_loop_end;

#ifdef HAVE_MPI
    MPI_Comm_rank(MACSIO_MAIN_Comm, &rank);
    MPI_Reduce(&bandwidth, &summedBandwidth, 1, MPI_DOUBLE, MPI_SUM, 0, MACSIO_MAIN_Comm);
    MPI_Reduce(&dumpBytes, &summedBytes, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, MACSIO_MAIN_Comm);
    MPI_Reduce(&dump_loop_start, &min_dump_loop_start, 1, MPI_DOUBLE, MPI_MIN, 0, MACSIO_MAIN_Comm);
    MPI_Reduce(&dump_loop_end, &max_dump_loop_end, 1, MPI_DOUBLE, MPI_MAX, 0, MACSIO_MAIN_Comm);
#endif

    if (rank == 0)
    {
        MACSIO_LOG_MSG(Info, ("Summed  BW: %s",
            MU_PrBW(summedBandwidth, 1.0, 0, bandwidth_str, sizeof(bandwidth_str))));
        MACSIO_LOG_MSG(Info, ("Total Bytes: %s; Last finisher - First starter = %s; BW = %s",
            MU_PrByts(summedBytes, 0, nbytes_str, sizeof(nbytes_str)),
            MU_PrSecs(max_dump_loop_end - min_dump_loop_start, 0, seconds_str, sizeof(seconds_str)),
            MU_PrBW(summedBytes, max_dump_loop_end - min_dump_loop_start, 0, bandwidth_str, sizeof(bandwidth_str))));
    }
}
예제 #9
0
파일: ferr.c 프로젝트: ton31337/frr
void log_ref_display(struct vty *vty, uint32_t code, bool json)
{
	struct log_ref *ref;
	struct json_object *top = NULL, *obj = NULL;
	struct list *errlist;
	struct listnode *ln;

	if (json)
		top = json_object_new_object();

	pthread_mutex_lock(&refs_mtx);
	{
		errlist = code ? list_new() : hash_to_list(refs);
	}
	pthread_mutex_unlock(&refs_mtx);

	if (code) {
		ref = log_ref_get(code);
		if (!ref) {
			vty_out(vty, "Code %"PRIu32" - Unknown\n", code);
			return;
		}
		listnode_add(errlist, ref);
	}

	for (ALL_LIST_ELEMENTS_RO(errlist, ln, ref)) {
		if (json) {
			char key[11];

			snprintf(key, sizeof(key), "%"PRIu32, ref->code);
			obj = json_object_new_object();
			json_object_string_add(obj, "title", ref->title);
			json_object_string_add(obj, "description",
					       ref->description);
			json_object_string_add(obj, "suggestion",
					       ref->suggestion);
			json_object_object_add(top, key, obj);
		} else {
			char pbuf[256];
			char ubuf[256];

			snprintf(pbuf, sizeof(pbuf), "\nError %"PRIu32" - %s",
				 ref->code, ref->title);
			memset(ubuf, '=', strlen(pbuf));
			ubuf[strlen(pbuf)] = '\0';

			vty_out(vty, "%s\n%s\n", pbuf, ubuf);
			vty_out(vty, "Description:\n%s\n\n", ref->description);
			vty_out(vty, "Recommendation:\n%s\n", ref->suggestion);
		}
	}

	if (json) {
		const char *str = json_object_to_json_string_ext(
			top, JSON_C_TO_STRING_PRETTY);
		vty_out(vty, "%s\n", str);
		json_object_free(top);
	}

	list_delete(&errlist);
}
예제 #10
0
static void dbus_req_success(struct dbus_req *dreq, struct json_object *obj, const char *info)
{
	dbus_req_reply(dreq, RETOK, json_object_to_json_string_ext(obj, JSON_C_TO_STRING_PLAIN), info);
}
예제 #11
0
uint8_t* ss_metadata_prepare_netflow(
    const char* source, nn_queue_t* nn_queue,
    struct store_flow_complete* flow,
    ss_ioc_entry_t* ioc_entry) {
    json_object* jobject    = NULL;
    json_object* item    = NULL;
    uint8_t*     rv      = NULL;
    uint8_t*     jstring = NULL;

    uint32_t fields;
    uint64_t (*fmt_ntoh64)(uint64_t) = netflow_swp_ntoh64;
    uint32_t (*fmt_ntoh32)(uint32_t) = netflow_swp_ntoh32;
    uint16_t (*fmt_ntoh16)(uint16_t) = netflow_swp_ntoh16;
    
    uint32_t display_mask = STORE_DISPLAY_ALL;
    fields = fmt_ntoh32(flow->hdr.fields) & display_mask;
    int utc_flag = 0;

    jobject = json_object_new_object();
    if (jobject == NULL) {
        RTE_LOG(ERR, EXTRACTOR, "could not allocate netflow json object\n");
        goto error_out;
    }

    if (SHASFIELD(TAG)) {
        item = json_object_new_int(fmt_ntoh32(flow->tag.tag));
        json_object_object_add(jobject, "tag", item);
    }
    if (SHASFIELD(RECV_TIME)) {
        item = json_object_new_string(iso_time(fmt_ntoh32(flow->recv_time.recv_sec), utc_flag));
        json_object_object_add(jobject, "flow_sec", item);
        item = json_object_new_int(fmt_ntoh32(flow->recv_time.recv_usec));
        json_object_object_add(jobject, "flow_usec", item);
    }
    if (SHASFIELD(PROTO_FLAGS_TOS)) {
        item = json_object_new_int(flow->pft.protocol);
        json_object_object_add(jobject, "ip_protocol", item);
        item = json_object_new_int(flow->pft.tcp_flags);
        json_object_object_add(jobject, "tcp_flags", item);
        item = json_object_new_int(flow->pft.tos);
        json_object_object_add(jobject, "ip_tos", item);
    }
    if (SHASFIELD(AGENT_ADDR4) || SHASFIELD(AGENT_ADDR6)) {
        item = json_object_new_string(addr_ntop_buf(&flow->agent_addr));
        json_object_object_add(jobject, "agentip", item);
    }
    if (SHASFIELD(SRC_ADDR4) || SHASFIELD(SRC_ADDR6)) {
        item = json_object_new_string(addr_ntop_buf(&flow->src_addr));
        json_object_object_add(jobject, "sip", item);
        item = json_object_new_int(fmt_ntoh16(flow->ports.src_port));
        json_object_object_add(jobject, "sport", item);
    }
    if (SHASFIELD(DST_ADDR4) || SHASFIELD(DST_ADDR6)) {
        item = json_object_new_string(addr_ntop_buf(&flow->dst_addr));
        json_object_object_add(jobject, "dip", item);
        item = json_object_new_int(fmt_ntoh16(flow->ports.dst_port));
        json_object_object_add(jobject, "dport", item);
    }
    if (SHASFIELD(GATEWAY_ADDR4) || SHASFIELD(GATEWAY_ADDR6)) {
        item = json_object_new_string(addr_ntop_buf(&flow->gateway_addr));
        json_object_object_add(jobject, "gatewayip", item);
    }
    if (SHASFIELD(PACKETS)) {
        item = json_object_new_int(fmt_ntoh64(flow->packets.flow_packets));
        json_object_object_add(jobject, "packets", item);
    }
    if (SHASFIELD(OCTETS)) {
        item = json_object_new_int(fmt_ntoh64(flow->octets.flow_octets));
        json_object_object_add(jobject, "bytes", item);
    }
    if (SHASFIELD(IF_INDICES)) {
        item = json_object_new_int(fmt_ntoh32(flow->ifndx.if_index_in));
        json_object_object_add(jobject, "sifindex", item);
        item = json_object_new_int(fmt_ntoh32(flow->ifndx.if_index_out));
        json_object_object_add(jobject, "difindex", item);
    }
    if (SHASFIELD(AGENT_INFO)) {
        item = json_object_new_string(interval_time(fmt_ntoh32(flow->ainfo.sys_uptime_ms) / 1000));
        json_object_object_add(jobject, "sys_uptime_sec", item);
        item = json_object_new_int(fmt_ntoh32(flow->ainfo.sys_uptime_ms) % 1000);
        json_object_object_add(jobject, "sys_uptime_msec", item);
        item = json_object_new_string(iso_time(fmt_ntoh32(flow->ainfo.time_sec), utc_flag));
        json_object_object_add(jobject, "sys_time_sec", item);
        item = json_object_new_int((u_long)fmt_ntoh32(flow->ainfo.time_nanosec));
        json_object_object_add(jobject, "sys_time_nsec", item);
        item = json_object_new_int(fmt_ntoh16(flow->ainfo.netflow_version));
        json_object_object_add(jobject, "netflow_version", item);
    }
    if (SHASFIELD(FLOW_TIMES)) {
        item = json_object_new_string(interval_time(fmt_ntoh32(flow->ftimes.flow_start) / 1000));
        json_object_object_add(jobject, "flow_start_sec", item);
        item = json_object_new_int(fmt_ntoh32(flow->ftimes.flow_start) % 1000);
        json_object_object_add(jobject, "flow_start_msec", item);
        item = json_object_new_string(interval_time(fmt_ntoh32(flow->ftimes.flow_finish) / 1000));
        json_object_object_add(jobject, "flow_stop_sec", item);
        item = json_object_new_int(fmt_ntoh32(flow->ftimes.flow_finish) % 1000);
        json_object_object_add(jobject, "flow_stop_msec", item);
    }
    if (SHASFIELD(AS_INFO)) {
        item = json_object_new_int(fmt_ntoh32(flow->asinf.src_as));
        json_object_object_add(jobject, "src_as", item);
        item = json_object_new_int(fmt_ntoh32(flow->asinf.src_mask));
        json_object_object_add(jobject, "src_masklen", item);
        item = json_object_new_int(fmt_ntoh32(flow->asinf.dst_as));
        json_object_object_add(jobject, "dst_as", item);
        item = json_object_new_int(fmt_ntoh32(flow->asinf.dst_mask));
        json_object_object_add(jobject, "dst_masklen", item);
    }
    if (SHASFIELD(FLOW_ENGINE_INFO)) {
        item = json_object_new_int(fmt_ntoh16(flow->finf.engine_type));
        json_object_object_add(jobject, "engine_type", item);
        item = json_object_new_int(fmt_ntoh16(flow->finf.engine_id));
        json_object_object_add(jobject, "engine_id", item);
        item = json_object_new_int((u_long)fmt_ntoh32(flow->finf.flow_sequence));
        json_object_object_add(jobject, "seq_num", item);
        item = json_object_new_int((u_long)fmt_ntoh32(flow->finf.source_id));
        json_object_object_add(jobject, "source_id", item);
    }
    if (SHASFIELD(CRC32)) {
        item = json_object_new_int(fmt_ntoh32(flow->crc32.crc32));
        json_object_object_add(jobject, "crc32", item);
    }

    item = NULL;
    rv = 0;
    
    // XXX: NOTE: String pointer is internal to JSON object.
    jstring = (uint8_t*) json_object_to_json_string_ext(jobject, JSON_C_TO_STRING_SPACED);
    rv = (uint8_t*) je_strdup((char*)jstring);
    if (!rv) goto error_out;
    
    json_object_put(jobject); jobject = NULL;
    
    return rv;
    
    error_out:
    fprintf(stderr, "could not serialize packet metadata\n");
    if (rv) { je_free(rv); rv = NULL; }
    if (jobject) { json_object_put(jobject); jobject = NULL; }
    if (item) { json_object_put(item); item = NULL; }

    return NULL;
}
예제 #12
0
void __connman_dbus_json_print_pretty(struct json_object *jobj)
{
        fprintf(stdout, "\n%s\n", json_object_to_json_string_ext(jobj,
	JSON_C_TO_STRING_PRETTY));
}
예제 #13
0
파일: test1.c 프로젝트: Bletchley13/MBA
int main(int argc, char **argv)
{
	json_object *my_string, *my_int, *my_object, *my_array;
	int i;
#ifdef TEST_FORMATTED
	int sflags = 0;
#endif

	MC_SET_DEBUG(1);

#ifdef TEST_FORMATTED
	sflags = parse_flags(argc, argv);
#endif

	my_string = json_object_new_string("\t");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	json_object_put(my_string);

	my_string = json_object_new_string("\\");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	json_object_put(my_string);

	my_string = json_object_new_string("/");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	printf("my_string.to_string(NOSLASHESCAPE)=%s\n", json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE));
	json_object_put(my_string);

	my_string = json_object_new_string("/foo/bar/baz");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));
	printf("my_string.to_string(NOSLASHESCAPE)=%s\n", json_object_to_json_string_ext(my_string, JSON_C_TO_STRING_NOSLASHESCAPE));
	json_object_put(my_string);

	my_string = json_object_new_string("foo");
	printf("my_string=%s\n", json_object_get_string(my_string));
	printf("my_string.to_string()=%s\n", json_object_to_json_string(my_string));

	my_int = json_object_new_int(9);
	printf("my_int=%d\n", json_object_get_int(my_int));
	printf("my_int.to_string()=%s\n", json_object_to_json_string(my_int));

	my_array = json_object_new_array();
	json_object_array_add(my_array, json_object_new_int(1));
	json_object_array_add(my_array, json_object_new_int(2));
	json_object_array_add(my_array, json_object_new_int(3));
	json_object_array_put_idx(my_array, 4, json_object_new_int(5));
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));

	json_object_put(my_array);

	test_array_del_idx();

	my_array = json_object_new_array();
	json_object_array_add(my_array, json_object_new_int(3));
	json_object_array_add(my_array, json_object_new_int(1));
	json_object_array_add(my_array, json_object_new_int(2));
	json_object_array_put_idx(my_array, 4, json_object_new_int(0));
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));
	json_object_array_sort(my_array, sort_fn);
	printf("my_array=\n");
	for(i=0; i < json_object_array_length(my_array); i++)
	{
		json_object *obj = json_object_array_get_idx(my_array, i);
		printf("\t[%d]=%s\n", i, json_object_to_json_string(obj));
	}
	printf("my_array.to_string()=%s\n", json_object_to_json_string(my_array));

	my_object = json_object_new_object();
	json_object_object_add(my_object, "abc", json_object_new_int(12));
	json_object_object_add(my_object, "foo", json_object_new_string("bar"));
	json_object_object_add(my_object, "bool0", json_object_new_boolean(0));
	json_object_object_add(my_object, "bool1", json_object_new_boolean(1));
	json_object_object_add(my_object, "baz", json_object_new_string("bang"));

	json_object *baz_obj = json_object_new_string("fark");
	json_object_get(baz_obj);
	json_object_object_add(my_object, "baz", baz_obj);
	json_object_object_del(my_object, "baz");

	/* baz_obj should still be valid */
	printf("baz_obj.to_string()=%s\n", json_object_to_json_string(baz_obj));
	json_object_put(baz_obj);

	/*json_object_object_add(my_object, "arr", my_array);*/
	printf("my_object=\n");
	json_object_object_foreach(my_object, key, val)
	{
		printf("\t%s: %s\n", key, json_object_to_json_string(val));
	}
예제 #14
0
int cmd_list(int argc, const char **argv)
{
	const struct option options[] = {
		OPT_STRING('b', "bus", &param.bus, "bus-id", "filter by bus"),
		OPT_STRING('r', "region", &param.region, "region-id",
				"filter by region"),
		OPT_BOOLEAN('B', "buses", &list.buses, "include bus info"),
		OPT_BOOLEAN('D', "dimms", &list.dimms, "include dimm info"),
		OPT_BOOLEAN('R', "regions", &list.regions,
				"include region info"),
		OPT_BOOLEAN('N', "namespaces", &list.namespaces,
				"include namespace info (default)"),
		OPT_BOOLEAN('i', "idle", &list.idle, "include idle devices"),
		OPT_END(),
	};
	const char * const u[] = {
		"ndctl list [<options>]",
		NULL
	};
	struct json_object *jnamespaces = NULL;
	struct json_object *jregions = NULL;
	struct json_object *jdimms = NULL;
	struct json_object *jbuses = NULL;
	struct ndctl_ctx *ctx;
	struct ndctl_bus *bus;
	int i, rc;

        argc = parse_options(argc, argv, options, u, 0);
	for (i = 0; i < argc; i++)
		error("unknown parameter \"%s\"\n", argv[i]);
	if (argc)
		usage_with_options(u, options);

	rc = ndctl_new(&ctx);
	if (rc < 0)
		return rc;

	ndctl_bus_foreach(ctx, bus) {
		struct json_object *jbus = NULL;
		struct ndctl_region *region;
		struct ndctl_dimm *dimm;

		if (!util_bus_filter(bus, param.bus))
			continue;

		if (list.buses) {
			if (!jbuses) {
				jbuses = json_object_new_array();
				if (!jbuses) {
					fail("\n");
					continue;
				}
			}

			jbus = util_bus_to_json(bus);
			if (!jbus) {
				fail("\n");
				continue;
			}
			json_object_array_add(jbuses, jbus);
		}

		ndctl_dimm_foreach(bus, dimm) {
			struct json_object *jdimm;

			/* are we emitting dimms? */
			if (!list.dimms)
				break;

			if (!list.idle && !ndctl_dimm_is_enabled(dimm))
				continue;

			if (!jdimms) {
				jdimms = json_object_new_array();
				if (!jdimms) {
					fail("\n");
					continue;
				}

				if (jbus)
					json_object_object_add(jbus, "dimms", jdimms);
			}

			jdimm = util_dimm_to_json(dimm);
			if (!jdimm) {
				fail("\n");
				continue;
			}

			/*
			 * Without a bus we are collecting dimms anonymously
			 * across the platform.
			 */
			json_object_array_add(jdimms, jdimm);
		}

		ndctl_region_foreach(bus, region) {
			struct json_object *jregion;

			if (!util_region_filter(region, param.region))
				continue;

			if (!list.regions) {
				jnamespaces = list_namespaces(region, jbus,
						jnamespaces, true);
				continue;
			}

			if (!list.idle && !ndctl_region_is_enabled(region))
				continue;

			if (!jregions) {
				jregions = json_object_new_array();
				if (!jregions) {
					fail("\n");
					continue;
				}

				if (jbus)
					json_object_object_add(jbus, "regions",
							jregions);
			}

			jregion = region_to_json(region);
			if (!jregion) {
				fail("\n");
				continue;
			}

			/*
			 * Without a bus we are collecting regions anonymously
			 * across the platform.
			 */
			json_object_array_add(jregions, jregion);
		}

		if (jbuses) {
			jdimms = NULL;
			jregions = NULL;
			jnamespaces = NULL;
		}
	}

	if (jbuses)
		display_array(jbuses);
	else if ((!!jdimms + !!jregions + !!jnamespaces) > 1) {
		struct json_object *jplatform = json_object_new_object();

		if (!jplatform) {
			fail("\n");
			return -ENOMEM;
		}

		if (jdimms)
			json_object_object_add(jplatform, "dimms", jdimms);
		if (jregions)
			json_object_object_add(jplatform, "regions", jregions);
		if (jnamespaces)
			json_object_object_add(jplatform, "namespaces",
					jnamespaces);
		printf("%s\n", json_object_to_json_string_ext(jplatform,
					jflag));
		json_object_put(jplatform);
	} else if (jdimms)
		display_array(jdimms);
	else if (jregions)
		display_array(jregions);
	else if (jnamespaces)
		display_array(jnamespaces);

	if (did_fail)
		return -ENOMEM;
	return 0;
}
예제 #15
0
void JsonTcpService::Task::execute()
{
    std::chrono::system_clock::time_point servingStarted = std::chrono::system_clock::now();
    // Composing JSON with statistics
    struct json_object* root = json_object_new_object();
    struct json_object* nfsV3Stat = json_object_new_object();
    // NFS3 procedures:
    json_object_object_add(nfsV3Stat, "null", json_object_new_int64(_service._analyzer.getNfsV3Stat().nullProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "getattr", json_object_new_int64(_service._analyzer.getNfsV3Stat().getattrProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "setattr", json_object_new_int64(_service._analyzer.getNfsV3Stat().setattrProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "lookup", json_object_new_int64(_service._analyzer.getNfsV3Stat().lookupProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "access", json_object_new_int64(_service._analyzer.getNfsV3Stat().accessProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "readlink", json_object_new_int64(_service._analyzer.getNfsV3Stat().readlinkProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "read", json_object_new_int64(_service._analyzer.getNfsV3Stat().readProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "write", json_object_new_int64(_service._analyzer.getNfsV3Stat().writeProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "create", json_object_new_int64(_service._analyzer.getNfsV3Stat().createProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "mkdir", json_object_new_int64(_service._analyzer.getNfsV3Stat().mkdirProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "symlink", json_object_new_int64(_service._analyzer.getNfsV3Stat().symlinkProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "mkdnod", json_object_new_int64(_service._analyzer.getNfsV3Stat().mknodProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "remove", json_object_new_int64(_service._analyzer.getNfsV3Stat().removeProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "rmdir", json_object_new_int64(_service._analyzer.getNfsV3Stat().rmdirProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "rename", json_object_new_int64(_service._analyzer.getNfsV3Stat().renameProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "link", json_object_new_int64(_service._analyzer.getNfsV3Stat().linkProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "readdir", json_object_new_int64(_service._analyzer.getNfsV3Stat().readdirProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "readdirplus", json_object_new_int64(_service._analyzer.getNfsV3Stat().readdirplusProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "fsstat", json_object_new_int64(_service._analyzer.getNfsV3Stat().fsstatProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "fsinfo", json_object_new_int64(_service._analyzer.getNfsV3Stat().fsinfoProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "pathconf", json_object_new_int64(_service._analyzer.getNfsV3Stat().pathconfProcsAmount.load()));
    json_object_object_add(nfsV3Stat, "commit", json_object_new_int64(_service._analyzer.getNfsV3Stat().commitProcsAmount.load()));
    json_object_object_add(root, "nfs_v3", nfsV3Stat);
    struct json_object* nfsV40Stat = json_object_new_object();
    // NFS4.0 procedures:
    json_object_object_add(nfsV40Stat, "null", json_object_new_int64(_service._analyzer.getNfsV40Stat().nullProcsAmount.load()));
    json_object_object_add(nfsV40Stat, "compound", json_object_new_int64(_service._analyzer.getNfsV40Stat().compoundProcsAmount.load()));
    // NFS4.0 operations:
    json_object_object_add(nfsV40Stat, "access", json_object_new_int64(_service._analyzer.getNfsV40Stat().accessOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "close", json_object_new_int64(_service._analyzer.getNfsV40Stat().closeOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "commit", json_object_new_int64(_service._analyzer.getNfsV40Stat().commitOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "create", json_object_new_int64(_service._analyzer.getNfsV40Stat().createOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "delegpurge", json_object_new_int64(_service._analyzer.getNfsV40Stat().delegpurgeOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "delegreturn", json_object_new_int64(_service._analyzer.getNfsV40Stat().delegreturnOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "getattr", json_object_new_int64(_service._analyzer.getNfsV40Stat().getattrOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "getfh", json_object_new_int64(_service._analyzer.getNfsV40Stat().getfhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "link", json_object_new_int64(_service._analyzer.getNfsV40Stat().linkOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "lock", json_object_new_int64(_service._analyzer.getNfsV40Stat().lockOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "lockt", json_object_new_int64(_service._analyzer.getNfsV40Stat().locktOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "locku", json_object_new_int64(_service._analyzer.getNfsV40Stat().lockuOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "lookup", json_object_new_int64(_service._analyzer.getNfsV40Stat().lookupOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "lookupp", json_object_new_int64(_service._analyzer.getNfsV40Stat().lookuppOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "nverify", json_object_new_int64(_service._analyzer.getNfsV40Stat().nverifyOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "open", json_object_new_int64(_service._analyzer.getNfsV40Stat().openOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "openattr", json_object_new_int64(_service._analyzer.getNfsV40Stat().openattrOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "open_confirm", json_object_new_int64(_service._analyzer.getNfsV40Stat().open_confirmOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "open_downgrade", json_object_new_int64(_service._analyzer.getNfsV40Stat().open_downgradeOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "putfh", json_object_new_int64(_service._analyzer.getNfsV40Stat().putfhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "putpubfh", json_object_new_int64(_service._analyzer.getNfsV40Stat().putpubfhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "putrootfh", json_object_new_int64(_service._analyzer.getNfsV40Stat().putrootfhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "read", json_object_new_int64(_service._analyzer.getNfsV40Stat().readOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "readdir", json_object_new_int64(_service._analyzer.getNfsV40Stat().readdirOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "readlink", json_object_new_int64(_service._analyzer.getNfsV40Stat().readlinkOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "remove", json_object_new_int64(_service._analyzer.getNfsV40Stat().removeOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "rename", json_object_new_int64(_service._analyzer.getNfsV40Stat().renameOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "renew", json_object_new_int64(_service._analyzer.getNfsV40Stat().renewOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "restorefh", json_object_new_int64(_service._analyzer.getNfsV40Stat().restorefhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "savefh", json_object_new_int64(_service._analyzer.getNfsV40Stat().savefhOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "secinfo", json_object_new_int64(_service._analyzer.getNfsV40Stat().secinfoOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "setattr", json_object_new_int64(_service._analyzer.getNfsV40Stat().setattrOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "setclientid", json_object_new_int64(_service._analyzer.getNfsV40Stat().setclientidOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "setclientid_confirm", json_object_new_int64(_service._analyzer.getNfsV40Stat().setclientid_confirmOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "verify", json_object_new_int64(_service._analyzer.getNfsV40Stat().verifyOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "write", json_object_new_int64(_service._analyzer.getNfsV40Stat().writeOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "release_lockowner", json_object_new_int64(_service._analyzer.getNfsV40Stat().release_lockownerOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "get_dir_delegation", json_object_new_int64(_service._analyzer.getNfsV40Stat().get_dir_delegationOpsAmount.load()));
    json_object_object_add(nfsV40Stat, "illegal", json_object_new_int64(_service._analyzer.getNfsV40Stat().illegalOpsAmount.load()));
    json_object_object_add(root, "nfs_v40", nfsV40Stat);
    struct json_object* nfsV41Stat = json_object_new_object();
    // NFS4.1 procedures:
    json_object_object_add(nfsV41Stat, "null", json_object_new_int64(_service._analyzer.getNfsV41Stat().nullProcsAmount.load()));
    json_object_object_add(nfsV41Stat, "compound", json_object_new_int64(_service._analyzer.getNfsV41Stat().compoundProcsAmount.load()));
    // NFS4.1 operations:
    json_object_object_add(nfsV41Stat, "access", json_object_new_int64(_service._analyzer.getNfsV41Stat().accessOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "close", json_object_new_int64(_service._analyzer.getNfsV41Stat().closeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "commit", json_object_new_int64(_service._analyzer.getNfsV41Stat().commitOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "create", json_object_new_int64(_service._analyzer.getNfsV41Stat().createOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "delegpurge", json_object_new_int64(_service._analyzer.getNfsV41Stat().delegpurgeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "delegreturn", json_object_new_int64(_service._analyzer.getNfsV41Stat().delegreturnOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "getattr", json_object_new_int64(_service._analyzer.getNfsV41Stat().getattrOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "getfh", json_object_new_int64(_service._analyzer.getNfsV41Stat().getfhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "link", json_object_new_int64(_service._analyzer.getNfsV41Stat().linkOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "lock", json_object_new_int64(_service._analyzer.getNfsV41Stat().lockOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "lockt", json_object_new_int64(_service._analyzer.getNfsV41Stat().locktOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "locku", json_object_new_int64(_service._analyzer.getNfsV41Stat().lockuOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "lookup", json_object_new_int64(_service._analyzer.getNfsV41Stat().lookupOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "lookupp", json_object_new_int64(_service._analyzer.getNfsV41Stat().lookuppOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "nverify", json_object_new_int64(_service._analyzer.getNfsV41Stat().nverifyOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "open", json_object_new_int64(_service._analyzer.getNfsV41Stat().openOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "openattr", json_object_new_int64(_service._analyzer.getNfsV41Stat().openattrOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "open_confirm", json_object_new_int64(_service._analyzer.getNfsV41Stat().open_confirmOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "open_downgrade", json_object_new_int64(_service._analyzer.getNfsV41Stat().open_downgradeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "putfh", json_object_new_int64(_service._analyzer.getNfsV41Stat().putfhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "putpubfh", json_object_new_int64(_service._analyzer.getNfsV41Stat().putpubfhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "putrootfh", json_object_new_int64(_service._analyzer.getNfsV41Stat().putrootfhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "read", json_object_new_int64(_service._analyzer.getNfsV41Stat().readOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "readdir", json_object_new_int64(_service._analyzer.getNfsV41Stat().readdirOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "readlink", json_object_new_int64(_service._analyzer.getNfsV41Stat().readlinkOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "remove", json_object_new_int64(_service._analyzer.getNfsV41Stat().removeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "rename", json_object_new_int64(_service._analyzer.getNfsV41Stat().renameOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "renew", json_object_new_int64(_service._analyzer.getNfsV41Stat().renewOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "restorefh", json_object_new_int64(_service._analyzer.getNfsV41Stat().restorefhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "savefh", json_object_new_int64(_service._analyzer.getNfsV41Stat().savefhOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "secinfo", json_object_new_int64(_service._analyzer.getNfsV41Stat().secinfoOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "setattr", json_object_new_int64(_service._analyzer.getNfsV41Stat().setattrOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "setclientid", json_object_new_int64(_service._analyzer.getNfsV41Stat().setclientidOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "setclientid_confirm", json_object_new_int64(_service._analyzer.getNfsV41Stat().setclientid_confirmOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "verify", json_object_new_int64(_service._analyzer.getNfsV41Stat().verifyOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "write", json_object_new_int64(_service._analyzer.getNfsV41Stat().writeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "release_lockowner", json_object_new_int64(_service._analyzer.getNfsV41Stat().release_lockownerOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "backchannel_ctl", json_object_new_int64(_service._analyzer.getNfsV41Stat().backchannel_ctlOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "bind_conn_to_session", json_object_new_int64(_service._analyzer.getNfsV41Stat().bind_conn_to_sessionOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "exchange_id", json_object_new_int64(_service._analyzer.getNfsV41Stat().exchange_idOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "create_session", json_object_new_int64(_service._analyzer.getNfsV41Stat().create_sessionOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "destroy_session", json_object_new_int64(_service._analyzer.getNfsV41Stat().destroy_sessionOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "free_stateid", json_object_new_int64(_service._analyzer.getNfsV41Stat().free_stateidOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "get_dir_delegation", json_object_new_int64(_service._analyzer.getNfsV41Stat().get_dir_delegationOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "getdeviceinfo", json_object_new_int64(_service._analyzer.getNfsV41Stat().getdeviceinfoOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "getdevicelist", json_object_new_int64(_service._analyzer.getNfsV41Stat().getdevicelistOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "layoutcommit", json_object_new_int64(_service._analyzer.getNfsV41Stat().layoutcommitOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "layoutget", json_object_new_int64(_service._analyzer.getNfsV41Stat().layoutgetOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "layoutreturn", json_object_new_int64(_service._analyzer.getNfsV41Stat().layoutreturnOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "secinfo_no_name", json_object_new_int64(_service._analyzer.getNfsV41Stat().secinfo_no_nameOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "sequence", json_object_new_int64(_service._analyzer.getNfsV41Stat().sequenceOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "set_ssv", json_object_new_int64(_service._analyzer.getNfsV41Stat().set_ssvOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "test_stateid", json_object_new_int64(_service._analyzer.getNfsV41Stat().test_stateidOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "want_delegation", json_object_new_int64(_service._analyzer.getNfsV41Stat().want_delegationOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "destroy_clientid", json_object_new_int64(_service._analyzer.getNfsV41Stat().destroy_clientidOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "reclaim_complete", json_object_new_int64(_service._analyzer.getNfsV41Stat().reclaim_completeOpsAmount.load()));
    json_object_object_add(nfsV41Stat, "illegal", json_object_new_int64(_service._analyzer.getNfsV41Stat().illegalOpsAmount.load()));
    json_object_object_add(root, "nfs_v41", nfsV41Stat);
    std::string json(json_object_to_json_string_ext(root, JSON_C_TO_STRING_PRETTY));
    json_object_put(root);

    // Sending JSON to the client
    std::size_t totalBytesSent = 0U;
    while (totalBytesSent < json.length())
    {
        if (!_service.isRunning())
        {
            LOG("WARNING: Service shutdown detected - terminating task execution");
            return;
        }
        if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - servingStarted).count() >
                static_cast<std::chrono::milliseconds::rep>(_service._maxServingDurationMs))
        {
            // TODO: Use general logging
            LOG("WARNING: A client is too slow - terminating task execution");
            return;
        }
        struct timespec writeDuration;
        AbstractTcpService::fillDuration(writeDuration);
        fd_set writeDescriptorsSet;
        FD_ZERO(&writeDescriptorsSet);
        FD_SET(socket(), &writeDescriptorsSet);
        int descriptorsCount = pselect(socket() + 1, NULL, &writeDescriptorsSet, NULL, &writeDuration, NULL);
        if (descriptorsCount < 0)
        {
            throw std::system_error{errno, std::system_category(), "Error awaiting for sending data availability on socket"};
        }
        else if (descriptorsCount == 0)
        {
            // Timeout expired
            continue;
        }
        ssize_t bytesSent = send(socket(), json.data() + totalBytesSent, json.length() - totalBytesSent, MSG_NOSIGNAL);
        if (bytesSent < 0)
        {
            std::system_error e{errno, std::system_category(), "Sending data to client error"};
            LOG("WARNING: %s", e.what());
            return;
        }
        else if (bytesSent == 0)
        {
            LOG("WARNING: Connection has been aborted by client while sending data");
            return;
        }
        totalBytesSent += bytesSent;
    }
    LOG("INFO: Serving of client has been completed");
}
예제 #16
0
int _ykp_json_export_cfg(const YKP_CONFIG *cfg, char *json, size_t len) {
	json_object *jobj = json_object_new_object();
	json_object *yprod_json = json_object_new_object();
	json_object *options_json = json_object_new_object();
	if(cfg) {
		YK_CONFIG ycfg = cfg->ykcore_config;

		int mode = MODE_OTP_YUBICO;
		struct map_st *p;
		json_object *target_config = NULL;
		json_object *prot_obj = NULL;
		int protection = ykp_get_acccode_type(cfg);

		if((ycfg.tktFlags & TKTFLAG_OATH_HOTP) == TKTFLAG_OATH_HOTP){
			if((ycfg.cfgFlags & CFGFLAG_CHAL_HMAC) == CFGFLAG_CHAL_HMAC) {
				mode = MODE_CHAL_HMAC;
			} else if((ycfg.cfgFlags & CFGFLAG_CHAL_YUBICO) == CFGFLAG_CHAL_YUBICO) {
				mode = MODE_CHAL_YUBICO;
			} else {
				mode = MODE_OATH_HOTP;
			}
		}
		else if((ycfg.cfgFlags & CFGFLAG_STATIC_TICKET) == CFGFLAG_STATIC_TICKET) {
			mode = MODE_STATIC_TICKET;
		}

		for(p = _modes_map; p->flag; p++) {
			if(p->flag == mode) {
				json_object *jmode = json_object_new_string(p->json_text);
				json_object_object_add(yprod_json, "mode", jmode);
				break;
			}
		}

		if(cfg->command == SLOT_CONFIG) {
			target_config = json_object_new_int(1);
		} else if(cfg->command == SLOT_CONFIG2) {
			target_config = json_object_new_int(2);
		}
		if(target_config) {
			json_object_object_add(yprod_json, "targetConfig", target_config);
		}

		if(protection == YKP_ACCCODE_NONE) {
			prot_obj = json_object_new_string("none");
		} else if(protection == YKP_ACCCODE_RANDOM) {
			prot_obj = json_object_new_string("random");
		} else if(protection == YKP_ACCCODE_SERIAL) {
			prot_obj = json_object_new_string("id");
		}
		if(prot_obj) {
			json_object_object_add(yprod_json, "protection", prot_obj);
		}

		json_object_object_add(jobj, "yubiProdConfig", yprod_json);
		json_object_object_add(yprod_json, "options", options_json);


		if(ycfg.fixedSize != 0 && mode != MODE_STATIC_TICKET) {
			json_object *jPrefix;
			char prefix[5] = {0};

			json_object *scope;
			if(mode == MODE_OTP_YUBICO &&
					ycfg.fixed[0] == 0x00 && ycfg.fixed[1] == 0x00) {
				scope = json_object_new_string("yubiCloud");
			} else {
				scope = json_object_new_string("privatePrefix");
			}
			json_object_object_add(yprod_json, "scope", scope);

			yubikey_modhex_encode(prefix, (const char*)ycfg.fixed, 2);
			if(mode == MODE_OATH_HOTP) {
				int flag = ycfg.cfgFlags & CFGFLAG_OATH_FIXED_MODHEX;
				json_object *fixed_modhex = json_object_new_boolean(
						flag == CFGFLAG_OATH_FIXED_MODHEX ? 1 : 0);
				json_object_object_add(options_json, "fixedModhex", fixed_modhex);

				if(flag == 0) {
					yubikey_hex_encode(prefix, (const char*)ycfg.fixed, 2);
				} else if(flag == CFGFLAG_OATH_FIXED_MODHEX1) {
					yubikey_hex_encode(prefix + 2, (const char*)ycfg.fixed + 1, 1);
				}
			}
			jPrefix = json_object_new_string(prefix);
			json_object_object_add(yprod_json, "prefix", jPrefix);
		} else if(mode != MODE_STATIC_TICKET) {
			json_object *scope = json_object_new_string("noPublicId");
			json_object_object_add(yprod_json, "scope", scope);
		}

		if(mode == MODE_OATH_HOTP) {
			json_object *oathDigits;
			json_object *randomSeed;
			if((ycfg.cfgFlags & CFGFLAG_OATH_HOTP8) == CFGFLAG_OATH_HOTP8) {
				oathDigits = json_object_new_int(8);
			} else {
				oathDigits = json_object_new_int(6);
			}
			json_object_object_add(options_json, "oathDigits", oathDigits);

			if((ycfg.uid[5] == 0x01 || ycfg.uid[5] == 0x00) && ycfg.uid[4] == 0x00) {
				json_object *fixedSeedvalue = json_object_new_int(ycfg.uid[5] << 4);
				json_object_object_add(options_json, "fixedSeedvalue", fixedSeedvalue);
				randomSeed = json_object_new_boolean(0);
			} else {
				randomSeed = json_object_new_boolean(1);
			}
			json_object_object_add(options_json, "randomSeed", randomSeed);
		}

		for(p = _ticket_flags_map; p->flag; p++) {
			if(!p->json_text) {
				continue;
			}
			if(p->mode && (mode & p->mode) == mode) {
				int set = (ycfg.tktFlags & p->flag) == p->flag;
				json_object *jsetting = json_object_new_boolean(set);
				json_object_object_add(options_json, p->json_text, jsetting);
			}
		}

		for(p = _config_flags_map; p->flag; p++) {
			if(!p->json_text) {
				continue;
			}
			if(p->mode && (mode & p->mode) == mode) {
				int set = (ycfg.cfgFlags & p->flag) == p->flag;
				json_object *jsetting = json_object_new_boolean(set);
				json_object_object_add(options_json, p->json_text, jsetting);
			}
		}

		for(p = _extended_flags_map; p->flag; p++) {
			if(!p->json_text) {
				continue;
			}
			if(p->mode && (mode & p->mode) == mode) {
				int set = (ycfg.extFlags & p->flag) == p->flag;
				json_object *jsetting = json_object_new_boolean(set);
				json_object_object_add(options_json, p->json_text, jsetting);
			}
		}
	}

#ifdef HAVE_JSON_OBJECT_TO_JSON_STRING_EXT
	strncpy(json, json_object_to_json_string_ext(jobj, JSON_C_TO_STRING_PRETTY), len);
#else
	strncpy(json, json_object_to_json_string(jobj), len);
#endif

	/* free the root object, will free all children */
	json_object_put(jobj);
	return strlen(json);
}
예제 #17
0
파일: json.c 프로젝트: Goos/r3
const char * r3_node_to_json_string_ext(const node * n, int options) {
    json_object *obj = r3_node_to_json_object(n);
    return json_object_to_json_string_ext(obj, options);
}
예제 #18
0
파일: json.c 프로젝트: OpenSIPS/opensips
int pv_get_json_ext(struct sip_msg* msg,  pv_param_t* pvp, pv_value_t* val, int flags)
{

	pv_json_t * var ;
	json_t * obj;
	json_name * id = (json_name *) pvp->pvn.u.dname;
	UNUSED(id);

	if( expand_tag_list( msg, ((json_name *)pvp->pvn.u.dname)->tags ) < 0)
	{
		LM_ERR("Cannot expand variables in path\n");
		return pv_get_null( msg, pvp, val);
	}


	var = get_pv_json(pvp);

	if( var == NULL )
	{
		/* this is not an error - we simply came across a json spec
		 * pointing a json var which was never set/init */
		LM_DBG("Variable named:%.*s not found\n",id->name.len,id->name.s);
		return pv_get_null( msg, pvp, val);
	}

	obj = get_object(var, pvp, NULL, 0, 0);

	memset(val, 0, sizeof(pv_value_t));

	if( obj == NULL )
		return pv_get_null( msg, pvp, val);

	if (pvp->pvi.type == PV_IDX_INT) {
		if (pv_json_iterate(&obj, pvp, id, val) < 0) {
			LM_DBG("Failed to iterate\n");
			return pv_get_null(msg, pvp, val);
		}

		if (val->flags == PV_VAL_STR || val->flags == PV_VAL_NULL)
			/* val is set */
			return 0;
		/* else we got an object */
	} else if (pvp->pvi.type == PV_IDX_ALL) {
		LM_ERR("\"[*]\" index only supported in for each statement\n");
		return pv_get_null(msg, pvp, val);
	}

	if( json_object_is_type(obj, json_type_int) )
	{
		val->rs.s = sint2str(json_object_get_int(obj), &val->rs.len);
		val->ri = json_object_get_int(obj);;
		val->flags |= PV_VAL_INT|PV_TYPE_INT|PV_VAL_STR;

	}
	else if( json_object_is_type(obj, json_type_string))
	{
		val->flags = PV_VAL_STR;
		val->rs.s = (char*)json_object_get_string( obj );
#if JSON_C_VERSION_NUM >= JSON_C_VERSION_010
		val->rs.len = json_object_get_string_len( obj );
#else
		val->rs.len = strlen(val->rs.s);
#endif
	} else {
		val->flags = PV_VAL_STR;
		val->rs.s = (char*)json_object_to_json_string_ext( obj, flags);
		val->rs.len = strlen(val->rs.s);
	}

	return 0;
}
/*
 * Convert in-memory LUKS2 header and write it to disk.
 * This will increase sequence id, write both header copies and calculate checksum.
 */
int LUKS2_disk_hdr_write(struct crypt_device *cd, struct luks2_hdr *hdr, struct device *device)
{
	char *json_area;
	const char *json_text;
	size_t json_area_len;
	int r;

	if (hdr->version != 2) {
		log_dbg("Unsupported LUKS2 header version (%u).", hdr->version);
		return -EINVAL;
	}

	if (hdr->hdr_size != LUKS2_HDR_16K_LEN) {
		log_dbg("Unsupported LUKS2 header size (%zu).", hdr->hdr_size);
		return -EINVAL;
	}

	r = LUKS2_check_device_size(cd, crypt_metadata_device(cd), LUKS2_hdr_and_areas_size(hdr->jobj), 1);
	if (r)
		return r;

	/*
	 * Allocate and zero JSON area (of proper header size).
	 */
	json_area_len = hdr->hdr_size - LUKS2_HDR_BIN_LEN;
	json_area = malloc(json_area_len);
	if (!json_area)
		return -ENOMEM;
	memset(json_area, 0, json_area_len);

	/*
	 * Generate text space-efficient JSON representation to json area.
	 */
	json_text = json_object_to_json_string_ext(hdr->jobj,
			JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE);
	if (!json_text || !*json_text) {
		log_dbg("Cannot parse JSON object to text representation.");
		free(json_area);
		return -ENOMEM;
	}
	if (strlen(json_text) > (json_area_len - 1)) {
		log_dbg("JSON is too large (%zu > %zu).", strlen(json_text), json_area_len);
		free(json_area);
		return -EINVAL;
	}
	strncpy(json_area, json_text, json_area_len);

	/* Increase sequence id before writing it to disk. */
	hdr->seqid++;

	r = device_write_lock(cd, device);
	if (r) {
		log_err(cd, _("Failed to acquire write device lock."));
		free(json_area);
		return r;
	}

	/* Write primary and secondary header */
	r = hdr_write_disk(device, hdr, json_area, 0);
	if (!r)
		r = hdr_write_disk(device, hdr, json_area, 1);

	if (r)
		log_dbg("LUKS2 header write failed (%d).", r);

	device_write_unlock(device);

	/* FIXME: try recovery here? */

	free(json_area);
	return r;
}