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