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})
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 groups=[+|-]<val>[,<val>...] set/add/remove groups that the host is a member of
59 ipaddr=[+|-]<val>[,<val>...] set/add/remove host ip addresses
60 subnet=[+|-]<val>[,<val>...] set/add/remove host announced subnets
61 endpoint=<val> set host endpoint address
62 gateway=<name> set host gateway (using name of other host)
63 ssh host options (add-ssh-host, set-ssh-host)
64 auth_key=<key> use <key> as public auth key on the remote host
65 priv_key=<key> use <key> as private host key on the remote host (default: generate a new key)
66 interface=<name> use <name> as interface in /etc/config/network on the remote host
67 domain=<name> use <name> as hosts file domain on the remote host (default: unet)
68 connect=<val>[,<val>...] set IP addresses that the host will contact for network updates
69 tunnels=<ifname>:<service>[,...] set active tunnel devices
70 service options (add-service, set-service):
71 type=<val> set service type (required for add-service)
72 members=[+|-]<val>[,<val>...] set/add/remove service member hosts/groups
73 vxlan service options (add-service, set-service):
75 port=<val> set VXLAN port
76 mtu=<val> set VXLAN device MTU
77 forward_ports=[+|-]<val>[,<val>...] set members allowed to receive broadcast/multicast/unknown-unicast
79 upload=<ip>[,<ip>...] upload signed file to hosts
91 let file = shift(ARGV);
92 let command = shift(ARGV);
95 int: function(object, name, val) {
96 object[name] = int(val);
98 string: function(object, name, val) {
101 array: function(object, name, val) {
102 let op = substr(val, 0, 1);
104 if (op == "+" || op == "-") {
105 val = substr(val, 1);
112 let vals = split(val, ",");
114 object[name] = filter(object[name], function(v) {
118 push(object[name], val);
121 if (!length(object[name]))
126 const service_field_types = {
131 forward_ports: "array",
143 if [ -n "$first" ]; then
148 uci $cmd "network.$INTERFACE.$field=$cur"
152 set_interface_attrs() {
153 [ -n "$AUTH_KEY" ] && uci set "network.$INTERFACE.auth_key=$AUTH_KEY"
154 set_list connect "$CONNECT"
155 set_list tunnels "$TUNNELS"
156 uci set "network.$INTERFACE.domain=$DOMAIN"
160 [ "$(uci -q get "network.$INTERFACE")" = "interface" -a "$(uci -q get "network.$INTERFACE.proto")" = "unet" ] && return 0
162 set network.$INTERFACE=interface
163 set network.$INTERFACE.proto=unet
164 set network.$INTERFACE.device=$INTERFACE
168 check_interface_key() {
169 key="$(uci -q get "network.$INTERFACE.key" | unet-tool -q -H -K -)"
171 uci set "network.$INTERFACE.key=$(unet-tool -G)"
172 key="$(uci get "network.$INTERFACE.key" | unet-tool -H -K -)"
185 let print_only = false;
187 function fetch_args() {
188 for (let arg in ARGV) {
189 let vals = match(arg, /^(.[[:alnum:]_-]*)=(.*)$/);
190 assert(vals, `Invalid argument: ${arg}`);
191 args[vals[1]] = vals[2]
195 function set_field(typename, object, name, val) {
196 if (!field_types[typename]) {
197 warn(`Invalid type ${type}\n`);
201 if (type(val) != "string")
209 field_types[typename](object, name, val);
212 function set_fields(object, list) {
214 set_field(list[f], object, f, args[f]);
217 function set_host(host) {
229 function set_service(service) {
230 set_fields(service, {
235 if (service_field_types[service.type])
236 set_fields(service.config, service_field_types[service.type]);
239 function sync_ssh_host(host) {
240 let interface = args.interface ?? "unet";
241 let connect = replace(args.connect ?? "", ",", " ");
242 let auth_key = args.auth_key;
243 let tunnels = replace(replace(args.tunnels ?? "", ",", " "), ":", "=");
244 let domain = args.domain ?? "unet";
248 system(`${unet_tool} -q -P -K ${file}.key >&${fh.fileno()}`);
250 auth_key = fh.read("line");
252 auth_key = replace(auth_key, "\n", "");
253 if (auth_key == "") {
254 warn("Could not read auth key\n");
260 fh.write(`INTERFACE='${interface}'\n`);
261 fh.write(`CONNECT='${connect}'\n`);
262 fh.write(`AUTH_KEY='${auth_key}'\n`);
263 fh.write(`TUNNELS='${tunnels}'\n`);
264 fh.write(`DOMAIN='${domain}'\n`);
265 fh.write(ssh_script);
270 system(`ssh ${host} sh <&${fh.fileno()} >&${fh2.fileno()}`);
276 while (line = fh2.read("line")) {
277 let vals = match(line, /^(.[[:alnum:]_-]*)=(.*)\n$/);
278 assert(vals, `Invalid argument: ${line}`);
279 data[vals[1]] = vals[2]
283 assert(data.key, "Could not read host key from SSH host");
288 while (substr(ARGV[0], 0, 1) == "-") {
289 let opt = shift(ARGV);
292 else if (opt == "-p")
298 let hostname, ssh_host, servicename;
300 if (command in [ "add-host", "set-host", "add-ssh-host", "set-ssh-host" ]) {
301 hostname = shift(ARGV);
302 assert(hostname, "Missing host name argument");
305 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
306 ssh_host = shift(ARGV);
307 assert(ssh_host, "Missing SSH host/user argument");
310 if (command in [ "add-service", "set-service" ]) {
311 servicename = shift(ARGV);
312 assert(servicename, "Missing service name argument");
317 if (command in [ "add-ssh-host", "set-ssh-host" ]) {
318 sync_ssh_host(ssh_host);
319 command = replace(command, "ssh-", "");
324 if (command == "create") {
332 assert(fh, `Could not open input file ${file}`);
337 assert(false, `Could not parse input file ${file}`);
341 if (command == "create") {
342 for (let key, val in defaults)
343 args[key] ??= `${val}`;
344 if (!access(`${file}.key`))
345 system(`${unet_tool} -G > ${file}.key`);
348 if (command == "sign") {
349 let ret = system(`${unet_tool} -S -K ${file}.key -o ${file}.bin ${file}`);
354 for (let host in split(args.upload, ",")) {
355 warn(`Uploading ${file}.bin to ${host}\n`);
356 ret = system(`${unet_tool} -U ${host} -K ${file}.key ${file}.bin`);
358 warn("Upload failed\n");
367 set_fields(net_data.config, {
371 set_field("int", net_data.config, "peer-exchange-port", args.pex_port);
375 net_data.hosts[hostname] = {};
376 assert(args.key, "Missing host key");
377 set_host(net_data.hosts[hostname]);
381 assert(net_data.hosts[hostname], `Host '${hostname}' does not exist`);
382 set_host(net_data.hosts[hostname]);
386 net_data.services[servicename] = {
390 assert(args.type, "Missing service type");
391 set_service(net_data.services[servicename]);
395 assert(net_data.services[servicename], `Service '${servicename}' does not exist`);
396 set_service(net_data.services[servicename]);
400 assert(false, "Unknown command");
403 const net_data_json = sprintf("%.J\n", net_data);
406 print(net_data_json);
408 writefile(file, net_data_json);