2019/02/12

OpenWRT 在 shell 使用 ubus 取得 wan, lan 的 ip address 和 mask

OpenWRT 的 uci get 是用來取得設定內容,假如 wan 是動態取得 ip address,就無法透過 uci get 來取得 wan 的 ip address。所以需要透過 ubus 跟 jsonfilter 來取得這些動態的資訊。

先參考官方的 ubus 說明

列出現有的 object 來參考
root@OpenWrt:~# ubus list
log
network
network.device
network.interface
network.interface.VLAN101
network.interface.lan
network.interface.loopback
network.interface.wan
network.interface.wan6
network.wireless
service
session
system
uci

看看 wan 的狀態
root@OpenWrt:~# ubus call network.interface.wan status
{
	"up": true,
	"pending": false,
	"available": true,
	"autostart": true,
	"dynamic": false,
	"uptime": 5493,
	"l3_device": "eth0",
	"proto": "dhcp",
	"device": "eth0",
	"updated": [
		"addresses",
		"routes",
		"data"
	],
	"metric": 0,
	"delegation": true,
	"ipv4-address": [
		{
			"address": "192.168.5.218",
			"mask": 24
		}
	],
	"ipv6-address": [
		
	],
	"ipv6-prefix": [
		
	],
	"ipv6-prefix-assignment": [
		
	],
	"route": [
		{
			"target": "192.168.5.254",
			"mask": 32,
			"nexthop": "0.0.0.0",
			"source": "192.168.5.218\/32"
		},
		{
			"target": "0.0.0.0",
			"mask": 0,
			"nexthop": "192.168.5.254",
			"source": "192.168.5.218\/32"
		}
	],
	"dns-server": [
		"8.8.8.8",
		"168.95.1.1"
	],
	"dns-search": [
		"WIFI"
	],
	"inactive": {
		"ipv4-address": [
			
		],
		"ipv6-address": [
			
		],
		"route": [
			
		],
		"dns-server": [
			
		],
		"dns-search": [
			
		]
	},
	"data": {
		"leasetime": 86400
	}
}
輸出是 json 的結構,從上面的內容看到 wan 是透過 dhcp 取得 192.168.5.218/24

接下來要透過 jsonfilter (官網) 來抽出我們想要的內容。不確定原因,但是直接執行沒看到說明,所以進去原始碼看看語法:
print_usage(char *app)
{
	printf(
	"== Usage ==\n\n"
	"  # %s [-a] [-i  | -s \"json...\"] {-t  | -e }\n"
	"  -q		Quiet, no errors are printed\n"
	"  -h, --help	Print this help\n"
	"  -a		Implicitely treat input as array, useful for JSON logs\n"
	"  -i path	Specify a JSON file to parse\n"
	"  -s \"json\"	Specify a JSON string to parse\n"
	"  -l limit	Specify max number of results to show\n"
	"  -F separator	Specify a field separator when using export\n"
	"  -t 	Print the type of values matched by pattern\n"
	"  -e 	Print the values matched by pattern\n"
	"  -e VAR=	Serialize matched value for shell \"eval\"\n\n"
	"== Patterns ==\n\n"
	"  Patterns are JsonPath: http://goessner.net/articles/JsonPath/\n"
	"  This tool implements $, @, [], * and the union operator ','\n"
	"  plus the usual expressions and literals.\n"
	"  It does not support the recursive child search operator '..' or\n"
	"  the '?()' and '()' filter expressions as those would require a\n"
	"  complete JavaScript engine to support them.\n\n"
	"== Examples ==\n\n"
	"  Display the first IPv4 address on lan:\n"
	"  # ifstatus lan | %s -e '@[\"ipv4-address\"][0].address'\n\n"
	"  Extract the release string from the board information:\n"
	"  # ubus call system board | %s -e '@.release.description'\n\n"
	"  Find all interfaces which are up:\n"
	"  # ubus call network.interface dump | \\\n"
	"  	%s -e '@.interface[@.up=true].interface'\n\n"
	"  Export br-lan traffic counters for shell eval:\n"
	"  # devstatus br-lan | %s -e 'RX=@.statistics.rx_bytes' \\\n"
	"	-e 'TX=@.statistics.tx_bytes'\n",
		app, app, app, app, app);
}

我們要用的是 -e 這個操作,以 ip address 為例,要取的值是 ipv4-address 底下的 address
root@OpenWrt:~# ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].address'
192.168.5.218
很順利的取得了 wan 的 ip 是 192.168.5.218

寫個 shell script 來測試
root@OpenWrt:/# cat /tmp/test.sh 
LAN_IP=`ubus call network.interface.lan status | jsonfilter -e '@["ipv4-address"][0].address'`
LAN_MASK=`ubus call network.interface.lan status | jsonfilter -e '@["ipv4-address"][0].mask'`
LAN_DEV=`ubus call network.interface.lan status | jsonfilter -e '@["device"]'`
WAN_IP=`ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].address'`
WAN_MASK=`ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].mask'`
WAN_DEV=`ubus call network.interface.wan status | jsonfilter -e '@["device"]'`
echo "LAN_IP=$LAN_IP"
echo "LAN_MASK=$LAN_MASK"
echo "LAN_DEV=$LAN_DEV"
echo "WAN_IP=$WAN_IP"
echo "WAN_MASK=$WAN_MASK"
echo "WAN_DEV=$WAN_DEV"
root@OpenWrt:/# /tmp/test.sh 
LAN_IP=192.168.1.1
LAN_MASK=24
LAN_DEV=br-lan
WAN_IP=192.168.5.218
WAN_MASK=24
WAN_DEV=eth0


2019/02/01

Leetcode 869. Reordered Power of 2

869. Reordered Power of 2
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this in a way such that the resulting number is a power of 2.
 Example 1:
Input: 1
Output: true
Example 2:
Input: 10
Output: false
Example 3:
Input: 16
Output: true
Example 4:
Input: 24
Output: false
Example 5:
Input: 46
Output: true
Note:
  1. 1 <= N <= 10^9

題意就是檢查輸入的數字能不能重組成2的次方倍,例如 46 可以重組成 64,是 2 的次方倍,所以要傳回 true。採用的方法就是計算個別數字出現的次數,跟 2 的次方倍相比,次數相同就表示可以重組成功。因為題目有限縮 N 的範圍,所以可以利用這一點來加快執行速度,程式碼如下:



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
bool check(int* d, int T) {
 int t[10] = {0};
 int m;
 
 while (T) {
  m = T % 10;
  ++t[m];
  T /= 10;
 }

 for (m=0; m<10; m++) {
  if (d[m] != t[m]) {
   return false;
  }
 }
 return true;
}

bool reorderedPowerOf2(int N) {
 int i, n, m, s, z, d[10]={0};
 
 if (N < 128) {
  if (64 == N) {
   return true;
  }
  if (46 == N) {
   return true;
  }
  if (32 == N) {
   return true;
  }
  if (23 == N) {
   return true;
  }
  if (16 == N) {
   return true;
  }
  if (61 == N) {
   return true;
  }
  if (8 == N) {
   return true;
  }
  if (4 == N) {
   return true;
  }
  if (2 == N) {
   return true;
  }
  if (1 == N) {
   return true;
  }
 }
 
 n = N;
 i = 0;
 s = 0;
 while (n) {
  m = n % 10;
  s += m;
  ++d[m];
  n /= 10;
 }

    if (N >= 100000000) {
  if ((41 == s) && check(d, 536870912)) {
   return true;
  }
  if ((43 == s) && check(d, 268435456)) {
   return true;
  }
  if ((35 == s) && check(d, 134217728)) {
   return true;
  }
 } else if (N >= 10000000) {
  if ((40 == s) && check(d, 67108864)) {
   return true;
  }
  if ((29 == s) && check(d, 33554432)) {
   return true;
  }
  if ((37 == s) && check(d, 16777216)) {
   return true;
  }
 } else if (N >= 1000000) {
  if ((41 == s) && check(d, 8388608)) {
   return true;
  }
  if ((25 == s) && check(d, 4194304)) {
   return true;
  }
  if ((26 == s) && check(d, 2097152)) {
   return true;
  }
  if ((31 == s) && check(d, 1048576)) {
   return true;
  }
 } else if (N >= 100000) {
  if ((29 == s) && check(d, 524288)) {
   return true;
  }
  if ((19 == s) && check(d, 262144)) {
   return true;
  }
  if ((14 == s) && check(d, 131072)) {
   return true;
  }
 } else if (N >= 10000) {
  if ((25 == s) && check(d, 65536)) {
   return true;
  }
  if ((26 == s) && check(d, 32768)) {
   return true;
  }
  if ((22 == s) && check(d, 16384)) {
   return true;
  }
 } else if (N >= 1000) { 
  if ((20 == s) && check(d, 8192)) {
   return true;
  }
  if ((19 == s) && check(d, 4096)) {
   return true;
  }
  if ((14 == s) && check(d, 2048)) {
   return true;
  }
  if ((7 == s) && check(d, 1024)) {
   return true;
  }
 } else if (N >= 100) {
  if ((8 == s) && check(d, 512)) {
   return true;
  }
  if ((13 == s) && check(d, 256)) {
   return true;
  }
  if ((11 == s) && check(d, 128)) {
   return true;
  }
 }
 
 return false;
}

另一個解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
bool check(int* d, int T) {
 int t[10] = {0};
 int m;

 while (T) {
  ++t[T % 10];
  T /= 10;
 }
 
 for (m=0; m<10; m++) {
  if (d[m] != t[m]) {
   return false;
  }
 }
 return true;
}

bool reorderedPowerOf2(int N) {
 int c, i, n, T;
 int d[10] = {0};
 int r[32] = {0,1,1,1,1,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10};

 if (1==N || 2==N || 4==N || 8==N) {
  return true;
 }

 n = N;
 c = 0;
 while (n) {
  ++d[n % 10];
  n /= 10;
  ++c;
 }

 T=16;
 for (i=5;i<32;i++) {
  if (r[i] > c) {
   break;
  } else if (r[i] == c && check(d, T)) {
   return true;
  }
  T<<=1;
 }

 return false;
}

2019/01/23

LeerCode 566. Reshape the Matrix

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positiveintegers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

這一題是要將一個原先是 r * c 的陣列轉換成 nr * nc 的陣列,沒有什麼特別的技巧,就是重新排列而已,因為是連續取值,所以原陣列的 row 跟 col 就用 ++ 的方式來處理,以加快速度。


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** matrixReshape(int** nums, int numsRowSize, int numsColSize, int r, int c, int** columnSizes, int* returnSize) {
    int **ret;
    int i, j, rr, cc;
    
    if (numsRowSize * numsColSize != r * c) {
        ret = nums;
        *returnSize = numsRowSize;
        columnSizes[0] = (int *) malloc (numsRowSize * sizeof(int));
        for (i=0; i<numsRowSize; i++) {
            columnSizes[0][i] = numsColSize;
        }
    } else {
        *returnSize = r;
        columnSizes[0] = (int *) malloc (r * sizeof(int));
        ret = (int **) malloc (r * sizeof(int *));
        rr = 0;
        cc = 0;
        for (i=0; i<r; i++) {
            ret[i] = (int *) malloc (c * sizeof(int));
            columnSizes[0][i] = c;
            for (j=0; j<c; j++) {
                ret[i][j] = nums[rr][cc];
                if (++cc == numsColSize) {
                    ++rr;
                    cc = 0;
                }
            }
        }
    }
    return ret;
}




2019/01/19

leetcode 885. Spiral Matrix III

On a 2 dimensional grid with R rows and C columns, we start at (r0, c0)facing east.
Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.
Now, we walk in a clockwise spiral shape to visit every position in this grid. 
Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.) 
Eventually, we reach all R * C spaces of the grid.
Return a list of coordinates representing the positions of the grid in the order they were visited.

Example 1:
Input: R = 1, C = 4, r0 = 0, c0 = 0
Output: [[0,0],[0,1],[0,2],[0,3]]



Example 2:
Input: R = 5, C = 6, r0 = 1, c0 = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]



Note:
  1. 1 <= R <= 100
  2. 1 <= C <= 100
  3. 0 <= r0 < R
  4. 0 <= c0 < C

這題用沒有向量的C不是很容易解,只好用暴力的方式求解,利用的方法很單純,就是讓 (r0, c0) 去繞圈圈,而且根據旋轉的特性,可以發現右下左上這樣的順序,格數變量是 1,1,2,2,3,3,4,4....,所以程式就長成下面這樣。leetcode 報 20ms,目前百分位置是 100%,期待出現更快的解法可以參考。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** spiralMatrixIII(int R, int C, int r0, int c0, int** columnSizes, int* returnSize) {
    int **ret;
    int i, j;
    int step;

    *returnSize = R * C;
    columnSizes[0] = (int *) malloc (R * C * sizeof(int));
    ret = (int **) malloc (R * C * sizeof(int *));

    i = 0;
    ret[i] = (int *) malloc (2 * sizeof(int));
    ret[i][0] = r0;
    ret[i][1] = c0;
    columnSizes[0][i] = 2;
    ++i;
    if (i == *returnSize) {
        return ret;
    }

    step = 1;
    while(1) {
        if (r0 >=0 && r0 < R) {
            for (j=1; j<=step; j++) {
                ++c0;
                if (c0 >= 0 && c0 < C) {
                    ret[i] = (int *) malloc (2 * sizeof(int));
                    ret[i][0] = r0;
                    ret[i][1] = c0;
                    columnSizes[0][i] = 2;
                    ++i;
                    if (i == *returnSize) {
                        return ret;
                    }
                }
            }
        } else {
            c0 += step;
        }
        if (c0 >= 0 && c0 < C) {
            for (j=1; j<=step; j++) {
                ++r0;
                if (r0 >=0 && r0 < R) {
                    ret[i] = (int *) malloc (2 * sizeof(int));
                    ret[i][0] = r0;
                    ret[i][1] = c0;
                    columnSizes[0][i] = 2;
                    ++i;
                    if (i == *returnSize) {
                        return ret;
                    }
                }
            }
        } else {
            r0 += step;
        }
        ++step;
        if (r0 >= 0 && r0 < R) {
            for (j=1; j<=step; j++) {
                --c0;
                if (c0 >= 0 && c0 < C) {
                    ret[i] = (int *) malloc (2 * sizeof(int));
                    ret[i][0] = r0;
                    ret[i][1] = c0;
                    columnSizes[0][i] = 2;
                    ++i;
                    if (i == *returnSize) {
                        return ret;
                    }
                }
            }
        } else {
            c0 -= step;
        }
        if (c0 >= 0 && c0 < C) {
            for (j=1; j<=step; j++) {
                --r0;
                if (r0 >=0 && r0 < R) {
                    ret[i] = (int *) malloc (2 * sizeof(int));
                    ret[i][0] = r0;
                    ret[i][1] = c0;
                    columnSizes[0][i] = 2;
                    ++i;
                    if (i == *returnSize) {
                        return ret;
                    }    
                }
            }
        } else {
            r0 -= step;
        }
        ++step;
    }
    return ret;
}

2018/11/07

自製 make menuconfig

linux kernel 提供的 kconfig 功能十分好用,openwrt 和 buildroot 也都拿來使用,但是內容太龐大,整包拿來用並不輕鬆,所幸找到一包已經從 kconfig 抽出來的 standalong 版本 (github 連結),可以好好的利用,以下就是利用這個 github 當基礎來建立一個簡單的 menuconfig template。

資料夾結構

名稱(Name) 描述(Descript)
~/build/ 編譯空間
~/defconfig/ 放置 defconfig 的地方
~/host-tools/ 集中放置 host 工具的地方,可再擴充,像是 toolchain
~/host-tools/menuconfig/ standalong 的原始碼,內層不再贅述

~/host-tools/menuconfig/Makefile
原始的專案採用 cmake,因為會產生 cmake 相關的檔案,所以自己建一個簡單的 Makefile 來用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
CC ?= gcc

lxdialog := lxdialog/checklist.o
lxdialog += lxdialog/util.o
lxdialog += lxdialog/inputbox.o
lxdialog += lxdialog/textbox.o
lxdialog += lxdialog/yesno.o
lxdialog += lxdialog/menubox.o

mconf-objs := mconf.o
mconf-objs += zconf.tab.o
mconf-objs += $(lxdialog)

conf-objs := conf.o
conf-objs += zconf.tab.o

clean-files	:= mconf conf
clean-files += $(mconf-objs)
clean-files += $(conf-objs)

all: mconf conf
	
$(obj)/%.o: %.c
	$(CC) -c $< -o $@

mconf: $(mconf-objs)
	$(CC) $(mconf-objs) -o mconf -lncurses

conf: $(conf-objs)
	$(CC) $(conf-objs) -o conf

clean:
	@rm -f $(clean-files)
這個 Makefile 預設使用 gcc 進行編譯,如果需要更改,需要 make 的時候予以告知,例如 make CC=your_compiler
make 完成後會產生 mconf 和 conf 兩個執行檔

~/Makefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
ifneq ("$(wildcard .config)","")
	include .config
endif

all: preconfig

preconfig:
ifeq ("$(wildcard .config)","")
	$(error "Please run make menuconfig first.")
endif

menuconfig:
	@mkdir -p build
	@rsync -ur host-tools/menuconfig build
	@make -C build/menuconfig
	@./build/menuconfig/mconf Config.in

list-defconfigs:
	@echo 'Built-in configs:'
	@$(foreach b, $(sort $(notdir $(wildcard defconfig/*_defconfig))), \
	  printf "  %-35s - Build for %s\\n" $(b) $(b:_defconfig=);)
	@echo

%_defconfig:
	@./build/menuconfig/conf --defconfig=defconfig/$@ Config.in~
1~3: 如果已經存在 .config 就將內容 include 進來
5: all 之前要先跑過 preconfig
7~10: preconfig 會檢查 .config 是不是存在,如果不存在就顯示要求執行 menuconfig 並且報錯跳出
12~16: menuconfig 主體,make 的機制是已經編譯過且沒有更改內容,就不會重新編譯
18~22: list-defconfigs 可以列出在 ~/defconfig 裡面的所有 *_defconfig
24~25: 當執行 make xxxx_defconfig 就會依據 xxxx_defconfig 來產生 .config

使用這個 template 可以建立一個基本的 menuconfig 功能,通常會根據不同的 target board 或是個別的客製化來製作 xxxx_defconfig,要編譯的時候就可以直接 make xxxx_defconfig 然後再 make all。

一般來說,build 放置的是 target 的編譯空間,砍掉 build 就會非常乾淨,但是 host-tools 也得重編,所以如果確定 host-tools 跟 target 無依存關係,也可以另外開 host-build 來用。