add support for overriding peer-exchange-port for individual hosts
[project/unetd.git] / scripts / unet-cli
1 #!/usr/bin/env ucode
2
3 'use strict';
4
5 import { access, basename, dirname, mkstemp, open, writefile } from 'fs';
6
7 function assert(cond, message) {
8 if (!cond) {
9 warn(message, "\n");
10 exit(1);
11 }
12
13 return true;
14 }
15
16 let unet_tool = "unet-tool";
17 let script_dir = sourcepath(0, true);
18
19 if (basename(script_dir) == "scripts") {
20 unet_tool = `${dirname(script_dir)}/unet-tool`;
21 assert(access(unet_tool, "x"), "unet-tool missing");
22 }
23
24 let args = {};
25
26 const defaults = {
27 port: 51830,
28 pex_port: 51831,
29 keepalive: 10,
30 };
31
32 const usage_message = `
33 Usage: ${basename(sourcepath())} [<flags>] <file> <command> [<args>] [<option>=<value> ...]
34
35 Commands:
36 - create: Create a new network file
37 - set-config: Change network config parameters
38 - add-host <name>: Add a host
39 - add-ssh-host <name> <host>: Add a remote OpenWrt host via SSH
40 (<host> can contain SSH options as well)
41 - set-host <name>: Change host settings
42 - set-ssh-host <name> <host>: Update local and remote host settings
43 - add-service <name>: Add a service
44 - set-service <name>: Change service settings
45 - sign Sign network data
46
47 Flags:
48 -p: Print modified JSON instead of updating file
49
50 Options:
51 - config options (create, set-config):
52 port=<val> set tunnel port (default: ${defaults.port})
53 pex_port=<val> set peer-exchange port (default: ${defaults.pex_port}, 0: disabled)
54 keepalive=<val> set keepalive interval (seconds, 0: off, default: ${defaults.keepalive})
55 - host options (add-host, add-ssh-host, set-host):
56 key=<val> set host public key (required for add-host)
57 port=<val> set host tunnel port number
58 pex_port=<val> set host peer-exchange port (default: network pex_port, 0: disabled)
59 groups=[+|-]<val>[,<val>...] set/add/remove groups that the host is a member of
60 ipaddr=[+|-]<val>[,<val>...] set/add/remove host ip addresses
61 subnet=[+|-]<val>[,<val>...] set/add/remove host announced subnets
62 endpoint=<val> set host endpoint address
63 gateway=<name> set host gateway (using name of other host)
64 - ssh host options (add-ssh-host, set-ssh-host)
65 auth_key=<key> use <key> as public auth key on the remote host
66 priv_key=<key> use <key> as private host key on the remote host (default: generate a new key)
67 interface=<name> use <name> as interface in /etc/config/network on the remote host
68 domain=<name> use <name> as hosts file domain on the remote host (default: unet)
69 connect=<val>[,<val>...] set IP addresses that the host will contact for network updates
70 tunnels=<ifname>:<service>[,...] set active tunnel devices
71 - service options (add-service, set-service):
72 type=<val> set service type (required for add-service)
73 members=[+|-]<val>[,<val>...] set/add/remove service member hosts/groups
74 - vxlan service options (add-service, set-service):
75 id=<val> set VXLAN ID
76 port=<val> set VXLAN port
77 mtu=<val> set VXLAN device MTU
78 forward_ports=[+|-]<val>[,<val>...] set members allowed to receive broadcast/multicast/unknown-unicast
79 - sign options:
80 upload=<ip>[,<ip>...] upload signed file to hosts
81
82 `;
83
84 function usage() {
85 warn(usage_message);
86 return 1;
87 }
88
89 if (length(ARGV) < 2)
90 exit(usage());
91
92 let file = shift(ARGV);
93 let command = shift(ARGV);
94
95 const field_types = {
96 int: function(object, name, val) {
97 object[name] = int(val);
98 },
99 string: function(object, name, val) {
100 object[name] = val;
101 },
102 array: function(object, name, val) {
103 let op = substr(val, 0, 1);
104
105 if (op == "+" || op == "-") {
106 val = substr(val, 1);
107 object[name] ??= [];
108 } else {
109 op = "=";
110 object[name] = [];
111 }
112
113 let vals = split(val, ",");
114 for (val in vals) {
115 object[name] = filter(object[name], function(v) {
116 return v != val
117 });
118 if (op != "-")
119 push(object[name], val);
120 }
121
122 if (!length(object[name]))
123 delete object[name];
124 },
125 };
126
127 const service_field_types = {
128 vxlan: {
129 id: "int",
130 port: "int",
131 mtu: "int",
132 forward_ports: "array",
133 },
134 };
135
136 const ssh_script = `
137
138 set_list() {
139 local field="$1"
140 local val="$2"
141
142 first=1
143 for cur in $val; do
144 if [ -n "$first" ]; then
145 cmd=set
146 else
147 cmd=add_list
148 fi
149 uci $cmd "network.$INTERFACE.$field=$cur"
150 first=
151 done
152 }
153 set_interface_attrs() {
154 [ -n "$AUTH_KEY" ] && uci set "network.$INTERFACE.auth_key=$AUTH_KEY"
155 set_list connect "$CONNECT"
156 set_list tunnels "$TUNNELS"
157 uci set "network.$INTERFACE.domain=$DOMAIN"
158 }
159
160 check_interface() {
161 [ "$(uci -q get "network.$INTERFACE")" = "interface" -a "$(uci -q get "network.$INTERFACE.proto")" = "unet" ] && return 0
162 uci batch <<EOF
163 set network.$INTERFACE=interface
164 set network.$INTERFACE.proto=unet
165 set network.$INTERFACE.device=$INTERFACE
166 EOF
167 }
168
169 check_interface_key() {
170 key="$(uci -q get "network.$INTERFACE.key" | unet-tool -q -H -K -)"
171 [ -n "$key" ] || {
172 uci set "network.$INTERFACE.key=$(unet-tool -G)"
173 key="$(uci get "network.$INTERFACE.key" | unet-tool -H -K -)"
174 }
175 echo "key=$key"
176 }
177
178 check_interface
179 check_interface_key
180 set_interface_attrs
181 uci commit
182 reload_config
183 ifup $INTERFACE
184 `;
185
186 let print_only = false;
187
188 function fetch_args() {
189 for (let arg in ARGV) {
190 let vals = match(arg, /^(.[[:alnum:]_-]*)=(.*)$/);
191 assert(vals, `Invalid argument: ${arg}`);
192 args[vals[1]] = vals[2]
193 }
194 }
195
196 function set_field(typename, object, name, val) {
197 if (!field_types[typename]) {
198 warn(`Invalid type ${type}\n`);
199 return;
200 }
201
202 if (type(val) != "string")
203 return;
204
205 if (val == "") {
206 delete object[name];
207 return;
208 }
209
210 field_types[typename](object, name, val);
211 }
212
213 function set_fields(object, list) {
214 for (let f in list)
215 set_field(list[f], object, f, args[f]);
216 }
217
218 function set_host(host) {
219 set_fields(host, {
220 key: "string",
221 endpoint: "string",
222 gateway: "string",
223 port: "int",
224 ipaddr: "array",
225 subnet: "array",
226 groups: "array",
227 });
228 set_field("int", host, "peer-exchange-port", args.pex_port);
229 }
230
231 function set_service(service) {
232 set_fields(service, {
233 type: "string",
234 members: "array",
235 });
236
237 if (service_field_types[service.type])
238 set_fields(service.config, service_field_types[service.type]);
239 }
240
241 function sync_ssh_host(host) {
242 let interface = args.interface ?? "unet";
243 let connect = replace(args.connect ?? "", ",", " ");
244 let auth_key = args.auth_key;
245 let tunnels = replace(replace(args.tunnels ?? "", ",", " "), ":", "=");
246 let domain = args.domain ?? "unet";
247
248 if (!auth_key) {
249 let fh = mkstemp();
250 system(`${unet_tool} -q -P -K ${file}.key >&${fh.fileno()}`);
251 fh.seek();
252 auth_key = fh.read("line");
253 fh.close();
254 auth_key = replace(auth_key, "\n", "");
255 if (auth_key == "") {
256 warn("Could not read auth key\n");
257 exit(1);
258 }
259 }
260
261 let fh = mkstemp();
262 fh.write(`INTERFACE='${interface}'\n`);
263 fh.write(`CONNECT='${connect}'\n`);
264 fh.write(`AUTH_KEY='${auth_key}'\n`);
265 fh.write(`TUNNELS='${tunnels}'\n`);
266 fh.write(`DOMAIN='${domain}'\n`);
267 fh.write(ssh_script);
268 fh.flush();
269 fh.seek();
270
271 let fh2 = mkstemp();
272 system(`ssh ${host} sh <&${fh.fileno()} >&${fh2.fileno()}`);
273 fh.close();
274
275 let data = {}, line;
276
277 fh2.seek();
278 while (line = fh2.read("line")) {
279 let vals = match(line, /^(.[[:alnum:]_-]*)=(.*)\n$/);
280 assert(vals, `Invalid argument: ${line}`);
281 data[vals[1]] = vals[2]
282 }
283 fh2.close();
284
285 assert(data.key, "Could not read host key from SSH host");
286
287 args.key = data.key;
288 }
289
290 while (substr(ARGV[0], 0, 1) == "-") {
291 let opt = shift(ARGV);
292 if (opt == "--")
293 break;
294 else if (opt == "-p")
295 print_only = true;
296 else
297 exit(usage());
298 }
299
300 let hostname, ssh_host, servicename;
301
302 if (command in [ "add-host", "set-host", "add-ssh-host", "set-ssh-host" ]) {
303 hostname = shift(ARGV);
304 assert(hostname, "Missing host name argument");
305 }
306
307 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
308 ssh_host = shift(ARGV);
309 assert(ssh_host, "Missing SSH host/user argument");
310 }
311
312 if (command in [ "add-service", "set-service" ]) {
313 servicename = shift(ARGV);
314 assert(servicename, "Missing service name argument");
315 }
316
317 fetch_args();
318
319 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
320 sync_ssh_host(ssh_host);
321 command = replace(command, "ssh-", "");
322 }
323
324 let net_data;
325
326 if (command == "create") {
327 net_data = {
328 config: {},
329 hosts: {},
330 services: {}
331 };
332 } else {
333 let fh = open(file);
334 assert(fh, `Could not open input file ${file}`);
335
336 try {
337 net_data = json(fh);
338 } catch(e) {
339 assert(false, `Could not parse input file ${file}`);
340 }
341 }
342
343 if (command == "create") {
344 for (let key, val in defaults)
345 args[key] ??= `${val}`;
346 if (!access(`${file}.key`))
347 system(`${unet_tool} -G > ${file}.key`);
348 }
349
350 if (command == "sign") {
351 let ret = system(`${unet_tool} -S -K ${file}.key -o ${file}.bin ${file}`);
352 if (ret != 0)
353 exit(ret);
354
355 if (args.upload) {
356 for (let host in split(args.upload, ",")) {
357 warn(`Uploading ${file}.bin to ${host}\n`);
358 ret = system(`${unet_tool} -U ${host} -K ${file}.key ${file}.bin`);
359 if (ret)
360 warn("Upload failed\n");
361 }
362 }
363 exit(0);
364 }
365
366 switch (command) {
367 case 'create':
368 case 'set-config':
369 set_fields(net_data.config, {
370 port: "int",
371 keepalive: "int",
372 });
373 set_field("int", net_data.config, "peer-exchange-port", args.pex_port);
374 break;
375
376 case 'add-host':
377 net_data.hosts[hostname] = {};
378 assert(args.key, "Missing host key");
379 set_host(net_data.hosts[hostname]);
380 break;
381
382 case 'set-host':
383 assert(net_data.hosts[hostname], `Host '${hostname}' does not exist`);
384 set_host(net_data.hosts[hostname]);
385 break;
386
387 case 'add-service':
388 net_data.services[servicename] = {
389 config: {},
390 members: [],
391 };
392 assert(args.type, "Missing service type");
393 set_service(net_data.services[servicename]);
394 break;
395
396 case 'set-service':
397 assert(net_data.services[servicename], `Service '${servicename}' does not exist`);
398 set_service(net_data.services[servicename]);
399 break;
400
401 default:
402 assert(false, "Unknown command");
403 }
404
405 const net_data_json = sprintf("%.J\n", net_data);
406
407 if (print_only)
408 print(net_data_json);
409 else
410 writefile(file, net_data_json);