Skip to content
Snippets Groups Projects
common.c 1.83 KiB
#include "common.h"

/*
TODO:
	Initial
		1. system call //"ubus call router.net ipv4_routes | grep -B 7 \"usb0\" | grep \"flag.
*H\" -B 4 | grep destination"
		2. grep for [H]ost flag
		3. find IP

	Once Successful
		1. Implement by invoking ubus

*/

char *get_ip(char *if_name)
{
	char response[1024] = {0};
	int rv;
	FILE *fp = popen("ubus call router.net ipv4_routes | grep -B 7 \"usb0\" | grep \"flag.*H\" -B 4 | grep destination | cut -d ' ' -f2 | cut -d '\"' -f2", "r");

	fscanf(fp, "%s", response);
	pclose(fp);
	printf("%s\n", response);

	return strdup(response);
}

int print_to_ubus(struct json_object *parsed_response, struct ubus_context *ctx, struct ubus_request_data *req)
{
	struct blob_buf bb;

	memset(&bb, 0, sizeof(struct blob_buf));
	blob_buf_init(&bb, 0);
	bb = json_to_blob(parsed_response, bb);
	ubus_send_reply(ctx, req, bb.head);
	blob_buf_free(&bb);

	json_object_put(parsed_response);
	return 0;
}

struct blob_buf json_to_blob(struct json_object *response, struct blob_buf bb)
{
	void *arr, *obj;
	int i;

	json_object_object_foreach(response, key, val) {
		int val_type = json_object_get_type(val);

		switch (val_type) {
		case json_type_int:
			blobmsg_add_u32(&bb, key, json_object_get_int(val));
			break;
		case json_type_double:
			blobmsg_add_double(&bb, key, json_object_get_double(val));
			break;
		case json_type_string:
			blobmsg_add_string(&bb, key, json_object_get_string(val));
			break;
		case json_type_array:
			arr = blobmsg_open_array(&bb, key);
			for (i = 0; i < json_object_array_length(val); i++) {
				// add open table
				bb = json_to_blob(json_object_array_get_idx(val, i), bb);
				// add close table
			}
			blobmsg_close_array(&bb, arr);
			break;
		case json_type_object:
			obj = blobmsg_open_table(&bb, key);
			bb = json_to_blob(val, bb);
			blobmsg_close_table(&bb, obj);
			break;
		}
	}

	return bb;
}