5 import { access, basename, dirname, mkstemp, open, writefile } from 'fs';
7 function assert(cond, message) {
16 let unet_tool = "unet-tool";
17 let script_dir = sourcepath(0, true);
19 if (basename(script_dir) == "scripts") {
20 unet_tool = `${dirname(script_dir)}/unet-tool`;
21 assert(access(unet_tool, "x"), "unet-tool missing");
32 const usage_message = `
33 Usage: ${basename(sourcepath())} [<flags>] <file> <command> [<args>] [<option>=<value> ...]
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
48 -p: Print modified JSON instead of updating file
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):
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
80 upload=<ip>[,<ip>...] upload signed file to hosts
92 let file = shift(ARGV);
93 let command = shift(ARGV);
96 int: function(object, name, val) {
97 object[name] = int(val);
99 string: function(object, name, val) {
102 array: function(object, name, val) {
103 let op = substr(val, 0, 1);
105 if (op == "+" || op == "-") {
106 val = substr(val, 1);
113 let vals = split(val, ",");
115 object[name] = filter(object[name], function(v) {
119 push(object[name], val);
122 if (!length(object[name]))
127 const service_field_types = {
132 forward_ports: "array",
144 if [ -n "$first" ]; then
149 uci $cmd "network.$INTERFACE.$field=$cur"
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"
161 [ "$(uci -q get "network.$INTERFACE")" = "interface" -a "$(uci -q get "network.$INTERFACE.proto")" = "unet" ] && return 0
163 set network.$INTERFACE=interface
164 set network.$INTERFACE.proto=unet
165 set network.$INTERFACE.device=$INTERFACE
169 check_interface_key() {
170 key="$(uci -q get "network.$INTERFACE.key" | unet-tool -q -H -K -)"
172 uci set "network.$INTERFACE.key=$(unet-tool -G)"
173 key="$(uci get "network.$INTERFACE.key" | unet-tool -H -K -)"
186 let print_only = false;
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]
196 function set_field(typename, object, name, val) {
197 if (!field_types[typename]) {
198 warn(`Invalid type ${type}\n`);
202 if (type(val) != "string")
210 field_types[typename](object, name, val);
213 function set_fields(object, list) {
215 set_field(list[f], object, f, args[f]);
218 function set_host(host) {
228 set_field("int", host, "peer-exchange-port", args.pex_port);
231 function set_service(service) {
232 set_fields(service, {
237 if (service_field_types[service.type])
238 set_fields(service.config, service_field_types[service.type]);
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";
250 system(`${unet_tool} -q -P -K ${file}.key >&${fh.fileno()}`);
252 auth_key = fh.read("line");
254 auth_key = replace(auth_key, "\n", "");
255 if (auth_key == "") {
256 warn("Could not read auth key\n");
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);
272 system(`ssh ${host} sh <&${fh.fileno()} >&${fh2.fileno()}`);
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]
285 assert(data.key, "Could not read host key from SSH host");
290 while (substr(ARGV[0], 0, 1) == "-") {
291 let opt = shift(ARGV);
294 else if (opt == "-p")
300 let hostname, ssh_host, servicename;
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");
307 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
308 ssh_host = shift(ARGV);
309 assert(ssh_host, "Missing SSH host/user argument");
312 if (command in [ "add-service", "set-service" ]) {
313 servicename = shift(ARGV);
314 assert(servicename, "Missing service name argument");
319 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
320 sync_ssh_host(ssh_host);
321 command = replace(command, "ssh-", "");
326 if (command == "create") {
334 assert(fh, `Could not open input file ${file}`);
339 assert(false, `Could not parse input file ${file}`);
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`);
350 if (command == "sign") {
351 let ret = system(`${unet_tool} -S -K ${file}.key -o ${file}.bin ${file}`);
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`);
360 warn("Upload failed\n");
369 set_fields(net_data.config, {
373 set_field("int", net_data.config, "peer-exchange-port", args.pex_port);
377 net_data.hosts[hostname] = {};
378 assert(args.key, "Missing host key");
379 set_host(net_data.hosts[hostname]);
383 assert(net_data.hosts[hostname], `Host '${hostname}' does not exist`);
384 set_host(net_data.hosts[hostname]);
388 net_data.services[servicename] = {
392 assert(args.type, "Missing service type");
393 set_service(net_data.services[servicename]);
397 assert(net_data.services[servicename], `Service '${servicename}' does not exist`);
398 set_service(net_data.services[servicename]);
402 assert(false, "Unknown command");
405 const net_data_json = sprintf("%.J\n", net_data);
408 print(net_data_json);
410 writefile(file, net_data_json);