Skip to contentSkip to conversation

Add JSON output options to 'iw' for scan results

PATCH In review Isaev Ruslan 4 participants 4 messages Mar 12, 2024 – Mar 26, 2024 Kbuild

lore
Share & tools
lore
#0 lore raw

PATCH v12 1/1 Add JSON output options to 'iw' for scan results

branch: master
Commit: c49eb9e

v12 changes:
- all json/plaintext printing functions renamed
All JSON printing functions have been renamed to reflect their functionality more accurately. Since all the printing functions operate similarly to printf, their names have been changed
accordingly and now end with 'f'.
For example, json_arr_open() is now iw_arr_openf(const char *fmt, ...), json_obj_open() is now iw_obj_openf(const char *fmt, ...) and so on.

- The patch has been rebased onto the latest update of the master branch. Commit c49eb9e.

v11 changes:
- patch rebased to master branch
- iw_json_print.c: iw_printf() add double int format "%d.%d", "%i.%i" to parse as number
- scan.c: add json output for print_interworking(), print_11u_advert(), print_11u_rcon()

v10 changes:
- revert printable text for iw <dev> scan to original
- add iw_json_format_key() for json output. It will replace commas with spaces, convert text to lowercase, remove multiple spaces, replace spaces with _

Examples:
text output:

root@ru-fap650-a3:/tmp# ./iw phy0-ap0 scan | head -n250
00:0c:43:26:60:18:
        Ifname: phy0-ap0
        Status:
        TSF:
                usec: 321559832898
                dd: 3
                hh: 17
                mm: 19
                ss: 19
        Frequency: 5180
        Beacon Interval, TUs: 100
        Capability:
                ESS
                Privacy
                ShortPreamble
        Capability Raw Value: 0x0031
        Signal: -72.00 dBm
        Last Seen Ago, ms: 2740
        BSS Probe Response Data Frame:
                SSID:
                        SSID: tobe52
                Supported rates:
                        Rates:
                                6.0*
                                9.0
                                12.0*
                                18.0
                                24.0*
                                36.0
                                48.0
                                54.0
                DS Parameter set:
                        Channel: 36
                HT capabilities:
                        capabilities_value: 0x9ee
                        capabilities:
                                HT20/HT40
                                SM Power Save disabled
                                RX HT20 SGI
                                RX HT40 SGI
                                TX STBC
                                RX STBC 1-stream
                                Max AMSDU length: 7935 bytes
                                No DSSS/CCK HT40
                        max_ampdu_length: 65535
                        max_ampdu_exponent: 0x003
                        min_rx_ampdu_time_spacing: 4 usec
                        min_rx_ampdu_time_spacing_value: 0x005
                        ht_rx_mcs_idx_supported:
                                0-32
                HT operation:
                        Primary Channel: 36
                        Secondary Channel Offset: above
                        STA Channel Width: any
                        RIFS: 0
                        HT Protection: no
                        Non-GF Present: 0
                        OBSS Non-GF Present: 0
                        Dual Beacon: 0
                        Dual CTS Protection: 0
                        STBC Beacon: 0
                        L-SIG TXOP Protection: 0
                        PCO Active: 0
                        PCO Phase: 0
                RSN:
                        version: 1
                        group_cipher_data:
                                CCMP
                        Pairwise Ciphers Data:
                                CCMP
                        Authentication Suites Data:
                                PSK
                        Capabilities Raw Value: 0x0000
                        Capabilities:
                                1-PTKSA-RC
                                1-GTKSA-RC
                Extended capabilities:
                        Capabilities:
                                BSS Transition
                                Operating Mode Notification
                        Max Number Of MSSDUs In A-MSDU: -1
                BSS Load:
                        Station Count: 0
                        Channel Utilisation: 0
                        Available Admission Capacity: 31250
                WMM:
                        Version: 1
                        BE:
                                CW: 15-1023
                                AIFSN: 3
                        BK:
                                CW: 15-1023
                                AIFSN: 7
                        VI:
                                CW: 7-15
                                AIFSN: 2
                                TXOP_usec: 3008
                        VO:
                                CW: 3-7
                                AIFSN: 2
                                TXOP_usec: 1504
                Country:
                        Country: DB
                        Environment: Indoor/Outdoor
                        Channels:
                                36:
                                        First: 36
                                        End: 64
                                        Max power, dBm: 20
                                100:
                                        First: 100
                                        End: 140
                                        Max power, dBm: 20
                                149:
                                        First: 149
                                        End: 165
                                        Max power, dBm: 20
                VHT capabilities:
                        VHT Capabilities:
                                VHT Capabilities Raw Value: 0x33c379b1
                                Data: 7991
                        Supported Channel Width:
                        RX LDPC: true
                        short GI (80 MHz): true
                        TX STBC: true
                        SU Beamformer: true
                        SU Beamformee: true
                        +HTC-VHT: true
                        RX antenna pattern consistency: true
                        TX antenna pattern consistency: true
                        VHT RX MCS set:
                                1 streams: MCS 0-9
                                2 streams: MCS 0-9
                                3 streams: MCS 0-9
                                4 streams: MCS 0-9
                                5 streams: not supported
                                6 streams: not supported
                                7 streams: not supported
                                8 streams: not supported
                        VHT RX highest supported Mbps: 1560
                        VHT TX MCS set:
                                1 streams: MCS 0-9
                                2 streams: MCS 0-9
                                3 streams: MCS 0-9
                                4 streams: MCS 0-9
                                5 streams: not supported
                                6 streams: not supported
                                7 streams: not supported
                                8 streams: not supported
                        VHT TX Highest Supported Mbps: 1560
                        VHT extended NSS Supported: (null)
                VHT operation:
                        Channel Width: 1 (80 MHz)
                        Center Freq Segment 1: 42
                        Center freq Segment 2: 0
                        VHT Basic MCS Set: 0xffaa

tail part trimmed

Same with pretty json:

root@ru-fap650-a3:/tmp# ./iw -jj phy0-ap0 scan | head -n250
{
    "00:0c:43:26:60:18": {
        "ifname": "phy0-ap0",
        "status": "",
        "tsf": {
            "usec": 321643188840,
            "dd": 3,
            "hh": 17,
            "mm": 20,
            "ss": 43
        },
        "frequency": 5180,
        "beacon_interval_tus": 100,
        "capability": [ "ESS","Privacy","ShortPreamble" ],
        "capability_raw_value": "0x0031",
        "signal": "-79.00 dBm",
        "last_seen_ago_ms": 2550,
        "bss_probe_response_data_frame": {
            "ssid": {
                "ssid": "tobe52"
            },
            "supported_rates": {
                "rates": [ "6.0*","9.0","12.0*","18.0","24.0*","36.0","48.0","54.0" ]
            },
            "ds_parameter_set": {
                "channel": 36
            },
            "ht_capabilities": {
                "capabilities_value": "0x9ee",
                "capabilities": [ "HT20/HT40","SM Power Save disabled","RX HT20 SGI","RX HT40 SGI","TX STBC","RX STBC 1-stream","Max AMSDU length: 7935 bytes","No DSSS/CCK HT40" ],
                "max_ampdu_length": 65535,
                "max_ampdu_exponent": "0x003",
                "min_rx_ampdu_time_spacing": "4 usec",
                "min_rx_ampdu_time_spacing_value": "0x005",
                "ht_rx_mcs_idx_supported": [ "0-32" ]
            },
            "ht_operation": {
                "primary_channel": 36,
                "secondary_channel_offset": "above",
                "sta_channel_width": "any",
                "rifs": 0,
                "ht_protection": "no",
                "non-gf_present": 0,
                "obss_non-gf_present": 0,
                "dual_beacon": 0,
                "dual_cts_protection": 0,
                "stbc_beacon": 0,
                "l-sig_txop_protection": 0,
                "pco_active": 0,
                "pco_phase": 0
            },
            "rsn": {
                "version": 1,
                "group_cipher_data": [ "CCMP" ],
                "pairwise_ciphers_data": [ "CCMP" ],
                "authentication_suites_data": [ "PSK" ],
                "capabilities_raw_value": "0x0000",
                "capabilities": [ "1-PTKSA-RC","1-GTKSA-RC" ]
            },
            "extended_capabilities": {
                "capabilities": [ "BSS Transition","Operating Mode Notification" ],
                "max_number_of_mssdus_in_a-msdu": -1
            },
            "bss_load": {
                "station_count": 0,
                "channel_utilisation": 0,
                "available_admission_capacity": 31250
            },
            "wmm": {
                "version": 1,
                "be": {
                    "cw": "15-1023",
                    "aifsn": 3
                },
                "bk": {
                    "cw": "15-1023",
                    "aifsn": 7
                },
                "vi": {
                    "cw": "7-15",
                    "aifsn": 2,
                    "txop_usec": 3008
                },
                "vo": {
                    "cw": "3-7",
                    "aifsn": 2,
                    "txop_usec": 1504
                }
            },
            "country": {
                "country": "DB",
                "environment": "Indoor/Outdoor",
                "channels": {
                    "36": {
                        "first": 36,
                        "end": 64,
                        "max_power_dbm": 20
                    },
                    "100": {
                        "first": 100,
                        "end": 140,
                        "max_power_dbm": 20
                    },
                    "149": {
                        "first": 149,
                        "end": 165,
                        "max_power_dbm": 20
                    }
                }
            },
            "vht_capabilities": {
                "vht_capabilities": {
                    "vht_capabilities_raw_value": "0x33c379b1",
                    "data": "7991"
                },
                "supported_channel_width": {},
                "rx_ldpc": "true",
                "short_gi_(80_mhz)": "true",
                "tx_stbc": "true",
                "su_beamformer": "true",
                "su_beamformee": "true",
                "+htc-vht": "true",
                "rx_antenna_pattern_consistency": "true",
                "tx_antenna_pattern_consistency": "true",
                "vht_rx_mcs_set": {
                    "1_streams": "MCS 0-9",
                    "2_streams": "MCS 0-9",
                    "3_streams": "MCS 0-9",
                    "4_streams": "MCS 0-9",
                    "5_streams": "not supported",
                    "6_streams": "not supported",
                    "7_streams": "not supported",
                    "8_streams": "not supported"
                },
                "vht_rx_highest_supported_mbps": 1560,
                "vht_tx_mcs_set": {
                    "1_streams": "MCS 0-9",
                    "2_streams": "MCS 0-9",
                    "3_streams": "MCS 0-9",
                    "4_streams": "MCS 0-9",
                    "5_streams": "not supported",
                    "6_streams": "not supported",
                    "7_streams": "not supported",
                    "8_streams": "not supported"
                },
                "vht_tx_highest_supported_mbps": 1560,
                "vht_extended_nss_supported": "(null)"
            },
            "vht_operation": {
                "channel_width": "1 (80 MHz)",
                "center_freq_segment_1": 42,
                "center_freq_segment_2": 0,
                "vht_basic_mcs_set": "0xffaa"
            }
        }
    }
}

tail part trimmed

v9 changes:
- remove binary json/iw_json_printer

v8 changes:
- json_print.c rewritten.
- all printf() calls to print iw scan info replaced with new iw_printf()

example text output:

root@ru-fap650-a3:/tmp# ./iw phy0-ap0 scan | head -n 30
00:0c:43:26:60:18:
        ifname: phy0-ap0
        status:
        TSF:
                usec: 278491388966
                dd: 3
                hh: 5
                mm: 21
                ss: 31
        freq: 5180
        beacon_interval_tus: 100
        capability:
                ESS
                Privacy
                ShortPreamble
        capability_raw: 0x0031
        signal: -78.00 dBm
        last_seen_ms_ago: 2540
        bss_probe_resp_data_frame:
                SSID:
                        SSID: tobe52
                Supported rates:
                        rates:
                                6.0*
                                9.0
                                12.0*
                                18.0
                                24.0*
                                36.0
                                48.0
root@ru-fap650-a3:/tmp#

example pretty json output:

root@ru-fap650-a3:/tmp# ./iw -jj phy0-ap0 scan | head -n 30
{
    "00:0c:43:26:60:18": {
        "ifname": "phy0-ap0",
        "status": "",
        "TSF": {
            "usec": 278643858296,
            "dd": 3,
            "hh": 5,
            "mm": 24,
            "ss": 3
        },
        "freq": 5180,
        "beacon_interval_tus": 100,
        "capability": [ "ESS","Privacy","ShortPreamble" ],
        "capability_raw": "0x0031",
        "signal": "-77.00 dBm",
        "last_seen_ms_ago": 2740,
        "bss_probe_resp_data_frame": {
            "SSID": {
                "SSID": "tobe52"
            },
            "Supported rates": {
                "rates": [ "6.0*","9.0","12.0*","18.0","24.0*","36.0","48.0","54.0" ]
            },

v7 changes:
- binaries json/a json/a.out removed

v6 changes:
- add iw_printf(const char *key, const char *fmt, ...)
- rewrite print_ssid_escaped() as a demo with new concept

void print_ssid_escaped(const uint8_t len, const uint8_t *data) {
	char *escaped_ssid = ssid_escape(len, data);
	iw_printf("SSID", "%s", escaped_ssid);
}

How it works:
text output:
Tabs for text output is based on json depth. For example: ssid is depth 3 or something so 3 tabs will be printed before "SSID: %s"

json output:
iw_printf will print number (without "") or text based on passed format.

For all number formats. Formats: %d %i %p %hu etc will print without quotes If else format is passed iw_print will print it with quotes. To make it work some new functions added.

branch: v5.19

This commit introduces the ability to output scan results from 'iw' in JSON format, similar to the 'ip' utility from the iproute2 package. The addition aims to enhance the tool's usability and scriptability by providing a structured data format option.

Two new command-line options are added:
- '-j': Outputs scan results in compact JSON format.
- '-jj': Outputs scan results in pretty-printed JSON format.

The implementation focuses on modifying the printing functions to format the output as JSON without altering the existing netlink response parsing logic. This patch demonstrates the concept with scan results, showcasing the potential for expanding JSON support to other 'iw' functionalities.

If these changes prove valuable, I am prepared to continue working on extending JSON output support throughout the tool. Feedback is welcome and appreciated.

Thank you.

---
 Makefile             |    2 +-
 iw.c                 |   27 +-
 json/Makefile        |   19 +
 json/iw_json_print.c |  263 +++++++++
 json/iw_json_print.h |   35 ++
 json/json_writer.c   |  298 ++++++++++
 json/json_writer.h   |   76 +++
 json/main.c          |   49 ++
 scan.c               | 1289 ++++++++++++++++++++----------------------
 util.c               |  436 ++++++++------
 10 files changed, 1641 insertions(+), 853 deletions(-)
 create mode 100644 json/Makefile
 create mode 100644 json/iw_json_print.c
 create mode 100644 json/iw_json_print.h
 create mode 100644 json/json_writer.c
 create mode 100644 json/json_writer.h
 create mode 100644 json/main.c
Makefile +1 -1
index 17be33f..42de11c 100644
@@ -20,7 +20,7 @@ CFLAGS += -Wdeclaration-after-statement
 CFLAGS += $(CFLAGS_EVAL)
 CFLAGS += $(EXTRA_CFLAGS)
 
-_OBJS := $(sort $(patsubst %.c,%.o,$(wildcard *.c)))
+_OBJS := $(sort $(patsubst %.c,%.o,$(wildcard *.c) json/json_writer.c json/iw_json_print.c))
 VERSION_OBJS := $(filter-out version.o, $(_OBJS))
 OBJS := $(VERSION_OBJS) version.o
 
iw.c +26 -1
index 35308ba..2273b05 100644
@@ -24,6 +24,8 @@
 #include "nl80211.h"
 #include "iw.h"
 
+#include "json/iw_json_print.h"
+
 /* libnl 1.x compatibility code */
 #if !defined(CONFIG_LIBNL20) && !defined(CONFIG_LIBNL30)
 static inline struct nl_handle *nl_socket_alloc(void)
@@ -181,7 +183,11 @@ static void __usage_cmd(const struct cmd *cmd, char *indent, bool full)
 static void usage_options(void)
 {
 	printf("Options:\n");
-	printf("\t--debug\t\tenable netlink debugging\n");
+	printf(""
+	"\t--debug\t\tenable netlink debugging\n"
+	"\t-j     \t\tjson output\n"
+	"\t-jj    \t\tjson pretty output\n"
+	"");
 }
 
 static const char *argv0;
@@ -592,6 +598,21 @@ int main(int argc, char **argv)
 		argv++;
 	}
 
+	if (argc > 0 && strcmp(*argv, "-j") == 0) {
+		iw_obj_new(1, 0); //pretty print disabled
+		argc--;
+		argv++;
+	}
+
+	if (argc > 0 && strcmp(*argv, "-jj") == 0) {
+		iw_obj_new(1, 1); //pretty print enabled
+		argc--;
+		argv++;
+	}
+
+	//call iw_obj_new() anyway to track depth
+	if (!iw_json) iw_obj_new(0, 0);
+
 	if (argc > 0 && strcmp(*argv, "--version") == 0) {
 		version();
 		return 0;
@@ -648,5 +669,9 @@ int main(int argc, char **argv)
 
 	nl80211_cleanup(&nlstate);
 
+	//close root json object and deinit jsonw
+	if(iw_json){
+		iw_obj_del();
+	}
 	return err;
 }
json/Makefile new file +19 -0
new file mode 100644
index 0000000..d7b0858
@@ -0,0 +1,19 @@
+CC = gcc
+CFLAGS = -Wall -Wextra -Iinclude
+
+SRC_DIR = .
+OBJ_DIR = .
+
+SRC_FILES = $(wildcard $(SRC_DIR)/*.c)
+OBJ_FILES = $(patsubst $(SRC_DIR)/%.c,$(OBJ_DIR)/%.o,$(SRC_FILES))
+
+all: iw_json_printer
+
+$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
+	$(CC) $(CFLAGS) -c $< -o $@
+
+iw_json_printer: $(OBJ_FILES)
+	$(CC) $(CFLAGS) $^ -o $@
+
+clean:
+	rm -f $(OBJ_DIR)/*.o iw_json_printer
json/iw_json_print.c new file +263 -0

264 lines not on this page · raw message

json/iw_json_print.h new file +35 -0
new file mode 100644
index 0000000..be58e31
@@ -0,0 +1,35 @@
+#ifndef _JSON_PRINT_H_
+#define _JSON_PRINT_H_
+#include "json_writer.h"
+
+extern int iw_json;
+
+json_writer_t *iw_get_json_writer(void);
+
+void iw_obj_new(int json, bool is_pretty);
+void iw_obj_del(void);
+void iw_obj_openf(const char *fmt, ...);
+void iw_obj_close(void);
+void iw_arr_openf(const char *fmt, ...);
+void iw_arr_close(void);
+
+#define _PRINT_FUNC(type_name, type)         \
+	void json_print_##type_name(const char *key, type value)
+_PRINT_FUNC(u8, uint8_t);
+_PRINT_FUNC(u16, uint16_t);
+_PRINT_FUNC(u32, uint32_t);
+_PRINT_FUNC(u64, uint64_t);
+_PRINT_FUNC(s8, int8_t);
+_PRINT_FUNC(s16, int16_t);
+_PRINT_FUNC(s32, int32_t);
+_PRINT_FUNC(s64, int64_t);
+_PRINT_FUNC(int, int);
+_PRINT_FUNC(float, double);
+_PRINT_FUNC(bool, bool);
+#undef _PRINT_FUNC
+
+void iw_print_stringf(const char *key, const char *fmt, ...);
+void iw_print_numf(const char *key, const char *fmt, ...);
+void iw_printf(const char *key, const char *fmt, ...);
+
+#endif /* _JSON_PRINT_H_ */
json/json_writer.c new file +298 -0

298 lines not on this page · raw message

json/json_writer.h new file +76 -0

76 lines not on this page · raw message

json/main.c new file +49 -0

49 lines not on this page · raw message

scan.c +618 -671

2,201 lines not on this page · raw message

util.c +256 -180

436 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.42.0

Part of the diff is not shown here. View the raw message.

#1 lore raw

Hmm.

Honestly, this output is awful. I can kind of understand where that's coming from (the desire to have an object created for each element in the frame, but ...)

Quoted 7 lines
        TSF:
                usec: 321559832898
                dd: 3
                hh: 17
                mm: 19
                ss: 19

Really? We used to print this as

	TSF: 0 usec (0d, 00:00:00)

(not sure why all zeroes here but anyway)

Quoted 7 lines
        Frequency: 5180
        Beacon Interval, TUs: 100
        Capability:
                ESS
                Privacy
                ShortPreamble
        Capability Raw Value: 0x0031
	capability: ESS Privacy SpectrumMgmt RadioMeasure (0x1111)
Quoted 5 lines
        Signal: -72.00 dBm
        Last Seen Ago, ms: 2740
        BSS Probe Response Data Frame:
                SSID:
                        SSID: tobe52

That's just silly.

Quoted 10 lines
                Supported rates:
                        Rates:
                                6.0*
                                9.0
                                12.0*
                                18.0
                                24.0*
                                36.0
                                48.0
                                54.0
	Supported rates: 6.0* 9.0 12.0* 18.0 24.0* 36.0 48.0 54.0 

And that stuff is a really pointless output in JSON, for JSON it'd be much more useful to output an object with actual (integer) values, and a flag to indicate 'basic', or something.

Anyway ... I think you're hyper-focused on exactly the wrong thing.

Arguably, for scan results, the right thing to do would be to just output the raw elements in the JSON, and not do any of this parsing. Then you can use your favourite parsing library (dpkt? tshark? ...) to actually understand the data there. We really don't need to expose the element parsing logic of iw, especially not in a bad way like this.

Also, outputting the *string* data in a machine-readable format like you do now has very little value, and yet it ties us to a specific output format that we'd probably have to consider stable. Bad idea.

So I guess I'm saying yhou should abandon this line of changes in this code entirely.

Much more interesting, IMHO, would be to focus in pretty much anything _else_ in the iw code, e.g. the output of 'iw dev', 'iw wlan0 info', statistics, etc. Maybe 'iw list' and similar too.

Although I suspect that what we really need is better access for tools from nl80211. Maybe the "JSON" output format should just dump the raw nl80211 message attributes that are involved, or something.

johannes

#2 lore raw

python nl80211 libraries?

Quoted 3 lines · Johannes Berg

Although I suspect that what we really need is better access for tools from nl80211. Maybe the "JSON" output format should just dump the raw nl80211 message attributes that are involved, or something.

Related to this, are there any recent/decent python libraries for using nl80211? A quick google search found these:

https://pypi.org/project/libnl3/
https://git.sipsolutions.net/pynl80211.git
https://pyroute2.org/

What do people use nowadays?

Signature · 3 lines
https://patchwork.kernel.org/project/linux-wireless/list/

https://wireless.wiki.kernel.org/en/developers/documentation/submittingpatches
#3 lore raw
In reply to Johannes Berg

On Mon Mar 25, 2024 at 5:32 PM CET, Johannes Berg wrote:
[...]

Quoted 20 lines

And that stuff is a really pointless output in JSON, for JSON it'd be much more useful to output an object with actual (integer) values, and a flag to indicate 'basic', or something.

Anyway ... I think you're hyper-focused on exactly the wrong thing.

Arguably, for scan results, the right thing to do would be to just output the raw elements in the JSON, and not do any of this parsing. Then you can use your favourite parsing library (dpkt? tshark? ...) to actually understand the data there. We really don't need to expose the element parsing logic of iw, especially not in a bad way like this.

Also, outputting the *string* data in a machine-readable format like you do now has very little value, and yet it ties us to a specific output format that we'd probably have to consider stable. Bad idea.

So I guess I'm saying yhou should abandon this line of changes in this code entirely.

Quoted 8 lines

Much more interesting, IMHO, would be to focus in pretty much anything _else_ in the iw code, e.g. the output of 'iw dev', 'iw wlan0 info', statistics, etc. Maybe 'iw list' and similar too.

Although I suspect that what we really need is better access for tools from nl80211. Maybe the "JSON" output format should just dump the raw nl80211 message attributes that are involved, or something.

+ 1 on this one. The whole goal of json is to be machine readable, it should not be just be the same output as iw (which is text/user readable) but with json syntax / separators insted of \n & \t

Quoted 1 line

johannes