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